Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Remove old literature databases
Timothy Kassiscc82696b1ffb
diff --git a/scientific-skills/arxiv-database/SKILL.md b/scientific-skills/arxiv-database/SKILL.mddeleted file mode 100644index 6b058fb2..00000000--- a/scientific-skills/arxiv-database/SKILL.md+++ /dev/null@@ -1,362 +0,0 @@-----name: arxiv-database-description: Search and retrieve preprints from arXiv via the Atom API. Use this skill when searching for papers in physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering, or economics by keywords, authors, arXiv IDs, date ranges, or categories.-license: MIT-metadata:- skill-author: Orchestra Research------# arXiv Database--## Overview--This skill provides Python tools for searching and retrieving preprints from arXiv.org via its public Atom API. It supports keyword search, author search, category filtering, arXiv ID lookup, and PDF download. Results are returned as structured JSON with titles, abstracts, authors, categories, and links.--## When to Use This Skill--Use this skill when:-- Searching for preprints in CS, ML, AI, physics, math, statistics, q-bio, q-fin, or economics-- Looking up specific papers by arXiv ID (e.g., `2309.10668`)-- Tracking an author's recent preprints-- Filtering papers by arXiv category (e.g., `cs.LG`, `cs.CL`, `stat.ML`)-- Downloading PDFs for full-text analysis-- Building literature review datasets for AI/ML research-- Monitoring new submissions in a subfield--Consider alternatives when:-- Searching for biomedical literature specifically -> Use **pubmed-database** or **biorxiv-database**-- You need citation counts or impact metrics -> Use **openalex-database**-- You need peer-reviewed journal articles only -> Use **pubmed-database**--## Core Search Capabilities--### 1. Keyword Search--Search for papers by keywords in titles, abstracts, or all fields.--```bash-python scripts/arxiv_search.py \- --keywords "sparse autoencoders" "mechanistic interpretability" \- --max-results 20 \- --output results.json-```--With category filter:-```bash-python scripts/arxiv_search.py \- --keywords "transformer" "attention mechanism" \- --category cs.LG \- --max-results 50 \- --output transformer_papers.json-```--Search specific fields:-```bash-# Title only-python scripts/arxiv_search.py \- --keywords "GRPO" \- --search-field ti \- --max-results 10--# Abstract only-python scripts/arxiv_search.py \- --keywords "reward model" "RLHF" \- --search-field abs \- --max-results 30-```--### 2. Author Search--```bash-python scripts/arxiv_search.py \- --author "Anthropic" \- --max-results 50 \- --output anthropic_papers.json-```--```bash-python scripts/arxiv_search.py \- --author "Ilya Sutskever" \- --category cs.LG \- --max-results 20-```--### 3. arXiv ID Lookup--Retrieve metadata for specific papers:--```bash-python scripts/arxiv_search.py \- --ids 2309.10668 2406.04093 2310.01405 \- --output sae_papers.json-```--Full arXiv URLs also accepted:-```bash-python scripts/arxiv_search.py \- --ids "https://arxiv.org/abs/2309.10668"-```--### 4. Category Browsing--List recent papers in a category:-```bash-python scripts/arxiv_search.py \- --category cs.AI \- --max-results 100 \- --sort-by submittedDate \- --output recent_cs_ai.json-```--### 5. PDF Download--```bash-python scripts/arxiv_search.py \- --ids 2309.10668 \- --download-pdf papers/-```--Batch download from search results:-```python-import json-from scripts.arxiv_search import ArxivSearcher--searcher = ArxivSearcher()--# Search first-results = searcher.search(query="ti:sparse autoencoder", max_results=5)--# Download all-for paper in results:- arxiv_id = paper["arxiv_id"]- searcher.download_pdf(arxiv_id, f"papers/{arxiv_id.replace('/', '_')}.pdf")-```--## arXiv Categories--### Computer Science (cs.*)-| Category | Description |-|----------|-------------|-| `cs.AI` | Artificial Intelligence |-| `cs.CL` | Computation and Language (NLP) |-| `cs.CV` | Computer Vision |-| `cs.LG` | Machine Learning |-| `cs.NE` | Neural and Evolutionary Computing |-| `cs.RO` | Robotics |-| `cs.CR` | Cryptography and Security |-| `cs.DS` | Data Structures and Algorithms |-| `cs.IR` | Information Retrieval |-| `cs.SE` | Software Engineering |--### Statistics & Math-| Category | Description |-|----------|-------------|-| `stat.ML` | Machine Learning (Statistics) |-| `stat.ME` | Methodology |-| `math.OC` | Optimization and Control |-| `math.ST` | Statistics Theory |--### Other Relevant Categories-| Category | Description |-|----------|-------------|-| `q-bio.BM` | Biomolecules |-| `q-bio.GN` | Genomics |-| `q-bio.QM` | Quantitative Methods |-| `q-fin.ST` | Statistical Finance |-| `eess.SP` | Signal Processing |-| `physics.comp-ph` | Computational Physics |--Full list: see [references/api_reference.md](references/api_reference.md).--## Query Syntax--The arXiv API uses prefix-based field searches combined with Boolean operators.--**Field prefixes:**-- `ti:` - Title-- `au:` - Author-- `abs:` - Abstract-- `cat:` - Category-- `all:` - All fields (default)-- `co:` - Comment-- `jr:` - Journal reference-- `id:` - arXiv ID--**Boolean operators** (must be UPPERCASE):-```-ti:transformer AND abs:attention-au:bengio OR au:lecun-cat:cs.LG ANDNOT cat:cs.CV-```--**Grouping with parentheses:**-```-(ti:sparse AND ti:autoencoder) AND cat:cs.LG-au:anthropic AND (abs:interpretability OR abs:alignment)-```--**Examples:**-```python-from scripts.arxiv_search import ArxivSearcher--searcher = ArxivSearcher()--# Papers about SAEs in ML-results = searcher.search(- query="ti:sparse autoencoder AND cat:cs.LG",- max_results=50,- sort_by="submittedDate"-)--# Specific author in specific field-results = searcher.search(- query="au:neel nanda AND cat:cs.LG",- max_results=20-)--# Complex boolean query-results = searcher.search(- query="(abs:RLHF OR abs:reinforcement learning from human feedback) AND cat:cs.CL",- max_results=100-)-```--## Output Format--All searches return structured JSON:--```json-{- "query": "ti:sparse autoencoder AND cat:cs.LG",- "result_count": 15,- "results": [- {- "arxiv_id": "2309.10668",- "title": "Towards Monosemanticity: Decomposing Language Models With Dictionary Learning",- "authors": ["Trenton Bricken", "Adly Templeton", "..."],- "abstract": "Full abstract text...",- "categories": ["cs.LG", "cs.AI"],- "primary_category": "cs.LG",- "published": "2023-09-19T17:58:00Z",- "updated": "2023-10-04T14:22:00Z",- "doi": "10.48550/arXiv.2309.10668",- "pdf_url": "http://arxiv.org/pdf/2309.10668v1",- "abs_url": "http://arxiv.org/abs/2309.10668v1",- "comment": "42 pages, 30 figures",- "journal_ref": ""- }- ]-}-```--## Common Usage Patterns--### Literature Review Workflow--```python-from scripts.arxiv_search import ArxivSearcher-import json--searcher = ArxivSearcher()--# 1. Broad search-results = searcher.search(- query="abs:mechanistic interpretability AND cat:cs.LG",- max_results=200,- sort_by="submittedDate"-)--# 2. Save results-with open("interp_papers.json", "w") as f:- json.dump({"result_count": len(results), "results": results}, f, indent=2)--# 3. Filter and analyze-import pandas as pd-df = pd.DataFrame(results)-print(f"Total papers: {len(df)}")-print(f"Date range: {df['published'].min()} to {df['published'].max()}")-print(f"\nTop categories:")-print(df["primary_category"].value_counts().head(10))-```--### Track a Research Group--```python-searcher = ArxivSearcher()--groups = {- "anthropic": "au:anthropic AND (cat:cs.LG OR cat:cs.CL)",- "openai": "au:openai AND cat:cs.CL",- "deepmind": "au:deepmind AND cat:cs.LG",-}--for name, query in groups.items():- results = searcher.search(query=query, max_results=50, sort_by="submittedDate")- print(f"{name}: {len(results)} recent papers")-```--### Monitor New Submissions--```python-searcher = ArxivSearcher()--# Most recent ML papers-results = searcher.search(- query="cat:cs.LG",- max_results=50,- sort_by="submittedDate",- sort_order="descending"-)--for paper in results[:10]:- print(f"[{paper['published'][:10]}] {paper['title']}")- print(f" {paper['abs_url']}\n")-```--## Python API--```python-from scripts.arxiv_search import ArxivSearcher--searcher = ArxivSearcher(verbose=True)--# Free-form query (uses arXiv query syntax)-results = searcher.search(query="...", max_results=50)--# Lookup by ID-papers = searcher.get_by_ids(["2309.10668", "2406.04093"])--# Download PDF-searcher.download_pdf("2309.10668", "paper.pdf")--# Build query from components-query = ArxivSearcher.build_query(- title="sparse autoencoder",- author="anthropic",- category="cs.LG"-)-results = searcher.search(query=query, max_results=20)-```--## Best Practices--1. **Respect rate limits**: The API requests 3-second delays between calls. The script handles this automatically.-2. **Use category filters**: Dramatically reduces noise. `cs.LG` is where most ML papers live.-3. **Cache results**: Save to JSON to avoid re-fetching.-4. **Use `sort_by=submittedDate`** for recent papers, `relevance` for keyword searches.-5. **Max 300 results per query**: arXiv API caps at this. For larger sets, paginate with `start` parameter.-6. **arXiv IDs**: Use bare IDs (`2309.10668`), not full URLs, in programmatic code.-7. **Combine with openalex-database**: For citation counts and impact metrics arXiv doesn't provide.--## Limitations--- **No full-text search**: Only searches metadata (title, abstract, authors, comments)-- **No citation data**: Use openalex-database or Semantic Scholar for citations-- **Max 300 results**: Per query. Use pagination for larger sets.-- **Rate limited**: ~1 request per 3 seconds recommended-- **Atom XML responses**: The script parses these into JSON automatically-- **Search lag**: New papers may take hours to appear in API results--## Reference Documentation--- **API Reference**: See [references/api_reference.md](references/api_reference.md) for full endpoint specs, all categories, and response schemasdiff --git a/scientific-skills/arxiv-database/references/api_reference.md b/scientific-skills/arxiv-database/references/api_reference.mddeleted file mode 100644index 11f8592e..00000000--- a/scientific-skills/arxiv-database/references/api_reference.md+++ /dev/null@@ -1,430 +0,0 @@-# arXiv API Reference--## Overview--The arXiv API provides programmatic access to preprint metadata via an Atom XML feed. It supports search queries with field-specific operators, boolean logic, ID-based retrieval, sorting, and pagination. No authentication required.--## Base URL--```-http://export.arxiv.org/api/query-```--## Rate Limiting--- Recommended: **1 request per 3 seconds**-- Aggressive crawling will result in temporary IP bans-- Use `time.sleep(3)` between requests-- Include a descriptive `User-Agent` header--## Query Parameters--| Parameter | Description | Default |-|-----------|-------------|---------|-| `search_query` | Query string with field prefixes and boolean operators | (none) |-| `id_list` | Comma-separated arXiv IDs | (none) |-| `start` | Starting index for pagination (0-based) | `0` |-| `max_results` | Number of results to return (max 300) | `10` |-| `sortBy` | Sort field: `relevance`, `lastUpdatedDate`, `submittedDate` | `relevance` |-| `sortOrder` | Sort direction: `ascending`, `descending` | `descending` |--**Note**: `search_query` and `id_list` can be used together (results are ANDed) or separately.--## Search Query Syntax--### Field Prefixes--| Prefix | Field | Example |-|--------|-------|---------|-| `ti:` | Title | `ti:transformer` |-| `au:` | Author | `au:bengio` |-| `abs:` | Abstract | `abs:attention mechanism` |-| `co:` | Comment | `co:accepted at NeurIPS` |-| `jr:` | Journal Reference | `jr:Nature` |-| `cat:` | Category | `cat:cs.LG` |-| `all:` | All fields | `all:deep learning` |-| `id:` | arXiv ID | `id:2309.10668` |--### Boolean Operators--Operators **must** be uppercase:--```-ti:transformer AND abs:attention # Both conditions-au:bengio OR au:lecun # Either condition-cat:cs.LG ANDNOT cat:cs.CV # Exclude category-```--### Grouping--Use parentheses for complex queries:--```-(ti:sparse AND ti:autoencoder) AND cat:cs.LG-au:anthropic AND (abs:interpretability OR abs:alignment)-(cat:cs.LG OR cat:cs.CL) AND ti:reinforcement learning-```--### Phrase Search--Quotes for exact phrases:--```-ti:"sparse autoencoder"-au:"Yoshua Bengio"-abs:"reinforcement learning from human feedback"-```--### Wildcards--Not supported by the arXiv API. Use broader terms and filter client-side.--## Example Requests--### Basic keyword search-```-GET http://export.arxiv.org/api/query?search_query=all:sparse+autoencoder&max_results=10-```--### Author + category-```-GET http://export.arxiv.org/api/query?search_query=au:anthropic+AND+cat:cs.LG&max_results=50&sortBy=submittedDate-```--### ID lookup-```-GET http://export.arxiv.org/api/query?id_list=2309.10668,2406.04093-```--### Combined search + ID-```-GET http://export.arxiv.org/api/query?search_query=cat:cs.LG&id_list=2309.10668-```--### Paginated results-```-# Page 1 (results 0-99)-GET ...?search_query=cat:cs.LG&start=0&max_results=100&sortBy=submittedDate--# Page 2 (results 100-199)-GET ...?search_query=cat:cs.LG&start=100&max_results=100&sortBy=submittedDate-```--## Response Format (Atom XML)--The API returns an Atom 1.0 XML feed.--### Feed-level elements--```xml-<?xml version="1.0" encoding="UTF-8"?>-<feed xmlns="http://www.w3.org/2005/Atom"- xmlns:arxiv="http://arxiv.org/schemas/atom">-- <title>ArXiv Query: ...</title>- <id>http://arxiv.org/api/...</id>- <updated>2024-01-15T00:00:00-05:00</updated>-- <!-- Total results available (not just returned) -->- <opensearch:totalResults>1500</opensearch:totalResults>- <opensearch:startIndex>0</opensearch:startIndex>- <opensearch:itemsPerPage>50</opensearch:itemsPerPage>-- <entry>...</entry>- <entry>...</entry>-</feed>-```--### Entry elements--```xml-<entry>- <!-- Unique identifier (includes version) -->- <id>http://arxiv.org/abs/2309.10668v2</id>-- <!-- Dates -->- <published>2023-09-19T17:58:00Z</published>- <updated>2023-10-04T14:22:00Z</updated>-- <!-- Metadata -->- <title>Towards Monosemanticity: Decomposing Language Models...</title>- <summary>We attempt to reverse-engineer a trained neural network...</summary>-- <!-- Authors -->- <author>- <name>Trenton Bricken</name>- </author>- <author>- <name>Adly Templeton</name>- </author>-- <!-- Categories -->- <arxiv:primary_category term="cs.LG" scheme="http://arxiv.org/schemas/atom"/>- <category term="cs.LG" scheme="http://arxiv.org/schemas/atom"/>- <category term="cs.AI" scheme="http://arxiv.org/schemas/atom"/>-- <!-- Links -->- <link href="http://arxiv.org/abs/2309.10668v2" rel="alternate" type="text/html"/>- <link href="http://arxiv.org/pdf/2309.10668v2" rel="related" type="application/pdf" title="pdf"/>-- <!-- Optional -->- <arxiv:comment>42 pages, 30 figures</arxiv:comment>- <arxiv:doi>10.48550/arXiv.2309.10668</arxiv:doi>- <arxiv:journal_ref>...</arxiv:journal_ref>-</entry>-```--### Entry field descriptions--| Field | Description |-|-------|-------------|-| `id` | Canonical arXiv URL with version (e.g., `http://arxiv.org/abs/2309.10668v2`) |-| `published` | First submission date (ISO 8601) |-| `updated` | Last update date (ISO 8601) |-| `title` | Paper title (may contain line breaks in XML) |-| `summary` | Full abstract text |-| `author/name` | Author full name (one per `<author>` element) |-| `arxiv:primary_category` | Primary arXiv category |-| `category` | All categories (multiple elements) |-| `link[@type='text/html']` | Abstract page URL |-| `link[@title='pdf']` | PDF download URL |-| `arxiv:comment` | Author comment (page count, conference, etc.) |-| `arxiv:doi` | Associated DOI (if exists) |-| `arxiv:journal_ref` | Journal publication reference (if published) |--## Complete Category List--### Computer Science (cs.*)--| Category | Name |-|----------|------|-| `cs.AI` | Artificial Intelligence |-| `cs.AR` | Hardware Architecture |-| `cs.CC` | Computational Complexity |-| `cs.CE` | Computational Engineering, Finance, and Science |-| `cs.CG` | Computational Geometry |-| `cs.CL` | Computation and Language |-| `cs.CR` | Cryptography and Security |-| `cs.CV` | Computer Vision and Pattern Recognition |-| `cs.CY` | Computers and Society |-| `cs.DB` | Databases |-| `cs.DC` | Distributed, Parallel, and Cluster Computing |-| `cs.DL` | Digital Libraries |-| `cs.DM` | Discrete Mathematics |-| `cs.DS` | Data Structures and Algorithms |-| `cs.ET` | Emerging Technologies |-| `cs.FL` | Formal Languages and Automata Theory |-| `cs.GL` | General Literature |-| `cs.GR` | Graphics |-| `cs.GT` | Computer Science and Game Theory |-| `cs.HC` | Human-Computer Interaction |-| `cs.IR` | Information Retrieval |-| `cs.IT` | Information Theory |-| `cs.LG` | Machine Learning |-| `cs.LO` | Logic in Computer Science |-| `cs.MA` | Multiagent Systems |-| `cs.MM` | Multimedia |-| `cs.MS` | Mathematical Software |-| `cs.NA` | Numerical Analysis |-| `cs.NE` | Neural and Evolutionary Computing |-| `cs.NI` | Networking and Internet Architecture |-| `cs.OH` | Other Computer Science |-| `cs.OS` | Operating Systems |-| `cs.PF` | Performance |-| `cs.PL` | Programming Languages |-| `cs.RO` | Robotics |-| `cs.SC` | Symbolic Computation |-| `cs.SD` | Sound |-| `cs.SE` | Software Engineering |-| `cs.SI` | Social and Information Networks |-| `cs.SY` | Systems and Control |--### Statistics (stat.*)--| Category | Name |-|----------|------|-| `stat.AP` | Applications |-| `stat.CO` | Computation |-| `stat.ME` | Methodology |-| `stat.ML` | Machine Learning |-| `stat.OT` | Other Statistics |-| `stat.TH` | Statistics Theory |--### Mathematics (math.*)--| Category | Name |-|----------|------|-| `math.AC` | Commutative Algebra |-| `math.AG` | Algebraic Geometry |-| `math.AP` | Analysis of PDEs |-| `math.AT` | Algebraic Topology |-| `math.CA` | Classical Analysis and ODEs |-| `math.CO` | Combinatorics |-| `math.CT` | Category Theory |-| `math.CV` | Complex Variables |-| `math.DG` | Differential Geometry |-| `math.DS` | Dynamical Systems |-| `math.FA` | Functional Analysis |-| `math.GM` | General Mathematics |-| `math.GN` | General Topology |-| `math.GR` | Group Theory |-| `math.GT` | Geometric Topology |-| `math.HO` | History and Overview |-| `math.IT` | Information Theory |-| `math.KT` | K-Theory and Homology |-| `math.LO` | Logic |-| `math.MG` | Metric Geometry |-| `math.MP` | Mathematical Physics |-| `math.NA` | Numerical Analysis |-| `math.NT` | Number Theory |-| `math.OA` | Operator Algebras |-| `math.OC` | Optimization and Control |-| `math.PR` | Probability |-| `math.QA` | Quantum Algebra |-| `math.RA` | Rings and Algebras |-| `math.RT` | Representation Theory |-| `math.SG` | Symplectic Geometry |-| `math.SP` | Spectral Theory |-| `math.ST` | Statistics Theory |--### Physics--| Category | Name |-|----------|------|-| `astro-ph` | Astrophysics (+ subcategories: .CO, .EP, .GA, .HE, .IM, .SR) |-| `cond-mat` | Condensed Matter (+ subcategories) |-| `gr-qc` | General Relativity and Quantum Cosmology |-| `hep-ex` | High Energy Physics - Experiment |-| `hep-lat` | High Energy Physics - Lattice |-| `hep-ph` | High Energy Physics - Phenomenology |-| `hep-th` | High Energy Physics - Theory |-| `math-ph` | Mathematical Physics |-| `nlin` | Nonlinear Sciences (+ subcategories) |-| `nucl-ex` | Nuclear Experiment |-| `nucl-th` | Nuclear Theory |-| `physics` | Physics (+ subcategories: .comp-ph, .data-an, .bio-ph, etc.) |-| `quant-ph` | Quantum Physics |--### Quantitative Biology (q-bio.*)--| Category | Name |-|----------|------|-| `q-bio.BM` | Biomolecules |-| `q-bio.CB` | Cell Behavior |-| `q-bio.GN` | Genomics |-| `q-bio.MN` | Molecular Networks |-| `q-bio.NC` | Neurons and Cognition |-| `q-bio.OT` | Other Quantitative Biology |-| `q-bio.PE` | Populations and Evolution |-| `q-bio.QM` | Quantitative Methods |-| `q-bio.SC` | Subcellular Processes |-| `q-bio.TO` | Tissues and Organs |--### Quantitative Finance (q-fin.*)--| Category | Name |-|----------|------|-| `q-fin.CP` | Computational Finance |-| `q-fin.EC` | Economics |-| `q-fin.GN` | General Finance |-| `q-fin.MF` | Mathematical Finance |-| `q-fin.PM` | Portfolio Management |-| `q-fin.PR` | Pricing of Securities |-| `q-fin.RM` | Risk Management |-| `q-fin.ST` | Statistical Finance |-| `q-fin.TR` | Trading and Market Microstructure |--### Electrical Engineering and Systems Science (eess.*)--| Category | Name |-|----------|------|-| `eess.AS` | Audio and Speech Processing |-| `eess.IV` | Image and Video Processing |-| `eess.SP` | Signal Processing |-| `eess.SY` | Systems and Control |--### Economics (econ.*)--| Category | Name |-|----------|------|-| `econ.EM` | Econometrics |-| `econ.GN` | General Economics |-| `econ.TH` | Theoretical Economics |--## Pagination--The API returns at most 300 results per request. For larger result sets, paginate:--```python-all_results = []-start = 0-batch_size = 100--while True:- params = {- "search_query": "cat:cs.LG",- "start": start,- "max_results": batch_size,- "sortBy": "submittedDate",- "sortOrder": "descending",- }- results = fetch(params) # your fetch function- if not results:- break- all_results.extend(results)- start += batch_size- time.sleep(3) # respect rate limit-```--The total number of results available is in the `opensearch:totalResults` element of the feed.--## Downloading Papers--```-http://arxiv.org/pdf/{arxiv_id}-http://arxiv.org/pdf/{arxiv_id}v{version}-```--### Abstract page-```-http://arxiv.org/abs/{arxiv_id}-```--### Source (LaTeX)-```-http://arxiv.org/e-print/{arxiv_id}-```--### HTML (experimental)-```-http://arxiv.org/html/{arxiv_id}-```--## arXiv ID Formats--| Format | Era | Example |-|--------|-----|---------|-| `YYMM.NNNNN` | 2015+ | `2309.10668` |-| `YYMM.NNNN` | 2007-2014 | `0706.0001` |-| `archive/YYMMNNN` | Pre-2007 | `hep-th/9901001` |--All formats are accepted by the API.--## Common Pitfalls--1. **Boolean operators must be UPPERCASE**: `AND`, `OR`, `ANDNOT` (lowercase is treated as search terms)-2. **URL encoding**: Spaces in queries must be encoded as `+` or `%20`-3. **No full-text search**: The API only searches metadata (title, abstract, authors, etc.)-4. **Empty result placeholder**: When no results are found, arXiv may return a single entry with an empty title and the id `http://arxiv.org/api/errors` - filter this out-5. **Version numbering**: `published` date is v1 submission; `updated` is latest version date-6. **Rate limiting**: Exceeding limits can result in 403 errors or temporary bans-7. **Max 300 per request**: Even if `max_results` is set higher, only 300 are returned--## External Resources--- arXiv API documentation: https://info.arxiv.org/help/api/index.html-- arXiv API user manual: https://info.arxiv.org/help/api/user-manual.html-- arXiv bulk data access: https://info.arxiv.org/help/bulk_data.html-- arXiv category taxonomy: https://arxiv.org/category_taxonomy-- OAI-PMH interface (for bulk metadata): http://export.arxiv.org/oai2diff --git a/scientific-skills/arxiv-database/scripts/arxiv_search.py b/scientific-skills/arxiv-database/scripts/arxiv_search.pydeleted file mode 100644index 9c7a91f8..00000000--- a/scientific-skills/arxiv-database/scripts/arxiv_search.py+++ /dev/null@@ -1,414 +0,0 @@-#!/usr/bin/env python3-"""-arXiv Search Tool-Search and retrieve preprints from arXiv via the Atom API.-Supports keyword search, author search, category filtering, ID lookup, and PDF download.-"""--import requests-import json-import argparse-import xml.etree.ElementTree as ET-import time-import sys-import os-import re-from typing import List, Dict, Optional-from urllib.parse import quote---class ArxivSearcher:- """Search interface for arXiv preprints via the Atom API."""-- BASE_URL = "http://export.arxiv.org/api/query"- ATOM_NS = "{http://www.w3.org/2005/Atom}"- ARXIV_NS = "{http://arxiv.org/schemas/atom}"-- VALID_SORT_BY = ["relevance", "lastUpdatedDate", "submittedDate"]- VALID_SORT_ORDER = ["ascending", "descending"]- VALID_SEARCH_FIELDS = ["ti", "au", "abs", "co", "jr", "cat", "all", "id"]-- def __init__(self, verbose: bool = False, delay: float = 3.0):- self.verbose = verbose- self.delay = delay- self.session = requests.Session()- self.session.headers.update({- "User-Agent": "ArxivSearchTool/1.0 (scientific-skills)"- })- self._last_request_time = 0.0-- def _log(self, message: str):- if self.verbose:- print(f"[INFO] {message}", file=sys.stderr)-- def _rate_limit(self):- """Enforce minimum delay between requests."""- elapsed = time.time() - self._last_request_time- if elapsed < self.delay:- wait = self.delay - elapsed- self._log(f"Rate limiting: waiting {wait:.1f}s")- time.sleep(wait)- self._last_request_time = time.time()-- def _parse_entry(self, entry: ET.Element) -> Dict:- """Parse a single Atom entry into a dict."""- def text(tag, ns=None):- ns = ns or self.ATOM_NS- el = entry.find(f"{ns}{tag}")- return el.text.strip() if el is not None and el.text else ""-- # Authors- authors = []- for author_el in entry.findall(f"{self.ATOM_NS}author"):- name_el = author_el.find(f"{self.ATOM_NS}name")- if name_el is not None and name_el.text:- authors.append(name_el.text.strip())-- # Categories- categories = []- primary_category = ""- for cat_el in entry.findall(f"{self.ATOM_NS}category"):- term = cat_el.get("term", "")- if term:- categories.append(term)- prim_el = entry.find(f"{self.ARXIV_NS}primary_category")- if prim_el is not None:- primary_category = prim_el.get("term", "")-- # Links- pdf_url = ""- abs_url = ""- for link_el in entry.findall(f"{self.ATOM_NS}link"):- href = link_el.get("href", "")- link_type = link_el.get("type", "")- link_title = link_el.get("title", "")- if link_title == "pdf" or link_type == "application/pdf":- pdf_url = href- elif link_type == "text/html" or (not link_type and "/abs/" in href):- abs_url = href-- # Extract arXiv ID from the Atom id field- raw_id = text("id")- arxiv_id = re.sub(r"^https?://arxiv\.org/abs/", "", raw_id)- # Strip version suffix for the canonical ID- arxiv_id_bare = re.sub(r"v\d+$", "", arxiv_id)-- return {- "arxiv_id": arxiv_id_bare,- "title": " ".join(text("title").split()), # collapse whitespace- "authors": authors,- "abstract": " ".join(text("summary").split()),- "categories": categories,- "primary_category": primary_category,- "published": text("published"),- "updated": text("updated"),- "doi": text("doi", self.ARXIV_NS),- "comment": text("comment", self.ARXIV_NS),- "journal_ref": text("journal_ref", self.ARXIV_NS),- "pdf_url": pdf_url,- "abs_url": abs_url or f"http://arxiv.org/abs/{arxiv_id}",- }-- def _fetch(self, params: Dict) -> List[Dict]:- """Execute API request and parse results."""- self._rate_limit()- self._log(f"Query params: {params}")-- try:- response = self.session.get(self.BASE_URL, params=params, timeout=30)- response.raise_for_status()- except requests.exceptions.RequestException as e:- self._log(f"Request error: {e}")- return []-- root = ET.fromstring(response.text)- entries = root.findall(f"{self.ATOM_NS}entry")- self._log(f"Parsed {len(entries)} entries")-- results = []- for entry in entries:- parsed = self._parse_entry(entry)- # Skip the "no results" placeholder entry arXiv returns- if not parsed["title"] or parsed["arxiv_id"] == "":- continue- results.append(parsed)-- return results-- def search(- self,- query: str,- max_results: int = 50,- start: int = 0,- sort_by: str = "relevance",- sort_order: str = "descending",- ) -> List[Dict]:- """- Search arXiv with a query string.-- Args:- query: arXiv query string (e.g., "ti:transformer AND cat:cs.LG")- max_results: Maximum number of results (max 300 per request)- start: Starting index for pagination- sort_by: One of "relevance", "lastUpdatedDate", "submittedDate"- sort_order: "ascending" or "descending"-- Returns:- List of paper dicts- """- if sort_by not in self.VALID_SORT_BY:- raise ValueError(f"sort_by must be one of {self.VALID_SORT_BY}")- if sort_order not in self.VALID_SORT_ORDER:- raise ValueError(f"sort_order must be one of {self.VALID_SORT_ORDER}")-- max_results = min(max_results, 300)-- params = {- "search_query": query,- "start": start,- "max_results": max_results,- "sortBy": sort_by,- "sortOrder": sort_order,- }-- return self._fetch(params)-- def get_by_ids(self, arxiv_ids: List[str]) -> List[Dict]:- """- Retrieve papers by their arXiv IDs.-- Args:- arxiv_ids: List of arXiv IDs (e.g., ["2309.10668", "2406.04093"])-- Returns:- List of paper dicts- """- # Clean IDs: strip URLs, versions- clean_ids = []- for aid in arxiv_ids:- aid = re.sub(r"^https?://arxiv\.org/abs/", "", aid.strip())- aid = re.sub(r"v\d+$", "", aid)- clean_ids.append(aid)-- params = {- "id_list": ",".join(clean_ids),- "max_results": len(clean_ids),- }-- return self._fetch(params)-- def download_pdf(self, arxiv_id: str, output_path: str) -> bool:- """- Download a paper's PDF.-- Args:- arxiv_id: arXiv ID (e.g., "2309.10668")- output_path: File path or directory to save to-- Returns:- True if successful- """- arxiv_id = re.sub(r"^https?://arxiv\.org/abs/", "", arxiv_id.strip())- arxiv_id = re.sub(r"v\d+$", "", arxiv_id)-- pdf_url = f"http://arxiv.org/pdf/{arxiv_id}"- self._log(f"Downloading: {pdf_url}")-- # If output_path is a directory, generate filename- if os.path.isdir(output_path):- filename = arxiv_id.replace("/", "_") + ".pdf"- output_path = os.path.join(output_path, filename)-- self._rate_limit()-- try:- response = self.session.get(pdf_url, timeout=60)- response.raise_for_status()-- os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True)- with open(output_path, "wb") as f:- f.write(response.content)-- self._log(f"Saved to: {output_path}")- return True- except Exception as e:- self._log(f"Download error: {e}")- return False-- @staticmethod- def build_query(- title: Optional[str] = None,- author: Optional[str] = None,- abstract: Optional[str] = None,- category: Optional[str] = None,- all_fields: Optional[str] = None,- ) -> str:- """- Build an arXiv query string from components.-- Args:- title: Search in title- author: Search by author name- abstract: Search in abstract- category: Filter by category (e.g., "cs.LG")- all_fields: Search all fields-- Returns:- arXiv query string- """- parts = []- if all_fields:- parts.append(f"all:{all_fields}")- if title:- parts.append(f"ti:{title}")- if author:- parts.append(f"au:{author}")- if abstract:- parts.append(f"abs:{abstract}")- if category:- parts.append(f"cat:{category}")-- return " AND ".join(parts)---def main():- parser = argparse.ArgumentParser(- description="Search arXiv preprints",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Examples:- %(prog)s --keywords "sparse autoencoder" --category cs.LG --max-results 20- %(prog)s --author "Anthropic" --max-results 50- %(prog)s --ids 2309.10668 2406.04093- %(prog)s --query "ti:GRPO AND cat:cs.LG" --sort-by submittedDate- %(prog)s --ids 2309.10668 --download-pdf papers/- """,- )-- parser.add_argument("--verbose", "-v", action="store_true")-- search_group = parser.add_argument_group("Search options")- search_group.add_argument("--keywords", "-k", nargs="+", help="Keywords to search")- search_group.add_argument("--author", "-a", help="Author name")- search_group.add_argument("--ids", nargs="+", help="arXiv IDs to look up")- search_group.add_argument("--query", "-q", help="Raw arXiv query string")- search_group.add_argument(- "--search-field",- choices=ArxivSearcher.VALID_SEARCH_FIELDS,- default="all",- help="Field to search keywords in (default: all)",- )-- filter_group = parser.add_argument_group("Filter options")- filter_group.add_argument("--category", "-c", help="arXiv category (e.g., cs.LG)")- filter_group.add_argument("--max-results", type=int, default=50, help="Max results (default: 50, max: 300)")- filter_group.add_argument(- "--sort-by",- choices=ArxivSearcher.VALID_SORT_BY,- default="relevance",- help="Sort order (default: relevance)",- )- filter_group.add_argument(- "--sort-order",- choices=ArxivSearcher.VALID_SORT_ORDER,- default="descending",- )-- output_group = parser.add_argument_group("Output options")- output_group.add_argument("--output", "-o", help="Output JSON file (default: stdout)")- output_group.add_argument("--download-pdf", help="Download PDFs to this directory")-- args = parser.parse_args()- searcher = ArxivSearcher(verbose=args.verbose)-- # --- ID lookup ---- if args.ids:- if args.download_pdf:- for aid in args.ids:- searcher.download_pdf(aid, args.download_pdf)- return 0-- results = searcher.get_by_ids(args.ids)- query_desc = f"id_list:{','.join(args.ids)}"-- # --- Raw query ---- elif args.query:- query = args.query- if args.category and f"cat:{args.category}" not in query:- query = f"({query}) AND cat:{args.category}"-- results = searcher.search(- query=query,- max_results=args.max_results,- sort_by=args.sort_by,- sort_order=args.sort_order,- )- query_desc = query-- # --- Keyword search ---- elif args.keywords:- field = args.search_field- keyword_parts = [f'{field}:"{kw}"' if " " in kw else f"{field}:{kw}" for kw in args.keywords]- query = " AND ".join(keyword_parts)- if args.category:- query = f"({query}) AND cat:{args.category}"-- results = searcher.search(- query=query,- max_results=args.max_results,- sort_by=args.sort_by,- sort_order=args.sort_order,- )- query_desc = query-- # --- Author search ---- elif args.author:- query = f'au:"{args.author}"'- if args.category:- query = f"{query} AND cat:{args.category}"-- results = searcher.search(- query=query,- max_results=args.max_results,- sort_by=args.sort_by,- sort_order=args.sort_order,- )- query_desc = query-- # --- Category browse ---- elif args.category:- query = f"cat:{args.category}"- results = searcher.search(- query=query,- max_results=args.max_results,- sort_by=args.sort_by or "submittedDate",- sort_order=args.sort_order,- )- query_desc = query-- else:- parser.error("Provide --keywords, --author, --ids, --query, or --category")- return 1-- # Output- output_data = {- "query": query_desc,- "result_count": len(results),- "results": results,- }-- output_json = json.dumps(output_data, indent=2, ensure_ascii=False)-- if args.output:- os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True)- with open(args.output, "w") as f:- f.write(output_json)- print(f"Results written to {args.output}", file=sys.stderr)- else:- print(output_json)-- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scientific-skills/biorxiv-database/SKILL.md b/scientific-skills/biorxiv-database/SKILL.mddeleted file mode 100644index 5730d638..00000000--- a/scientific-skills/biorxiv-database/SKILL.md+++ /dev/null@@ -1,481 +0,0 @@-----name: biorxiv-database-description: Efficient database search tool for bioRxiv preprint server. Use this skill when searching for life sciences preprints by keywords, authors, date ranges, or categories, retrieving paper metadata, downloading PDFs, or conducting literature reviews.-license: Unknown-metadata:- skill-author: K-Dense Inc.------# bioRxiv Database--## Overview--This skill provides efficient Python-based tools for searching and retrieving preprints from the bioRxiv database. It enables comprehensive searches by keywords, authors, date ranges, and categories, returning structured JSON metadata that includes titles, abstracts, DOIs, and citation information. The skill also supports PDF downloads for full-text analysis.--## When to Use This Skill--Use this skill when:-- Searching for recent preprints in specific research areas-- Tracking publications by particular authors-- Conducting systematic literature reviews-- Analyzing research trends over time periods-- Retrieving metadata for citation management-- Downloading preprint PDFs for analysis-- Filtering papers by bioRxiv subject categories--## Core Search Capabilities--### 1. Keyword Search--Search for preprints containing specific keywords in titles, abstracts, or author lists.--**Basic Usage:**-```python-python scripts/biorxiv_search.py \- --keywords "CRISPR" "gene editing" \- --start-date 2024-01-01 \- --end-date 2024-12-31 \- --output results.json-```--**With Category Filter:**-```python-python scripts/biorxiv_search.py \- --keywords "neural networks" "deep learning" \- --days-back 180 \- --category neuroscience \- --output recent_neuroscience.json-```--**Search Fields:**-By default, keywords are searched in both title and abstract. Customize with `--search-fields`:-```python-python scripts/biorxiv_search.py \- --keywords "AlphaFold" \- --search-fields title \- --days-back 365-```--### 2. Author Search--Find all papers by a specific author within a date range.--**Basic Usage:**-```python-python scripts/biorxiv_search.py \- --author "Smith" \- --start-date 2023-01-01 \- --end-date 2024-12-31 \- --output smith_papers.json-```--**Recent Publications:**-```python-# Last year by default if no dates specified-python scripts/biorxiv_search.py \- --author "Johnson" \- --output johnson_recent.json-```--### 3. Date Range Search--Retrieve all preprints posted within a specific date range.--**Basic Usage:**-```python-python scripts/biorxiv_search.py \- --start-date 2024-01-01 \- --end-date 2024-01-31 \- --output january_2024.json-```--**With Category Filter:**-```python-python scripts/biorxiv_search.py \- --start-date 2024-06-01 \- --end-date 2024-06-30 \- --category genomics \- --output genomics_june.json-```--**Days Back Shortcut:**-```python-# Last 30 days-python scripts/biorxiv_search.py \- --days-back 30 \- --output last_month.json-```--### 4. Paper Details by DOI--Retrieve detailed metadata for a specific preprint.--**Basic Usage:**-```python-python scripts/biorxiv_search.py \- --doi "10.1101/2024.01.15.123456" \- --output paper_details.json-```--**Full DOI URLs Accepted:**-```python-python scripts/biorxiv_search.py \- --doi "https://doi.org/10.1101/2024.01.15.123456"-```--### 5. PDF Downloads--Download the full-text PDF of any preprint.--**Basic Usage:**-```python-python scripts/biorxiv_search.py \- --doi "10.1101/2024.01.15.123456" \- --download-pdf paper.pdf-```--**Batch Processing:**-For multiple PDFs, extract DOIs from a search result JSON and download each paper:-```python-import json-from biorxiv_search import BioRxivSearcher--# Load search results-with open('results.json') as f:- data = json.load(f)--searcher = BioRxivSearcher(verbose=True)--# Download each paper-for i, paper in enumerate(data['results'][:10]): # First 10 papers- doi = paper['doi']- searcher.download_pdf(doi, f"papers/paper_{i+1}.pdf")-```--## Valid Categories--Filter searches by bioRxiv subject categories:--- `animal-behavior-and-cognition`-- `biochemistry`-- `bioengineering`-- `bioinformatics`-- `biophysics`-- `cancer-biology`-- `cell-biology`-- `clinical-trials`-- `developmental-biology`-- `ecology`-- `epidemiology`-- `evolutionary-biology`-- `genetics`-- `genomics`-- `immunology`-- `microbiology`-- `molecular-biology`-- `neuroscience`-- `paleontology`-- `pathology`-- `pharmacology-and-toxicology`-- `physiology`-- `plant-biology`-- `scientific-communication-and-education`-- `synthetic-biology`-- `systems-biology`-- `zoology`--## Output Format--All searches return structured JSON with the following format:--```json-{- "query": {- "keywords": ["CRISPR"],- "start_date": "2024-01-01",- "end_date": "2024-12-31",- "category": "genomics"- },- "result_count": 42,- "results": [- {- "doi": "10.1101/2024.01.15.123456",- "title": "Paper Title Here",- "authors": "Smith J, Doe J, Johnson A",- "author_corresponding": "Smith J",- "author_corresponding_institution": "University Example",- "date": "2024-01-15",- "version": "1",- "type": "new results",- "license": "cc_by",- "category": "genomics",- "abstract": "Full abstract text...",- "pdf_url": "https://www.biorxiv.org/content/10.1101/2024.01.15.123456v1.full.pdf",- "html_url": "https://www.biorxiv.org/content/10.1101/2024.01.15.123456v1",- "jatsxml": "https://www.biorxiv.org/content/...",- "published": ""- }- ]-}-```--## Common Usage Patterns--### Literature Review Workflow--1. **Broad keyword search:**-```python-python scripts/biorxiv_search.py \- --keywords "organoids" "tissue engineering" \- --start-date 2023-01-01 \- --end-date 2024-12-31 \- --category bioengineering \- --output organoid_papers.json-```--2. **Extract and review results:**-```python-import json--with open('organoid_papers.json') as f:- data = json.load(f)--print(f"Found {data['result_count']} papers")--for paper in data['results'][:5]:- print(f"\nTitle: {paper['title']}")- print(f"Authors: {paper['authors']}")- print(f"Date: {paper['date']}")- print(f"DOI: {paper['doi']}")-```--3. **Download selected papers:**-```python-from biorxiv_search import BioRxivSearcher--searcher = BioRxivSearcher()-selected_dois = ["10.1101/2024.01.15.123456", "10.1101/2024.02.20.789012"]--for doi in selected_dois:- filename = doi.replace("/", "_").replace(".", "_") + ".pdf"- searcher.download_pdf(doi, f"papers/{filename}")-```--### Trend Analysis--Track research trends by analyzing publication frequencies over time:--```python-python scripts/biorxiv_search.py \- --keywords "machine learning" \- --start-date 2020-01-01 \- --end-date 2024-12-31 \- --category bioinformatics \- --output ml_trends.json-```--Then analyze the temporal distribution in the results.--### Author Tracking--Monitor specific researchers' preprints:--```python-# Track multiple authors-authors = ["Smith", "Johnson", "Williams"]--for author in authors:- python scripts/biorxiv_search.py \- --author "{author}" \- --days-back 365 \- --output "{author}_papers.json"-```--## Python API Usage--For more complex workflows, import and use the `BioRxivSearcher` class directly:--```python-from scripts.biorxiv_search import BioRxivSearcher--# Initialize-searcher = BioRxivSearcher(verbose=True)--# Multiple search operations-keywords_papers = searcher.search_by_keywords(- keywords=["CRISPR", "gene editing"],- start_date="2024-01-01",- end_date="2024-12-31",- category="genomics"-)--author_papers = searcher.search_by_author(- author_name="Smith",- start_date="2023-01-01",- end_date="2024-12-31"-)--# Get specific paper details-paper = searcher.get_paper_details("10.1101/2024.01.15.123456")--# Download PDF-success = searcher.download_pdf(- doi="10.1101/2024.01.15.123456",- output_path="paper.pdf"-)--# Format results consistently-formatted = searcher.format_result(paper, include_abstract=True)-```--## Best Practices--1. **Use appropriate date ranges**: Smaller date ranges return faster. For keyword searches over long periods, consider splitting into multiple queries.--2. **Filter by category**: When possible, use `--category` to reduce data transfer and improve search precision.--3. **Respect rate limits**: The script includes automatic delays (0.5s between requests). For large-scale data collection, add additional delays.--4. **Cache results**: Save search results to JSON files to avoid repeated API calls.--5. **Version tracking**: Preprints can have multiple versions. The `version` field indicates which version is returned. PDF URLs include the version number.--6. **Handle errors gracefully**: Check the `result_count` in output JSON. Empty results may indicate date range issues or API connectivity problems.--7. **Verbose mode for debugging**: Use `--verbose` flag to see detailed logging of API requests and responses.--## Advanced Features--### Custom Date Range Logic--```python-from datetime import datetime, timedelta--# Last quarter-end_date = datetime.now()-start_date = end_date - timedelta(days=90)--python scripts/biorxiv_search.py \- --start-date {start_date.strftime('%Y-%m-%d')} \- --end-date {end_date.strftime('%Y-%m-%d')}-```--### Result Limiting--Limit the number of results returned:--```python-python scripts/biorxiv_search.py \- --keywords "COVID-19" \- --days-back 30 \- --limit 50 \- --output covid_top50.json-```--### Exclude Abstracts for Speed--When only metadata is needed:--```python-# Note: Abstract inclusion is controlled in Python API-from scripts.biorxiv_search import BioRxivSearcher--searcher = BioRxivSearcher()-papers = searcher.search_by_keywords(keywords=["AI"], days_back=30)-formatted = [searcher.format_result(p, include_abstract=False) for p in papers]-```--## Programmatic Integration--Integrate search results into downstream analysis pipelines:--```python-import json-import pandas as pd--# Load results-with open('results.json') as f:- data = json.load(f)--# Convert to DataFrame for analysis-df = pd.DataFrame(data['results'])--# Analyze-print(f"Total papers: {len(df)}")-print(f"Date range: {df['date'].min()} to {df['date'].max()}")-print(f"\nTop authors by paper count:")-print(df['authors'].str.split(',').explode().str.strip().value_counts().head(10))--# Filter and export-recent = df[df['date'] >= '2024-06-01']-recent.to_csv('recent_papers.csv', index=False)-```--## Testing the Skill--To verify that the bioRxiv database skill is working correctly, run the comprehensive test suite.--**Prerequisites:**-```bash-uv pip install requests-```--**Run tests:**-```bash-python tests/test_biorxiv_search.py-```--The test suite validates:-- **Initialization**: BioRxivSearcher class instantiation-- **Date Range Search**: Retrieving papers within specific date ranges-- **Category Filtering**: Filtering papers by bioRxiv categories-- **Keyword Search**: Finding papers containing specific keywords-- **DOI Lookup**: Retrieving specific papers by DOI-- **Result Formatting**: Proper formatting of paper metadata-- **Interval Search**: Fetching recent papers by time intervals--**Expected Output:**-```-🧬 bioRxiv Database Search Skill Test Suite-======================================================================--🧪 Test 1: Initialization-✅ BioRxivSearcher initialized successfully--🧪 Test 2: Date Range Search-✅ Found 150 papers between 2024-01-01 and 2024-01-07- First paper: Novel CRISPR-based approach for genome editing...--[... additional tests ...]--======================================================================-📊 Test Summary-======================================================================-✅ PASS: Initialization-✅ PASS: Date Range Search-✅ PASS: Category Filtering-✅ PASS: Keyword Search-✅ PASS: DOI Lookup-✅ PASS: Result Formatting-✅ PASS: Interval Search-======================================================================-Results: 7/7 tests passed (100%)-======================================================================--🎉 All tests passed! The bioRxiv database skill is working correctly.-```--**Note:** Some tests may show warnings if no papers are found in specific date ranges or categories. This is normal and does not indicate a failure.--## Reference Documentation--For detailed API specifications, endpoint documentation, and response schemas, refer to:-- `references/api_reference.md` - Complete bioRxiv API documentation--The reference file includes:-- Full API endpoint specifications-- Response format details-- Error handling patterns-- Rate limiting guidelines-- Advanced search patterns-diff --git a/scientific-skills/biorxiv-database/references/api_reference.md b/scientific-skills/biorxiv-database/references/api_reference.mddeleted file mode 100644index 2f3f0c78..00000000--- a/scientific-skills/biorxiv-database/references/api_reference.md+++ /dev/null@@ -1,280 +0,0 @@-# bioRxiv API Reference--## Overview--The bioRxiv API provides programmatic access to preprint metadata from the bioRxiv server. The API returns JSON-formatted data with comprehensive metadata about life sciences preprints.--## Base URL--```-https://api.biorxiv.org-```--## Rate Limiting--Be respectful of the API:-- Add delays between requests (minimum 0.5 seconds recommended)-- Use appropriate User-Agent headers-- Cache results when possible--## API Endpoints--### 1. Details by Date Range--Retrieve preprints posted within a specific date range.--**Endpoint:**-```-GET /details/biorxiv/{start_date}/{end_date}-GET /details/biorxiv/{start_date}/{end_date}/{category}-```--**Parameters:**-- `start_date`: Start date in YYYY-MM-DD format-- `end_date`: End date in YYYY-MM-DD format-- `category` (optional): Filter by subject category--**Example:**-```-GET https://api.biorxiv.org/details/biorxiv/2024-01-01/2024-01-31-GET https://api.biorxiv.org/details/biorxiv/2024-01-01/2024-01-31/neuroscience-```--**Response:**-```json-{- "messages": [- {- "status": "ok",- "count": 150,- "total": 150- }- ],- "collection": [- {- "doi": "10.1101/2024.01.15.123456",- "title": "Example Paper Title",- "authors": "Smith J, Doe J, Johnson A",- "author_corresponding": "Smith J",- "author_corresponding_institution": "University Example",- "date": "2024-01-15",- "version": "1",- "type": "new results",- "license": "cc_by",- "category": "neuroscience",- "jatsxml": "https://www.biorxiv.org/content/...",- "abstract": "This is the abstract...",- "published": ""- }- ]-}-```--### 2. Details by DOI--Retrieve details for a specific preprint by DOI.--**Endpoint:**-```-GET /details/biorxiv/{doi}-```--**Parameters:**-- `doi`: The DOI of the preprint (e.g., `10.1101/2024.01.15.123456`)--**Example:**-```-GET https://api.biorxiv.org/details/biorxiv/10.1101/2024.01.15.123456-```--### 3. Publications by Interval--Retrieve recent publications from a time interval.--**Endpoint:**-```-GET /pubs/biorxiv/{interval}/{cursor}/{format}-```--**Parameters:**-- `interval`: Number of days back to search (e.g., `1` for last 24 hours)-- `cursor`: Pagination cursor (0 for first page, increment by 100 for subsequent pages)-- `format`: Response format (`json` or `xml`)--**Example:**-```-GET https://api.biorxiv.org/pubs/biorxiv/1/0/json-```--**Response includes pagination:**-```json-{- "messages": [- {- "status": "ok",- "count": 100,- "total": 250,- "cursor": 100- }- ],- "collection": [...]-}-```--## Valid Categories--bioRxiv organizes preprints into the following categories:--- `animal-behavior-and-cognition`-- `biochemistry`-- `bioengineering`-- `bioinformatics`-- `biophysics`-- `cancer-biology`-- `cell-biology`-- `clinical-trials`-- `developmental-biology`-- `ecology`-- `epidemiology`-- `evolutionary-biology`-- `genetics`-- `genomics`-- `immunology`-- `microbiology`-- `molecular-biology`-- `neuroscience`-- `paleontology`-- `pathology`-- `pharmacology-and-toxicology`-- `physiology`-- `plant-biology`-- `scientific-communication-and-education`-- `synthetic-biology`-- `systems-biology`-- `zoology`--## Paper Metadata Fields--Each paper in the `collection` array contains:--| Field | Description | Type |-|-------|-------------|------|-| `doi` | Digital Object Identifier | string |-| `title` | Paper title | string |-| `authors` | Comma-separated author list | string |-| `author_corresponding` | Corresponding author name | string |-| `author_corresponding_institution` | Corresponding author's institution | string |-| `date` | Publication date (YYYY-MM-DD) | string |-| `version` | Version number | string |-| `type` | Type of submission (e.g., "new results") | string |-| `license` | License type (e.g., "cc_by") | string |-| `category` | Subject category | string |-| `jatsxml` | URL to JATS XML | string |-| `abstract` | Paper abstract | string |-| `published` | Journal publication info (if published) | string |--## Downloading Full Papers--### PDF Download--PDFs can be downloaded directly (not through API):--```-https://www.biorxiv.org/content/{doi}v{version}.full.pdf-```--Example:-```-https://www.biorxiv.org/content/10.1101/2024.01.15.123456v1.full.pdf-```--### HTML Version--```-https://www.biorxiv.org/content/{doi}v{version}-```--### JATS XML--Full structured XML is available via the `jatsxml` field in the API response.--## Common Search Patterns--### Author Search--1. Get papers from date range-2. Filter by author name (case-insensitive substring match in `authors` field)--### Keyword Search--1. Get papers from date range (optionally filtered by category)-2. Search in title, abstract, or both fields-3. Filter papers containing keywords (case-insensitive)--### Recent Papers by Category--1. Use `/pubs/biorxiv/{interval}/0/json` endpoint-2. Filter by category if needed--## Error Handling--Common HTTP status codes:-- `200`: Success-- `404`: Resource not found-- `500`: Server error--Always check the `messages` array in the response:-```json-{- "messages": [- {- "status": "ok",- "count": 100- }- ]-}-```--## Best Practices--1. **Cache results**: Store retrieved papers to avoid repeated API calls-2. **Use appropriate date ranges**: Smaller date ranges return faster-3. **Filter by category**: Reduces data transfer and processing time-4. **Batch processing**: When downloading multiple PDFs, add delays between requests-5. **Error handling**: Always check response status and handle errors gracefully-6. **Version tracking**: Note that papers can have multiple versions--## Python Usage Example--```python-from biorxiv_search import BioRxivSearcher--searcher = BioRxivSearcher(verbose=True)--# Search by keywords-papers = searcher.search_by_keywords(- keywords=["CRISPR", "gene editing"],- start_date="2024-01-01",- end_date="2024-12-31",- category="genomics"-)--# Search by author-papers = searcher.search_by_author(- author_name="Smith",- start_date="2023-01-01",- end_date="2024-12-31"-)--# Get specific paper-paper = searcher.get_paper_details("10.1101/2024.01.15.123456")--# Download PDF-searcher.download_pdf("10.1101/2024.01.15.123456", "paper.pdf")-```--## External Resources--- bioRxiv homepage: https://www.biorxiv.org/-- API documentation: https://api.biorxiv.org/-- JATS XML specification: https://jats.nlm.nih.gov/diff --git a/scientific-skills/biorxiv-database/scripts/biorxiv_search.py b/scientific-skills/biorxiv-database/scripts/biorxiv_search.pydeleted file mode 100755index 14108505..00000000--- a/scientific-skills/biorxiv-database/scripts/biorxiv_search.py+++ /dev/null@@ -1,445 +0,0 @@-#!/usr/bin/env python3-"""-bioRxiv Search Tool-A comprehensive Python tool for searching and retrieving preprints from bioRxiv.-Supports keyword search, author search, date filtering, category filtering, and more.--Note: This tool is focused exclusively on bioRxiv (life sciences preprints).-"""--import requests-import json-import argparse-from datetime import datetime, timedelta-from typing import List, Dict, Optional, Any-import time-import sys-from urllib.parse import quote---class BioRxivSearcher:- """Efficient search interface for bioRxiv preprints."""-- BASE_URL = "https://api.biorxiv.org"-- # Valid bioRxiv categories- CATEGORIES = [- "animal-behavior-and-cognition", "biochemistry", "bioengineering",- "bioinformatics", "biophysics", "cancer-biology", "cell-biology",- "clinical-trials", "developmental-biology", "ecology", "epidemiology",- "evolutionary-biology", "genetics", "genomics", "immunology",- "microbiology", "molecular-biology", "neuroscience", "paleontology",- "pathology", "pharmacology-and-toxicology", "physiology",- "plant-biology", "scientific-communication-and-education",- "synthetic-biology", "systems-biology", "zoology"- ]-- def __init__(self, verbose: bool = False):- """Initialize the searcher."""- self.verbose = verbose- self.session = requests.Session()- self.session.headers.update({- 'User-Agent': 'BioRxiv-Search-Tool/1.0'- })-- def _log(self, message: str):- """Print verbose logging messages."""- if self.verbose:- print(f"[INFO] {message}", file=sys.stderr)-- def _make_request(self, endpoint: str, params: Optional[Dict] = None) -> Dict:- """Make an API request with error handling and rate limiting."""- url = f"{self.BASE_URL}/{endpoint}"- self._log(f"Requesting: {url}")-- try:- response = self.session.get(url, params=params, timeout=30)- response.raise_for_status()-- # Rate limiting - be respectful to the API- time.sleep(0.5)-- return response.json()- except requests.exceptions.RequestException as e:- self._log(f"Error making request: {e}")- return {"messages": [{"status": "error", "message": str(e)}], "collection": []}-- def search_by_date_range(- self,- start_date: str,- end_date: str,- category: Optional[str] = None- ) -> List[Dict]:- """- Search for preprints within a date range.-- Args:- start_date: Start date in YYYY-MM-DD format- end_date: End date in YYYY-MM-DD format- category: Optional category filter (e.g., 'neuroscience')-- Returns:- List of preprint dictionaries- """- self._log(f"Searching bioRxiv from {start_date} to {end_date}")-- if category:- endpoint = f"details/biorxiv/{start_date}/{end_date}/{category}"- else:- endpoint = f"details/biorxiv/{start_date}/{end_date}"-- data = self._make_request(endpoint)-- if "collection" in data:- self._log(f"Found {len(data['collection'])} preprints")- return data["collection"]-- return []-- def search_by_interval(- self,- interval: str = "1",- cursor: int = 0,- format: str = "json"- ) -> Dict:- """- Retrieve preprints from a specific time interval.-- Args:- interval: Number of days back to search- cursor: Pagination cursor (0 for first page, then use returned cursor)- format: Response format ('json' or 'xml')-- Returns:- Dictionary with collection and pagination info- """- endpoint = f"pubs/biorxiv/{interval}/{cursor}/{format}"- return self._make_request(endpoint)-- def get_paper_details(self, doi: str) -> Dict:- """- Get detailed information about a specific paper by DOI.-- Args:- doi: The DOI of the paper (e.g., '10.1101/2021.01.01.123456')-- Returns:- Dictionary with paper details- """- # Clean DOI if full URL was provided- if 'doi.org' in doi:- doi = doi.split('doi.org/')[-1]-- self._log(f"Fetching details for DOI: {doi}")- endpoint = f"details/biorxiv/{doi}"-- data = self._make_request(endpoint)-- if "collection" in data and len(data["collection"]) > 0:- return data["collection"][0]-- return {}-- def search_by_author(- self,- author_name: str,- start_date: Optional[str] = None,- end_date: Optional[str] = None- ) -> List[Dict]:- """- Search for papers by author name.-- Args:- author_name: Author name to search for- start_date: Optional start date (YYYY-MM-DD)- end_date: Optional end date (YYYY-MM-DD)-- Returns:- List of matching preprints- """- # If no date range specified, search last 3 years- if not start_date:- end_date = datetime.now().strftime("%Y-%m-%d")- start_date = (datetime.now() - timedelta(days=1095)).strftime("%Y-%m-%d")-- self._log(f"Searching for author: {author_name}")-- # Get all papers in date range- papers = self.search_by_date_range(start_date, end_date)-- # Filter by author name (case-insensitive)- author_lower = author_name.lower()- matching_papers = []-- for paper in papers:- authors = paper.get("authors", "")- if author_lower in authors.lower():- matching_papers.append(paper)-- self._log(f"Found {len(matching_papers)} papers by {author_name}")- return matching_papers-- def search_by_keywords(- self,- keywords: List[str],- start_date: Optional[str] = None,- end_date: Optional[str] = None,- category: Optional[str] = None,- search_fields: List[str] = ["title", "abstract"]- ) -> List[Dict]:- """- Search for papers containing specific keywords.-- Args:- keywords: List of keywords to search for- start_date: Optional start date (YYYY-MM-DD)- end_date: Optional end date (YYYY-MM-DD)- category: Optional category filter- search_fields: Fields to search in (title, abstract, authors)-- Returns:- List of matching preprints- """- # If no date range specified, search last year- if not start_date:- end_date = datetime.now().strftime("%Y-%m-%d")- start_date = (datetime.now() - timedelta(days=365)).strftime("%Y-%m-%d")-- self._log(f"Searching for keywords: {keywords}")-- # Get all papers in date range- papers = self.search_by_date_range(start_date, end_date, category)-- # Filter by keywords- matching_papers = []- keywords_lower = [k.lower() for k in keywords]-- for paper in papers:- # Build search text from specified fields- search_text = ""- for field in search_fields:- if field in paper:- search_text += " " + str(paper[field]).lower()-- # Check if any keyword matches- if any(keyword in search_text for keyword in keywords_lower):- matching_papers.append(paper)-- self._log(f"Found {len(matching_papers)} papers matching keywords")- return matching_papers-- def download_pdf(self, doi: str, output_path: str) -> bool:- """- Download the PDF of a paper.-- Args:- doi: The DOI of the paper- output_path: Path where PDF should be saved-- Returns:- True if download successful, False otherwise- """- # Clean DOI- if 'doi.org' in doi:- doi = doi.split('doi.org/')[-1]-- # Construct PDF URL- pdf_url = f"https://www.biorxiv.org/content/{doi}v1.full.pdf"-- self._log(f"Downloading PDF from: {pdf_url}")-- try:- response = self.session.get(pdf_url, timeout=60)- response.raise_for_status()-- with open(output_path, 'wb') as f:- f.write(response.content)-- self._log(f"PDF saved to: {output_path}")- return True- except Exception as e:- self._log(f"Error downloading PDF: {e}")- return False-- def format_result(self, paper: Dict, include_abstract: bool = True) -> Dict:- """- Format a paper result with standardized fields.-- Args:- paper: Raw paper dictionary from API- include_abstract: Whether to include the abstract-- Returns:- Formatted paper dictionary- """- result = {- "doi": paper.get("doi", ""),- "title": paper.get("title", ""),- "authors": paper.get("authors", ""),- "author_corresponding": paper.get("author_corresponding", ""),- "author_corresponding_institution": paper.get("author_corresponding_institution", ""),- "date": paper.get("date", ""),- "version": paper.get("version", ""),- "type": paper.get("type", ""),- "license": paper.get("license", ""),- "category": paper.get("category", ""),- "jatsxml": paper.get("jatsxml", ""),- "published": paper.get("published", "")- }-- if include_abstract:- result["abstract"] = paper.get("abstract", "")-- # Add PDF and HTML URLs- if result["doi"]:- result["pdf_url"] = f"https://www.biorxiv.org/content/{result['doi']}v{result['version']}.full.pdf"- result["html_url"] = f"https://www.biorxiv.org/content/{result['doi']}v{result['version']}"-- return result---def main():- """Command-line interface for bioRxiv search."""- parser = argparse.ArgumentParser(- description="Search bioRxiv preprints efficiently",- formatter_class=argparse.RawDescriptionHelpFormatter- )-- parser.add_argument("--verbose", "-v", action="store_true",- help="Enable verbose logging")-- # Search type arguments- search_group = parser.add_argument_group("Search options")- search_group.add_argument("--keywords", "-k", nargs="+",- help="Keywords to search for")- search_group.add_argument("--author", "-a",- help="Author name to search for")- search_group.add_argument("--doi",- help="Get details for specific DOI")-- # Date range arguments- date_group = parser.add_argument_group("Date range options")- date_group.add_argument("--start-date",- help="Start date (YYYY-MM-DD)")- date_group.add_argument("--end-date",- help="End date (YYYY-MM-DD)")- date_group.add_argument("--days-back", type=int,- help="Search N days back from today")-- # Filter arguments- filter_group = parser.add_argument_group("Filter options")- filter_group.add_argument("--category", "-c",- choices=BioRxivSearcher.CATEGORIES,- help="Filter by category")- filter_group.add_argument("--search-fields", nargs="+",- default=["title", "abstract"],- choices=["title", "abstract", "authors"],- help="Fields to search in for keywords")-- # Output arguments- output_group = parser.add_argument_group("Output options")- output_group.add_argument("--output", "-o",- help="Output file (default: stdout)")- output_group.add_argument("--include-abstract", action="store_true",- default=True, help="Include abstracts in output")- output_group.add_argument("--download-pdf",- help="Download PDF to specified path (requires --doi)")- output_group.add_argument("--limit", type=int,- help="Limit number of results")-- args = parser.parse_args()-- # Initialize searcher- searcher = BioRxivSearcher(verbose=args.verbose)-- # Handle date range- end_date = args.end_date or datetime.now().strftime("%Y-%m-%d")- if args.days_back:- start_date = (datetime.now() - timedelta(days=args.days_back)).strftime("%Y-%m-%d")- else:- start_date = args.start_date-- # Execute search based on arguments- results = []-- if args.download_pdf:- if not args.doi:- print("Error: --doi required with --download-pdf", file=sys.stderr)- return 1-- success = searcher.download_pdf(args.doi, args.download_pdf)- return 0 if success else 1-- elif args.doi:- # Get specific paper by DOI- paper = searcher.get_paper_details(args.doi)- if paper:- results = [paper]-- elif args.author:- # Search by author- results = searcher.search_by_author(- args.author, start_date, end_date- )-- elif args.keywords:- # Search by keywords- if not start_date:- print("Error: --start-date or --days-back required for keyword search",- file=sys.stderr)- return 1-- results = searcher.search_by_keywords(- args.keywords, start_date, end_date,- args.category, args.search_fields- )-- else:- # Date range search- if not start_date:- print("Error: Must specify search criteria (--keywords, --author, or --doi)",- file=sys.stderr)- return 1-- results = searcher.search_by_date_range(- start_date, end_date, args.category- )-- # Apply limit- if args.limit:- results = results[:args.limit]-- # Format results- formatted_results = [- searcher.format_result(paper, args.include_abstract)- for paper in results- ]-- # Output results- output_data = {- "query": {- "keywords": args.keywords,- "author": args.author,- "doi": args.doi,- "start_date": start_date,- "end_date": end_date,- "category": args.category- },- "result_count": len(formatted_results),- "results": formatted_results- }-- output_json = json.dumps(output_data, indent=2)-- if args.output:- with open(args.output, 'w') as f:- f.write(output_json)- print(f"Results written to {args.output}", file=sys.stderr)- else:- print(output_json)-- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scientific-skills/openalex-database/SKILL.md b/scientific-skills/openalex-database/SKILL.mddeleted file mode 100644index 2ebfe8d1..00000000--- a/scientific-skills/openalex-database/SKILL.md+++ /dev/null@@ -1,492 +0,0 @@-----name: openalex-database-description: Query and analyze scholarly literature using the OpenAlex database. This skill should be used when searching for academic papers, analyzing research trends, finding works by authors or institutions, tracking citations, discovering open access publications, or conducting bibliometric analysis across 240M+ scholarly works. Use for literature searches, research output analysis, citation analysis, and academic database queries.-license: Unknown-metadata:- skill-author: K-Dense Inc.------# OpenAlex Database--## Overview--OpenAlex is a comprehensive open catalog of 240M+ scholarly works, authors, institutions, topics, sources, publishers, and funders. This skill provides tools and workflows for querying the OpenAlex API to search literature, analyze research output, track citations, and conduct bibliometric studies.--## Quick Start--### Basic Setup--Always initialize the client with an email address to access the polite pool (10x rate limit boost):--```python-from scripts.openalex_client import OpenAlexClient--client = OpenAlexClient(email="[email protected]")-```--### Installation Requirements--Install required package using uv:--```bash-uv pip install requests-```--No API key required - OpenAlex is completely open.--## Core Capabilities--### 1. Search for Papers--**Use for**: Finding papers by title, abstract, or topic--```python-# Simple search-results = client.search_works(- search="machine learning",- per_page=100-)--# Search with filters-results = client.search_works(- search="CRISPR gene editing",- filter_params={- "publication_year": ">2020",- "is_oa": "true"- },- sort="cited_by_count:desc"-)-```--### 2. Find Works by Author--**Use for**: Getting all publications by a specific researcher--Use the two-step pattern (entity name → ID → works):--```python-from scripts.query_helpers import find_author_works--works = find_author_works(- author_name="Jennifer Doudna",- client=client,- limit=100-)-```--**Manual two-step approach**:-```python-# Step 1: Get author ID-author_response = client._make_request(- '/authors',- params={'search': 'Jennifer Doudna', 'per-page': 1}-)-author_id = author_response['results'][0]['id'].split('/')[-1]--# Step 2: Get works-works = client.search_works(- filter_params={"authorships.author.id": author_id}-)-```--### 3. Find Works from Institution--**Use for**: Analyzing research output from universities or organizations--```python-from scripts.query_helpers import find_institution_works--works = find_institution_works(- institution_name="Stanford University",- client=client,- limit=200-)-```--### 4. Highly Cited Papers--**Use for**: Finding influential papers in a field--```python-from scripts.query_helpers import find_highly_cited_recent_papers--papers = find_highly_cited_recent_papers(- topic="quantum computing",- years=">2020",- client=client,- limit=100-)-```--### 5. Open Access Papers--**Use for**: Finding freely available research--```python-from scripts.query_helpers import get_open_access_papers--papers = get_open_access_papers(- search_term="climate change",- client=client,- oa_status="any", # or "gold", "green", "hybrid", "bronze"- limit=200-)-```--### 6. Publication Trends Analysis--**Use for**: Tracking research output over time--```python-from scripts.query_helpers import get_publication_trends--trends = get_publication_trends(- search_term="artificial intelligence",- filter_params={"is_oa": "true"},- client=client-)--# Sort and display-for trend in sorted(trends, key=lambda x: x['key'])[-10:]:- print(f"{trend['key']}: {trend['count']} publications")-```--### 7. Research Output Analysis--**Use for**: Comprehensive analysis of author or institution research--```python-from scripts.query_helpers import analyze_research_output--analysis = analyze_research_output(- entity_type='institution', # or 'author'- entity_name='MIT',- client=client,- years='>2020'-)--print(f"Total works: {analysis['total_works']}")-print(f"Open access: {analysis['open_access_percentage']}%")-print(f"Top topics: {analysis['top_topics'][:5]}")-```--### 8. Batch Lookups--**Use for**: Getting information for multiple DOIs, ORCIDs, or IDs efficiently--```python-dois = [- "https://doi.org/10.1038/s41586-021-03819-2",- "https://doi.org/10.1126/science.abc1234",- # ... up to 50 DOIs-]--works = client.batch_lookup(- entity_type='works',- ids=dois,- id_field='doi'-)-```--### 9. Random Sampling--**Use for**: Getting representative samples for analysis--```python-# Small sample-works = client.sample_works(- sample_size=100,- seed=42, # For reproducibility- filter_params={"publication_year": "2023"}-)--# Large sample (>10k) - automatically handles multiple requests-works = client.sample_works(- sample_size=25000,- seed=42,- filter_params={"is_oa": "true"}-)-```--### 10. Citation Analysis--**Use for**: Finding papers that cite a specific work--```python-# Get the work-work = client.get_entity('works', 'https://doi.org/10.1038/s41586-021-03819-2')--# Get citing papers using cited_by_api_url-import requests-citing_response = requests.get(- work['cited_by_api_url'],- params={'mailto': client.email, 'per-page': 200}-)-citing_works = citing_response.json()['results']-```--### 11. Topic and Subject Analysis--**Use for**: Understanding research focus areas--```python-# Get top topics for an institution-topics = client.group_by(- entity_type='works',- group_field='topics.id',- filter_params={- "authorships.institutions.id": "I136199984", # MIT- "publication_year": ">2020"- }-)--for topic in topics[:10]:- print(f"{topic['key_display_name']}: {topic['count']} works")-```--### 12. Large-Scale Data Extraction--**Use for**: Downloading large datasets for analysis--```python-# Paginate through all results-all_papers = client.paginate_all(- endpoint='/works',- params={- 'search': 'synthetic biology',- 'filter': 'publication_year:2020-2024'- },- max_results=10000-)--# Export to CSV-import csv-with open('papers.csv', 'w', newline='', encoding='utf-8') as f:- writer = csv.writer(f)- writer.writerow(['Title', 'Year', 'Citations', 'DOI', 'OA Status'])-- for paper in all_papers:- writer.writerow([- paper.get('title', 'N/A'),- paper.get('publication_year', 'N/A'),- paper.get('cited_by_count', 0),- paper.get('doi', 'N/A'),- paper.get('open_access', {}).get('oa_status', 'closed')- ])-```--## Critical Best Practices--### Always Use Email for Polite Pool-Add email to get 10x rate limit (1 req/sec → 10 req/sec):-```python-client = OpenAlexClient(email="[email protected]")-```--### Use Two-Step Pattern for Entity Lookups-Never filter by entity names directly - always get ID first:-```python-# ✅ Correct-# 1. Search for entity → get ID-# 2. Filter by ID--# ❌ Wrong-# filter=author_name:Einstein # This doesn't work!-```--### Use Maximum Page Size-Always use `per-page=200` for efficient data retrieval:-```python-results = client.search_works(search="topic", per_page=200)-```--### Batch Multiple IDs-Use batch_lookup() for multiple IDs instead of individual requests:-```python-# ✅ Correct - 1 request for 50 DOIs-works = client.batch_lookup('works', doi_list, 'doi')--# ❌ Wrong - 50 separate requests-for doi in doi_list:- work = client.get_entity('works', doi)-```--### Use Sample Parameter for Random Data-Use `sample_works()` with seed for reproducible random sampling:-```python-# ✅ Correct-works = client.sample_works(sample_size=100, seed=42)--# ❌ Wrong - random page numbers bias results-# Using random page numbers doesn't give true random sample-```--### Select Only Needed Fields-Reduce response size by selecting specific fields:-```python-results = client.search_works(- search="topic",- select=['id', 'title', 'publication_year', 'cited_by_count']-)-```--## Common Filter Patterns--### Date Ranges-```python-# Single year-filter_params={"publication_year": "2023"}--# After year-filter_params={"publication_year": ">2020"}--# Range-filter_params={"publication_year": "2020-2024"}-```--### Multiple Filters (AND)-```python-# All conditions must match-filter_params={- "publication_year": ">2020",- "is_oa": "true",- "cited_by_count": ">100"-}-```--### Multiple Values (OR)-```python-# Any institution matches-filter_params={- "authorships.institutions.id": "I136199984|I27837315" # MIT or Harvard-}-```--### Collaboration (AND within attribute)-```python-# Papers with authors from BOTH institutions-filter_params={- "authorships.institutions.id": "I136199984+I27837315" # MIT AND Harvard-}-```--### Negation-```python-# Exclude type-filter_params={- "type": "!paratext"-}-```--## Entity Types--OpenAlex provides these entity types:-- **works** - Scholarly documents (articles, books, datasets)-- **authors** - Researchers with disambiguated identities-- **institutions** - Universities and research organizations-- **sources** - Journals, repositories, conferences-- **topics** - Subject classifications-- **publishers** - Publishing organizations-- **funders** - Funding agencies--Access any entity type using consistent patterns:-```python-client.search_works(...)-client.get_entity('authors', author_id)-client.group_by('works', 'topics.id', filter_params={...})-```--## External IDs--Use external identifiers directly:-```python-# DOI for works-work = client.get_entity('works', 'https://doi.org/10.7717/peerj.4375')--# ORCID for authors-author = client.get_entity('authors', 'https://orcid.org/0000-0003-1613-5981')--# ROR for institutions-institution = client.get_entity('institutions', 'https://ror.org/02y3ad647')--# ISSN for sources-source = client.get_entity('sources', 'issn:0028-0836')-```--## Reference Documentation--### Detailed API Reference-See `references/api_guide.md` for:-- Complete filter syntax-- All available endpoints-- Response structures-- Error handling-- Performance optimization-- Rate limiting details--### Common Query Examples-See `references/common_queries.md` for:-- Complete working examples-- Real-world use cases-- Complex query patterns-- Data export workflows-- Multi-step analysis procedures--## Scripts--### openalex_client.py-Main API client with:-- Automatic rate limiting-- Exponential backoff retry logic-- Pagination support-- Batch operations-- Error handling--Use for direct API access with full control.--### query_helpers.py-High-level helper functions for common operations:-- `find_author_works()` - Get papers by author-- `find_institution_works()` - Get papers from institution-- `find_highly_cited_recent_papers()` - Get influential papers-- `get_open_access_papers()` - Find OA publications-- `get_publication_trends()` - Analyze trends over time-- `analyze_research_output()` - Comprehensive analysis--Use for common research queries with simplified interfaces.--## Troubleshooting--### Rate Limiting-If encountering 403 errors:-1. Ensure email is added to requests-2. Verify not exceeding 10 req/sec-3. Client automatically implements exponential backoff--### Empty Results-If searches return no results:-1. Check filter syntax (see `references/api_guide.md`)-2. Use two-step pattern for entity lookups (don't filter by names)-3. Verify entity IDs are correct format--### Timeout Errors-For large queries:-1. Use pagination with `per-page=200`-2. Use `select=` to limit returned fields-3. Break into smaller queries if needed--## Rate Limits--- **Default**: 1 request/second, 100k requests/day-- **Polite pool (with email)**: 10 requests/second, 100k requests/day--Always use polite pool for production workflows by providing email to client.--## Notes--- No authentication required-- All data is open and free-- Rate limits apply globally, not per IP-- Use LitLLM with OpenRouter if LLM-based analysis is needed (don't use Perplexity API directly)-- Client handles pagination, retries, and rate limiting automatically-diff --git a/scientific-skills/openalex-database/references/api_guide.md b/scientific-skills/openalex-database/references/api_guide.mddeleted file mode 100644index 8f9033fe..00000000--- a/scientific-skills/openalex-database/references/api_guide.md+++ /dev/null@@ -1,371 +0,0 @@-# OpenAlex API Complete Guide--## Base Information--**Base URL:** `https://api.openalex.org`-**Authentication:** None required-**Rate Limits:**-- Default: 1 request/second, 100k requests/day-- Polite pool (with email): 10 requests/second, 100k requests/day--## Critical Best Practices--### ✅ DO: Use `?sample` parameter for random sampling-```-https://api.openalex.org/works?sample=20&seed=123-```-For large samples (10k+), use multiple seeds and deduplicate.--### ❌ DON'T: Use random page numbers for sampling-Incorrect: `?page=5`, `?page=17` - This biases results!--### ✅ DO: Use two-step lookup for entity filtering-```-1. Find entity ID: /authors?search=einstein-2. Use ID: /works?filter=authorships.author.id:A5023888391-```--### ❌ DON'T: Filter by entity names directly-Incorrect: `/works?filter=author_name:Einstein` - Names are ambiguous!--### ✅ DO: Use maximum page size for bulk extraction-```-?per-page=200-```-This is 8x faster than default (25).--### ❌ DON'T: Use default page sizes-Default is only 25 results per page.--### ✅ DO: Use OR filter (pipe |) for batch lookups-```-/works?filter=doi:10.1/abc|10.2/def|10.3/ghi-```-Up to 50 values per filter.--### ❌ DON'T: Make sequential API calls for lists-Making 100 separate calls when you can batch them is inefficient.--### ✅ DO: Implement exponential backoff for retries-```python-for attempt in range(max_retries):- try:- response = requests.get(url)- if response.status_code == 200:- return response.json()- except:- wait_time = 2 ** attempt- time.sleep(wait_time)-```--### ✅ DO: Add email for 10x rate limit boost-```-```-Increases from 1 req/sec → 10 req/sec.--## Entity Endpoints--- `/works` - 240M+ scholarly documents-- `/authors` - Researcher profiles-- `/sources` - Journals, repositories, conferences-- `/institutions` - Universities, research organizations-- `/topics` - Subject classifications (3-level hierarchy)-- `/publishers` - Publishing organizations-- `/funders` - Funding agencies-- `/text` - Tag your own text with topics/keywords (POST)--## Essential Query Parameters--| Parameter | Description | Example |-|-----------|-------------|---------|-| `filter=` | Filter results | `?filter=publication_year:2020` |-| `search=` | Full-text search | `?search=machine+learning` |-| `sort=` | Sort results | `?sort=cited_by_count:desc` |-| `per-page=` | Results per page (max 200) | `?per-page=200` |-| `page=` | Page number | `?page=2` |-| `sample=` | Random results | `?sample=50&seed=42` |-| `select=` | Limit fields | `?select=id,title` |-| `group_by=` | Aggregate by field | `?group_by=publication_year` |-| `mailto=` | Email for polite pool | `[email protected]` |--## Filter Syntax--### Basic Filtering-```-Single filter: ?filter=publication_year:2020-Multiple (AND): ?filter=publication_year:2020,is_oa:true-Values (OR): ?filter=type:journal-article|book-Negation: ?filter=type:!journal-article-```--### Comparison Operators-```-Greater than: ?filter=cited_by_count:>100-Less than: ?filter=publication_year:<2020-Range: ?filter=publication_year:2020-2023-```--### Multiple Values in Same Attribute-```-Repeat filter: ?filter=institutions.country_code:us,institutions.country_code:gb-Use + symbol: ?filter=institutions.country_code:us+gb-```-Both mean: "works with author from US AND author from GB"--### OR Queries-```-Any of these: ?filter=institutions.country_code:us|gb|ca-Batch IDs: ?filter=doi:10.1/abc|10.2/def-```-Up to 50 values with pipes.--## Common Query Patterns--### Get Random Sample-```bash-# Small sample-https://api.openalex.org/works?sample=20&seed=42--# Large sample (10k+) - make multiple requests-https://api.openalex.org/works?sample=1000&seed=1-https://api.openalex.org/works?sample=1000&seed=2-# Then deduplicate by ID-```--### Search Works-```bash-# Simple search-https://api.openalex.org/works?search=machine+learning--# Search specific field-https://api.openalex.org/works?filter=title.search:CRISPR--# Search + filter-https://api.openalex.org/works?search=climate&filter=publication_year:2023-```--### Find Works by Author (Two-Step)-```bash-# Step 1: Get author ID-https://api.openalex.org/authors?search=Heather+Piwowar-# Returns: "id": "https://openalex.org/A5023888391"--# Step 2: Get their works-https://api.openalex.org/works?filter=authorships.author.id:A5023888391-```--### Find Works by Institution (Two-Step)-```bash-# Step 1: Get institution ID-https://api.openalex.org/institutions?search=MIT-# Returns: "id": "https://openalex.org/I136199984"--# Step 2: Get their works-https://api.openalex.org/works?filter=authorships.institutions.id:I136199984-```--### Highly Cited Recent Papers-```bash-https://api.openalex.org/works?filter=publication_year:>2020&sort=cited_by_count:desc&per-page=200-```--### Open Access Works-```bash-# All OA-https://api.openalex.org/works?filter=is_oa:true--# Gold OA only-https://api.openalex.org/works?filter=open_access.oa_status:gold-```--### Multiple Criteria-```bash-# Recent OA works about COVID from top institutions-https://api.openalex.org/works?filter=publication_year:2022,is_oa:true,title.search:covid,authorships.institutions.id:I136199984|I27837315-```--### Bulk DOI Lookup-```bash-# Get specific works by DOI (up to 50 per request)-https://api.openalex.org/works?filter=doi:https://doi.org/10.1371/journal.pone.0266781|https://doi.org/10.1371/journal.pone.0267149&per-page=50-```--### Aggregate Data-```bash-# Top topics-https://api.openalex.org/works?group_by=topics.id--# Papers per year-https://api.openalex.org/works?group_by=publication_year--# Most prolific institutions-https://api.openalex.org/works?group_by=authorships.institutions.id-```--### Pagination-```bash-# First page-https://api.openalex.org/works?filter=publication_year:2023&per-page=200--# Next pages-https://api.openalex.org/works?filter=publication_year:2023&per-page=200&page=2-```--## Response Structure--### List Endpoints-```json-{- "meta": {- "count": 240523418,- "db_response_time_ms": 42,- "page": 1,- "per_page": 25- },- "results": [- { /* entity object */ }- ]-}-```--### Single Entity-```-https://api.openalex.org/works/W2741809807-→ Returns Work object directly (no meta/results wrapper)-```--### Group By-```json-{- "meta": { "count": 100 },- "group_by": [- {- "key": "https://openalex.org/T10001",- "key_display_name": "Artificial Intelligence",- "count": 15234- }- ]-}-```--## Works Filters (Most Common)--| Filter | Description | Example |-|--------|-------------|---------|-| `authorships.author.id` | Author's OpenAlex ID | `A5023888391` |-| `authorships.institutions.id` | Institution's ID | `I136199984` |-| `cited_by_count` | Citation count | `>100` |-| `is_oa` | Is open access | `true/false` |-| `publication_year` | Year published | `2020`, `>2020`, `2018-2022` |-| `primary_location.source.id` | Source (journal) ID | `S137773608` |-| `topics.id` | Topic ID | `T10001` |-| `type` | Document type | `article`, `book`, `dataset` |-| `has_doi` | Has DOI | `true/false` |-| `has_fulltext` | Has fulltext | `true/false` |--## Authors Filters--| Filter | Description |-|--------|-------------|-| `last_known_institution.id` | Current/last institution |-| `works_count` | Number of works |-| `cited_by_count` | Total citations |-| `orcid` | ORCID identifier |--## External ID Support--### Works-```-DOI: /works/https://doi.org/10.7717/peerj.4375-PMID: /works/pmid:29844763-```--### Authors-```-ORCID: /authors/https://orcid.org/0000-0003-1613-5981-```--### Institutions-```-ROR: /institutions/https://ror.org/02y3ad647-```--### Sources-```-ISSN: /sources/issn:0028-0836-```--## Performance Tips--1. **Use maximum page size**: `?per-page=200` (8x fewer calls)-2. **Batch ID lookups**: Use pipe operator for up to 50 IDs-3. **Select only needed fields**: `?select=id,title,publication_year`-4. **Use concurrent requests**: With rate limiting (10 req/sec with email)-5. **Add email**: `[email protected]` for 10x speed boost--## Error Handling--### HTTP Status Codes-- `200` - Success-- `400` - Bad request (check filter syntax)-- `403` - Rate limit exceeded (implement backoff)-- `404` - Entity doesn't exist-- `500` - Server error (retry with backoff)--### Exponential Backoff-```python-def fetch_with_retry(url, max_retries=5):- for attempt in range(max_retries):- try:- response = requests.get(url, timeout=30)- if response.status_code == 200:- return response.json()- elif response.status_code in [403, 500, 502, 503, 504]:- wait_time = 2 ** attempt- time.sleep(wait_time)- else:- response.raise_for_status()- except requests.exceptions.Timeout:- if attempt < max_retries - 1:- time.sleep(2 ** attempt)- else:- raise- raise Exception(f"Failed after {max_retries} retries")-```--## Rate Limiting--### Without Email (Default Pool)-- 1 request/second-- 100,000 requests/day--### With Email (Polite Pool)-- 10 requests/second-- 100,000 requests/day-- **Always use for production**--### Concurrent Request Strategy-1. Track requests per second globally-2. Use semaphore or rate limiter across threads-3. Monitor for 403 responses-4. Back off if limits hit--## Common Mistakes to Avoid--1. ❌ Using page numbers for sampling → ✅ Use `?sample=`-2. ❌ Filtering by entity names → ✅ Get IDs first-3. ❌ Default page size → ✅ Use `per-page=200`-4. ❌ Sequential ID lookups → ✅ Batch with pipe operator-5. ❌ No error handling → ✅ Implement retry with backoff-6. ❌ Ignoring rate limits → ✅ Global rate limiting-7. ❌ Not including email → ✅ Add `mailto=`-8. ❌ Fetching all fields → ✅ Use `select=`--## Additional Resources--- Full documentation: https://docs.openalex.org-- API Overview: https://docs.openalex.org/how-to-use-the-api/api-overview-- Entity schemas: https://docs.openalex.org/api-entities-- Help: https://openalex.org/help-- User group: https://groups.google.com/g/openalex-usersdiff --git a/scientific-skills/openalex-database/references/common_queries.md b/scientific-skills/openalex-database/references/common_queries.mddeleted file mode 100644index d270c422..00000000--- a/scientific-skills/openalex-database/references/common_queries.md+++ /dev/null@@ -1,381 +0,0 @@-# Common OpenAlex Query Examples--This document provides practical examples for common research queries using OpenAlex.--## Finding Papers by Author--**User query**: "Find papers by Albert Einstein"--**Approach**: Two-step pattern-1. Search for author to get ID-2. Filter works by author ID--**Python example**:-```python-from scripts.openalex_client import OpenAlexClient-from scripts.query_helpers import find_author_works--client = OpenAlexClient(email="[email protected]")-works = find_author_works("Albert Einstein", client, limit=100)--for work in works:- print(f"{work['title']} ({work['publication_year']})")-```--## Finding Papers from an Institution--**User query**: "What papers has MIT published in the last year?"--**Approach**: Two-step pattern with date filter-1. Search for institution to get ID-2. Filter works by institution ID and year--**Python example**:-```python-from scripts.query_helpers import find_institution_works--works = find_institution_works("MIT", client, limit=200)--# Filter for recent papers-import datetime-current_year = datetime.datetime.now().year-recent_works = [w for w in works if w['publication_year'] == current_year]-```--## Highly Cited Papers on a Topic--**User query**: "Find the most cited papers on CRISPR from the last 5 years"--**Approach**: Search + filter + sort--**Python example**:-```python-works = client.search_works(- search="CRISPR",- filter_params={- "publication_year": ">2019"- },- sort="cited_by_count:desc",- per_page=100-)--for work in works['results']:- title = work['title']- citations = work['cited_by_count']- year = work['publication_year']- print(f"{title} ({year}): {citations} citations")-```--## Open Access Papers on a Topic--**User query**: "Find open access papers about climate change"--**Approach**: Search + OA filter--**Python example**:-```python-from scripts.query_helpers import get_open_access_papers--papers = get_open_access_papers(- search_term="climate change",- client=client,- oa_status="any", # or "gold", "green", "hybrid", "bronze"- limit=200-)--for paper in papers:- print(f"{paper['title']}")- print(f" OA Status: {paper['open_access']['oa_status']}")- print(f" URL: {paper['open_access']['oa_url']}")-```--## Publication Trends Analysis--**User query**: "Show me publication trends for machine learning over the years"--**Approach**: Use group_by to aggregate by year--**Python example**:-```python-from scripts.query_helpers import get_publication_trends--trends = get_publication_trends(- search_term="machine learning",- client=client-)--# Sort by year-trends_sorted = sorted(trends, key=lambda x: x['key'])--for trend in trends_sorted[-10:]: # Last 10 years- year = trend['key']- count = trend['count']- print(f"{year}: {count} publications")-```--## Analyzing Research Output--**User query**: "Analyze the research output of Stanford University from 2020-2024"--**Approach**: Multiple aggregations for comprehensive analysis--**Python example**:-```python-from scripts.query_helpers import analyze_research_output--analysis = analyze_research_output(- entity_type='institution',- entity_name='Stanford University',- client=client,- years='2020-2024'-)--print(f"Institution: {analysis['entity_name']}")-print(f"Total works: {analysis['total_works']}")-print(f"Open access: {analysis['open_access_percentage']}%")-print("\nTop topics:")-for topic in analysis['top_topics'][:5]:- print(f" - {topic['key_display_name']}: {topic['count']} works")-```--## Finding Papers by DOI (Batch)--**User query**: "Get information for these 10 DOIs: ..."--**Approach**: Batch lookup with pipe separator--**Python example**:-```python-dois = [- "https://doi.org/10.1371/journal.pone.0266781",- "https://doi.org/10.1371/journal.pone.0267149",- "https://doi.org/10.1038/s41586-021-03819-2",- # ... up to 50 DOIs-]--works = client.batch_lookup(- entity_type='works',- ids=dois,- id_field='doi'-)--for work in works:- print(f"{work['title']} - {work['publication_year']}")-```--## Random Sample of Papers--**User query**: "Give me 50 random papers from 2023"--**Approach**: Use sample parameter with seed for reproducibility--**Python example**:-```python-works = client.sample_works(- sample_size=50,- seed=42, # For reproducibility- filter_params={- "publication_year": "2023",- "is_oa": "true"- }-)--print(f"Got {len(works)} random papers from 2023")-```--## Papers from Multiple Institutions--**User query**: "Find papers with authors from both MIT and Stanford"--**Approach**: Use + operator for AND within same attribute--**Python example**:-```python-# First, get institution IDs-mit_response = client._make_request(- '/institutions',- params={'search': 'MIT', 'per-page': 1}-)-mit_id = mit_response['results'][0]['id'].split('/')[-1]--stanford_response = client._make_request(- '/institutions',- params={'search': 'Stanford', 'per-page': 1}-)-stanford_id = stanford_response['results'][0]['id'].split('/')[-1]--# Find works with authors from both institutions-works = client.search_works(- filter_params={- "authorships.institutions.id": f"{mit_id}+{stanford_id}"- },- per_page=100-)--print(f"Found {works['meta']['count']} collaborative papers")-```--## Papers in a Specific Journal--**User query**: "Get all papers from Nature published in 2023"--**Approach**: Two-step - find journal ID, then filter works--**Python example**:-```python-# Step 1: Find journal source ID-source_response = client._make_request(- '/sources',- params={'search': 'Nature', 'per-page': 1}-)-source = source_response['results'][0]-source_id = source['id'].split('/')[-1]--print(f"Found journal: {source['display_name']} (ID: {source_id})")--# Step 2: Get works from that source-works = client.search_works(- filter_params={- "primary_location.source.id": source_id,- "publication_year": "2023"- },- per_page=200-)--print(f"Found {works['meta']['count']} papers from Nature in 2023")-```--## Topic Analysis by Institution--**User query**: "What topics does MIT research most?"--**Approach**: Filter by institution, group by topics--**Python example**:-```python-# Get MIT ID-inst_response = client._make_request(- '/institutions',- params={'search': 'MIT', 'per-page': 1}-)-mit_id = inst_response['results'][0]['id'].split('/')[-1]--# Group by topics-topics = client.group_by(- entity_type='works',- group_field='topics.id',- filter_params={- "authorships.institutions.id": mit_id,- "publication_year": ">2020"- }-)--print("Top research topics at MIT (2020+):")-for i, topic in enumerate(topics[:10], 1):- print(f"{i}. {topic['key_display_name']}: {topic['count']} works")-```--## Citation Analysis--**User query**: "Find papers that cite this specific DOI"--**Approach**: Get work by DOI, then use cited_by_api_url--**Python example**:-```python-# Get the work-doi = "https://doi.org/10.1038/s41586-021-03819-2"-work = client.get_entity('works', doi)--# Get papers that cite it-cited_by_url = work['cited_by_api_url']--# Extract just the query part and use it-import requests-response = requests.get(cited_by_url, params={'mailto': client.email})-citing_works = response.json()--print(f"{work['title']}")-print(f"Total citations: {work['cited_by_count']}")-print(f"\nRecent citing papers:")-for citing_work in citing_works['results'][:5]:- print(f" - {citing_work['title']} ({citing_work['publication_year']})")-```--## Large-Scale Data Extraction--**User query**: "Get all papers on quantum computing from the last 3 years"--**Approach**: Paginate through all results--**Python example**:-```python-all_papers = client.paginate_all(- endpoint='/works',- params={- 'search': 'quantum computing',- 'filter': 'publication_year:2022-2024'- },- max_results=10000 # Limit to prevent excessive API calls-)--print(f"Retrieved {len(all_papers)} papers")--# Save to CSV-import csv-with open('quantum_papers.csv', 'w', newline='') as f:- writer = csv.writer(f)- writer.writerow(['Title', 'Year', 'Citations', 'DOI', 'OA Status'])-- for paper in all_papers:- writer.writerow([- paper['title'],- paper['publication_year'],- paper['cited_by_count'],- paper.get('doi', 'N/A'),- paper['open_access']['oa_status']- ])-```--## Complex Multi-Filter Query--**User query**: "Find recent, highly-cited, open access papers on AI from top institutions"--**Approach**: Combine multiple filters--**Python example**:-```python-# Get IDs for top institutions-top_institutions = ['MIT', 'Stanford', 'Oxford']-inst_ids = []--for inst_name in top_institutions:- response = client._make_request(- '/institutions',- params={'search': inst_name, 'per-page': 1}- )- if response['results']:- inst_id = response['results'][0]['id'].split('/')[-1]- inst_ids.append(inst_id)--# Combine with pipe for OR-inst_filter = '|'.join(inst_ids)--# Complex query-works = client.search_works(- search="artificial intelligence",- filter_params={- "publication_year": ">2022",- "cited_by_count": ">50",- "is_oa": "true",- "authorships.institutions.id": inst_filter- },- sort="cited_by_count:desc",- per_page=200-)--print(f"Found {works['meta']['count']} papers matching criteria")-for work in works['results'][:10]:- print(f"{work['title']}")- print(f" Citations: {work['cited_by_count']}, Year: {work['publication_year']}")-```diff --git a/scientific-skills/openalex-database/scripts/openalex_client.py b/scientific-skills/openalex-database/scripts/openalex_client.pydeleted file mode 100644index 1f1215b0..00000000--- a/scientific-skills/openalex-database/scripts/openalex_client.py+++ /dev/null@@ -1,337 +0,0 @@-#!/usr/bin/env python3-"""-OpenAlex API Client with rate limiting and error handling.--Provides a robust client for interacting with the OpenAlex API with:-- Automatic rate limiting (polite pool: 10 req/sec)-- Exponential backoff retry logic-- Pagination support-- Batch operations support-"""--import time-import requests-from typing import Dict, List, Optional, Any-from urllib.parse import urljoin---class OpenAlexClient:- """Client for OpenAlex API with rate limiting and error handling."""-- BASE_URL = "https://api.openalex.org"-- def __init__(self, email: Optional[str] = None, requests_per_second: int = 10):- """- Initialize OpenAlex client.-- Args:- email: Email for polite pool (10x rate limit boost)- requests_per_second: Max requests per second (default: 10 for polite pool)- """- self.email = email- self.requests_per_second = requests_per_second- self.min_delay = 1.0 / requests_per_second- self.last_request_time = 0-- def _rate_limit(self):- """Ensure requests don't exceed rate limit."""- current_time = time.time()- time_since_last = current_time - self.last_request_time- if time_since_last < self.min_delay:- time.sleep(self.min_delay - time_since_last)- self.last_request_time = time.time()-- def _make_request(- self,- endpoint: str,- params: Optional[Dict] = None,- max_retries: int = 5- ) -> Dict[str, Any]:- """- Make API request with retry logic.-- Args:- endpoint: API endpoint (e.g., '/works', '/authors')- params: Query parameters- max_retries: Maximum number of retry attempts-- Returns:- JSON response as dictionary- """- if params is None:- params = {}-- # Add email to params for polite pool- if self.email:- params['mailto'] = self.email-- url = urljoin(self.BASE_URL, endpoint)-- for attempt in range(max_retries):- try:- self._rate_limit()- response = requests.get(url, params=params, timeout=30)-- if response.status_code == 200:- return response.json()- elif response.status_code == 403:- # Rate limited- wait_time = 2 ** attempt- print(f"Rate limited. Waiting {wait_time}s before retry...")- time.sleep(wait_time)- elif response.status_code >= 500:- # Server error- wait_time = 2 ** attempt- print(f"Server error. Waiting {wait_time}s before retry...")- time.sleep(wait_time)- else:- # Other error - don't retry- response.raise_for_status()-- except requests.exceptions.Timeout:- if attempt < max_retries - 1:- wait_time = 2 ** attempt- print(f"Request timeout. Waiting {wait_time}s before retry...")- time.sleep(wait_time)- else:- raise-- raise Exception(f"Failed after {max_retries} retries")-- def search_works(- self,- search: Optional[str] = None,- filter_params: Optional[Dict] = None,- per_page: int = 200,- page: int = 1,- sort: Optional[str] = None,- select: Optional[List[str]] = None- ) -> Dict[str, Any]:- """- Search works with filters.-- Args:- search: Full-text search query- filter_params: Dictionary of filter parameters- per_page: Results per page (max: 200)- page: Page number- sort: Sort parameter (e.g., 'cited_by_count:desc')- select: List of fields to return-- Returns:- API response with meta and results- """- params = {- 'per-page': min(per_page, 200),- 'page': page- }-- if search:- params['search'] = search-- if filter_params:- filter_str = ','.join([f"{k}:{v}" for k, v in filter_params.items()])- params['filter'] = filter_str-- if sort:- params['sort'] = sort-- if select:- params['select'] = ','.join(select)-- return self._make_request('/works', params)-- def get_entity(self, entity_type: str, entity_id: str) -> Dict[str, Any]:- """- Get single entity by ID.-- Args:- entity_type: Type of entity ('works', 'authors', 'institutions', etc.)- entity_id: OpenAlex ID or external ID (DOI, ORCID, etc.)-- Returns:- Entity object- """- endpoint = f"/{entity_type}/{entity_id}"- return self._make_request(endpoint)-- def batch_lookup(- self,- entity_type: str,- ids: List[str],- id_field: str = 'openalex_id'- ) -> List[Dict[str, Any]]:- """- Look up multiple entities by ID efficiently.-- Args:- entity_type: Type of entity ('works', 'authors', etc.)- ids: List of IDs (up to 50 per batch)- id_field: ID field name ('openalex_id', 'doi', 'orcid', etc.)-- Returns:- List of entity objects- """- all_results = []-- # Process in batches of 50- for i in range(0, len(ids), 50):- batch = ids[i:i+50]- filter_value = '|'.join(batch)-- params = {- 'filter': f"{id_field}:{filter_value}",- 'per-page': 50- }-- response = self._make_request(f"/{entity_type}", params)- all_results.extend(response.get('results', []))-- return all_results-- def paginate_all(- self,- endpoint: str,- params: Optional[Dict] = None,- max_results: Optional[int] = None- ) -> List[Dict[str, Any]]:- """- Paginate through all results.-- Args:- endpoint: API endpoint- params: Query parameters- max_results: Maximum number of results to retrieve (None for all)-- Returns:- List of all results- """- if params is None:- params = {}-- params['per-page'] = 200 # Use maximum page size- params['page'] = 1-- all_results = []-- while True:- response = self._make_request(endpoint, params)- results = response.get('results', [])- all_results.extend(results)-- # Check if we've hit max_results- if max_results and len(all_results) >= max_results:- return all_results[:max_results]-- # Check if there are more pages- meta = response.get('meta', {})- total_count = meta.get('count', 0)- current_count = len(all_results)-- if current_count >= total_count:- break-- params['page'] += 1-- return all_results-- def sample_works(- self,- sample_size: int,- seed: Optional[int] = None,- filter_params: Optional[Dict] = None- ) -> List[Dict[str, Any]]:- """- Get random sample of works.-- Args:- sample_size: Number of samples to retrieve- seed: Random seed for reproducibility- filter_params: Optional filters to apply-- Returns:- List of sampled works- """- params = {- 'sample': min(sample_size, 10000), # API limit per request- 'per-page': 200- }-- if seed is not None:- params['seed'] = seed-- if filter_params:- filter_str = ','.join([f"{k}:{v}" for k, v in filter_params.items()])- params['filter'] = filter_str-- # For large samples, need multiple requests with different seeds- if sample_size > 10000:- all_samples = []- seen_ids = set()-- for i in range((sample_size // 10000) + 1):- current_seed = seed + i if seed else i- params['seed'] = current_seed- params['sample'] = min(10000, sample_size - len(all_samples))-- response = self._make_request('/works', params)- results = response.get('results', [])-- # Deduplicate- for result in results:- work_id = result.get('id')- if work_id not in seen_ids:- seen_ids.add(work_id)- all_samples.append(result)-- if len(all_samples) >= sample_size:- break-- return all_samples[:sample_size]- else:- response = self._make_request('/works', params)- return response.get('results', [])-- def group_by(- self,- entity_type: str,- group_field: str,- filter_params: Optional[Dict] = None- ) -> List[Dict[str, Any]]:- """- Aggregate results by field.-- Args:- entity_type: Type of entity ('works', 'authors', etc.)- group_field: Field to group by- filter_params: Optional filters-- Returns:- List of grouped results with counts- """- params = {- 'group_by': group_field- }-- if filter_params:- filter_str = ','.join([f"{k}:{v}" for k, v in filter_params.items()])- params['filter'] = filter_str-- response = self._make_request(f"/{entity_type}", params)- return response.get('group_by', [])---if __name__ == "__main__":- # Example usage- client = OpenAlexClient(email="[email protected]")-- # Search for works about machine learning- results = client.search_works(- search="machine learning",- filter_params={"publication_year": "2023"},- per_page=10- )-- print(f"Found {results['meta']['count']} works")- for work in results['results']:- print(f"- {work['title']}")diff --git a/scientific-skills/openalex-database/scripts/query_helpers.py b/scientific-skills/openalex-database/scripts/query_helpers.pydeleted file mode 100644index 454c3f74..00000000--- a/scientific-skills/openalex-database/scripts/query_helpers.py+++ /dev/null@@ -1,306 +0,0 @@-#!/usr/bin/env python3-"""-Helper functions for common OpenAlex query patterns.--Provides high-level functions for typical research queries.-"""--from typing import List, Dict, Optional, Any-from openalex_client import OpenAlexClient---def find_author_works(- author_name: str,- client: OpenAlexClient,- limit: Optional[int] = None-) -> List[Dict[str, Any]]:- """- Find all works by an author (two-step pattern).-- Args:- author_name: Author name to search for- client: OpenAlexClient instance- limit: Maximum number of works to return-- Returns:- List of works by the author- """- # Step 1: Find author ID- author_response = client._make_request(- '/authors',- params={'search': author_name, 'per-page': 1}- )-- if not author_response.get('results'):- print(f"No author found for: {author_name}")- return []-- author = author_response['results'][0]- author_id = author['id'].split('/')[-1] # Extract ID from URL-- print(f"Found author: {author['display_name']} (ID: {author_id})")-- # Step 2: Get works by author- works_params = {- 'filter': f'authorships.author.id:{author_id}',- 'per-page': 200- }-- if limit and limit <= 200:- works_params['per-page'] = limit- response = client._make_request('/works', works_params)- return response.get('results', [])- else:- # Need pagination- return client.paginate_all('/works', works_params, max_results=limit)---def find_institution_works(- institution_name: str,- client: OpenAlexClient,- limit: Optional[int] = None-) -> List[Dict[str, Any]]:- """- Find all works from an institution (two-step pattern).-- Args:- institution_name: Institution name to search for- client: OpenAlexClient instance- limit: Maximum number of works to return-- Returns:- List of works from the institution- """- # Step 1: Find institution ID- inst_response = client._make_request(- '/institutions',- params={'search': institution_name, 'per-page': 1}- )-- if not inst_response.get('results'):- print(f"No institution found for: {institution_name}")- return []-- institution = inst_response['results'][0]- inst_id = institution['id'].split('/')[-1] # Extract ID from URL-- print(f"Found institution: {institution['display_name']} (ID: {inst_id})")-- # Step 2: Get works from institution- works_params = {- 'filter': f'authorships.institutions.id:{inst_id}',- 'per-page': 200- }-- if limit and limit <= 200:- works_params['per-page'] = limit- response = client._make_request('/works', works_params)- return response.get('results', [])- else:- return client.paginate_all('/works', works_params, max_results=limit)---def find_highly_cited_recent_papers(- topic: Optional[str] = None,- years: str = ">2020",- client: Optional[OpenAlexClient] = None,- limit: int = 100-) -> List[Dict[str, Any]]:- """- Find highly cited recent papers, optionally filtered by topic.-- Args:- topic: Optional search term for topic filtering- years: Year filter (e.g., ">2020", "2020-2023")- client: OpenAlexClient instance- limit: Maximum number of papers to return-- Returns:- List of highly cited papers sorted by citation count- """- if client is None:- client = OpenAlexClient()-- params = {- 'filter': f'publication_year:{years}',- 'sort': 'cited_by_count:desc',- 'per-page': min(limit, 200)- }-- if topic:- params['search'] = topic-- if limit <= 200:- response = client._make_request('/works', params)- return response.get('results', [])- else:- return client.paginate_all('/works', params, max_results=limit)---def get_open_access_papers(- search_term: str,- client: OpenAlexClient,- oa_status: str = "any", # "any", "gold", "green", "hybrid", "bronze"- limit: int = 100-) -> List[Dict[str, Any]]:- """- Find open access papers on a topic.-- Args:- search_term: Search query- client: OpenAlexClient instance- oa_status: Type of OA ("any" for is_oa:true, or specific status)- limit: Maximum number of papers to return-- Returns:- List of open access papers- """- if oa_status == "any":- filter_str = "is_oa:true"- else:- filter_str = f"open_access.oa_status:{oa_status}"-- params = {- 'search': search_term,- 'filter': filter_str,- 'per-page': min(limit, 200)- }-- if limit <= 200:- response = client._make_request('/works', params)- return response.get('results', [])- else:- return client.paginate_all('/works', params, max_results=limit)---def get_publication_trends(- search_term: Optional[str] = None,- filter_params: Optional[Dict] = None,- client: Optional[OpenAlexClient] = None-) -> List[Dict[str, Any]]:- """- Get publication counts by year.-- Args:- search_term: Optional search query- filter_params: Optional additional filters- client: OpenAlexClient instance-- Returns:- List of {year, count} dictionaries- """- if client is None:- client = OpenAlexClient()-- params = {'group_by': 'publication_year'}-- if search_term:- params['search'] = search_term-- if filter_params:- filter_str = ','.join([f"{k}:{v}" for k, v in filter_params.items()])- params['filter'] = filter_str-- response = client._make_request('/works', params)- return response.get('group_by', [])---def analyze_research_output(- entity_type: str, # 'author' or 'institution'- entity_name: str,- client: OpenAlexClient,- years: str = ">2020"-) -> Dict[str, Any]:- """- Analyze research output for an author or institution.-- Args:- entity_type: 'author' or 'institution'- entity_name: Name to search for- client: OpenAlexClient instance- years: Year filter-- Returns:- Dictionary with analysis results- """- # Find entity ID- if entity_type == 'author':- endpoint = '/authors'- filter_prefix = 'authorships.author.id'- else:- endpoint = '/institutions'- filter_prefix = 'authorships.institutions.id'-- # Step 1: Find entity- entity_response = client._make_request(- endpoint,- params={'search': entity_name, 'per-page': 1}- )-- if not entity_response.get('results'):- return {'error': f'No {entity_type} found for: {entity_name}'}-- entity = entity_response['results'][0]- entity_id = entity['id'].split('/')[-1]-- # Step 2: Get statistics- filter_params = {- filter_prefix: entity_id,- 'publication_year': years- }-- # Total works- works_response = client.search_works(- filter_params=filter_params,- per_page=1- )- total_works = works_response['meta']['count']-- # Works by year- trends = client.group_by(- 'works',- 'publication_year',- filter_params={filter_prefix: entity_id, 'publication_year': years}- )-- # Top topics- topics = client.group_by(- 'works',- 'topics.id',- filter_params=filter_params- )-- # OA percentage- oa_works = client.search_works(- filter_params={**filter_params, 'is_oa': 'true'},- per_page=1- )- oa_count = oa_works['meta']['count']- oa_percentage = (oa_count / total_works * 100) if total_works > 0 else 0-- return {- 'entity_name': entity['display_name'],- 'entity_id': entity_id,- 'total_works': total_works,- 'open_access_works': oa_count,- 'open_access_percentage': round(oa_percentage, 1),- 'publications_by_year': trends[:10], # Last 10 years- 'top_topics': topics[:10] # Top 10 topics- }---if __name__ == "__main__":- # Example usage- import json-- client = OpenAlexClient(email="[email protected]")-- # Find works by author- print("\n=== Finding works by author ===")- works = find_author_works("Einstein", client, limit=5)- print(f"Found {len(works)} works")-- # Analyze research output- print("\n=== Analyzing institution research output ===")- analysis = analyze_research_output('institution', 'MIT', client)- print(json.dumps(analysis, indent=2))diff --git a/scientific-skills/pubmed-database/SKILL.md b/scientific-skills/pubmed-database/SKILL.mddeleted file mode 100644index 30fa55eb..00000000--- a/scientific-skills/pubmed-database/SKILL.md+++ /dev/null@@ -1,458 +0,0 @@-----name: pubmed-database-description: Direct REST API access to PubMed. Advanced Boolean/MeSH queries, E-utilities API, batch processing, citation management. For Python workflows, prefer biopython (Bio.Entrez). Use this for direct HTTP/REST work or custom API implementations.-license: Unknown-metadata:- skill-author: K-Dense Inc.------# PubMed Database--## Overview--PubMed is the U.S. National Library of Medicine's comprehensive database providing free access to MEDLINE and life sciences literature. Construct advanced queries with Boolean operators, MeSH terms, and field tags, access data programmatically via E-utilities API for systematic reviews and literature analysis.--## When to Use This Skill--This skill should be used when:-- Searching for biomedical or life sciences research articles-- Constructing complex search queries with Boolean operators, field tags, or MeSH terms-- Conducting systematic literature reviews or meta-analyses-- Accessing PubMed data programmatically via the E-utilities API-- Finding articles by specific criteria (author, journal, publication date, article type)-- Retrieving citation information, abstracts, or full-text articles-- Working with PMIDs (PubMed IDs) or DOIs-- Creating automated workflows for literature monitoring or data extraction--## Core Capabilities--### 1. Advanced Search Query Construction--Construct sophisticated PubMed queries using Boolean operators, field tags, and specialized syntax.--**Basic Search Strategies**:-- Combine concepts with Boolean operators (AND, OR, NOT)-- Use field tags to limit searches to specific record parts-- Employ phrase searching with double quotes for exact matches-- Apply wildcards for term variations-- Use proximity searching for terms within specified distances--**Example Queries**:-```-# Recent systematic reviews on diabetes treatment-diabetes mellitus[mh] AND treatment[tiab] AND systematic review[pt] AND 2023:2024[dp]--# Clinical trials comparing two drugs-(metformin[nm] OR insulin[nm]) AND diabetes mellitus, type 2[mh] AND randomized controlled trial[pt]--# Author-specific research-smith ja[au] AND cancer[tiab] AND 2023[dp] AND english[la]-```--**When to consult search_syntax.md**:-- Need comprehensive list of available field tags-- Require detailed explanation of search operators-- Constructing complex proximity searches-- Understanding automatic term mapping behavior-- Need specific syntax for date ranges, wildcards, or special characters--Grep pattern for field tags: `\[au\]|\[ti\]|\[ab\]|\[mh\]|\[pt\]|\[dp\]`--### 2. MeSH Terms and Controlled Vocabulary--Use Medical Subject Headings (MeSH) for precise, consistent searching across the biomedical literature.--**MeSH Searching**:-- [mh] tag searches MeSH terms with automatic inclusion of narrower terms-- [majr] tag limits to articles where the topic is the main focus-- Combine MeSH terms with subheadings for specificity (e.g., diabetes mellitus/therapy[mh])--**Common MeSH Subheadings**:-- /diagnosis - Diagnostic methods-- /drug therapy - Pharmaceutical treatment-- /epidemiology - Disease patterns and prevalence-- /etiology - Disease causes-- /prevention & control - Preventive measures-- /therapy - Treatment approaches--**Example**:-```-# Diabetes therapy with specific focus-diabetes mellitus, type 2[mh]/drug therapy AND cardiovascular diseases[mh]/prevention & control-```--### 3. Article Type and Publication Filtering--Filter results by publication type, date, text availability, and other attributes.--**Publication Types** (use [pt] field tag):-- Clinical Trial-- Meta-Analysis-- Randomized Controlled Trial-- Review-- Systematic Review-- Case Reports-- Guideline--**Date Filtering**:-- Single year: `2024[dp]`-- Date range: `2020:2024[dp]`-- Specific date: `2024/03/15[dp]`--**Text Availability**:-- Free full text: Add `AND free full text[sb]` to query-- Has abstract: Add `AND hasabstract[text]` to query--**Example**:-```-# Recent free full-text RCTs on hypertension-hypertension[mh] AND randomized controlled trial[pt] AND 2023:2024[dp] AND free full text[sb]-```--### 4. Programmatic Access via E-utilities API--Access PubMed data programmatically using the NCBI E-utilities REST API for automation and bulk operations.--**Core API Endpoints**:-1. **ESearch** - Search database and retrieve PMIDs-2. **EFetch** - Download full records in various formats-3. **ESummary** - Get document summaries-4. **EPost** - Upload UIDs for batch processing-5. **ELink** - Find related articles and linked data--**Basic Workflow**:-```python-import requests--# Step 1: Search for articles-base_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"-search_url = f"{base_url}esearch.fcgi"-params = {- "db": "pubmed",- "term": "diabetes[tiab] AND 2024[dp]",- "retmax": 100,- "retmode": "json",- "api_key": "YOUR_API_KEY" # Optional but recommended-}-response = requests.get(search_url, params=params)-pmids = response.json()["esearchresult"]["idlist"]--# Step 2: Fetch article details-fetch_url = f"{base_url}efetch.fcgi"-params = {- "db": "pubmed",- "id": ",".join(pmids),- "rettype": "abstract",- "retmode": "text",- "api_key": "YOUR_API_KEY"-}-response = requests.get(fetch_url, params=params)-abstracts = response.text-```--**Rate Limits**:-- Without API key: 3 requests/second-- With API key: 10 requests/second-- Always include User-Agent header--**Best Practices**:-- Use history server (usehistory=y) for large result sets-- Implement batch operations via EPost for multiple UIDs-- Cache results locally to minimize redundant calls-- Respect rate limits to avoid service disruption--**When to consult api_reference.md**:-- Need detailed endpoint documentation-- Require parameter specifications for each E-utility-- Constructing batch operations or history server workflows-- Understanding response formats (XML, JSON, text)-- Troubleshooting API errors or rate limit issues--Grep pattern for API endpoints: `esearch|efetch|esummary|epost|elink|einfo`--### 5. Citation Matching and Article Retrieval--Find articles using partial citation information or specific identifiers.--**By Identifier**:-```-# By PMID-12345678[pmid]--# By DOI-10.1056/NEJMoa123456[doi]--# By PMC ID-PMC123456[pmc]-```--**Citation Matching** (via ECitMatch API):-Use journal name, year, volume, page, and author to find PMIDs:-```-Format: journal|year|volume|page|author|key|-Example: Science|2008|320|5880|1185|key1|-```--**By Author and Metadata**:-```-# First author with year and topic-smith ja[1au] AND 2023[dp] AND cancer[tiab]--# Journal, volume, and page-nature[ta] AND 2024[dp] AND 456[vi] AND 123-130[pg]-```--### 6. Systematic Literature Reviews--Conduct comprehensive literature searches for systematic reviews and meta-analyses.--**PICO Framework** (Population, Intervention, Comparison, Outcome):-Structure clinical research questions systematically:-```-# Example: Diabetes treatment effectiveness-# P: diabetes mellitus, type 2[mh]-# I: metformin[nm]-# C: lifestyle modification[tiab]-# O: glycemic control[tiab]--diabetes mellitus, type 2[mh] AND-(metformin[nm] OR lifestyle modification[tiab]) AND-glycemic control[tiab] AND-randomized controlled trial[pt]-```--**Comprehensive Search Strategy**:-```-# Include multiple synonyms and MeSH terms-(disease name[tiab] OR disease name[mh] OR synonym[tiab]) AND-(treatment[tiab] OR therapy[tiab] OR intervention[tiab]) AND-(systematic review[pt] OR meta-analysis[pt] OR randomized controlled trial[pt]) AND-2020:2024[dp] AND-english[la]-```--**Search Refinement**:-1. Start broad, review results-2. Add specificity with field tags-3. Apply date and publication type filters-4. Use Advanced Search to view query translation-5. Combine search history for complex queries--**When to consult common_queries.md**:-- Need example queries for specific disease types or research areas-- Require templates for different study designs-- Looking for population-specific query patterns (pediatric, geriatric, etc.)-- Constructing methodology-specific searches-- Need quality filters or best practice patterns--Grep pattern for query examples: `diabetes|cancer|cardiovascular|clinical trial|systematic review`--### 7. Search History and Saved Searches--Use PubMed's search history and My NCBI features for efficient research workflows.--**Search History** (via Advanced Search):-- Maintains up to 100 searches-- Expires after 8 hours of inactivity-- Combine previous searches using # references-- Preview result counts before executing--**Example**:-```-#1: diabetes mellitus[mh]-#2: cardiovascular diseases[mh]-#3: #1 AND #2 AND risk factors[tiab]-```--**My NCBI Features**:-- Save searches indefinitely-- Set up email alerts for new matching articles-- Create collections of saved articles-- Organize research by project or topic--**RSS Feeds**:-Create RSS feeds for any search to monitor new publications in your area of interest.--### 8. Related Articles and Citation Discovery--Find related research and explore citation networks.--**Similar Articles Feature**:-Every PubMed article includes pre-calculated related articles based on:-- Title and abstract similarity-- MeSH term overlap-- Weighted algorithmic matching--**ELink for Related Data**:-```-# Find related articles programmatically-elink.fcgi?dbfrom=pubmed&db=pubmed&id=PMID&cmd=neighbor-```--**Citation Links**:-- LinkOut to full text from publishers-- Links to PubMed Central free articles-- Connections to related NCBI databases (GenBank, ClinicalTrials.gov, etc.)--### 9. Export and Citation Management--Export search results in various formats for citation management and further analysis.--**Export Formats**:-- .nbib files for reference managers (Zotero, Mendeley, EndNote)-- AMA, MLA, APA, NLM citation styles-- CSV for data analysis-- XML for programmatic processing--**Clipboard and Collections**:-- Clipboard: Temporary storage for up to 500 items (8-hour expiration)-- Collections: Permanent storage via My NCBI account--**Batch Export via API**:-```python-# Export citations in MEDLINE format-efetch.fcgi?db=pubmed&id=PMID1,PMID2&rettype=medline&retmode=text-```--## Working with Reference Files--This skill includes three comprehensive reference files in the `references/` directory:--### references/api_reference.md-Complete E-utilities API documentation including all nine endpoints, parameters, response formats, and best practices. Consult when:-- Implementing programmatic PubMed access-- Constructing API requests-- Understanding rate limits and authentication-- Working with large datasets via history server-- Troubleshooting API errors--### references/search_syntax.md-Detailed guide to PubMed search syntax including field tags, Boolean operators, wildcards, and special characters. Consult when:-- Constructing complex search queries-- Understanding automatic term mapping-- Using advanced search features (proximity, wildcards)-- Applying filters and limits-- Troubleshooting unexpected search results--### references/common_queries.md-Extensive collection of example queries for various research scenarios, disease types, and methodologies. Consult when:-- Starting a new literature search-- Need templates for specific research areas-- Looking for best practice query patterns-- Conducting systematic reviews-- Searching for specific study designs or populations--**Reference Loading Strategy**:-Load reference files into context as needed based on the specific task. For brief queries or basic searches, the information in this SKILL.md may be sufficient. For complex operations, consult the appropriate reference file.--## Common Workflows--### Workflow 1: Basic Literature Search--1. Identify key concepts and synonyms-2. Construct query with Boolean operators and field tags-3. Review initial results and refine query-4. Apply filters (date, article type, language)-5. Export results for analysis--### Workflow 2: Systematic Review Search--1. Define research question using PICO framework-2. Identify all relevant MeSH terms and synonyms-3. Construct comprehensive search strategy-4. Search multiple databases (include PubMed)-5. Document search strategy and date-6. Export results for screening and review--### Workflow 3: Programmatic Data Extraction--1. Design search query and test in web interface-2. Implement search using ESearch API-3. Use history server for large result sets-4. Retrieve detailed records with EFetch-5. Parse XML/JSON responses-6. Store data locally with caching-7. Implement rate limiting and error handling--### Workflow 4: Citation Discovery--1. Start with known relevant article-2. Use Similar Articles to find related work-3. Check citing articles (when available)-4. Explore MeSH terms from relevant articles-5. Construct new searches based on discoveries-6. Use ELink to find related database entries--### Workflow 5: Ongoing Literature Monitoring--1. Construct comprehensive search query-2. Test and refine query for precision-3. Save search to My NCBI account-4. Set up email alerts for new matches-5. Create RSS feed for feed reader monitoring-6. Review new articles regularly--## Tips and Best Practices--### Search Strategy-- Start broad, then narrow with field tags and filters-- Include synonyms and MeSH terms for comprehensive coverage-- Use quotation marks for exact phrases-- Check Search Details in Advanced Search to verify query translation-- Combine multiple searches using search history--### API Usage-- Obtain API key for higher rate limits (10 req/sec vs 3 req/sec)-- Use history server for result sets > 500 articles-- Implement exponential backoff for rate limit handling-- Cache results locally to minimize redundant requests-- Always include descriptive User-Agent header--### Quality Filtering-- Prefer systematic reviews and meta-analyses for synthesized evidence-- Use publication type filters to find specific study designs-- Filter by date for most recent research-- Apply language filters as appropriate-- Use free full text filter for immediate access--### Citation Management-- Export early and often to avoid losing search results-- Use .nbib format for compatibility with most reference managers-- Create My NCBI account for permanent collections-- Document search strategies for reproducibility-- Use Collections to organize research by project--## Limitations and Considerations--### Database Coverage-- Primarily biomedical and life sciences literature-- Pre-1975 articles often lack abstracts-- Full author names available from 2002 forward-- Non-English abstracts available but may default to English display--### Search Limitations-- Display limited to 10,000 results maximum-- Search history expires after 8 hours of inactivity-- Clipboard holds max 500 items with 8-hour expiration-- Automatic term mapping may produce unexpected results--### API Considerations-- Rate limits apply (3-10 requests/second)-- Large queries may time out (use history server)-- XML parsing required for detailed data extraction-- API key recommended for production use--### Access Limitations-- PubMed provides citations and abstracts (not always full text)-- Full text access depends on publisher, institutional access, or open access status-- LinkOut availability varies by journal and institution-- Some content requires subscription or payment--## Support Resources--- **PubMed Help**: https://pubmed.ncbi.nlm.nih.gov/help/-- **E-utilities Documentation**: https://www.ncbi.nlm.nih.gov/books/NBK25501/-- **NLM Help Desk**: 1-888-FIND-NLM (1-888-346-3656)-- **Technical Support**: vog.hin.mln.ibcn@seitilitue-- **Mailing List**: [email protected]-diff --git a/scientific-skills/pubmed-database/references/api_reference.md b/scientific-skills/pubmed-database/references/api_reference.mddeleted file mode 100644index c30bae4e..00000000--- a/scientific-skills/pubmed-database/references/api_reference.md+++ /dev/null@@ -1,298 +0,0 @@-# PubMed E-utilities API Reference--## Overview--The NCBI E-utilities provide programmatic access to PubMed and other Entrez databases through a REST API. The base URL for all E-utilities is:--```-https://eutils.ncbi.nlm.nih.gov/entrez/eutils/-```--## API Key Requirements--As of December 1, 2018, NCBI enforces API key usage for E-utility calls. API keys increase rate limits from 3 requests/second to 10 requests/second. To obtain an API key, register for an NCBI account and generate a key from your account settings.--Include the API key in requests using the `&api_key` parameter:-```-esearch.fcgi?db=pubmed&term=cancer&api_key=YOUR_API_KEY-```--## Rate Limits--- **Without API key**: 3 requests per second-- **With API key**: 10 requests per second-- Always include a User-Agent header in requests--## Core E-utility Tools--### 1. ESearch - Query Databases--**Endpoint**: `esearch.fcgi`--**Purpose**: Search an Entrez database and retrieve a list of UIDs (e.g., PMIDs for PubMed)--**Required Parameters**:-- `db` - Database to search (e.g., pubmed, gene, protein)-- `term` - Search query--**Optional Parameters**:-- `retmax` - Maximum records to return (default: 20, max: 10000)-- `retstart` - Index of first record to return (default: 0)-- `usehistory=y` - Store results on history server for large result sets-- `retmode` - Return format (xml, json)-- `sort` - Sort order (relevance, pub_date, first_author, last_author, journal)-- `field` - Limit search to specific field-- `datetype` - Type of date to use for filtering (pdat for publication date)-- `mindate` - Minimum date (YYYY/MM/DD format)-- `maxdate` - Maximum date (YYYY/MM/DD format)--**Example Request**:-```-esearch.fcgi?db=pubmed&term=breast+cancer&retmax=100&retmode=json&api_key=YOUR_API_KEY-```--**Response Elements**:-- `Count` - Total number of records matching query-- `RetMax` - Number of records returned in this response-- `RetStart` - Index of first returned record-- `IdList` - List of UIDs (PMIDs)-- `WebEnv` - History server environment string (when usehistory=y)-- `QueryKey` - Query key for history server (when usehistory=y)--### 2. EFetch - Download Records--**Endpoint**: `efetch.fcgi`--**Purpose**: Retrieve full records from a database in various formats--**Required Parameters**:-- `db` - Database name-- `id` - Comma-separated list of UIDs, or use WebEnv/query_key from ESearch--**Optional Parameters**:-- `rettype` - Record type (abstract, medline, xml, uilist)-- `retmode` - Return mode (text, xml)-- `retstart` - Starting record index-- `retmax` - Maximum records per request--**Example Request**:-```-efetch.fcgi?db=pubmed&id=123456,234567&rettype=abstract&retmode=text&api_key=YOUR_API_KEY-```--**Common rettype Values for PubMed**:-- `abstract` - Abstract text-- `medline` - Full MEDLINE format-- `xml` - PubMed XML format-- `uilist` - List of UIDs only--### 3. ESummary - Retrieve Document Summaries--**Endpoint**: `esummary.fcgi`--**Purpose**: Get document summaries (DocSum) for a list of UIDs--**Required Parameters**:-- `db` - Database name-- `id` - Comma-separated UIDs or WebEnv/query_key--**Optional Parameters**:-- `retmode` - Return format (xml, json)-- `version` - DocSum version (1.0 or 2.0, default is 1.0)--**Example Request**:-```-esummary.fcgi?db=pubmed&id=123456,234567&retmode=json&version=2.0&api_key=YOUR_API_KEY-```--**DocSum Fields** (vary by database, common PubMed fields):-- Title-- Authors-- Source (journal)-- PubDate-- Volume, Issue, Pages-- DOI-- PmcRefCount (citations in PMC)--### 4. EPost - Upload UIDs--**Endpoint**: `epost.fcgi`--**Purpose**: Upload a list of UIDs to the history server for use in subsequent requests--**Required Parameters**:-- `db` - Database name-- `id` - Comma-separated list of UIDs--**Example Request**:-```-epost.fcgi?db=pubmed&id=123456,234567,345678&api_key=YOUR_API_KEY-```--**Response**:-Returns WebEnv and QueryKey for use in subsequent requests--### 5. ELink - Find Related Data--**Endpoint**: `elink.fcgi`--**Purpose**: Find related records within the same database or in different databases--**Required Parameters**:-- `dbfrom` - Source database-- `db` - Target database (can be same as dbfrom)-- `id` - UID(s) from source database--**Optional Parameters**:-- `cmd` - Link command (neighbor, neighbor_history, prlinks, llinks, etc.)-- `linkname` - Specific link type to retrieve-- `term` - Filter results with search query-- `holding` - Filter by library holdings--**Example Request**:-```-elink.fcgi?dbfrom=pubmed&db=pubmed&id=123456&cmd=neighbor&api_key=YOUR_API_KEY-```--**Common Link Commands**:-- `neighbor` - Return related records-- `neighbor_history` - Post related records to history server-- `prlinks` - Return provider URLs-- `llinks` - Return LinkOut URLs--### 6. EInfo - Database Information--**Endpoint**: `einfo.fcgi`--**Purpose**: Get information about available Entrez databases or specific database fields--**Parameters**:-- `db` - Database name (optional; omit to list all databases)-- `retmode` - Return format (xml, json)--**Example Request**:-```-einfo.fcgi?db=pubmed&retmode=json&api_key=YOUR_API_KEY-```--**Returns**:-- Database description-- Record count-- Last update date-- Available search fields with descriptions--### 7. EGQuery - Global Query--**Endpoint**: `egquery.fcgi`--**Purpose**: Search term counts across all Entrez databases--**Required Parameters**:-- `term` - Search query--**Example Request**:-```-egquery.fcgi?term=cancer&api_key=YOUR_API_KEY-```--### 8. ESpell - Spelling Suggestions--**Endpoint**: `espell.fcgi`--**Purpose**: Get spelling suggestions for queries--**Required Parameters**:-- `db` - Database name-- `term` - Search term with potential misspelling--**Example Request**:-```-espell.fcgi?db=pubmed&term=cancre&api_key=YOUR_API_KEY-```--### 9. ECitMatch - Citation Matching--**Endpoint**: `ecitmatch.cgi`--**Purpose**: Search PubMed citations using journal, year, volume, page, author information--**Request Format**: POST request with citation strings--**Citation String Format**:-```-journal|year|volume|page|author|key|-```--**Example**:-```-Science|2008|320|5880|1185|key1|-Nature|2010|463|7279|318|key2|-```--**Rate Limit**: 3 requests per second with User-Agent header required--## Best Practices--### Use History Server for Large Result Sets--For queries returning more than 500 records, use the history server:--1. **Initial Search with History**:-```-esearch.fcgi?db=pubmed&term=cancer&usehistory=y&retmode=json&api_key=YOUR_API_KEY-```--2. **Retrieve Records in Batches**:-```-efetch.fcgi?db=pubmed&query_key=1&WebEnv=MCID_12345&retstart=0&retmax=500&rettype=xml&api_key=YOUR_API_KEY-efetch.fcgi?db=pubmed&query_key=1&WebEnv=MCID_12345&retstart=500&retmax=500&rettype=xml&api_key=YOUR_API_KEY-```--### Batch Operations--Use EPost to upload large lists of UIDs before fetching:--```-# Step 1: Post UIDs-epost.fcgi?db=pubmed&id=123,456,789,...&api_key=YOUR_API_KEY--# Step 2: Fetch using WebEnv/query_key-efetch.fcgi?db=pubmed&query_key=1&WebEnv=MCID_12345&rettype=xml&api_key=YOUR_API_KEY-```--### Error Handling--Common HTTP status codes:-- `200` - Success-- `400` - Bad request (check parameters)-- `414` - URI too long (use POST or history server)-- `429` - Rate limit exceeded--### Caching--Implement local caching to:-- Reduce redundant API calls-- Stay within rate limits-- Improve response times-- Respect NCBI resources--## Response Formats--### XML (Default)--Most detailed format with full structured data. Each database has its own DTD (Document Type Definition).--### JSON--Available for most utilities with `retmode=json`. Easier to parse in modern applications.--### Text--Plain text format, useful for abstracts and simple data retrieval.--## Support and Resources--- **API Documentation**: https://www.ncbi.nlm.nih.gov/books/NBK25501/-- **Mailing List**: [email protected]-- **Support**: vog.hin.mln.ibcn@seitilitue-- **NLM Help Desk**: 1-888-FIND-NLM (1-888-346-3656)diff --git a/scientific-skills/pubmed-database/references/common_queries.md b/scientific-skills/pubmed-database/references/common_queries.mddeleted file mode 100644index 68c246e2..00000000--- a/scientific-skills/pubmed-database/references/common_queries.md+++ /dev/null@@ -1,453 +0,0 @@-# Common PubMed Query Patterns--This reference provides practical examples of common PubMed search patterns for various research scenarios.--## General Research Queries--### Finding Recent Research on a Topic-```-breast cancer[tiab] AND 2023:2024[dp]-```--### Systematic Reviews on a Topic-```-(diabetes[tiab] OR diabetes mellitus[mh]) AND systematic review[pt]-```--### Meta-Analyses-```-hypertension[tiab] AND meta-analysis[pt] AND 2020:2024[dp]-```--### Clinical Trials-```-alzheimer disease[mh] AND randomized controlled trial[pt]-```--### Finding Guidelines-```-asthma[tiab] AND (guideline[pt] OR practice guideline[pt])-```--## Disease-Specific Queries--### Cancer Research-```-# General cancer screening-cancer screening[tiab] AND systematic review[pt] AND 2020:2024[dp]--# Specific cancer type with treatment-lung cancer[tiab] AND immunotherapy[tiab] AND clinical trial[pt]--# Cancer genetics-breast neoplasms[mh] AND BRCA1[tiab] AND genetic testing[tiab]-```--### Cardiovascular Disease-```-# Heart disease prevention-(heart disease[tiab] OR cardiovascular disease[mh]) AND prevention[tiab] AND 2022:2024[dp]--# Stroke treatment-stroke[mh] AND (thrombectomy[tiab] OR thrombolysis[tiab]) AND randomized controlled trial[pt]--# Hypertension management-hypertension[mh]/drug therapy AND comparative effectiveness[tiab]-```--### Infectious Diseases-```-# COVID-19 research-COVID-19[tiab] AND (vaccine[tiab] OR vaccination[tiab]) AND 2023:2024[dp]--# Antibiotic resistance-(antibiotic resistance[tiab] OR drug resistance, bacterial[mh]) AND systematic review[pt]--# Tuberculosis treatment-tuberculosis[mh]/drug therapy AND (multidrug-resistant[tiab] OR MDR-TB[tiab])-```--### Neurological Disorders-```-# Alzheimer's disease-alzheimer disease[mh] AND (diagnosis[sh] OR biomarkers[tiab]) AND 2020:2024[dp]--# Parkinson's disease treatment-parkinson disease[mh] AND treatment[tiab] AND clinical trial[pt]--# Multiple sclerosis-multiple sclerosis[mh] AND disease modifying[tiab] AND review[pt]-```--### Diabetes-```-# Type 2 diabetes management-diabetes mellitus, type 2[mh] AND (lifestyle[tiab] OR diet[tiab]) AND randomized controlled trial[pt]--# Diabetes complications-diabetes mellitus[mh] AND (complications[sh] OR diabetic neuropathy[mh])--# New diabetes drugs-diabetes mellitus, type 2[mh] AND (GLP-1[tiab] OR SGLT2[tiab]) AND 2022:2024[dp]-```--## Drug and Treatment Research--### Drug Efficacy Studies-```-# Compare two drugs-(drug A[nm] OR drug B[nm]) AND condition[mh] AND comparative effectiveness[tiab]--# Drug side effects-medication name[nm] AND (adverse effects[sh] OR side effects[tiab])--# Drug combination therapy-(aspirin[nm] AND clopidogrel[nm]) AND acute coronary syndrome[mh]-```--### Treatment Comparisons-```-# Surgery vs medication-condition[mh] AND (surgery[tiab] OR surgical[tiab]) AND (medication[tiab] OR drug therapy[sh]) AND comparative study[pt]--# Different surgical approaches-procedure[tiab] AND (laparoscopic[tiab] OR open surgery[tiab]) AND outcomes[tiab]-```--### Alternative Medicine-```-# Herbal supplements-(herbal medicine[mh] OR phytotherapy[mh]) AND condition[tiab] AND clinical trial[pt]--# Acupuncture-acupuncture[mh] AND pain[tiab] AND randomized controlled trial[pt]-```--## Diagnostic Research--### Diagnostic Tests-```-# Sensitivity and specificity-test name[tiab] AND condition[tiab] AND (sensitivity[tiab] AND specificity[tiab])--# Diagnostic imaging-(MRI[tiab] OR magnetic resonance imaging[tiab]) AND brain tumor[tiab] AND diagnosis[sh]--# Lab test evaluation-biomarker name[tiab] AND disease[tiab] AND (diagnostic[tiab] OR screening[tiab])-```--### Screening Programs-```-# Cancer screening-cancer type[tiab] AND screening[tiab] AND (cost effectiveness[tiab] OR benefit[tiab])--# Population screening-condition[tiab] AND mass screening[mh] AND public health[tiab]-```--## Population-Specific Queries--### Pediatric Research-```-# Children with specific condition-condition[tiab] AND (child[mh] OR pediatric[tiab]) AND treatment[tiab]--# Age-specific-disease[tiab] AND (infant[mh] OR child, preschool[mh])--# Pediatric dosing-drug name[nm] AND pediatric[tiab] AND (dosing[tiab] OR dose[tiab])-```--### Geriatric Research-```-# Elderly population-condition[tiab] AND (aged[mh] OR elderly[tiab] OR geriatric[tiab])--# Aging and disease-aging[mh] AND disease[tiab] AND mechanism[tiab]--# Polypharmacy-polypharmacy[tiab] AND elderly[tiab] AND adverse effects[tiab]-```--### Pregnant Women-```-# Pregnancy and medications-drug name[nm] AND (pregnancy[mh] OR pregnant women[tiab]) AND safety[tiab]--# Pregnancy complications-pregnancy complication[tiab] AND management[tiab]-```--### Sex-Specific Research-```-# Female-specific-condition[tiab] AND female[mh] AND hormones[tiab]--# Male-specific-disease[tiab] AND male[mh] AND risk factors[tiab]--# Sex differences-condition[tiab] AND (sex factors[mh] OR gender differences[tiab])-```--## Epidemiology and Public Health--### Prevalence Studies-```-disease[tiab] AND (prevalence[tiab] OR epidemiology[sh]) AND country/region[tiab]-```--### Incidence Studies-```-condition[tiab] AND incidence[tiab] AND population[tiab] AND 2020:2024[dp]-```--### Risk Factors-```-disease[mh] AND (risk factors[mh] OR etiology[sh]) AND cohort study[tiab]-```--### Global Health-```-disease[tiab] AND (developing countries[mh] OR low income[tiab]) AND burden[tiab]-```--### Health Disparities-```-condition[tiab] AND (health disparities[tiab] OR health equity[tiab]) AND minority groups[tiab]-```--## Methodology-Specific Queries--### Research Methodology--#### Cohort Studies-```-condition[tiab] AND cohort study[tiab] AND prospective[tiab]-```--#### Case-Control Studies-```-disease[tiab] AND case-control studies[mh] AND risk factors[tiab]-```--#### Cross-Sectional Studies-```-condition[tiab] AND cross-sectional studies[mh] AND prevalence[tiab]-```--### Statistical Methods-```-# Machine learning in medicine-(machine learning[tiab] OR artificial intelligence[tiab]) AND diagnosis[tiab] AND validation[tiab]--# Bayesian analysis-condition[tiab] AND bayes theorem[mh] AND clinical decision[tiab]-```--### Genetic and Molecular Research-```-# GWAS studies-disease[tiab] AND (genome-wide association study[tiab] OR GWAS[tiab])--# Gene expression-gene name[tiab] AND (gene expression[mh] OR mRNA[tiab]) AND disease[tiab]--# Proteomics-condition[tiab] AND proteomics[mh] AND biomarkers[tiab]--# CRISPR research-CRISPR[tiab] AND (gene editing[tiab] OR genome editing[tiab]) AND 2020:2024[dp]-```--## Author and Institution Queries--### Finding Work by Specific Author-```-# Single author-smith ja[au] AND cancer[tiab] AND 2023:2024[dp]--# First author only-jones m[1au] AND cardiology[tiab]--# Multiple authors from same group-(smith ja[au] OR jones m[au] OR wilson k[au]) AND research topic[tiab]-```--### Institution-Specific Research-```-# University affiliation-harvard[affil] AND cancer research[tiab] AND 2023:2024[dp]--# Hospital research-"mayo clinic"[affil] AND clinical trial[pt]--# Country-specific-japan[affil] AND robotics[tiab] AND surgery[tiab]-```--## Journal-Specific Queries--### High-Impact Journals-```-# Specific journal-nature[ta] AND genetics[tiab] AND 2024[dp]--# Multiple journals-(nature[ta] OR science[ta] OR cell[ta]) AND immunology[tiab]--# Journal with ISSN-0028-4793[issn] AND clinical trial[pt]-```--## Citation and Reference Queries--### Finding Specific Articles-```-# By PMID-12345678[pmid]--# By DOI-10.1056/NEJMoa123456[doi]--# By first author and year-smith ja[1au] AND 2023[dp] AND cancer[tiab]-```--### Finding Cited Work-```-# Related articles-Similar Articles feature from any PubMed result--# By keyword in references-Use "Cited by" links when available-```--## Advanced Combination Queries--### Comprehensive Literature Review-```-(disease name[tiab] OR disease name[mh]) AND-((treatment[tiab] OR therapy[tiab] OR management[tiab]) OR-(diagnosis[tiab] OR screening[tiab]) OR-(epidemiology[tiab] OR prevalence[tiab])) AND-(systematic review[pt] OR meta-analysis[pt] OR review[pt]) AND-2019:2024[dp] AND english[la]-```--### Precision Medicine Query-```-(precision medicine[tiab] OR personalized medicine[tiab] OR pharmacogenomics[mh]) AND-cancer[tiab] AND-(biomarkers[tiab] OR genetic testing[tiab]) AND-clinical application[tiab] AND-2020:2024[dp]-```--### Translational Research-```-(basic science[tiab] OR bench to bedside[tiab] OR translational medical research[mh]) AND-disease[tiab] AND-(clinical trial[pt] OR clinical application[tiab]) AND-2020:2024[dp]-```--## Quality Filters--### High-Quality Evidence-```-condition[tiab] AND-(randomized controlled trial[pt] OR systematic review[pt] OR meta-analysis[pt]) AND-humans[mh] AND-english[la] AND-2020:2024[dp]-```--### Free Full Text Articles-```-topic[tiab] AND free full text[sb] AND 2023:2024[dp]-```--### Articles with Abstracts-```-condition[tiab] AND hasabstract[text] AND review[pt]-```--## Staying Current--### Latest Publications-```-topic[tiab] AND 2024[dp] AND english[la]-```--### Preprints and Early Access-```-topic[tiab] AND (epub ahead of print[tiab] OR publisher[sb])-```--### Setting Up Alerts-```-# Create search and save to My NCBI-# Enable email alerts for new matching articles-topic[tiab] AND (randomized controlled trial[pt] OR systematic review[pt])-```--## COVID-19 Specific Queries--### Vaccine Research-```-(COVID-19[tiab] OR SARS-CoV-2[tiab]) AND-(vaccine[tiab] OR vaccination[tiab]) AND-(efficacy[tiab] OR effectiveness[tiab]) AND-2023:2024[dp]-```--### Long COVID-```-(long covid[tiab] OR post-acute covid[tiab] OR PASC[tiab]) AND-(symptoms[tiab] OR treatment[tiab])-```--### COVID Treatment-```-COVID-19[tiab] AND-(antiviral[tiab] OR monoclonal antibody[tiab] OR treatment[tiab]) AND-randomized controlled trial[pt]-```--## Tips for Constructing Queries--### 1. PICO Framework-Use PICO (Population, Intervention, Comparison, Outcome) to structure clinical queries:--```-P: diabetes mellitus, type 2[mh]-I: metformin[nm]-C: lifestyle modification[tiab]-O: glycemic control[tiab]--Query: diabetes mellitus, type 2[mh] AND (metformin[nm] OR lifestyle modification[tiab]) AND glycemic control[tiab]-```--### 2. Iterative Refinement-Start broad, review results, refine:-```-1. diabetes → too broad-2. diabetes mellitus type 2 → better-3. diabetes mellitus, type 2[mh] AND metformin[nm] → more specific-4. diabetes mellitus, type 2[mh] AND metformin[nm] AND randomized controlled trial[pt] → focused-```--### 3. Use Search History-Combine previous searches in Advanced Search:-```-#1: diabetes mellitus, type 2[mh]-#2: cardiovascular disease[mh]-#3: #1 AND #2 AND risk factors[tiab]-```--### 4. Save Effective Searches-Create My NCBI account to save successful queries for future use and set up automatic alerts.diff --git a/scientific-skills/pubmed-database/references/search_syntax.md b/scientific-skills/pubmed-database/references/search_syntax.mddeleted file mode 100644index 47020205..00000000--- a/scientific-skills/pubmed-database/references/search_syntax.md+++ /dev/null@@ -1,436 +0,0 @@-# PubMed Search Syntax and Field Tags--## Boolean Operators--PubMed supports standard Boolean operators to combine search terms:--### AND-Retrieves results containing all search terms. PubMed automatically applies AND between separate concepts.--**Example**:-```-diabetes AND hypertension-```--### OR-Retrieves results containing at least one of the search terms. Useful for synonyms or related concepts.--**Example**:-```-heart attack OR myocardial infarction-```--### NOT-Excludes results containing the specified term. Use cautiously as it may eliminate relevant results.--**Example**:-```-cancer NOT lung-```--**Precedence**: Operations are processed left to right. Use parentheses to control evaluation order:-```-(heart attack OR myocardial infarction) AND treatment-```--## Phrase Searching--### Double Quotes-Enclose exact phrases in double quotes to search for terms in specific order:--```-"kidney allograft"-"machine learning"-"systematic review"-```--### Field Tags-Alternative method using field tags:-```-kidney allograft[Title]-```--## Wildcards--Use asterisk (*) to substitute for zero or more characters:--**Rules**:-- Minimum 4 characters before first wildcard-- Matches word variations and plurals--**Examples**:-```-vaccin* → matches vaccine, vaccination, vaccines, vaccinate-pediatr* → matches pediatric, pediatrics, pediatrician-colo*r → matches color, colour-```--**Limitations**:-- Cannot use at beginning of search term-- May retrieve unexpected variations--## Proximity Searching--Search for terms within a specified distance from each other. Only available in Title, Title/Abstract, and Affiliation fields.--**Syntax**: `"search terms"[field:~N]`-- N = maximum number of words between terms--**Examples**:-```-"vitamin C"[Title:~3] → vitamin within 3 words of C in title-"breast cancer screening"[TIAB:~5] → terms within 5 words in title/abstract-```--## Search Field Tags--Field tags limit searches to specific parts of PubMed records. Format: `term[tag]`--### Author Searching--| Tag | Field | Example |-|-----|-------|---------|-| [au] | Author | smith j[au] |-| [1au] | First Author | jones m[1au] |-| [lastau] | Last Author | wilson k[lastau] |-| [fau] | Full Author Name | smith john a[fau] |--**Author Search Notes**:-- Full author names searchable from 2002 forward-- Format: last name + initials (e.g., `smith ja[au]`)-- Can search without field tag, but [au] ensures accuracy--**Corporate Authors**:-Search organizations as authors:-```-world health organization[au]-```--### Title and Abstract--| Tag | Field | Example |-|-----|-------|---------|-| [ti] | Title | diabetes[ti] |-| [ab] | Abstract | treatment[ab] |-| [tiab] | Title/Abstract | cancer screening[tiab] |-| [tw] | Text Word | cardiovascular[tw] |--**Notes**:-- [tw] searches title, abstract, and other text fields-- [tiab] is most commonly used for comprehensive searching--### Journal Information--| Tag | Field | Example |-|-----|-------|---------|-| [ta] | Journal Title Abbreviation | Science[ta] |-| [jour] | Journal | New England Journal of Medicine[jour] |-| [issn] | ISSN | 0028-4793[issn] |--### Date Fields--| Tag | Field | Format | Example |-|-----|-------|--------|---------|-| [dp] | Publication Date | YYYY/MM/DD | 2023[dp] |-| [edat] | Entrez Date | YYYY/MM/DD | 2023/01/15[edat] |-| [crdt] | Create Date | YYYY/MM/DD | 2023[crdt] |-| [mhda] | MeSH Date | YYYY/MM/DD | 2023[mhda] |--**Date Ranges**:-Use colon to specify ranges:-```-2020:2023[dp] → publications from 2020 to 2023-2023/01/01:2023/06/30[dp] → first half of 2023-```--**Relative Dates**:-PubMed filters provide common ranges:-- Last 1 year-- Last 5 years-- Last 10 years-- Custom date range--### MeSH and Subject Headings--| Tag | Field | Example |-|-----|-------|---------|-| [mh] | MeSH Terms | diabetes mellitus[mh] |-| [majr] | MeSH Major Topic | hypertension[majr] |-| [mesh] | MeSH Terms | cancer[mesh] |-| [sh] | MeSH Subheading | therapy[sh] |--**MeSH Searching**:-- Medical Subject Headings provide controlled vocabulary-- [mh] includes narrower terms automatically-- [majr] limits to articles where topic is main focus-- Combine with subheadings: `diabetes mellitus/therapy[mh]`--**Common MeSH Subheadings**:-- /diagnosis-- /drug therapy-- /epidemiology-- /etiology-- /prevention & control-- /therapy--### Publication Types--| Tag | Field | Example |-|-----|-------|---------|-| [pt] | Publication Type | clinical trial[pt] |-| [ptyp] | Publication Type | review[ptyp] |--**Common Publication Types**:-- Clinical Trial-- Meta-Analysis-- Randomized Controlled Trial-- Review-- Systematic Review-- Case Reports-- Letter-- Editorial-- Guideline--**Example**:-```-cancer AND systematic review[pt]-```--### Other Useful Fields--| Tag | Field | Example |-|-----|-------|---------|-| [la] | Language | english[la] |-| [affil] | Affiliation | harvard[affil] |-| [pmid] | PubMed ID | 12345678[pmid] |-| [pmc] | PMC ID | PMC123456[pmc] |-| [doi] | DOI | 10.1234/example[doi] |-| [gr] | Grant Number | R01CA123456[gr] |-| [isbn] | ISBN | 9780123456789[isbn] |-| [pg] | Pagination | 123-145[pg] |-| [vi] | Volume | 45[vi] |-| [ip] | Issue | 3[ip] |--### Supplemental Concepts--| Tag | Field | Example |-|-----|-------|---------|-| [nm] | Substance Name | aspirin[nm] |-| [ps] | Personal Name | darwin charles[ps] |--## Automatic Term Mapping (ATM)--When searching without field tags, PubMed automatically:--1. **Searches MeSH translation table** for matching MeSH terms-2. **Searches journal translation table** for journal names-3. **Searches author index** for author names-4. **Searches full text** for remaining terms--**Bypass ATM**:-- Use double quotes: `"breast cancer"`-- Use field tags: `breast cancer[tiab]`--**View Translation**:-Use Advanced Search to see how PubMed translated your query in the Search Details box.--## Filters and Limits--### Article Types-- Clinical Trial-- Meta-Analysis-- Randomized Controlled Trial-- Review-- Systematic Review--### Text Availability-- Free full text-- Full text-- Abstract--### Publication Date-- Last 1 year-- Last 5 years-- Last 10 years-- Custom date range--### Species-- Humans-- Animals (specific species available)--### Sex-- Female-- Male--### Age Groups-- Child (0-18 years)-- Infant (birth-23 months)-- Child, Preschool (2-5 years)-- Child (6-12 years)-- Adolescent (13-18 years)-- Adult (19+ years)-- Aged (65+ years)-- 80 and over--### Languages-- English-- Spanish-- French-- German-- Chinese-- And many others--### Other Filters-- Journal categories-- Subject area-- Article attributes (e.g., has abstract, free PMC article)--## Advanced Search Strategies--### Clinical Queries-PubMed provides specialized filters for clinical research:--**Study Categories**:-- Therapy (narrow/broad)-- Diagnosis (narrow/broad)-- Etiology (narrow/broad)-- Prognosis (narrow/broad)-- Clinical prediction guides--**Medical Genetics**:-- Diagnosis-- Differential diagnosis-- Clinical description-- Management-- Genetic counseling--### Hedges and Filters-Pre-built search strategies for specific purposes:-- Systematic review filters-- Quality filters for study types-- Geographic filters--### Combining Searches-Use Advanced Search to combine previous queries:-```-#1 AND #2-#3 OR #4-#5 NOT #6-```--### Search History-- Saves up to 100 searches-- Expires after 8 hours of inactivity-- Access via Advanced Search page-- Combine using # references--## Best Practices--### 1. Start Broad, Then Narrow-Begin with general terms and add specificity:-```-diabetes → too broad-diabetes mellitus type 2 → better-diabetes mellitus type 2[mh] AND treatment[tiab] → more specific-```--### 2. Use Synonyms with OR-Include alternative terms:-```-heart attack OR myocardial infarction OR MI-```--### 3. Combine Concepts with AND-Link different aspects of your research question:-```-(heart attack OR myocardial infarction) AND (aspirin OR acetylsalicylic acid) AND prevention-```--### 4. Leverage MeSH Terms-Use MeSH for consistent indexing:-```-diabetes mellitus[mh] AND hypertension[mh]-```--### 5. Use Filters Strategically-Apply filters to refine results:-- Publication date for recent research-- Article type for specific study designs-- Free full text for accessible articles--### 6. Review Search Details-Check how PubMed interpreted your search in Advanced Search to ensure accuracy.--### 7. Save Effective Searches-Create My NCBI account to:-- Save searches-- Set up email alerts-- Create collections--## Common Search Patterns--### Systematic Review Search-```-(breast cancer[tiab] OR breast neoplasm[mh]) AND (screening[tiab] OR early detection[tiab]) AND systematic review[pt]-```--### Clinical Trial Search-```-diabetes mellitus type 2[mh] AND metformin[nm] AND randomized controlled trial[pt] AND 2020:2024[dp]-```--### Recent Research by Author-```-smith ja[au] AND cancer[tiab] AND 2023:2024[dp] AND english[la]-```--### Drug Treatment Studies-```-hypertension[mh] AND (amlodipine[nm] OR losartan[nm]) AND drug therapy[sh] AND humans[mh]-```--### Geographic-Specific Research-```-malaria[tiab] AND (africa[affil] OR african[tiab]) AND 2020:2024[dp]-```--## Special Characters--| Character | Purpose | Example |-|-----------|---------|---------|-| * | Wildcard | colo*r |-| " " | Phrase search | "breast cancer" |-| ( ) | Group terms | (A OR B) AND C |-| : | Range | 2020:2023[dp] |-| - | Hyphenated terms | COVID-19 |-| / | MeSH subheading | diabetes/therapy[mh] |--## Troubleshooting--### Too Many Results-- Add more specific terms-- Use field tags to limit search scope-- Apply date restrictions-- Use filters for article type-- Add additional concepts with AND--### Too Few Results-- Remove restrictive terms-- Use OR to add synonyms-- Check spelling and terminology-- Remove field tags for broader search-- Expand date range-- Remove filters--### No Results-- Check spelling using ESpell-- Try alternative terminology-- Remove field tags-- Verify correct database (PubMed vs. PMC)-- Broaden search terms--### Unexpected Results-- Review Search Details to see query translation-- Use field tags to prevent automatic term mapping-- Check for common synonyms that may be included-- Refine with additional limiting termsdiff --git a/scientific-skills/writing/SKILL.md b/scientific-skills/writing/SKILL.mddeleted file mode 100644index f3ec3f50..00000000--- a/scientific-skills/writing/SKILL.md+++ /dev/null@@ -1,414 +0,0 @@-----name: writing-description: "Use this skill to create high-quality academic papers, literature reviews, grant proposals, clinical reports, and other research and scientific documents backed by comprehensive research and real, verifiable citations. Use this skill whenever the user asks for written output such as a report, paper...etc."-license: MIT license-metadata:- skill-author: K-Dense Inc.-------# Agent System Instructions--## Core Mission--You are a **deep research and scientific writing assistant** that combines AI-driven research with well-formatted written outputs. Create high-quality academic papers, literature reviews, grant proposals, clinical reports, and other scientific documents backed by comprehensive research and real, verifiable citations.--**Default Format:** LaTeX with BibTeX citations unless otherwise requested.--**Quality Assurance:** Every PDF is automatically reviewed for formatting issues and iteratively improved until visually clean and professional.--**CRITICAL COMPLETION POLICY:**-- **ALWAYS complete the ENTIRE task without stopping**-- **NEVER ask "Would you like me to continue?" mid-task**-- **NEVER offer abbreviated versions or stop after partial completion**-- For long documents (market research reports, comprehensive papers): Write from start to finish until 100% complete-- **Token usage is unlimited** - complete the full document--**CONTEXT WINDOW & AUTONOMOUS OPERATION:**--Your context window will be automatically compacted as it approaches its limit, allowing you to continue working indefinitely from where you left off. Do not stop tasks early due to token budget concerns. Save progress before context window refreshes. Always complete tasks fully, even if the end of your budget is approaching. Never artificially stop any task early.--## CRITICAL: Output Length Awareness & Multi-Pass Verification--**Not all models have the same maximum output token limit.** Some models (e.g. Gemini via OpenRouter) may cap a single response at 8K-65K tokens, while others (e.g. Claude) can produce up to 128K tokens per response. The model powering this session may silently truncate long outputs without warning.--**You MUST follow these rules to guarantee completeness:**--1. **Write to files, never to stdout.** Always use the Write or Edit tool to save document content directly into `.tex`, `.md`, or other output files. Never rely on producing the entire document as inline text -- the response may be cut short by a token ceiling you cannot observe.--2. **Section-at-a-time strategy.** When generating a document longer than ~4000 words:- - Write the skeleton/structure first (all section headings, empty bodies).- - Then fill each section in a **separate write/edit pass**.- - After each pass, read the file back and confirm the section is present and complete.--3. **Post-write length check (MANDATORY after every major write).**- After writing or appending a section, immediately run:- ```bash- wc -w <output_file>- ```- Compare the word count against what the user requested (or a reasonable expectation for the document type). If the file is significantly shorter than expected:- - Log: `[WARNING] Output file is <N> words -- expected ~<M>. Re-generating missing sections.`- - Identify which sections are missing or truncated.- - Re-generate **only** the missing/truncated content and append/replace it.--4. **Final completeness gate.** Before declaring the task done:- - Read the output file.- - Verify every planned section heading has non-empty body content.- - Verify the bibliography exists and is non-empty (for LaTeX documents).- - If any section body is empty, a placeholder, or obviously truncated, fill it now.--5. **Never assume a single write produced the whole document.** If a write operation produced fewer words than the section outline anticipated, treat it as a partial write and continue from where it left off.--## CRITICAL: Real Citations Only Policy--**Every citation must be a real, verifiable paper found through the `research-lookup` skill.**--- ZERO tolerance for placeholder citations ("Smith et al. 2023" unless verified)-- ZERO tolerance for invented citations or "[citation needed]" placeholders-- Activate the **`research-lookup`** skill extensively to find actual published papers-- Verify every citation exists before adding to references.bib--**Research-Lookup First Approach:**-1. Before writing ANY section, activate **`research-lookup`** to perform extensive literature search-2. Find 5-10 real papers per major section-3. Begin writing, integrating ONLY the real papers found-4. If additional citations needed, perform more research-lookup first--## CRITICAL: Web Search and Research Policy--**Activate the `research-lookup` skill for all academic paper searches and deep research.** It automatically routes queries to the best backend (Parallel Chat API for general research, Perplexity for academic paper searches).--**Activate the `parallel-web` skill for all web searches, URL extraction, and general web research.** Do NOT use built-in WebSearch tools except as a last-resort fallback.--| Task | Skill to Activate |-|------|-------------------|-| Web search (any) | `parallel-web` |-| Extract URL content | `parallel-web` |-| Deep research | `parallel-web` or `research-lookup` |-| Academic paper search | `research-lookup` |-| DOI/metadata verification | `parallel-web` |-| Current events/news | `parallel-web` |--## CRITICAL: Save All Research Results to Sources Folder--**Every research result MUST be saved to the project's `sources/` folder.**--This is non-negotiable. Research results are expensive to obtain and critical for reproducibility, auditability, and context window recovery.--**Saving Rules:**--| Operation | Filename Pattern | Example |-|-----------|-----------------|---------|-| Web Search | `search_YYYYMMDD_HHMMSS_<topic>.md` | `sources/search_20250217_143000_quantum_computing.md` |-| URL Extract | `extract_YYYYMMDD_HHMMSS_<source>.md` | `sources/extract_20250217_143500_nature_article.md` |-| Deep Research | `research_YYYYMMDD_HHMMSS_<topic>.md` | `sources/research_20250217_144000_ev_battery_market.md` |-| Academic Paper Search | `papers_YYYYMMDD_HHMMSS_<topic>.md` | `sources/papers_20250217_144500_crispr_offtarget.md` |--**Key Rules:**-- **ALWAYS** save research output to `sources/` -- never discard it-- **ALWAYS** ensure saved files preserve all citations, source URLs, and DOIs-- **ALWAYS** check `sources/` for existing results before making new API calls (avoid duplicate queries)-- **ALWAYS** log saved results: `[HH:MM:SS] SAVED: [type] to sources/[filename] ([N] words/results, [N] citations)`-- The `sources/` folder provides a complete audit trail of all research conducted for the project-- Saved results enable context window recovery -- re-read from `sources/` instead of re-querying APIs--## Workflow Protocol--### Phase 1: Planning and Execution--1. **Analyze the Request**- - Identify document type and scientific field- - Note specific requirements (journal, citation style, page limits)- - **Default to LaTeX** unless user specifies otherwise- - **Detect special document types** (see Special Documents section)--2. **Present Brief Plan and Execute Immediately**- - Outline approach and structure- - State LaTeX will be used (unless otherwise requested)- - Begin execution immediately without waiting for approval--3. **Execute with Continuous Updates**- - Provide real-time progress updates: `[HH:MM:SS] ACTION: Description`- - Log all actions to progress.md- - Update progress every 1-2 minutes--### Phase 2: Project Setup--1. **Create Unique Project Folder**- - All work in: `writing_outputs/<timestamp>_<brief_description>/`- - Create subfolders: `drafts/`, `references/`, `figures/`, `final/`, `data/`, `sources/`--2. **Initialize Progress Tracking**- - Create `progress.md` with timestamps, status, and metrics--### Phase 3: Quality Assurance and Delivery--1. **Verify All Deliverables** - files created, citations verified, PDF clean-2. **Create Summary Report** - `SUMMARY.md` with files list and usage instructions-3. **Conduct Peer Review** - Activate the `peer-review` skill, save as `PEER_REVIEW.md`--## Special Document Types--For specialized documents, activate the dedicated skill which contains detailed templates, workflows, and requirements:--| Document Type | Skill to Activate |-|--------------|-------------------|-| Hypothesis generation | `hypothesis-generation` |-| Treatment plans (individual patients) | `treatment-plans` |-| Clinical decision support (cohorts, guidelines) | `clinical-decision-support` |-| Scientific posters | `latex-posters` |-| Presentations/slides | `scientific-slides` |-| Research grants | `research-grants` |-| Market research reports | `market-research-reports` |-| Literature reviews | `literature-review` |-| Infographics | `infographics` |-| Web search, URL extraction, deep research | `parallel-web` |--**INFOGRAPHICS: Do NOT use LaTeX or PDF compilation.** When the user asks for an infographic, activate the `infographics` skill directly. Infographics are generated as standalone PNG images, not as LaTeX documents.--## File Organization--```-writing_outputs/-+-- YYYYMMDD_HHMMSS_<description>/- |-- progress.md, SUMMARY.md, PEER_REVIEW.md- |-- drafts/ # v1_draft.tex, v2_draft.tex, revision_notes.md- |-- references/ # references.bib- |-- figures/ # figure_01.png, figure_02.pdf- |-- data/ # csv, json, xlsx- |-- sources/ # ALL research results (web search, deep research, URL extracts, paper lookups)- +-- final/ # manuscript.pdf, manuscript.tex-```--### Manuscript Editing Workflow--When files are in the `data/` folder:-- **.tex files** -> `drafts/` [EDITING MODE]-- **Images** (.png, .jpg, .svg) -> `figures/`-- **Data files** (.csv, .json, .xlsx) -> `data/`-- **Other files** (.md, .docx, .pdf) -> `sources/`--When .tex files are present in drafts/, EDIT the existing manuscript.--### Version Management--**Always increment version numbers when editing:**-- Initial: `v1_draft.tex`-- Each revision: `v2_draft.tex`, `v3_draft.tex`, etc.-- Never overwrite previous versions-- Document changes in `revision_notes.md`--## Document Creation Standards--### Multi-Pass Writing Approach--#### Pass 1: Create Skeleton-- Create full LaTeX document structure with sections/subsections-- Add placeholder comments for each section-- Create empty `references/references.bib`--#### Pass 2+: Fill Sections with Research-For each section:-1. **Activate `research-lookup` BEFORE writing** - find 5-10 real papers-2. Write content integrating real citations only-3. Add BibTeX entries as you cite-4. Log: `[HH:MM:SS] COMPLETED: [Section] - [words] words, [N] citations`-5. **Run `wc -w` on the output file** and compare to expectation; re-fill if short--#### Final Pass: Polish and Review-1. Write Abstract (always last)-2. Verify citations and compile LaTeX (pdflatex -> bibtex -> pdflatex x 2)-3. **PDF Formatting Review** (see below)-4. **Final completeness gate** -- re-read the entire file; confirm no empty sections--### PDF Formatting Review (MANDATORY)--After compiling any PDF, you must visually inspect it for formatting issues. Convert the PDF to images for inspection:--```bash-# Use Python with pdf2image (install via: uv add pdf2image)-python -c "-from pdf2image import convert_from_path-pages = convert_from_path('document.pdf', dpi=150)-for i, page in enumerate(pages):- page.save(f'review/page_{i+1}.png', 'PNG')-"-```--If `pdf2image` is not available, use ImageMagick or poppler-utils:-```bash-# ImageMagick-convert -density 150 document.pdf review/page_%d.png--# poppler-utils-pdftoppm -png -r 150 document.pdf review/page-```--Then:-1. **Inspect each page image** for: text overlaps, figure placement, margins, spacing-2. **Fix issues and recompile** (max 3 iterations)-3. **Clean up**: `rm -rf review/`--**Focus Areas:** Text overlaps, figure placement, table issues, margins, page breaks, caption spacing, bibliography formatting--### Figure Generation (EXTENSIVE USE REQUIRED)--**CRITICAL: Every document MUST be richly illustrated. Activate the `scientific-schematics` and `generate-image` skills extensively.**--Documents without sufficient visual elements are incomplete. Generate figures liberally throughout all outputs.--**MANDATORY: Graphical Abstract**--Every scientific writeup (research papers, literature reviews, reports) MUST include a graphical abstract as the first figure. Activate the **`scientific-schematics`** skill and describe the desired graphical abstract.--**Graphical Abstract Requirements:**-- **Position**: Always Figure 1 or placed before the abstract in the document-- **Content**: Visual summary of the entire paper's key message-- **Style**: Clean, professional, suitable for journal table of contents-- **Size**: Landscape orientation, typically 1200x600px or similar aspect ratio-- **Elements**: Include key workflow steps, main results visualization, and conclusions-- Log: `[HH:MM:SS] GENERATED: Graphical abstract for paper summary`--**Activate the `scientific-schematics` skill EXTENSIVELY for technical diagrams:**-- Graphical abstracts (MANDATORY for all writeups)-- Flowcharts, process diagrams, CONSORT/PRISMA diagrams-- System architecture, neural network diagrams-- Biological pathways, molecular structures, circuit diagrams-- Data analysis pipelines, experimental workflows-- Conceptual frameworks, comparison matrices-- Decision trees, algorithm visualizations-- Timeline diagrams, Gantt charts-- Any concept that benefits from schematic visualization--**Activate the `generate-image` skill EXTENSIVELY for visual content:**-- Photorealistic illustrations of concepts-- Artistic visualizations-- Medical/anatomical illustrations-- Environmental/ecological scenes-- Equipment and lab setup visualizations-- Product mockups, prototype visualizations-- Cover images, header graphics-- Any visual that enhances understanding or engagement--**MINIMUM Figure Requirements by Document Type:**--| Document Type | Minimum Figures | Recommended | Skills to Activate |-|--------------|-----------------|-------------|-------------------|-| Research papers | 5 | 6-8 | `scientific-schematics` + `generate-image` |-| Literature reviews | 4 | 5-7 | `scientific-schematics` (PRISMA, frameworks) |-| Market research | 20 | 25-30 | Both extensively |-| Presentations | 1 per slide | 1-2 per slide | Both |-| Posters | 6 | 8-10 | Both |-| Grants | 4 | 5-7 | `scientific-schematics` (aims, design) |-| Clinical reports | 3 | 4-6 | `scientific-schematics` (pathways, algorithms) |--**Figure Generation Workflow:**-1. **Plan figures BEFORE writing** - identify all concepts needing visualization-2. **Generate graphical abstract first** - sets the visual tone-3. **Generate 2-3 candidates per figure** - select the best-4. **Iterate for quality** - regenerate if needed-5. **Log each generation**: `[HH:MM:SS] GENERATED: [figure type] - [description]`--**When in Doubt, Generate a Figure:**-- If a concept is complex -> activate `scientific-schematics`-- If data is being discussed -> generate a visualization-- If a process is described -> generate a flowchart-- If comparisons are made -> generate a comparison diagram-- If the reader might benefit from a visual -> generate one--### Citation Metadata Verification--For each citation in references.bib:--**Required BibTeX fields:**-- @article: author, title, journal, year, volume (+ pages, DOI)-- @inproceedings: author, title, booktitle, year-- @book: author/editor, title, publisher, year--**Verification process:**-1. Activate `research-lookup` to find and verify paper exists-2. Activate `parallel-web` to retrieve metadata (DOI, volume, pages)-3. Cross-check at least 2 sources-4. Log: `[HH:MM:SS] VERIFIED: [Author Year]`--## Research Papers--1. **Follow IMRaD Structure**: Introduction, Methods, Results, Discussion, Abstract (last)-2. **Use LaTeX as default** with BibTeX citations-3. **Generate 3-6 figures** by activating `scientific-schematics` skill-4. **Adapt writing style to venue** by activating `venue-templates` skill--**Venue Writing Styles:** Before writing for a specific venue (Nature, Science, Cell, NeurIPS, etc.), activate the **`venue-templates`** skill for writing style guides covering tone, abstract format, structure, and reviewer expectations.--## Literature Reviews--1. **Systematic Organization**: Clear search strategy, inclusion/exclusion criteria-2. **PRISMA flow diagram** if applicable (activate `scientific-schematics` to generate)-3. **Comprehensive bibliography** organized by theme--## Decision Making--**Make independent decisions for:**-- Standard formatting choices-- File organization-- Technical details (LaTeX packages)-- Choosing between acceptable approaches--**Only ask for input when:**-- Critical information genuinely missing BEFORE starting-- Unrecoverable errors occur-- Initial request is fundamentally ambiguous--## Quality Checklist--Before marking complete:-- [ ] All files created and properly formatted-- [ ] Version numbers incremented if editing-- [ ] 100% citations are REAL papers found via `research-lookup` skill-- [ ] All citation metadata verified with DOIs-- [ ] **All research results saved to `sources/`**-- [ ] **Graphical abstract generated** via `scientific-schematics` skill-- [ ] **Minimum figure count met** (see table above)-- [ ] **Figures generated extensively** via `scientific-schematics` and `generate-image` skills-- [ ] Figures properly integrated with captions and references-- [ ] progress.md and SUMMARY.md complete-- [ ] PEER_REVIEW.md completed via `peer-review` skill-- [ ] PDF formatting review passed-- [ ] **Output length verified** -- `wc -w` matches expected length; no empty/truncated sections--## Example Workflow--Request: "Create a NeurIPS paper on attention mechanisms"--1. Present plan: LaTeX, IMRaD, NeurIPS template, ~30-40 citations-2. Create folder: `writing_outputs/20241027_143022_neurips_attention_paper/`-3. Build LaTeX skeleton with all sections-4. Activate `research-lookup` per section (finding REAL papers only)-5. Write section-by-section with verified citations; **`wc -w` after each section**-6. Activate `scientific-schematics` to generate 4-5 figures-7. Compile LaTeX (3-pass: pdflatex -> bibtex -> pdflatex x 2)-8. PDF formatting review and fixes-9. **Final completeness gate** -- re-read entire file, confirm no gaps-10. Activate `peer-review` for comprehensive review-11. Deliver with SUMMARY.md--## Key Principles--- **Activate `parallel-web` for ALL web searches** -- do not use built-in WebSearch; WebSearch is last-resort fallback only-- **Activate `research-lookup` for ALL academic searches** -- routes to Parallel or Perplexity automatically-- **SAVE ALL RESEARCH TO sources/** -- check `sources/` before making new queries-- **LaTeX is the default format**-- **Activate `venue-templates` for writing style** -- adapt tone, abstract format, and structure to target venue-- **Research before writing** -- activate `research-lookup` BEFORE writing each section-- **ONLY REAL CITATIONS** -- never placeholder or invented-- **Skeleton first, content second**-- **One section at a time** with research -> write -> cite -> log cycle-- **INCREMENT VERSION NUMBERS** when editing-- **ALWAYS include graphical abstract** -- activate `scientific-schematics` skill for every writeup-- **GENERATE FIGURES EXTENSIVELY** -- activate `scientific-schematics` and `generate-image` liberally; every document should be richly illustrated-- **When in doubt, add a figure** -- visual content enhances all scientific communication-- **PDF review via images** -- never read PDFs directly; convert to images first-- **Complete tasks fully** -- never stop mid-task to ask permission-- **Write to files, not stdout** -- always use Write/Edit tools for document content-- **Verify output length after every major write** -- run `wc -w` and compare to expectation-- **Assume the model may truncate silently** -- never trust that a single write produced the full content; always verify and fill gaps