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
Update research-lookup and statistical-analysis skills
Timothy Kassisafa84b445efc
diff --git a/skills/research-lookup/README.md b/skills/research-lookup/README.mdindex d1a2a899..20a21659 100644--- a/skills/research-lookup/README.md+++ b/skills/research-lookup/README.md@@ -1,156 +1,67 @@# Research Lookup Skill-This skill provides real-time research information lookup using Perplexity's Sonar Pro Search model through OpenRouter.+Real-time research information lookup that routes each query to the backend best suited to it, then saves the result to `sources/` so every citation stays traceable.-## Setup--1. **Get OpenRouter API Key:**- - Visit [openrouter.ai](https://openrouter.ai)- - Create account and generate API key- - Add credits to your account+`SKILL.md` is the authoritative reference for how the skill behaves. This README is a quick human-facing overview.-2. **Configure Environment:**- ```bash- export OPENROUTER_API_KEY="your_api_key_here"- ```+## Backends-3. **Test Setup:**- ```bash- python scripts/research_lookup.py --model-info- ```+| Backend | Speed | Best for | Key |+|---------|-------|----------|-----|+| `parallel-cli search` (default) | 2–10 s | General research, market data, technical lookups, fact-checking | `PARALLEL_API_KEY` |+| Perplexity `sonar-pro-search` | 5–15 s | Scholarly paper searches (papers, DOIs, systematic reviews) | `OPENROUTER_API_KEY` |+| Parallel Chat API (`core`) | 60 s–5 min | Deep, exhaustive multi-source synthesis (on explicit request) | `PARALLEL_API_KEY` |-## Usage+> **Two different "Parallel" things:** `parallel-cli search` is the fast web-search CLI (the default). The Parallel Chat API `core` model is a separate, slow deep-research endpoint reached only through `scripts/research_lookup.py`. `--force-backend parallel` selects the *slow* Chat API.-### Command Line Usage+## Setup```bash-# Single research query-python scripts/research_lookup.py "Recent advances in CRISPR gene editing 2024"+# Install the primary dependency+curl -fsSL https://parallel.ai/install.sh | bash+# or: uv tool install "parallel-web-tools[cli]"-# Multiple queries with delay-python scripts/research_lookup.py --batch "CRISPR applications" "gene therapy trials" "ethical considerations"--# Claude Code integration (called automatically)-python lookup.py "your research query here"+# Authenticate / set keys+parallel-cli auth # or: export PARALLEL_API_KEY="..."+export OPENROUTER_API_KEY="..." # optional, for Perplexity academic search```-### Claude Code Integration--The research lookup tool is automatically available in Claude Code when you:--1. **Ask research questions:** "Research recent advances in quantum computing"-2. **Request literature reviews:** "Find current studies on climate change impacts"-3. **Need citations:** "What are the latest papers on transformer attention mechanisms?"-4. **Want technical information:** "Standard protocols for flow cytometry"--## Features--- **Academic Focus:** Prioritizes peer-reviewed papers and reputable sources-- **Current Information:** Focuses on recent publications (2020-2024)-- **Complete Citations:** Provides full bibliographic information with DOIs-- **Multiple Formats:** Supports various query types and research needs-- **High Search Context:** Always uses high search context for deeper, more comprehensive research-- **Quality Prioritization:** Automatically prioritizes highly-cited papers from top venues-- **Cost Effective:** Typically $0.01-0.05 per research query--## Paper Quality Prioritization--This skill **always prioritizes high-impact, influential papers** over obscure publications. Results are ranked by:--### Citation-Based Ranking--| Paper Age | Citation Threshold | Classification |-|-----------|-------------------|----------------|-| 0-3 years | 20+ citations | Noteworthy |-| 0-3 years | 100+ citations | Highly Influential |-| 3-7 years | 100+ citations | Significant |-| 3-7 years | 500+ citations | Landmark |-| 7+ years | 500+ citations | Seminal |-| 7+ years | 1000+ citations | Foundational |--### Venue Quality Tiers--Papers from higher-tier venues are always preferred:--- **Tier 1 (Highest Priority):** Nature, Science, Cell, NEJM, Lancet, JAMA, PNAS, Nature Medicine, Nature Biotechnology-- **Tier 2 (High Priority):** High-impact journals (IF>10), top conferences (NeurIPS, ICML, ICLR for ML/AI)-- **Tier 3 (Good):** Respected specialized journals (IF 5-10)-- **Tier 4 (Use Sparingly):** Other peer-reviewed venues--### Author Reputation--The skill prefers papers from:-- Senior researchers with high h-index-- Established research groups at recognized institutions-- Authors with multiple publications in Tier-1 venues-- Researchers with recognized expertise (awards, editorial positions)--### Relevance Priority--1. Papers directly addressing the research question-2. Papers with applicable methods/data-3. Tangentially related papers (only from top venues or highly cited)--## Query Examples--### Academic Research-- "Recent systematic reviews on AI in medical diagnosis 2024"-- "Meta-analysis of randomized controlled trials for depression treatment"-- "Current state of quantum computing error correction research"--### Technical Methods-- "Standard protocols for immunohistochemistry in tissue samples"-- "Best practices for machine learning model validation"-- "Statistical methods for analyzing longitudinal data"--### Statistical Data-- "Global renewable energy adoption statistics 2024"-- "Prevalence of diabetes in different populations"-- "Market size for autonomous vehicles industry"--## Response Format--Each research result includes:-- **Summary:** Brief overview of key findings-- **Key Studies:** 3-5 most relevant recent papers-- **Citations:** Complete bibliographic information-- **Usage Stats:** Token usage for cost tracking-- **Timestamp:** When the research was performed--## Integration with Scientific Writing--This skill enhances the scientific writing process by providing:--1. **Literature Reviews:** Current research for introduction sections-2. **Methods Validation:** Verify protocols against current standards-3. **Results Context:** Compare findings with recent similar studies-4. **Discussion Support:** Latest evidence for arguments-5. **Citation Management:** Properly formatted references+## Usage-## Troubleshooting+```bash+# Default: fast web search (save results to sources/)+mkdir -p sources+parallel-cli search "recent advances in CRISPR gene editing 2025" \+ -q "CRISPR" -q "gene editing" --json --max-results 10 \+ -o sources/research_crispr.json++# Academic paper search (Perplexity)+python scripts/research_lookup.py "find papers on CRISPR off-target effects" \+ --force-backend perplexity -o sources/papers_crispr.md++# Deep research (Parallel Chat API — slow, on request only)+python scripts/research_lookup.py "state of quantum error correction" \+ --force-backend parallel -o sources/research_qec.md++# Auto-route between the two API backends+python scripts/research_lookup.py "your query" -o sources/research_topic.md+```-**"API key not found"**-- Ensure `OPENROUTER_API_KEY` environment variable is set-- Check that you have credits in your OpenRouter account+`scripts/research_lookup.py` is also imported by the `market-research-reports` skill, so its CLI stays stable.-**"Model not available"**-- Verify your API key has access to Perplexity models-- Check OpenRouter status page for service issues+## What you get back-**"Rate limit exceeded"**-- Add delays between requests using `--delay` option-- Check your OpenRouter account limits+- **`parallel-cli search`** — JSON with `title`, `url`, `publish_date`, and content `excerpts` per result.+- **Perplexity / Chat API** — a markdown report plus a Sources list and Additional References (DOIs, academic URLs). Add `--json` to `research_lookup.py` for structured citation objects.-**"No relevant results"**-- Try more specific or broader queries-- Include time frames (e.g., "2023-2024")-- Use academic keywords and technical terms+## Notes-## Cost Management+- Save every result to `sources/` — it makes the research reproducible, recoverable after context compaction, and cheap to reuse. Check `sources/` before making a new call.+- When a query is about the literature, prefer highly-cited papers from top-tier venues; note citation counts and venues in-line where known. See the quality guidance in `SKILL.md`.+- Query text is sent to `api.parallel.ai` and, for academic searches, to `openrouter.ai`.-- Monitor usage through OpenRouter dashboard-- Typical costs: $0.01-0.05 per research query-- Batch processing available for multiple queries-- Consider query specificity to optimize token usage+## Related skills-This skill is designed for academic and research purposes, providing high-quality, cited information to support scientific writing and research activities.+- **`parallel-web`** — the full parallel-cli toolkit (search, extract, enrichment, deep research).+- **`citation-management`** — Google Scholar / PubMed search and DOI→BibTeX.+- **`scientific-schematics`** — publication-quality diagrams for research documents.diff --git a/skills/research-lookup/SKILL.md b/skills/research-lookup/SKILL.mdindex 6aab4246..9fc6ca85 100644--- a/skills/research-lookup/SKILL.md+++ b/skills/research-lookup/SKILL.md@@ -1,78 +1,70 @@---name: research-lookup-description: 'Look up current research information using parallel-cli search (primary, fast web search), the Parallel Chat API (deep research), or Perplexity sonar-pro-search (academic paper searches). Automatically routes queries to the best backend. Use for finding papers, gathering research data, and verifying scientific information. Note: query text is transmitted to api.parallel.ai (PARALLEL_API_KEY) and, for academic searches, to openrouter.ai (OPENROUTER_API_KEY).'+description: 'Look up current research and scientific information across three backends: fast web search via parallel-cli (default), the Parallel Chat API for deep multi-source synthesis, and Perplexity sonar-pro-search for scholarly paper searches. Automatically routes each query to the best backend and saves every result to sources/ for reproducible citation. Use this whenever you need to find papers, gather statistics or market data, verify a scientific claim, collect citations, or research any topic for scientific/technical writing — even if the user does not say "research" explicitly. Note: query text is sent to api.parallel.ai (PARALLEL_API_KEY) and, for academic searches, to openrouter.ai (OPENROUTER_API_KEY).'allowed-tools: Read Write Edit Bashlicense: MIT licensecompatibility: parallel-cli required (primary); PARALLEL_API_KEY and OPENROUTER_API_KEY optional for deep/academic backendsrequired_environment_variables: [{"name": "PARALLEL_API_KEY", "prompt": "Parallel web search API key.", "required_for": "optional features"}, {"name": "OPENROUTER_API_KEY", "prompt": "OpenRouter API key (fallback model access).", "required_for": "optional features"}]-metadata: {"version": "1.1", "skill-author": "K-Dense Inc.", "openclaw": {"primaryEnv": "PARALLEL_API_KEY", "envVars": [{"name": "PARALLEL_API_KEY", "required": false, "description": "Parallel web search API key."}, {"name": "OPENROUTER_API_KEY", "required": false, "description": "OpenRouter API key (fallback model access)."}]}}+metadata: {"version": "1.2", "skill-author": "K-Dense Inc.", "openclaw": {"primaryEnv": "PARALLEL_API_KEY", "envVars": [{"name": "PARALLEL_API_KEY", "required": false, "description": "Parallel web search API key."}, {"name": "OPENROUTER_API_KEY", "required": false, "description": "OpenRouter API key (fallback model access)."}]}}---# Research Information Lookup-## Overview+Real-time research lookup that routes each query to the backend best suited to it, then saves the result so every citation can be traced later.-This skill provides real-time research information lookup with **intelligent backend routing**:+## The three backends-- **parallel-cli search** (parallel-web skill): **Primary and default backend** for all research queries. Fast, cost-effective web search with academic source prioritization. Uses `parallel-cli search` with `--include-domains` for scholarly sources.-- **Parallel Chat API** (`core` model): Secondary backend for complex, multi-source deep research requiring extended synthesis (60s-5min latency). Use only when explicitly needed.-- **Perplexity sonar-pro-search** (via OpenRouter): Used only for academic-specific paper searches where scholarly database access is critical.+| Backend | Speed | Use it for | How to call |+|---------|-------|-----------|-------------|+| **`parallel-cli search`** (default) | 2–10 s | Almost everything: general research, market/industry data, technical lookups, current events, fact-checking, comparisons | `parallel-cli search` (direct) |+| **Perplexity sonar-pro-search** | 5–15 s | Scholarly paper searches where peer-reviewed database coverage matters (find papers, DOIs, systematic reviews) | `scripts/research_lookup.py --force-backend perplexity` |+| **Parallel Chat API** (`core` model) | 60 s–5 min | Deep, exhaustive multi-source synthesis — only when the user explicitly asks for "deep research" | `scripts/research_lookup.py --force-backend parallel` |-The skill automatically detects query type and routes to the optimal backend.+> **Naming caution — there are two different "Parallel" things.**+> `parallel-cli search` is the fast web-search CLI (the default). The "Parallel Chat API (`core` model)" is a separate, slow deep-research endpoint reached only through `research_lookup.py`. `--force-backend parallel` selects the *slow* Chat API, **not** the fast CLI. Don't conflate them.-## When to Use This Skill+Default to `parallel-cli search`. It is fast and cheap and handles the large majority of research needs. Reach for the other two only when the query specifically calls for scholarly paper coverage (Perplexity) or exhaustive synthesis (Chat API).-Use this skill when you need:+## When to use this skill-- **Current Research Information**: Latest studies, papers, and findings-- **Literature Verification**: Check facts, statistics, or claims against current research-- **Background Research**: Gather context and supporting evidence for scientific writing-- **Citation Sources**: Find relevant papers and studies to cite-- **Technical Documentation**: Look up specifications, protocols, or methodologies-- **Market/Industry Data**: Current statistics, trends, competitive intelligence-- **Recent Developments**: Emerging trends, breakthroughs, announcements--## Visual Enhancement with Scientific Schematics--**When creating documents with this skill, always consider adding scientific diagrams and schematics to enhance visual communication.**--If your document does not already contain schematics or diagrams:-- Use the **scientific-schematics** skill to generate AI-powered publication-quality diagrams-- Simply describe your desired diagram in natural language--```bash-python scripts/generate_schematic.py "your diagram description" -o figures/output.png-```+- **Current research**: latest studies, findings, and developments+- **Literature verification**: check facts, statistics, or claims against current sources+- **Background research**: gather context and evidence for scientific writing+- **Citations**: find relevant papers and studies to cite+- **Technical documentation**: specifications, protocols, methodologies+- **Market/industry data**: current statistics, trends, competitive intelligence----## Automatic Backend Selection--The skill automatically routes queries to the best backend based on content:--### Routing Logic+## Backend selection```Query arrives|- +-- Contains academic keywords? (papers, DOI, journal, peer-reviewed, etc.)- | YES --> Perplexity sonar-pro-search (academic search mode)+ +-- Asks for papers/DOIs/scholarly review? ("find papers", "cite", "systematic review", ...)+ | --> Perplexity sonar-pro-search (scripts/research_lookup.py --force-backend perplexity)|- +-- Needs deep multi-source synthesis? (user says "deep research", "exhaustive")- | YES --> Parallel Chat API (core model, 60s-5min)+ +-- User explicitly wants deep/exhaustive/comprehensive research?+ | --> Parallel Chat API (core) (scripts/research_lookup.py --force-backend parallel)|- +-- Everything else (general research, market data, technical info, analysis)- --> parallel-cli search (fast, default)+ +-- Everything else (the common case)+ --> parallel-cli search (fast, default)```-### Default: parallel-cli search (parallel-web skill)+`research_lookup.py` applies this same logic automatically when you give it a bare query (no `--force-backend`): it routes academic-keyword queries to Perplexity and everything else to the Parallel Chat API. Use it that way when you want auto-routing between the two API backends; use `parallel-cli search` directly when you want the fast default.-**Primary backend for all standard research queries.** Fast, cost-effective, and supports academic source prioritization.+**Academic keywords that signal a paper search:** `find papers`, `research papers on`, `published studies`, `cite`, `citation`, `doi`, `pubmed`, `pmid`, `peer-reviewed`, `journal article`, `scholarly`, `arxiv`, `preprint`, `systematic review`, `meta-analysis`, `literature search`, `foundational/seminal/landmark papers`, `highly cited`.-For scientific/technical queries, run two searches to ensure academic coverage:+---++## Default backend: `parallel-cli search`++Fast, cost-effective web search with optional academic source prioritization. For scientific or technical topics, run **two** searches — one restricted to scholarly domains, one general — and merge them, leading with the academic sources. This surfaces peer-reviewed work that a general search alone tends to bury. For non-scientific queries, a single general search is enough.```bash-# 1. Academic-focused search+mkdir -p sources # so -o can write here (parallel-cli won't create the dir)++# 1. Academic-focused search (scholarly domains only)parallel-cli search "your research query" -q "keyword1" -q "keyword2" \--json --max-results 10 --excerpt-max-chars-total 27000 \--include-domains "scholar.google.com,arxiv.org,pubmed.ncbi.nlm.nih.gov,semanticscholar.org,biorxiv.org,medrxiv.org,ncbi.nlm.nih.gov,nature.com,science.org,ieee.org,acm.org,springer.com,wiley.com,cell.com,pnas.org,nih.gov" \@@ -84,467 +76,175 @@ parallel-cli search "your research query" -q "keyword1" -q "keyword2" \-o sources/research_<topic>-general.json```-Options:-- `--after-date YYYY-MM-DD` for time-sensitive queries-- `--include-domains domain1.com,domain2.com` to limit to specific sources--Merge results, leading with academic sources. For non-scientific queries, a single general search is sufficient.--All other queries route here by default, including:--- General research questions-- Market and industry analysis-- Technical information and documentation-- Current events and recent developments-- Comparative analysis-- Statistical data retrieval-- Fact-checking and verification--### Academic Keywords (Routes to Perplexity)+Useful flags:+- `--after-date YYYY-MM-DD` — restrict to recent results for time-sensitive queries+- `--include-domains a.com,b.com` — limit to specific sources+- `--max-results N` — how many results to return+- `-o path.json` — save results (always do this; see [Saving results](#saving-results))-Queries containing these terms are routed to Perplexity for academic-focused search:+Saved JSON contains the full result objects — `title`, `url`, `publish_date`, and content `excerpts` — everything needed to cite and to re-read later without re-querying.-- Paper finding: `find papers`, `find articles`, `research papers on`, `published studies`-- Citations: `cite`, `citation`, `doi`, `pubmed`, `pmid`-- Academic sources: `peer-reviewed`, `journal article`, `scholarly`, `arxiv`, `preprint`-- Review types: `systematic review`, `meta-analysis`, `literature search`-- Paper quality: `foundational papers`, `seminal papers`, `landmark papers`, `highly cited`--### Deep Research (Routes to Parallel Chat API)--Only used when the user explicitly requests deep, exhaustive, or comprehensive research. Much slower and more expensive than parallel-cli search.--### Manual Override--You can force a specific backend:+To pull the full text of a specific result, extract it:```bash-# Force parallel-cli search (fast web search)-parallel-cli search "your query" -q "keyword" --json --max-results 10 -o sources/research_<topic>.json--# Force Parallel Deep Research (slow, exhaustive)-python research_lookup.py "your query" --force-backend parallel--# Force Perplexity academic search-python research_lookup.py "your query" --force-backend perplexity+parallel-cli extract "https://example.com/paper" --json```----## Core Capabilities--### 1. General Research Queries (parallel-cli search — DEFAULT)+## Academic paper search: Perplexity sonar-pro-search-**Primary backend.** Fast, cost-effective web search with academic source prioritization via the parallel-web skill.+Use when the query specifically asks for papers, citations, or DOIs. Perplexity searches in academic mode, prioritizing peer-reviewed sources, and returns a summary plus complete citations.-```-Query Examples:-- "Recent advances in CRISPR gene editing 2025"-- "Compare mRNA vaccines vs traditional vaccines for cancer treatment"-- "AI adoption in healthcare industry statistics"-- "Global renewable energy market trends and projections"-- "Explain the mechanism underlying gut microbiome and depression"+```bash+python scripts/research_lookup.py "Find papers on CRISPR off-target effects in clinical trials" \+ --force-backend perplexity \+ -o sources/papers_<topic>.md```-```bash-# Example: research on CRISPR advances-parallel-cli search "Recent advances in CRISPR gene editing 2025" \- -q "CRISPR" -q "gene editing" -q "2025" \- --json --max-results 10 --excerpt-max-chars-total 27000 \- --include-domains "scholar.google.com,arxiv.org,pubmed.ncbi.nlm.nih.gov,nature.com,science.org,cell.com,pnas.org,nih.gov" \- -o sources/research_crispr_advances-academic.json+Returns: a summary of key findings, 5–8 high-quality citations (authors, title, journal, year, DOI when available), citation-count and venue signals where known, and research gaps. Requires `OPENROUTER_API_KEY`.-parallel-cli search "Recent advances in CRISPR gene editing 2025" \- -q "CRISPR" -q "gene editing" \- --json --max-results 10 --excerpt-max-chars-total 27000 \- -o sources/research_crispr_advances-general.json-```+Add `--json` if you need the structured citation objects (`url`, `title`, `date`, `snippet`, `doi`, `type`) for programmatic use such as BibTeX generation.-**Response includes:**-- Synthesized findings with inline citations from search results-- Academic sources prioritized (peer-reviewed, preprints)-- Specific facts, numbers, and dates-- Sources section listing all referenced URLs grouped by type+----### 2. Academic Paper Search (Perplexity sonar-pro-search)+## Deep research: Parallel Chat API (`core` model)-**Used for academic-specific queries.** Prioritizes scholarly databases and peer-reviewed sources. Use when queries specifically ask for papers, citations, or DOIs.+Use **only** when the user explicitly asks for deep, exhaustive, or comprehensive research. It is much slower (60 s–5 min) and more expensive than `parallel-cli search` — never make it the default.+```bash+python scripts/research_lookup.py "current state of quantum computing error correction" \+ --force-backend parallel \+ -o sources/research_<topic>.md```-Query Examples:-- "Find papers on transformer attention mechanisms in NeurIPS 2024"-- "Foundational papers on quantum error correction"-- "Systematic review of immunotherapy in non-small cell lung cancer"-- "Cite the original BERT paper and its most influential follow-ups"-- "Published studies on CRISPR off-target effects in clinical trials"-```--**Response includes:**-- Summary of key findings from academic literature-- 5-8 high-quality citations with authors, titles, journals, years, DOIs-- Citation counts and venue tier indicators-- Key statistics and methodology highlights-- Research gaps and future directions-### 3. Deep Research (Parallel Chat API — on request only)+Returns a comprehensive markdown report with inline citations plus a Sources list (title, URL) and Additional References (DOIs, academic URLs). Requires `PARALLEL_API_KEY`.-**Used only when user explicitly requests deep/exhaustive research.** Provides comprehensive, multi-source synthesis via the Chat API (`core` model). 60s-5min latency.+----```-Query Examples:-- "Deep research on the current state of quantum computing error correction"-- "Exhaustive analysis of mRNA vaccine platforms for cancer immunotherapy"-```+## Prioritizing high-quality papers-### 4. Technical and Methodological Information+When a query is about the literature, favor influential, well-established work over obscure publications — a reader trusts a claim backed by a landmark paper in a top venue far more than one backed by an unvetted source. Use citation counts and venue as the two main quality signals.-Use parallel-cli search (default) for quick lookups:+### Citation thresholds (rough guide)-```bash-parallel-cli search "Western blot protocol for protein detection" \- -q "western blot" -q "protocol" \- --json --max-results 10 --excerpt-max-chars-total 27000 \- -o sources/research_western_blot.json-```+| Paper age | Citations | Classification |+|-----------|-----------|----------------|+| 0–3 years | 20+ | Noteworthy |+| 0–3 years | 100+ | Highly influential |+| 3–7 years | 100+ | Significant |+| 3–7 years | 500+ | Landmark |+| 7+ years | 500+ | Seminal |+| 7+ years | 1000+ | Foundational |-### 5. Statistical and Market Data+### Venue tiers (prefer higher)-Use parallel-cli search (default) for current data:+- **Tier 1 — premier:** Nature, Science, Cell, PNAS; NEJM, Lancet, JAMA, BMJ; Nature Medicine/Biotechnology/Methods; NeurIPS, ICML, ICLR, ACL, CVPR+- **Tier 2 — high-impact specialized:** journals with impact factor > 10; top subfield conferences (EMNLP, NAACL, ECCV, MICCAI)+- **Tier 3 — respected specialized:** journals with impact factor 5–10-```bash-parallel-cli search "Global AI market size and growth projections 2025" \- -q "AI market" -q "statistics" -q "growth" \- --json --max-results 10 --excerpt-max-chars-total 27000 \- --after-date 2024-01-01 \- -o sources/research_ai_market.json-```+These are heuristics, not gates — a directly relevant Tier-3 paper beats a tangential Tier-1 one. When you have the numbers, note them in-line (e.g. "cited 800+ times, Nature 2021") so the reader can judge the evidence themselves.----## Paper Quality and Popularity Prioritization+## Saving results-**CRITICAL**: When searching for papers, ALWAYS prioritize high-quality, influential papers.+Save every research result to the project's `sources/` folder. Research results are expensive to obtain and are the evidence base for every downstream citation, so keeping them makes the work reproducible and cheap to revisit. Concretely, saved results let you:-### Citation-Based Ranking+- **Trace** any claim back to the raw source that supports it (and let a reviewer do the same).+- **Recover** context after compaction — re-read a saved file instead of re-querying.+- **Reuse** one lookup across multiple sections without paying for it again.+- **Skip** redundant calls — check `sources/` before querying (`ls sources/`); if a prior result already covers the topic, read it instead.-| Paper Age | Citation Threshold | Classification |-|-----------|-------------------|----------------|-| 0-3 years | 20+ citations | Noteworthy |-| 0-3 years | 100+ citations | Highly Influential |-| 3-7 years | 100+ citations | Significant |-| 3-7 years | 500+ citations | Landmark Paper |-| 7+ years | 500+ citations | Seminal Work |-| 7+ years | 1000+ citations | Foundational |+Use the `-o` flag on every call. Preserve all citations, URLs, and DOIs in the saved file.-### Venue Quality Tiers+| Backend | Save target | Filename pattern |+|---------|-------------|------------------|+| `parallel-cli search` (default) | `sources/research_<topic>.json` | `research_<topic>-academic.json`, `research_<topic>-general.json` |+| Perplexity (academic) | `sources/papers_<topic>.md` | `papers_<topic>.md` (add `--json` for structured citations) |+| Parallel Chat API (deep) | `sources/research_<topic>.md` | `research_<topic>.md` |-**Tier 1 - Premier Venues** (Always prefer):-- **General Science**: Nature, Science, Cell, PNAS-- **Medicine**: NEJM, Lancet, JAMA, BMJ-- **Field-Specific**: Nature Medicine, Nature Biotechnology, Nature Methods-- **Top CS/AI**: NeurIPS, ICML, ICLR, ACL, CVPR+`research_lookup.py` creates the `sources/` directory automatically. When calling `parallel-cli` directly, run `mkdir -p sources` first — it won't create the directory for you.-**Tier 2 - High-Impact Specialized** (Strong preference):-- Journals with Impact Factor > 10-- Top conferences in subfields (EMNLP, NAACL, ECCV, MICCAI)+When you save a result, log a one-line note so the audit trail is legible, e.g.:-**Tier 3 - Respected Specialized** (Include when relevant):-- Journals with Impact Factor 5-10+```+[14:30:00] SAVED: sources/research_crispr_advances-academic.json (10 results)+[14:30:05] SAVED: sources/papers_transformer_attention.md (6 papers)+```----## Technical Integration+## Setup-### Prerequisites+`parallel-cli` is the primary dependency. If it isn't installed:```bash-# Primary backend (parallel-cli) - REQUIRED-# Install parallel-cli if not already available:curl -fsSL https://parallel.ai/install.sh | bash-# Or: uv tool install "parallel-web-tools[cli]"+# or: uv tool install "parallel-web-tools[cli]"-# Authenticate:-parallel-cli auth-# Or: export PARALLEL_API_KEY="your_parallel_api_key"+parallel-cli auth # or: export PARALLEL_API_KEY="..."```-### Environment Variables+Environment variables:```bash-# Primary backend (parallel-cli search) - REQUIRED-export PARALLEL_API_KEY="your_parallel_api_key"--# Deep research backend (Parallel Chat API) - optional, for deep research only-# Uses the same PARALLEL_API_KEY--# Academic search backend (Perplexity) - optional, for academic paper queries-export OPENROUTER_API_KEY="your_openrouter_api_key"+export PARALLEL_API_KEY="..." # parallel-cli search AND the Parallel Chat API (deep research)+export OPENROUTER_API_KEY="..." # Perplexity academic search (optional)```-### API Specifications--**parallel-cli search (PRIMARY):**-- Command: `parallel-cli search` with `--json` output-- Latency: 2-10 seconds (fast)-- Output: JSON with title, URL, publish_date, excerpts-- Academic domains: Use `--include-domains` for scholarly sources-- Saves results: `-o filename.json` for follow-up and reproducibility--**Parallel Chat API (deep research only):**-- Endpoint: `https://api.parallel.ai` (OpenAI SDK compatible)-- Model: `core` (60s-5min latency, complex multi-source synthesis)-- Output: Markdown text with inline citations-- Citations: Research basis with URLs, reasoning, and confidence levels-- Rate limits: 300 req/min-- Python package: `openai`--**Perplexity sonar-pro-search (academic only):**-- Model: `perplexity/sonar-pro-search` (via OpenRouter)-- Search mode: Academic (prioritizes peer-reviewed sources)-- Search context: High (comprehensive research)-- Response time: 5-15 seconds+----### Command-Line Usage+## Command reference```bash-# Fast web search via parallel-cli (DEFAULT — recommended) — ALWAYS save to sources/-parallel-cli search "your query" -q "keyword1" -q "keyword2" \+# Fast web search (DEFAULT) — always save to sources/+parallel-cli search "query" -q "kw1" -q "kw2" \--json --max-results 10 --excerpt-max-chars-total 27000 \-o sources/research_<topic>.json-# Academic-focused search via parallel-cli — ALWAYS save to sources/-parallel-cli search "your query" -q "keyword1" \+# Academic-focused variant (add scholarly domains)+parallel-cli search "query" -q "kw1" \--json --max-results 10 --excerpt-max-chars-total 27000 \- --include-domains "scholar.google.com,arxiv.org,pubmed.ncbi.nlm.nih.gov,semanticscholar.org,biorxiv.org,medrxiv.org,nature.com,science.org,cell.com,pnas.org,nih.gov" \+ --include-domains "arxiv.org,pubmed.ncbi.nlm.nih.gov,nature.com,science.org,cell.com,pnas.org,nih.gov" \-o sources/research_<topic>-academic.json-# Time-sensitive search via parallel-cli-parallel-cli search "your query" -q "keyword" \- --json --max-results 10 --after-date 2024-01-01 \+# Time-sensitive+parallel-cli search "query" -q "kw" --json --max-results 10 --after-date 2024-01-01 \-o sources/research_<topic>.json-# Extract full content from a specific URL (use parallel-web extract)+# Extract full text from a URLparallel-cli extract "https://example.com/paper" --json-# Force Parallel Deep Research (slow, exhaustive) — via research_lookup.py-python research_lookup.py "your query" --force-backend parallel -o sources/research_<topic>.md--# Force Perplexity academic search — via research_lookup.py-python research_lookup.py "your query" --force-backend perplexity -o sources/papers_<topic>.md--# Auto-routed via research_lookup.py (legacy) — ALWAYS save to sources/-python research_lookup.py "your query" -o sources/research_YYYYMMDD_HHMMSS_<topic>.md--# Batch queries via research_lookup.py — ALWAYS save to sources/-python research_lookup.py --batch "query 1" "query 2" "query 3" -o sources/batch_research_<topic>.md-```-------## MANDATORY: Save All Results to Sources Folder--**Every research-lookup result MUST be saved to the project's `sources/` folder.**--This is non-negotiable. Research results are expensive to obtain and critical for reproducibility.--### Saving Rules--| Backend | `-o` Flag Target | Filename Pattern |-|---------|-----------------|------------------|-| parallel-cli search (default) | `sources/research_<topic>.json` | `research_<brief_topic>.json` or `research_<brief_topic>-academic.json` |-| Parallel Deep Research | `sources/research_<topic>.md` | `research_YYYYMMDD_HHMMSS_<brief_topic>.md` |-| Perplexity (academic) | `sources/papers_<topic>.md` | `papers_YYYYMMDD_HHMMSS_<brief_topic>.md` |-| Batch queries | `sources/batch_<topic>.md` | `batch_research_YYYYMMDD_HHMMSS_<brief_topic>.md` |--### How to Save+# Academic paper search (Perplexity)+python scripts/research_lookup.py "find papers on <topic>" --force-backend perplexity \+ -o sources/papers_<topic>.md-**CRITICAL: Every search MUST save results to the `sources/` folder using the `-o` flag.**+# Deep research (Parallel Chat API, slow/expensive — on request only)+python scripts/research_lookup.py "deep dive on <topic>" --force-backend parallel \+ -o sources/research_<topic>.md-**CRITICAL: Saved files MUST preserve all citations, source URLs, and DOIs.**--```bash-# parallel-cli search (DEFAULT) — save JSON to sources/-parallel-cli search "Recent advances in CRISPR gene editing 2025" \- -q "CRISPR" -q "gene editing" \- --json --max-results 10 --excerpt-max-chars-total 27000 \- --include-domains "scholar.google.com,arxiv.org,pubmed.ncbi.nlm.nih.gov,nature.com,science.org,cell.com,pnas.org,nih.gov" \- -o sources/research_crispr_advances-academic.json--parallel-cli search "Recent advances in CRISPR gene editing 2025" \- -q "CRISPR" -q "gene editing" \- --json --max-results 10 --excerpt-max-chars-total 27000 \- -o sources/research_crispr_advances-general.json--# Academic paper search via Perplexity — save to sources/-python research_lookup.py "Find papers on transformer attention mechanisms in NeurIPS 2024" \- -o sources/papers_20250217_143500_transformer_attention.md--# Deep research via Parallel Chat API — save to sources/-python research_lookup.py "AI regulation landscape" --force-backend parallel \- -o sources/research_20250217_144000_ai_regulation.md--# Batch queries — save to sources/-python research_lookup.py --batch "mRNA vaccines efficacy" "mRNA vaccines safety" \- -o sources/batch_research_20250217_144500_mrna_vaccines.md-```--### Citation Preservation in Saved Files--Each output format preserves citations differently:--| Format | Citations Included | When to Use |-|--------|-------------------|-------------|-| parallel-cli JSON (default) | Full result objects: `title`, `url`, `publish_date`, `excerpts` | Standard use — structured, parseable, fast |-| Text (research_lookup.py) | `Sources (N):` section with `[title] (date) + URL` + `Additional References (N):` with DOIs and academic URLs | Deep research / Perplexity — human-readable |-| JSON (`--json` via research_lookup.py) | Full citation objects: `url`, `title`, `date`, `snippet`, `doi`, `type` | When you need maximum citation metadata from deep research |--**For parallel-cli search**, saved JSON files include: full search results with title, URL, publish date, and content excerpts for each result.-**For Parallel Chat API backend**, saved files include: research report + Sources list (title, URL) + Additional References (DOIs, academic URLs).-**For Perplexity backend**, saved files include: academic summary + Sources list (title, date, URL, snippet) + Additional References (DOIs, academic URLs).--**Use `--json` when you need to:**-- Parse citation metadata programmatically-- Preserve full DOI and URL data for BibTeX generation-- Maintain the structured citation objects for cross-referencing--### Why Save Everything--1. **Reproducibility**: Every citation and claim can be traced back to its raw research source-2. **Context Window Recovery**: If context is compacted, saved results can be re-read without re-querying-3. **Audit Trail**: The `sources/` folder documents exactly how all research information was gathered-4. **Reuse Across Sections**: Multiple sections can reference the same saved research without duplicate queries-5. **Cost Efficiency**: Check `sources/` for existing results before making new API calls-6. **Peer Review Support**: Reviewers can verify the research backing every citation--### Before Making a New Query, Check Sources First--Before calling `research_lookup.py`, check if a relevant result already exists:--```bash-ls sources/ # Check existing saved results-```--If a prior lookup covers the same topic, re-read the saved file instead of making a new API call.--### Logging--When saving research results, always log:+# Auto-route between the two API backends (academic->Perplexity, else->Chat API)+python scripts/research_lookup.py "query" -o sources/research_<topic>.md-```-[HH:MM:SS] SAVED: Research lookup to sources/research_20250217_143000_crispr_advances.md (3,800 words, 8 citations)-[HH:MM:SS] SAVED: Paper search to sources/papers_20250217_143500_transformer_attention.md (6 papers found)+# Batch several queries through the API backends+python scripts/research_lookup.py --batch "query 1" "query 2" -o sources/batch_<topic>.md```----## Integration with Scientific Writing--This skill enhances scientific writing by providing:--1. **Literature Review Support**: Gather current research for introduction and discussion — **save to `sources/`**-2. **Methods Validation**: Verify protocols against current standards — **save to `sources/`**-3. **Results Contextualization**: Compare findings with recent similar studies — **save to `sources/`**-4. **Discussion Enhancement**: Support arguments with latest evidence — **save to `sources/`**-5. **Citation Management**: Provide properly formatted citations — **save to `sources/`**--## Complementary Tools+## Related skills-| Task | Tool |-|------|------|-| General web search (fast) | `parallel-cli search` (built into this skill) |-| Academic-focused web search | `parallel-cli search --include-domains` (built into this skill) |-| URL content extraction | `parallel-cli extract` (parallel-web skill) |-| Deep research (exhaustive) | `research-lookup` via Parallel Chat API or `parallel-web` deep research |-| Academic paper search | `research-lookup` (auto-routes to Perplexity) |-| Google Scholar search | `citation-management` skill |-| PubMed search | `citation-management` skill |-| DOI to BibTeX | `citation-management` skill |-| Metadata verification | `parallel-cli extract` (parallel-web skill) |+- **`parallel-web`** — the full parallel-cli toolkit (search, extract, data enrichment, deep research) with more options than the essentials shown here. Reach for it for enrichment jobs or advanced extraction.+- **`citation-management`** — Google Scholar / PubMed search and DOI→BibTeX conversion. Use it to turn the DOIs and URLs found here into formatted references.+- **`scientific-schematics`** — generate publication-quality diagrams. If a research document would be clearer with a figure, hand off to this skill rather than embedding image-generation here.----## Error Handling and Limitations--**Known Limitations:**-- parallel-cli search: Requires `parallel-cli` to be installed and authenticated-- Parallel Chat API (core model): Complex queries may take up to 5 minutes-- Perplexity: Information cutoff, may not access full text behind paywalls-- All backends: Cannot access proprietary or restricted databases--**Fallback Behavior:**-- If `parallel-cli` is not found, install with `curl -fsSL https://parallel.ai/install.sh | bash` or `uv tool install "parallel-web-tools[cli]"`-- If parallel-cli search returns insufficient results, fall back to Perplexity or Parallel Chat API-- If the selected backend's API key is missing, tries the other backend-- If all backends fail, returns structured error response-- Rephrase queries for better results if initial response is insufficient-------## Usage Examples--### Example 1: General Research (Routes to parallel-cli search)--**Query**: "Recent advances in transformer attention mechanisms 2025"--**Backend**: parallel-cli search (default, fast)--**Commands**:-```bash-parallel-cli search "Recent advances in transformer attention mechanisms 2025" \- -q "transformer" -q "attention" -q "2025" \- --json --max-results 10 --excerpt-max-chars-total 27000 \- --include-domains "arxiv.org,semanticscholar.org,nature.com,science.org,ieee.org,acm.org" \- -o sources/research_transformer_attention-academic.json--parallel-cli search "Recent advances in transformer attention mechanisms 2025" \- -q "transformer" -q "attention" \- --json --max-results 10 --excerpt-max-chars-total 27000 \- -o sources/research_transformer_attention-general.json-```--**Response**: Synthesized findings with inline citations from academic and general sources, covering recent papers, key innovations, and performance benchmarks.--### Example 2: Academic Paper Search (Routes to Perplexity)--**Query**: "Find papers on CRISPR off-target effects in clinical trials"--**Backend**: Perplexity sonar-pro-search (academic mode)--**Response**: Curated list of 5-8 high-impact papers with full citations, DOIs, citation counts, and venue tier indicators.--### Example 3: Comparative Analysis (Routes to parallel-cli search)--**Query**: "Compare and contrast mRNA vaccines vs traditional vaccines for cancer treatment"--**Backend**: parallel-cli search (default, fast)--**Response**: Synthesized comparison from multiple web sources with inline citations, structured analysis, and evidence quality notes.--### Example 4: Market Data (Routes to parallel-cli search)--**Query**: "Global AI adoption in healthcare statistics 2025"--**Backend**: parallel-cli search (default, fast)--```bash-parallel-cli search "Global AI adoption in healthcare statistics 2025" \- -q "AI healthcare" -q "adoption statistics" \- --json --max-results 10 --excerpt-max-chars-total 27000 \- --after-date 2024-01-01 \- -o sources/research_ai_healthcare_adoption.json-```--**Response**: Current market data, adoption rates, growth projections, and regional analysis with source citations.-------## Summary--This skill serves as the primary research interface with intelligent tri-backend routing:+## Errors and limitations-- **parallel-cli search** (default): Fast, cost-effective web search with academic source prioritization via the parallel-web skill-- **Parallel Chat API** (`core` model): Deep, exhaustive multi-source synthesis (on explicit request only)-- **Perplexity sonar-pro-search**: Academic-specific paper searches only-- **Automatic routing**: Detects query type and routes to the optimal backend-- **Manual override**: Force any backend when needed-- **Academic prioritization**: Two-search pattern ensures scholarly sources surface for scientific queries+- **`parallel-cli` not found** — install it (see [Setup](#setup)).+- **Missing API key** — `parallel-cli search` and the Chat API need `PARALLEL_API_KEY`; Perplexity needs `OPENROUTER_API_KEY`. `research_lookup.py` reports clearly if none is set and, when auto-routing, falls back to whichever backend has a key.+- **Deep research is slow** — the Chat API `core` model can take up to 5 minutes; expect it and don't use it for quick lookups.+- **Paywalls / restricted data** — none of the backends can read proprietary databases or full text behind paywalls.+- **Weak results** — rephrase with more specific terms or a date range, or try a different backend before giving up.diff --git a/skills/research-lookup/examples.py b/skills/research-lookup/examples.pydeleted file mode 100644index 669eacee..00000000--- a/skills/research-lookup/examples.py+++ /dev/null@@ -1,174 +0,0 @@-#!/usr/bin/env python3-"""-Example usage of the Research Lookup skill with automatic model selection.--This script demonstrates:-1. Automatic model selection based on query complexity-2. Manual model override options-3. Batch query processing-4. Integration with scientific writing workflows-"""--import os-from research_lookup import ResearchLookup---def example_automatic_selection():- """Demonstrate automatic model selection."""- print("=" * 80)- print("EXAMPLE 1: Automatic Model Selection")- print("=" * 80)- print()-- research = ResearchLookup()-- # Simple lookup - will use Sonar Pro Search- query1 = "Recent advances in CRISPR gene editing 2024"- print(f"Query: {query1}")- print(f"Expected model: Sonar Pro Search (fast lookup)")- result1 = research.lookup(query1)- print(f"Actual model: {result1.get('model')}")- print()-- # Complex analysis - will use Sonar Reasoning Pro- query2 = "Compare and contrast the efficacy of mRNA vaccines versus traditional vaccines"- print(f"Query: {query2}")- print(f"Expected model: Sonar Reasoning Pro (analytical)")- result2 = research.lookup(query2)- print(f"Actual model: {result2.get('model')}")- print()---def example_manual_override():- """Demonstrate manual model override."""- print("=" * 80)- print("EXAMPLE 2: Manual Model Override")- print("=" * 80)- print()-- # Force Sonar Pro Search for budget-constrained rapid lookup- research_pro = ResearchLookup(force_model='pro')- query = "Explain the mechanism of CRISPR-Cas9"- print(f"Query: {query}")- print(f"Forced model: Sonar Pro Search")- result = research_pro.lookup(query)- print(f"Model used: {result.get('model')}")- print()-- # Force Sonar Reasoning Pro for critical analysis- research_reasoning = ResearchLookup(force_model='reasoning')- print(f"Query: {query}")- print(f"Forced model: Sonar Reasoning Pro")- result = research_reasoning.lookup(query)- print(f"Model used: {result.get('model')}")- print()---def example_batch_queries():- """Demonstrate batch query processing."""- print("=" * 80)- print("EXAMPLE 3: Batch Query Processing")- print("=" * 80)- print()-- research = ResearchLookup()-- # Mix of simple and complex queries- queries = [- "Recent clinical trials for Alzheimer's disease", # Sonar Pro Search- "Compare deep learning vs traditional ML in drug discovery", # Sonar Reasoning Pro- "Statistical power analysis methods", # Sonar Pro Search- ]-- print("Processing batch queries...")- print("Each query will automatically select the appropriate model")- print()-- results = research.batch_lookup(queries, delay=1.0)-- for i, result in enumerate(results):- print(f"Query {i+1}: {result['query'][:50]}...")- print(f" Model: {result.get('model')}")- print(f" Type: {result.get('model_type')}")- print()---def example_scientific_writing_workflow():- """Demonstrate integration with scientific writing workflow."""- print("=" * 80)- print("EXAMPLE 4: Scientific Writing Workflow")- print("=" * 80)- print()-- research = ResearchLookup()-- # Literature review phase - use Pro for breadth- print("PHASE 1: Literature Review (Breadth)")- lit_queries = [- "Recent papers on machine learning in genomics 2024",- "Clinical applications of AI in radiology",- "RNA sequencing analysis methods"- ]-- for query in lit_queries:- print(f" - {query}")- # These will automatically use Sonar Pro Search- print()-- # Discussion phase - use Reasoning Pro for synthesis- print("PHASE 2: Discussion (Synthesis & Analysis)")- discussion_queries = [- "Compare the advantages and limitations of different ML approaches in genomics",- "Explain the relationship between model interpretability and clinical adoption",- "Analyze the ethical implications of AI in medical diagnosis"- ]-- for query in discussion_queries:- print(f" - {query}")- # These will automatically use Sonar Reasoning Pro- print()---def main():- """Run all examples (requires OPENROUTER_API_KEY to be set)."""-- if not os.getenv("OPENROUTER_API_KEY"):- print("Note: Set OPENROUTER_API_KEY environment variable to run live queries")- print("These examples show the structure without making actual API calls")- print()-- # Uncomment to run examples (requires API key)- # example_automatic_selection()- # example_manual_override()- # example_batch_queries()- # example_scientific_writing_workflow()-- # Show complexity assessment without API calls- print("=" * 80)- print("COMPLEXITY ASSESSMENT EXAMPLES (No API calls required)")- print("=" * 80)- print()-- os.environ.setdefault("OPENROUTER_API_KEY", "test")- research = ResearchLookup()-- test_queries = [- ("Recent CRISPR studies", "pro"),- ("Compare CRISPR vs TALENs", "reasoning"),- ("Explain how CRISPR works", "reasoning"),- ("Western blot protocol", "pro"),- ("Pros and cons of different sequencing methods", "reasoning"),- ]-- for query, expected in test_queries:- complexity = research._assess_query_complexity(query)- model_name = "Sonar Reasoning Pro" if complexity == "reasoning" else "Sonar Pro Search"- status = "✓" if complexity == expected else "✗"- print(f"{status} '{query}'")- print(f" → {model_name}")- print()---if __name__ == "__main__":- main()-diff --git a/skills/research-lookup/lookup.py b/skills/research-lookup/lookup.pydeleted file mode 100755index 85452a2a..00000000--- a/skills/research-lookup/lookup.py+++ /dev/null@@ -1,187 +0,0 @@-#!/usr/bin/env python3-"""-Research Lookup Tool for Claude Code-Performs research queries using Perplexity Sonar Pro Search via OpenRouter.-"""--import os-import sys-import json-from typing import Dict, List, Optional--# Import the main research lookup class-sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'scripts'))-from research_lookup import ResearchLookup---def format_response(result: Dict) -> str:- """Format the research result for display."""- if not result["success"]:- return f"❌ Research lookup failed: {result['error']}"-- response = result["response"]- citations = result["citations"]- sources = result.get("sources", [])-- # Format the output for Claude Code- output = f"""🔍 **Research Results**--**Query:** {result['query']}-**Model:** {result['model']}-**Timestamp:** {result['timestamp']}-**Note:** Results prioritized by citation count, venue prestige, and author reputation-------{response}--"""-- # Display API-provided sources with venue/citation info- if sources:- output += f"\n📚 **Sources ({len(sources)}):**\n"- output += "_Prioritized by venue quality and citation impact_\n\n"- for i, source in enumerate(sources, 1):- title = source.get("title", "Untitled")- url = source.get("url", "")- date = source.get("date", "")- snippet = source.get("snippet", "")-- # Format source entry with available metadata- date_str = f" ({date})" if date else ""- output += f"{i}. **{title}**{date_str}\n"-- # Add venue indicator if detectable from URL- venue_indicator = _detect_venue_tier(url)- if venue_indicator:- output += f" 📊 Venue: {venue_indicator}\n"-- if url:- output += f" 🔗 {url}\n"- if snippet:- output += f" _{snippet[:150]}{'...' if len(snippet) > 150 else ''}_\n"- output += "\n"-- # Display extracted citations (DOIs, etc.)- if citations:- doi_citations = [c for c in citations if c.get("type") == "doi"]- url_citations = [c for c in citations if c.get("type") == "url"]-- if doi_citations:- output += f"\n🔗 **DOI References ({len(doi_citations)}):**\n"- for i, citation in enumerate(doi_citations, 1):- output += f"{i}. DOI: {citation.get('doi', '')} → {citation.get('url', '')}\n"-- if url_citations:- output += f"\n🌐 **Additional URLs ({len(url_citations)}):**\n"- for i, citation in enumerate(url_citations, 1):- url = citation.get('url', '')- venue = _detect_venue_tier(url)- venue_str = f" [{venue}]" if venue else ""- output += f"{i}. {url}{venue_str}\n"-- if result.get("usage"):- usage = result["usage"]- output += f"\n**Usage:** {usage.get('total_tokens', 'N/A')} tokens"-- return output---def _detect_venue_tier(url: str) -> Optional[str]:- """Detect venue tier from URL to indicate source quality."""- if not url:- return None-- url_lower = url.lower()-- # Tier 1 - Premier venues- tier1_indicators = {- "nature.com": "Nature (Tier 1)",- "science.org": "Science (Tier 1)",- "cell.com": "Cell Press (Tier 1)",- "nejm.org": "NEJM (Tier 1)",- "thelancet.com": "Lancet (Tier 1)",- "jamanetwork.com": "JAMA (Tier 1)",- "pnas.org": "PNAS (Tier 1)",- }-- # Tier 2 - High-impact specialized- tier2_indicators = {- "neurips.cc": "NeurIPS (Tier 2 - Top ML)",- "icml.cc": "ICML (Tier 2 - Top ML)",- "openreview.net": "Top ML Conference (Tier 2)",- "aacrjournals.org": "AACR Journals (Tier 2)",- "ahajournals.org": "AHA Journals (Tier 2)",- "bloodjournal.org": "Blood (Tier 2)",- "jci.org": "JCI (Tier 2)",- }-- # Tier 3 - Respected academic sources- tier3_indicators = {- "springer.com": "Springer",- "wiley.com": "Wiley",- "elsevier.com": "Elsevier",- "oup.com": "Oxford University Press",- "arxiv.org": "arXiv (Preprint)",- "biorxiv.org": "bioRxiv (Preprint)",- "medrxiv.org": "medRxiv (Preprint)",- "pubmed": "PubMed",- "ncbi.nlm.nih.gov": "NCBI/PubMed",- "ieee.org": "IEEE",- "acm.org": "ACM",- }-- for domain, label in tier1_indicators.items():- if domain in url_lower:- return label-- for domain, label in tier2_indicators.items():- if domain in url_lower:- return label-- for domain, label in tier3_indicators.items():- if domain in url_lower:- return label-- return None---def main():- """Main entry point for Claude Code tool."""- # Check for API key- if not os.getenv("OPENROUTER_API_KEY"):- print("❌ Error: OPENROUTER_API_KEY environment variable not set")- print("Please set it in your .env file or export it:")- print(" export OPENROUTER_API_KEY='your_openrouter_api_key'")- return 1-- # Get query from command line arguments- if len(sys.argv) < 2:- print("❌ Error: No query provided")- print("Usage: python lookup.py 'your research query here'")- return 1-- query = " ".join(sys.argv[1:])-- try:- # Initialize research tool- research = ResearchLookup()-- # Perform lookup- print(f"🔍 Researching: {query}")- result = research.lookup(query)-- # Format and output result- formatted_output = format_response(result)- print(formatted_output)-- # Return success code- return 0 if result["success"] else 1-- except Exception as e:- print(f"❌ Error: {str(e)}")- return 1---if __name__ == "__main__":- exit(main())diff --git a/skills/research-lookup/research_lookup.py b/skills/research-lookup/research_lookup.pydeleted file mode 100644index dc86938b..00000000--- a/skills/research-lookup/research_lookup.py+++ /dev/null@@ -1,566 +0,0 @@-#!/usr/bin/env python3-"""-Research Information Lookup Tool--Routes research queries to the best backend:- - Parallel Chat API (core model): Default for all general research queries- - Perplexity sonar-pro-search (via OpenRouter): Academic-specific paper searches--Environment variables:- PARALLEL_API_KEY - Required for Parallel Chat API (primary backend)- OPENROUTER_API_KEY - Required for Perplexity academic searches (fallback)-"""--import os-import sys-import json-import re-import time-import requests-from datetime import datetime-from typing import Any, Dict, List, Optional---class ResearchLookup:- """Research information lookup with intelligent backend routing.-- Routes queries to the Parallel Chat API (default) or Perplexity- sonar-pro-search (academic paper searches only).- """-- ACADEMIC_KEYWORDS = [- "find papers", "find paper", "find articles", "find article",- "cite ", "citation", "citations for",- "doi ", "doi:", "pubmed", "pmid",- "journal article", "peer-reviewed",- "systematic review", "meta-analysis",- "literature search", "literature on",- "academic papers", "academic paper",- "research papers on", "research paper on",- "published studies", "published study",- "scholarly", "scholar",- "arxiv", "preprint",- "foundational papers", "seminal papers", "landmark papers",- "highly cited", "most cited",- ]-- PARALLEL_SYSTEM_PROMPT = (- "You are a deep research analyst. Provide a comprehensive, well-cited "- "research report on the user's topic. Include:\n"- "- Key findings with specific data, statistics, and quantitative evidence\n"- "- Detailed analysis organized by themes\n"- "- Multiple authoritative sources cited inline\n"- "- Methodologies and implications where relevant\n"- "- Future outlook and research gaps\n"- "Use markdown formatting with clear section headers. "- "Prioritize authoritative and recent sources."- )-- CHAT_BASE_URL = "https://api.parallel.ai"-- def __init__(self, force_backend: Optional[str] = None):- """Initialize the research lookup tool.-- Args:- force_backend: Force a specific backend ('parallel' or 'perplexity').- If None, backend is auto-selected based on query content.- """- self.force_backend = force_backend- self.parallel_available = bool(os.getenv("PARALLEL_API_KEY"))- self.perplexity_available = bool(os.getenv("OPENROUTER_API_KEY"))-- if not self.parallel_available and not self.perplexity_available:- raise ValueError(- "No API keys found. Set at least one of:\n"- " PARALLEL_API_KEY (for Parallel Chat API - primary)\n"- " OPENROUTER_API_KEY (for Perplexity academic search - fallback)"- )-- def _select_backend(self, query: str) -> str:- """Select the best backend for a query."""- if self.force_backend:- if self.force_backend == "perplexity" and self.perplexity_available:- return "perplexity"- if self.force_backend == "parallel" and self.parallel_available:- return "parallel"-- query_lower = query.lower()- is_academic = any(kw in query_lower for kw in self.ACADEMIC_KEYWORDS)-- if is_academic and self.perplexity_available:- return "perplexity"-- if self.parallel_available:- return "parallel"-- if self.perplexity_available:- return "perplexity"-- raise ValueError("No backend available. Check API keys.")-- # ------------------------------------------------------------------- # Parallel Chat API backend- # -------------------------------------------------------------------- def _get_chat_client(self):- """Lazy-load and cache the OpenAI client for Parallel Chat API."""- if not hasattr(self, "_chat_client"):- try:- from openai import OpenAI- except ImportError:- raise ImportError(- "The 'openai' package is required for Parallel Chat API.\n"- "Install it with: pip install openai"- )- self._chat_client = OpenAI(- api_key=os.getenv("PARALLEL_API_KEY"),- base_url=self.CHAT_BASE_URL,- )- return self._chat_client-- def _parallel_lookup(self, query: str) -> Dict[str, Any]:- """Run research via the Parallel Chat API (core model)."""- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")- model = "core"-- try:- client = self._get_chat_client()-- print(f"[Research] Parallel Chat API (model={model})...", file=sys.stderr)-- response = client.chat.completions.create(- model=model,- messages=[- {"role": "system", "content": self.PARALLEL_SYSTEM_PROMPT},- {"role": "user", "content": query},- ],- stream=False,- )-- content = ""- if response.choices and len(response.choices) > 0:- content = response.choices[0].message.content or ""-- api_citations = self._extract_basis_citations(response)- text_citations = self._extract_citations_from_text(content)-- return {- "success": True,- "query": query,- "response": content,- "citations": api_citations + text_citations,- "sources": api_citations,- "timestamp": timestamp,- "backend": "parallel",- "model": f"parallel-chat/{model}",- }-- except Exception as e:- return {- "success": False,- "query": query,- "error": str(e),- "timestamp": timestamp,- "backend": "parallel",- "model": f"parallel-chat/{model}",- }-- def _extract_basis_citations(self, response) -> List[Dict[str, str]]:- """Extract citation sources from the Chat API research basis."""- citations = []- basis = getattr(response, "basis", None)- if not basis:- return citations-- seen_urls = set()- if isinstance(basis, list):- for item in basis:- cits = (- item.get("citations", []) if isinstance(item, dict)- else getattr(item, "citations", None) or []- )- for cit in cits:- url = cit.get("url", "") if isinstance(cit, dict) else getattr(cit, "url", "")- if url and url not in seen_urls:- seen_urls.add(url)- title = cit.get("title", "") if isinstance(cit, dict) else getattr(cit, "title", "")- excerpts = cit.get("excerpts", []) if isinstance(cit, dict) else getattr(cit, "excerpts", [])- citations.append({- "type": "source",- "url": url,- "title": title,- "excerpts": excerpts,- })-- return citations-- # ------------------------------------------------------------------- # Perplexity academic search backend- # -------------------------------------------------------------------- def _perplexity_lookup(self, query: str) -> Dict[str, Any]:- """Run academic search via Perplexity sonar-pro-search through OpenRouter."""- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")-- api_key = os.getenv("OPENROUTER_API_KEY")- model = "perplexity/sonar-pro-search"-- headers = {- "Authorization": f"Bearer {api_key}",- "Content-Type": "application/json",- "HTTP-Referer": "https://scientific-writer.local",- "X-Title": "Scientific Writer Research Tool",- }-- research_prompt = self._format_academic_prompt(query)-- messages = [- {- "role": "system",- "content": (- "You are an academic research assistant specializing in finding "- "HIGH-IMPACT, INFLUENTIAL research.\n\n"- "QUALITY PRIORITIZATION (CRITICAL):\n"- "- ALWAYS prefer highly-cited papers over obscure publications\n"- "- ALWAYS prioritize Tier-1 venues: Nature, Science, Cell, NEJM, Lancet, JAMA, PNAS\n"- "- ALWAYS prefer papers from established researchers\n"- "- Include citation counts when known (e.g., 'cited 500+ times')\n"- "- Quality matters more than quantity\n\n"- "VENUE HIERARCHY:\n"- "1. Nature/Science/Cell family, NEJM, Lancet, JAMA (highest)\n"- "2. High-impact specialized journals (IF>10), top conferences (NeurIPS, ICML, ICLR)\n"- "3. Respected field-specific journals (IF 5-10)\n"- "4. Other peer-reviewed sources (only if no better option)\n\n"- "Focus exclusively on scholarly sources. Prioritize recent literature (2020-2026) "- "and provide complete citations with DOIs."- ),- },- {"role": "user", "content": research_prompt},- ]-- data = {- "model": model,- "messages": messages,- "max_tokens": 8000,- "temperature": 0.1,- "search_mode": "academic",- "search_context_size": "high",- }-- try:- response = requests.post(- "https://openrouter.ai/api/v1/chat/completions",- headers=headers,- json=data,- timeout=90,- )- response.raise_for_status()- resp_json = response.json()-- if "choices" in resp_json and len(resp_json["choices"]) > 0:- choice = resp_json["choices"][0]- if "message" in choice and "content" in choice["message"]:- content = choice["message"]["content"]-- api_citations = self._extract_api_citations(resp_json, choice)- text_citations = self._extract_citations_from_text(content)- citations = api_citations + text_citations-- return {- "success": True,- "query": query,- "response": content,- "citations": citations,- "sources": api_citations,- "timestamp": timestamp,- "backend": "perplexity",- "model": model,- "usage": resp_json.get("usage", {}),- }- else:- raise Exception("Invalid response format from API")- else:- raise Exception("No response choices received from API")-- except Exception as e:- return {- "success": False,- "query": query,- "error": str(e),- "timestamp": timestamp,- "backend": "perplexity",- "model": model,- }-- # ------------------------------------------------------------------- # Shared utilities- # -------------------------------------------------------------------- def _format_academic_prompt(self, query: str) -> str:- """Format a query for academic research results via Perplexity."""- return f"""You are an expert research assistant. Please provide comprehensive, accurate research information for the following query: "{query}"--IMPORTANT INSTRUCTIONS:-1. Focus on ACADEMIC and SCIENTIFIC sources (peer-reviewed papers, reputable journals, institutional research)-2. Include RECENT information (prioritize 2020-2026 publications)-3. Provide COMPLETE citations with authors, title, journal/conference, year, and DOI when available-4. Structure your response with clear sections and proper attribution-5. Be comprehensive but concise - aim for 800-1200 words-6. Include key findings, methodologies, and implications when relevant-7. Note any controversies, limitations, or conflicting evidence--PAPER QUALITY PRIORITIZATION (CRITICAL):-8. ALWAYS prioritize HIGHLY-CITED papers over obscure publications-9. ALWAYS prioritize papers from TOP-TIER VENUES (Nature, Science, Cell, NEJM, Lancet, JAMA, PNAS)-10. PREFER papers from ESTABLISHED, REPUTABLE AUTHORS-11. For EACH citation include when available: citation count, venue tier, author credentials-12. PRIORITIZE papers that DIRECTLY address the research question--RESPONSE FORMAT:-- Start with a brief summary (2-3 sentences)-- Present key findings and studies in organized sections-- Rank papers by impact: most influential/cited first-- End with future directions or research gaps if applicable-- Include 5-8 high-quality citations--Remember: Quality over quantity. Prioritize influential, highly-cited papers from prestigious venues."""-- def _extract_api_citations(self, response: Dict[str, Any], choice: Dict[str, Any]) -> List[Dict[str, str]]:- """Extract citations from Perplexity API response fields."""- citations = []-- search_results = (- response.get("search_results")- or choice.get("search_results")- or choice.get("message", {}).get("search_results")- or []- )-- for result in search_results:- citation = {- "type": "source",- "title": result.get("title", ""),- "url": result.get("url", ""),- "date": result.get("date", ""),- }- if result.get("snippet"):- citation["snippet"] = result["snippet"]- citations.append(citation)-- legacy_citations = (- response.get("citations")- or choice.get("citations")- or choice.get("message", {}).get("citations")- or []- )-- for url in legacy_citations:- if isinstance(url, str):- citations.append({"type": "source", "url": url, "title": "", "date": ""})- elif isinstance(url, dict):- citations.append({- "type": "source",- "url": url.get("url", ""),- "title": url.get("title", ""),- "date": url.get("date", ""),- })-- return citations-- def _extract_citations_from_text(self, text: str) -> List[Dict[str, str]]:- """Extract DOIs and academic URLs from response text as fallback."""- citations = []-- doi_pattern = r'(?:doi[:\s]*|https?://(?:dx\.)?doi\.org/)(10\.[0-9]{4,}/[^\s\)\]\,\[\<\>]+)'- doi_matches = re.findall(doi_pattern, text, re.IGNORECASE)- seen_dois = set()-- for doi in doi_matches:- doi_clean = doi.strip().rstrip(".,;:)]")- if doi_clean and doi_clean not in seen_dois:- seen_dois.add(doi_clean)- citations.append({- "type": "doi",- "doi": doi_clean,- "url": f"https://doi.org/{doi_clean}",- })-- url_pattern = (- r'https?://[^\s\)\]\,\<\>\"\']+(?:arxiv\.org|pubmed|ncbi\.nlm\.nih\.gov|'- r'nature\.com|science\.org|wiley\.com|springer\.com|ieee\.org|acm\.org)'- r'[^\s\)\]\,\<\>\"\']*'- )- url_matches = re.findall(url_pattern, text, re.IGNORECASE)- seen_urls = set()-- for url in url_matches:- url_clean = url.rstrip(".")- if url_clean not in seen_urls:- seen_urls.add(url_clean)- citations.append({"type": "url", "url": url_clean})-- return citations-- # ------------------------------------------------------------------- # Public API- # -------------------------------------------------------------------- def lookup(self, query: str) -> Dict[str, Any]:- """Perform a research lookup, routing to the best backend.-- Parallel Chat API is used by default. Perplexity sonar-pro-search- is used only for academic-specific queries (paper searches, DOI lookups).- """- backend = self._select_backend(query)- print(f"[Research] Backend: {backend} | Query: {query[:80]}...", file=sys.stderr)-- if backend == "parallel":- return self._parallel_lookup(query)- else:- return self._perplexity_lookup(query)-- def batch_lookup(self, queries: List[str], delay: float = 1.0) -> List[Dict[str, Any]]:- """Perform multiple research lookups with delay between requests."""- results = []- for i, query in enumerate(queries):- if i > 0 and delay > 0:- time.sleep(delay)- result = self.lookup(query)- results.append(result)- print(f"[Research] Completed query {i+1}/{len(queries)}: {query[:50]}...", file=sys.stderr)- return results---# ----------------------------------------------------------------------------# CLI-# -----------------------------------------------------------------------------def main():- """Command-line interface for the research lookup tool."""- import argparse-- parser = argparse.ArgumentParser(- description="Research Information Lookup Tool (Parallel Chat API + Perplexity)",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Examples:- # General research (uses Parallel Chat API, core model)- python research_lookup.py "latest advances in quantum computing 2025"-- # Academic paper search (auto-routes to Perplexity)- python research_lookup.py "find papers on CRISPR gene editing clinical trials"-- # Force a specific backend- python research_lookup.py "topic" --force-backend parallel- python research_lookup.py "topic" --force-backend perplexity-- # Save output to file- python research_lookup.py "topic" -o results.txt-- # JSON output- python research_lookup.py "topic" --json -o results.json- """,- )- parser.add_argument("query", nargs="?", help="Research query to look up")- parser.add_argument("--batch", nargs="+", help="Run multiple queries")- parser.add_argument(- "--force-backend",- choices=["parallel", "perplexity"],- help="Force a specific backend (default: auto-select)",- )- parser.add_argument("-o", "--output", help="Write output to file")- parser.add_argument("--json", action="store_true", help="Output as JSON")-- args = parser.parse_args()-- output_file = None- if args.output:- output_file = open(args.output, "w", encoding="utf-8")-- def write_output(text):- if output_file:- output_file.write(text + "\n")- else:- print(text)-- has_parallel = bool(os.getenv("PARALLEL_API_KEY"))- has_perplexity = bool(os.getenv("OPENROUTER_API_KEY"))- if not has_parallel and not has_perplexity:- print("Error: No API keys found. Set at least one:", file=sys.stderr)- print(" export PARALLEL_API_KEY='...' (primary - Parallel Chat API)", file=sys.stderr)- print(" export OPENROUTER_API_KEY='...' (fallback - Perplexity academic)", file=sys.stderr)- if output_file:- output_file.close()- return 1-- if not args.query and not args.batch:- parser.print_help()- if output_file:- output_file.close()- return 1-- try:- research = ResearchLookup(force_backend=args.force_backend)-- if args.batch:- print(f"Running batch research for {len(args.batch)} queries...", file=sys.stderr)- results = research.batch_lookup(args.batch)- else:- print(f"Researching: {args.query}", file=sys.stderr)- results = [research.lookup(args.query)]-- if args.json:- write_output(json.dumps(results, indent=2, ensure_ascii=False, default=str))- if output_file:- output_file.close()- return 0-- for i, result in enumerate(results):- if result["success"]:- write_output(f"\n{'='*80}")- write_output(f"Query {i+1}: {result['query']}")- write_output(f"Timestamp: {result['timestamp']}")- write_output(f"Backend: {result.get('backend', 'unknown')} | Model: {result.get('model', 'unknown')}")- write_output(f"{'='*80}")- write_output(result["response"])-- sources = result.get("sources", [])- if sources:- write_output(f"\nSources ({len(sources)}):")- for j, source in enumerate(sources):- title = source.get("title", "Untitled")- url = source.get("url", "")- date = source.get("date", "")- date_str = f" ({date})" if date else ""- write_output(f" [{j+1}] {title}{date_str}")- if url:- write_output(f" {url}")-- citations = result.get("citations", [])- text_citations = [c for c in citations if c.get("type") in ("doi", "url")]- if text_citations:- write_output(f"\nAdditional References ({len(text_citations)}):")- for j, citation in enumerate(text_citations):- if citation.get("type") == "doi":- write_output(f" [{j+1}] DOI: {citation.get('doi', '')} - {citation.get('url', '')}")- elif citation.get("type") == "url":- write_output(f" [{j+1}] {citation.get('url', '')}")-- if result.get("usage"):- write_output(f"\nUsage: {result['usage']}")- else:- write_output(f"\nError in query {i+1}: {result['error']}")-- if output_file:- output_file.close()- return 0-- except Exception as e:- print(f"Error: {e}", file=sys.stderr)- if output_file:- output_file.close()- return 1---if __name__ == "__main__":- sys.exit(main())diff --git a/skills/research-lookup/scripts/generate_schematic.py b/skills/research-lookup/scripts/generate_schematic.pydeleted file mode 100644index 6843e0a1..00000000--- a/skills/research-lookup/scripts/generate_schematic.py+++ /dev/null@@ -1,139 +0,0 @@-#!/usr/bin/env python3-"""-Scientific schematic generation using Nano Banana 2.--Generate any scientific diagram by describing it in natural language.-Nano Banana 2 handles everything automatically with smart iterative refinement.--Smart iteration: Only regenerates if quality is below threshold for your document type.-Quality review: Uses Gemini 3.1 Pro Preview for professional scientific evaluation.--Usage:- # Generate for journal paper (highest quality threshold)- python generate_schematic.py "CONSORT flowchart" -o flowchart.png --doc-type journal-- # Generate for presentation (lower threshold, faster)- python generate_schematic.py "Transformer architecture" -o transformer.png --doc-type presentation-- # Generate for poster- python generate_schematic.py "MAPK signaling pathway" -o pathway.png --doc-type poster-"""--import argparse-import os-import subprocess-import sys-from pathlib import Path---def main():- """Command-line interface."""- parser = argparse.ArgumentParser(- description="Generate scientific schematics using AI with smart iterative refinement",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-How it works:- Simply describe your diagram in natural language- Nano Banana 2 generates it automatically with:- - Smart iteration (only regenerates if quality is below threshold)- - Quality review by Gemini 3.1 Pro Preview- - Document-type aware quality thresholds- - Publication-ready output--Document Types (quality thresholds):- journal 8.5/10 - Nature, Science, peer-reviewed journals- conference 8.0/10 - Conference papers- thesis 8.0/10 - Dissertations, theses- grant 8.0/10 - Grant proposals- preprint 7.5/10 - arXiv, bioRxiv, etc.- report 7.5/10 - Technical reports- poster 7.0/10 - Academic posters- presentation 6.5/10 - Slides, talks- default 7.5/10 - General purpose--Examples:- # Generate for journal paper (strict quality)- python generate_schematic.py "CONSORT participant flow" -o flowchart.png --doc-type journal-- # Generate for poster (moderate quality)- python generate_schematic.py "Transformer architecture" -o arch.png --doc-type poster-- # Generate for slides (faster, lower threshold)- python generate_schematic.py "System diagram" -o system.png --doc-type presentation-- # Custom max iterations- python generate_schematic.py "Complex pathway" -o pathway.png --iterations 2-- # Verbose output- python generate_schematic.py "Circuit diagram" -o circuit.png -v--Environment Variables:- OPENROUTER_API_KEY Required for AI generation- """- )-- parser.add_argument("prompt",- help="Description of the diagram to generate")- parser.add_argument("-o", "--output", required=True,- help="Output file path")- parser.add_argument("--doc-type", default="default",- choices=["journal", "conference", "poster", "presentation",- "report", "grant", "thesis", "preprint", "default"],- help="Document type for quality threshold (default: default)")- parser.add_argument("--iterations", type=int, default=2,- help="Maximum refinement iterations (default: 2, max: 2)")- parser.add_argument("--api-key",- help="OpenRouter API key (or use OPENROUTER_API_KEY env var)")- parser.add_argument("-v", "--verbose", action="store_true",- help="Verbose output")-- args = parser.parse_args()-- # Check for API key- api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")- if not api_key:- print("Error: OPENROUTER_API_KEY environment variable not set")- print("\nFor AI generation, you need an OpenRouter API key.")- print("Get one at: https://openrouter.ai/keys")- print("\nSet it with:")- print(" export OPENROUTER_API_KEY='your_api_key'")- print("\nOr use --api-key flag")- sys.exit(1)-- # Find AI generation script- script_dir = Path(__file__).parent- ai_script = script_dir / "generate_schematic_ai.py"-- if not ai_script.exists():- print(f"Error: AI generation script not found: {ai_script}")- sys.exit(1)-- # Build command- cmd = [sys.executable, str(ai_script), args.prompt, "-o", args.output]-- if args.doc_type != "default":- cmd.extend(["--doc-type", args.doc_type])-- # Enforce max 2 iterations- iterations = min(args.iterations, 2)- if iterations != 2:- cmd.extend(["--iterations", str(iterations)])-- if args.verbose:- cmd.append("-v")-- # Execute — pass API key via environment to avoid exposure in process listings- try:- env = os.environ.copy()- if api_key:- env["OPENROUTER_API_KEY"] = api_key- result = subprocess.run(cmd, check=False, env=env)- sys.exit(result.returncode)- except Exception as e:- print(f"Error executing AI generation: {e}")- sys.exit(1)---if __name__ == "__main__":- main()-diff --git a/skills/research-lookup/scripts/generate_schematic_ai.py b/skills/research-lookup/scripts/generate_schematic_ai.pydeleted file mode 100644index 52170753..00000000--- a/skills/research-lookup/scripts/generate_schematic_ai.py+++ /dev/null@@ -1,817 +0,0 @@-#!/usr/bin/env python3-"""-AI-powered scientific schematic generation using Nano Banana 2.--This script uses a smart iterative refinement approach:-1. Generate initial image with Nano Banana 2-2. AI quality review using Gemini 3.1 Pro Preview for scientific critique-3. Only regenerate if quality is below threshold for document type-4. Repeat until quality meets standards (max iterations)--Requirements:- - OPENROUTER_API_KEY environment variable- - requests library--Usage:- python generate_schematic_ai.py "Create a flowchart showing CONSORT participant flow" -o flowchart.png- python generate_schematic_ai.py "Neural network architecture diagram" -o architecture.png --iterations 2- python generate_schematic_ai.py "Simple block diagram" -o diagram.png --doc-type poster-"""--import argparse-import base64-import json-import os-import sys-import time-from pathlib import Path-from typing import Optional, Dict, Any, List, Tuple--try:- import requests-except ImportError:- print("Error: requests library not found. Install with: pip install requests")- sys.exit(1)--# Try to load .env file from multiple potential locations-def _load_env_file():- """Load .env file from current directory or script directory only."""- try:- from dotenv import load_dotenv- except ImportError:- return False-- for candidate in [Path.cwd() / ".env", Path(__file__).resolve().parent / ".env"]:- if candidate.exists():- load_dotenv(dotenv_path=candidate, override=False)- return True-- return False---class ScientificSchematicGenerator:- """Generate scientific schematics using AI with smart iterative refinement.-- Uses Gemini 3.1 Pro Preview for quality review to determine if regeneration is needed.- Multiple passes only occur if the generated schematic doesn't meet the- quality threshold for the target document type.- """-- # Quality thresholds by document type (score out of 10)- # Higher thresholds for more formal publications- QUALITY_THRESHOLDS = {- "journal": 8.5, # Nature, Science, etc. - highest standards- "conference": 8.0, # Conference papers - high standards- "poster": 7.0, # Academic posters - good quality- "presentation": 6.5, # Slides/talks - clear but less formal- "report": 7.5, # Technical reports - professional- "grant": 8.0, # Grant proposals - must be compelling- "thesis": 8.0, # Dissertations - formal academic- "preprint": 7.5, # arXiv, etc. - good quality- "default": 7.5, # Default threshold- }-- # Scientific diagram best practices prompt template- SCIENTIFIC_DIAGRAM_GUIDELINES = """-Create a high-quality scientific diagram with these requirements:--VISUAL QUALITY:-- Clean white or light background (no textures or gradients)-- High contrast for readability and printing-- Professional, publication-ready appearance-- Sharp, clear lines and text-- Adequate spacing between elements to prevent crowding--TYPOGRAPHY:-- Clear, readable sans-serif fonts (Arial, Helvetica style)-- Minimum 10pt font size for all labels-- Consistent font sizes throughout-- All text horizontal or clearly readable-- No overlapping text--SCIENTIFIC STANDARDS:-- Accurate representation of concepts-- Clear labels for all components-- Include scale bars, legends, or axes where appropriate-- Use standard scientific notation and symbols-- Include units where applicable--ACCESSIBILITY:-- Colorblind-friendly color palette (use Okabe-Ito colors if using color)-- High contrast between elements-- Redundant encoding (shapes + colors, not just colors)-- Works well in grayscale--LAYOUT:-- Logical flow (left-to-right or top-to-bottom)-- Clear visual hierarchy-- Balanced composition-- Appropriate use of whitespace-- No clutter or unnecessary decorative elements--IMPORTANT - NO FIGURE NUMBERS:-- Do NOT include "Figure 1:", "Fig. 1", or any figure numbering in the image-- Do NOT add captions or titles like "Figure: ..." at the top or bottom-- Figure numbers and captions are added separately in the document/LaTeX-- The diagram should contain only the visual content itself-"""-- def __init__(self, api_key: Optional[str] = None, verbose: bool = False):- """- Initialize the generator.-- Args:- api_key: OpenRouter API key (or use OPENROUTER_API_KEY env var)- verbose: Print detailed progress information- """- # Priority: 1) explicit api_key param, 2) environment variable, 3) .env file- self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")-- # If not found in environment, try loading from .env file- if not self.api_key:- _load_env_file()- self.api_key = os.getenv("OPENROUTER_API_KEY")-- if not self.api_key:- raise ValueError(- "OPENROUTER_API_KEY not found. Please either:\n"- " 1. Set the OPENROUTER_API_KEY environment variable\n"- " 2. Add OPENROUTER_API_KEY to your .env file\n"- " 3. Pass api_key parameter to the constructor\n"- "Get your API key from: https://openrouter.ai/keys"- )-- self.verbose = verbose- self._last_error = None # Track last error for better reporting- self.base_url = "https://openrouter.ai/api/v1"- # Nano Banana 2 - Google's advanced image generation model- # https://openrouter.ai/google/gemini-3-pro-image-preview- self.image_model = "google/gemini-3.1-flash-image-preview"- # Gemini 3.1 Pro Preview for quality review - excellent vision and reasoning- self.review_model = "google/gemini-3.1-pro-preview"-- def _log(self, message: str):- """Log message if verbose mode is enabled."""- if self.verbose:- print(f"[{time.strftime('%H:%M:%S')}] {message}")-- def _make_request(self, model: str, messages: List[Dict[str, Any]],- modalities: Optional[List[str]] = None) -> Dict[str, Any]:- """- Make a request to OpenRouter API.-- Args:- model: Model identifier- messages: List of message dictionaries- modalities: Optional list of modalities (e.g., ["image", "text"])-- Returns:- API response as dictionary- """- headers = {- "Authorization": f"Bearer {self.api_key}",- "Content-Type": "application/json",- "HTTP-Referer": "https://github.com/scientific-writer",- "X-Title": "Scientific Schematic Generator"- }-- payload = {- "model": model,- "messages": messages- }-- if modalities:- payload["modalities"] = modalities-- self._log(f"Making request to {model}...")-- try:- response = requests.post(- f"{self.base_url}/chat/completions",- headers=headers,- json=payload,- timeout=120- )-- # Try to get response body even on error- try:- response_json = response.json()- except json.JSONDecodeError:- response_json = {"raw_text": response.text[:500]}-- # Check for HTTP errors but include response body in error message- if response.status_code != 200:- error_detail = response_json.get("error", response_json)- self._log(f"HTTP {response.status_code}: {error_detail}")- raise RuntimeError(f"API request failed (HTTP {response.status_code}): {error_detail}")-- return response_json- except requests.exceptions.Timeout:- raise RuntimeError("API request timed out after 120 seconds")- except requests.exceptions.RequestException as e:- raise RuntimeError(f"API request failed: {str(e)}")-- def _extract_image_from_response(self, response: Dict[str, Any]) -> Optional[bytes]:- """- Extract base64-encoded image from API response.-- For Nano Banana 2, images are returned in the 'images' field of the message,- not in the 'content' field.-- Args:- response: API response dictionary-- Returns:- Image bytes or None if not found- """- try:- choices = response.get("choices", [])- if not choices:- self._log("No choices in response")- return None-- message = choices[0].get("message", {})-- # IMPORTANT: Nano Banana 2 returns images in the 'images' field- images = message.get("images", [])- if images and len(images) > 0:- self._log(f"Found {len(images)} image(s) in 'images' field")-- # Get first image- first_image = images[0]- if isinstance(first_image, dict):- # Extract image_url- if first_image.get("type") == "image_url":- url = first_image.get("image_url", {})- if isinstance(url, dict):- url = url.get("url", "")-- if url and url.startswith("data:image"):- # Extract base64 data after comma- if "," in url:- base64_str = url.split(",", 1)[1]- # Clean whitespace- base64_str = base64_str.replace('\n', '').replace('\r', '').replace(' ', '')- self._log(f"Extracted base64 data (length: {len(base64_str)})")- return base64.b64decode(base64_str)-- # Fallback: check content field (for other models or future changes)- content = message.get("content", "")-- if self.verbose:- self._log(f"Content type: {type(content)}, length: {len(str(content))}")-- # Handle string content- if isinstance(content, str) and "data:image" in content:- import re- match = re.search(r'data:image/[^;]+;base64,([A-Za-z0-9+/=\n\r]+)', content, re.DOTALL)- if match:- base64_str = match.group(1).replace('\n', '').replace('\r', '').replace(' ', '')- self._log(f"Found image in content field (length: {len(base64_str)})")- return base64.b64decode(base64_str)-- # Handle list content- if isinstance(content, list):- for i, block in enumerate(content):- if isinstance(block, dict) and block.get("type") == "image_url":- url = block.get("image_url", {})- if isinstance(url, dict):- url = url.get("url", "")- if url and url.startswith("data:image") and "," in url:- base64_str = url.split(",", 1)[1].replace('\n', '').replace('\r', '').replace(' ', '')- self._log(f"Found image in content block {i}")- return base64.b64decode(base64_str)-- self._log("No image data found in response")- return None-- except Exception as e:- self._log(f"Error extracting image: {str(e)}")- import traceback- if self.verbose:- traceback.print_exc()- return None-- def _image_to_base64(self, image_path: str) -> str:- """- Convert image file to base64 data URL.-- Args:- image_path: Path to image file-- Returns:- Base64 data URL string- """- with open(image_path, "rb") as f:- image_data = f.read()-- # Determine image type from extension- ext = Path(image_path).suffix.lower()- mime_type = {- ".png": "image/png",- ".jpg": "image/jpeg",- ".jpeg": "image/jpeg",- ".gif": "image/gif",- ".webp": "image/webp"- }.get(ext, "image/png")-- base64_data = base64.b64encode(image_data).decode("utf-8")- return f"data:{mime_type};base64,{base64_data}"-- def generate_image(self, prompt: str) -> Optional[bytes]:- """- Generate an image using Nano Banana 2.-- Args:- prompt: Description of the diagram to generate-- Returns:- Image bytes or None if generation failed- """- self._last_error = None # Reset error-- messages = [- {- "role": "user",- "content": prompt- }- ]-- try:- response = self._make_request(- model=self.image_model,- messages=messages,- modalities=["image", "text"]- )-- # Debug: print response structure if verbose- if self.verbose:- self._log(f"Response keys: {response.keys()}")- if "error" in response:- self._log(f"API Error: {response['error']}")- if "choices" in response and response["choices"]:- msg = response["choices"][0].get("message", {})- self._log(f"Message keys: {msg.keys()}")- # Show content preview without printing huge base64 data- content = msg.get("content", "")- if isinstance(content, str):- preview = content[:200] + "..." if len(content) > 200 else content- self._log(f"Content preview: {preview}")- elif isinstance(content, list):- self._log(f"Content is list with {len(content)} items")- for i, item in enumerate(content[:3]):- if isinstance(item, dict):- self._log(f" Item {i}: type={item.get('type')}")-- # Check for API errors in response- if "error" in response:- error_msg = response["error"]- if isinstance(error_msg, dict):- error_msg = error_msg.get("message", str(error_msg))- self._last_error = f"API Error: {error_msg}"- print(f"✗ {self._last_error}")- return None-- image_data = self._extract_image_from_response(response)- if image_data:- self._log(f"✓ Generated image ({len(image_data)} bytes)")- else:- self._last_error = "No image data in API response - model may not support image generation"- self._log(f"✗ {self._last_error}")- # Additional debug info when image extraction fails- if self.verbose and "choices" in response:- msg = response["choices"][0].get("message", {})- self._log(f"Full message structure: {json.dumps({k: type(v).__name__ for k, v in msg.items()})}")-- return image_data- except RuntimeError as e:- self._last_error = str(e)- self._log(f"✗ Generation failed: {self._last_error}")- return None- except Exception as e:- self._last_error = f"Unexpected error: {str(e)}"- self._log(f"✗ Generation failed: {self._last_error}")- import traceback- if self.verbose:- traceback.print_exc()- return None-- def review_image(self, image_path: str, original_prompt: str,- iteration: int, doc_type: str = "default",- max_iterations: int = 2) -> Tuple[str, float, bool]:- """- Review generated image using Gemini 3.1 Pro Preview for quality analysis.-- Uses Gemini 3.1 Pro Preview's superior vision and reasoning capabilities to- evaluate the schematic quality and determine if regeneration is needed.-- Args:- image_path: Path to the generated image- original_prompt: Original user prompt- iteration: Current iteration number- doc_type: Document type (journal, poster, presentation, etc.)- max_iterations: Maximum iterations allowed-- Returns:- Tuple of (critique text, quality score 0-10, needs_improvement bool)- """- # Use Gemini 3.1 Pro Preview for review - excellent vision and analysis- image_data_url = self._image_to_base64(image_path)-- # Get quality threshold for this document type- threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),- self.QUALITY_THRESHOLDS["default"])-- review_prompt = f"""You are an expert reviewer evaluating a scientific diagram for publication quality.--ORIGINAL REQUEST: {original_prompt}--DOCUMENT TYPE: {doc_type} (quality threshold: {threshold}/10)-ITERATION: {iteration}/{max_iterations}--Carefully evaluate this diagram on these criteria:--1. **Scientific Accuracy** (0-2 points)- - Correct representation of concepts- - Proper notation and symbols- - Accurate relationships shown--2. **Clarity and Readability** (0-2 points)- - Easy to understand at a glance- - Clear visual hierarchy- - No ambiguous elements--3. **Label Quality** (0-2 points)- - All important elements labeled- - Labels are readable (appropriate font size)- - Consistent labeling style--4. **Layout and Composition** (0-2 points)- - Logical flow (top-to-bottom or left-to-right)- - Balanced use of space- - No overlapping elements--5. **Professional Appearance** (0-2 points)- - Publication-ready quality- - Clean, crisp lines and shapes- - Appropriate colors/contrast--RESPOND IN THIS EXACT FORMAT:-SCORE: [total score 0-10]--STRENGTHS:-- [strength 1]-- [strength 2]--ISSUES:-- [issue 1 if any]-- [issue 2 if any]--VERDICT: [ACCEPTABLE or NEEDS_IMPROVEMENT]--If score >= {threshold}, the diagram is ACCEPTABLE for {doc_type} publication.-If score < {threshold}, mark as NEEDS_IMPROVEMENT with specific suggestions."""-- messages = [- {- "role": "user",- "content": [- {- "type": "text",- "text": review_prompt- },- {- "type": "image_url",- "image_url": {- "url": image_data_url- }- }- ]- }- ]-- try:- # Use Gemini 3.1 Pro Preview for high-quality review- response = self._make_request(- model=self.review_model,- messages=messages- )-- # Extract text response- choices = response.get("choices", [])- if not choices:- return "Image generated successfully", 8.0-- message = choices[0].get("message", {})- content = message.get("content", "")-- # Check reasoning field (Nano Banana 2 puts analysis here)- reasoning = message.get("reasoning", "")- if reasoning and not content:- content = reasoning-- if isinstance(content, list):- # Extract text from content blocks- text_parts = []- for block in content:- if isinstance(block, dict) and block.get("type") == "text":- text_parts.append(block.get("text", ""))- content = "\n".join(text_parts)-- # Try to extract score- score = 7.5 # Default score if extraction fails- import re-- # Look for SCORE: X or SCORE: X/10 format- score_match = re.search(r'SCORE:\s*(\d+(?:\.\d+)?)', content, re.IGNORECASE)- if score_match:- score = float(score_match.group(1))- else:- # Fallback: look for any score pattern- score_match = re.search(r'(?:score|rating|quality)[:\s]+(\d+(?:\.\d+)?)\s*(?:/\s*10)?', content, re.IGNORECASE)- if score_match:- score = float(score_match.group(1))-- # Determine if improvement is needed based on verdict or score- needs_improvement = False- if "NEEDS_IMPROVEMENT" in content.upper():- needs_improvement = True- elif score < threshold:- needs_improvement = True-- self._log(f"✓ Review complete (Score: {score}/10, Threshold: {threshold}/10)")- self._log(f" Verdict: {'Needs improvement' if needs_improvement else 'Acceptable'}")-- return (content if content else "Image generated successfully",- score,- needs_improvement)- except Exception as e:- self._log(f"Review skipped: {str(e)}")- # Don't fail the whole process if review fails - assume acceptable- return "Image generated successfully (review skipped)", 7.5, False-- def improve_prompt(self, original_prompt: str, critique: str,- iteration: int) -> str:- """- Improve the generation prompt based on critique.-- Args:- original_prompt: Original user prompt- critique: Review critique from previous iteration- iteration: Current iteration number-- Returns:- Improved prompt for next generation- """- improved_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}--USER REQUEST: {original_prompt}--ITERATION {iteration}: Based on previous feedback, address these specific improvements:-{critique}--Generate an improved version that addresses all the critique points while maintaining scientific accuracy and professional quality."""-- return improved_prompt-- def generate_iterative(self, user_prompt: str, output_path: str,- iterations: int = 2,- doc_type: str = "default") -> Dict[str, Any]:- """- Generate scientific schematic with smart iterative refinement.-- Only regenerates if the quality score is below the threshold for the- specified document type. This saves API calls and time when the first- generation is already good enough.-- Args:- user_prompt: User's description of desired diagram- output_path: Path to save final image- iterations: Maximum refinement iterations (default: 2, max: 2)- doc_type: Document type for quality threshold (journal, poster, etc.)-- Returns:- Dictionary with generation results and metadata- """- output_path = Path(output_path)- output_dir = output_path.parent- output_dir.mkdir(parents=True, exist_ok=True)-- base_name = output_path.stem- extension = output_path.suffix or ".png"-- # Get quality threshold for this document type- threshold = self.QUALITY_THRESHOLDS.get(doc_type.lower(),- self.QUALITY_THRESHOLDS["default"])-- results = {- "user_prompt": user_prompt,- "doc_type": doc_type,- "quality_threshold": threshold,- "iterations": [],- "final_image": None,- "final_score": 0.0,- "success": False,- "early_stop": False,- "early_stop_reason": None- }-- current_prompt = f"""{self.SCIENTIFIC_DIAGRAM_GUIDELINES}--USER REQUEST: {user_prompt}--Generate a publication-quality scientific diagram that meets all the guidelines above."""-- print(f"\n{'='*60}")- print(f"Generating Scientific Schematic")- print(f"{'='*60}")- print(f"Description: {user_prompt}")- print(f"Document Type: {doc_type}")- print(f"Quality Threshold: {threshold}/10")- print(f"Max Iterations: {iterations}")- print(f"Output: {output_path}")- print(f"{'='*60}\n")-- for i in range(1, iterations + 1):- print(f"\n[Iteration {i}/{iterations}]")- print("-" * 40)-- # Generate image- print(f"Generating image...")- image_data = self.generate_image(current_prompt)-- if not image_data:- error_msg = getattr(self, '_last_error', 'Image generation failed - no image data returned')- print(f"✗ Generation failed: {error_msg}")- results["iterations"].append({- "iteration": i,- "success": False,- "error": error_msg- })- continue-- # Save iteration image- iter_path = output_dir / f"{base_name}_v{i}{extension}"- with open(iter_path, "wb") as f:- f.write(image_data)- print(f"✓ Saved: {iter_path}")-- # Review image using Gemini 3.1 Pro Preview- print(f"Reviewing image with Gemini 3.1 Pro Preview...")- critique, score, needs_improvement = self.review_image(- str(iter_path), user_prompt, i, doc_type, iterations- )- print(f"✓ Score: {score}/10 (threshold: {threshold}/10)")-- # Save iteration results- iteration_result = {- "iteration": i,- "image_path": str(iter_path),- "prompt": current_prompt,- "critique": critique,- "score": score,- "needs_improvement": needs_improvement,- "success": True- }- results["iterations"].append(iteration_result)-- # Check if quality is acceptable - STOP EARLY if so- if not needs_improvement:- print(f"\n✓ Quality meets {doc_type} threshold ({score} >= {threshold})")- print(f" No further iterations needed!")- results["final_image"] = str(iter_path)- results["final_score"] = score- results["success"] = True- results["early_stop"] = True- results["early_stop_reason"] = f"Quality score {score} meets threshold {threshold} for {doc_type}"- break-- # If this is the last iteration, we're done regardless- if i == iterations:- print(f"\n⚠ Maximum iterations reached")- results["final_image"] = str(iter_path)- results["final_score"] = score- results["success"] = True- break-- # Quality below threshold - improve prompt for next iteration- print(f"\n⚠ Quality below threshold ({score} < {threshold})")- print(f"Improving prompt based on feedback...")- current_prompt = self.improve_prompt(user_prompt, critique, i + 1)-- # Copy final version to output path- if results["success"] and results["final_image"]:- final_iter_path = Path(results["final_image"])- if final_iter_path != output_path:- import shutil- shutil.copy(final_iter_path, output_path)- print(f"\n✓ Final image: {output_path}")-- # Save review log- log_path = output_dir / f"{base_name}_review_log.json"- with open(log_path, "w") as f:- json.dump(results, f, indent=2)- print(f"✓ Review log: {log_path}")-- print(f"\n{'='*60}")- print(f"Generation Complete!")- print(f"Final Score: {results['final_score']}/10")- if results["early_stop"]:- print(f"Iterations Used: {len([r for r in results['iterations'] if r.get('success')])}/{iterations} (early stop)")- print(f"{'='*60}\n")-- return results---def main():- """Command-line interface."""- parser = argparse.ArgumentParser(- description="Generate scientific schematics using AI with smart iterative refinement",- formatter_class=argparse.RawDescriptionHelpFormatter,- epilog="""-Examples:- # Generate a flowchart for a journal paper- python generate_schematic_ai.py "CONSORT participant flow diagram" -o flowchart.png --doc-type journal-- # Generate neural network architecture for presentation (lower threshold)- python generate_schematic_ai.py "Transformer encoder-decoder architecture" -o transformer.png --doc-type presentation-- # Generate with custom max iterations for poster- python generate_schematic_ai.py "Biological signaling pathway" -o pathway.png --iterations 2 --doc-type poster-- # Verbose output- python generate_schematic_ai.py "Circuit diagram" -o circuit.png -v--Document Types (quality thresholds):- journal 8.5/10 - Nature, Science, peer-reviewed journals- conference 8.0/10 - Conference papers- thesis 8.0/10 - Dissertations, theses- grant 8.0/10 - Grant proposals- preprint 7.5/10 - arXiv, bioRxiv, etc.- report 7.5/10 - Technical reports- poster 7.0/10 - Academic posters- presentation 6.5/10 - Slides, talks- default 7.5/10 - General purpose--Note: Multiple iterations only occur if quality is BELOW the threshold.- If the first generation meets the threshold, no extra API calls are made.--Environment:- OPENROUTER_API_KEY OpenRouter API key (required)- """- )-- parser.add_argument("prompt", help="Description of the diagram to generate")- parser.add_argument("-o", "--output", required=True,- help="Output image path (e.g., diagram.png)")- parser.add_argument("--iterations", type=int, default=2,- help="Maximum refinement iterations (default: 2, max: 2)")- parser.add_argument("--doc-type", default="default",- choices=["journal", "conference", "poster", "presentation",- "report", "grant", "thesis", "preprint", "default"],- help="Document type for quality threshold (default: default)")- parser.add_argument("--api-key", help="OpenRouter API key (or set OPENROUTER_API_KEY)")- parser.add_argument("-v", "--verbose", action="store_true",- help="Verbose output")-- args = parser.parse_args()-- # Check for API key- api_key = args.api_key or os.getenv("OPENROUTER_API_KEY")- if not api_key:- print("Error: OPENROUTER_API_KEY environment variable not set")- print("\nSet it with:")- print(" export OPENROUTER_API_KEY='your_api_key'")- print("\nOr provide via --api-key flag")- sys.exit(1)-- # Validate iterations - enforce max of 2- if args.iterations < 1 or args.iterations > 2:- print("Error: Iterations must be between 1 and 2")- sys.exit(1)-- try:- generator = ScientificSchematicGenerator(api_key=api_key, verbose=args.verbose)- results = generator.generate_iterative(- user_prompt=args.prompt,- output_path=args.output,- iterations=args.iterations,- doc_type=args.doc_type- )-- if results["success"]:- print(f"\n✓ Success! Image saved to: {args.output}")- if results.get("early_stop"):- print(f" (Completed in {len([r for r in results['iterations'] if r.get('success')])} iteration(s) - quality threshold met)")- sys.exit(0)- else:- print(f"\n✗ Generation failed. Check review log for details.")- sys.exit(1)- except Exception as e:- print(f"\n✗ Error: {str(e)}")- sys.exit(1)---if __name__ == "__main__":- main()-diff --git a/skills/research-lookup/scripts/research_lookup.py b/skills/research-lookup/scripts/research_lookup.pyindex dc86938b..ac01ca8b 100755--- a/skills/research-lookup/scripts/research_lookup.py+++ b/skills/research-lookup/scripts/research_lookup.py@@ -475,6 +475,10 @@ Examples:output_file = Noneif args.output:+ # Create the parent directory (e.g. sources/) if it doesn't exist yet,+ # so `-o sources/foo.md` works even on a fresh project.+ parent = os.path.dirname(os.path.abspath(args.output))+ os.makedirs(parent, exist_ok=True)output_file = open(args.output, "w", encoding="utf-8")def write_output(text):diff --git a/skills/statistical-analysis/SKILL.md b/skills/statistical-analysis/SKILL.mdindex 6b159655..22267128 100644--- a/skills/statistical-analysis/SKILL.md+++ b/skills/statistical-analysis/SKILL.md@@ -1,20 +1,20 @@---name: statistical-analysis-description: Guided statistical analysis with test selection and reporting. Use when you need help choosing appropriate tests for your data, assumption checking, power analysis, and APA-formatted results. Best for academic research reporting, test selection guidance. For implementing specific models programmatically use statsmodels.+description: Guided statistical analysis for research data - test selection, assumption checking, effect sizes, power analysis, Bayesian alternatives, and APA-formatted reporting. Use whenever a user wants to compare groups, test a hypothesis, analyze experimental or survey data, check statistical assumptions, compute required sample sizes, or write up results - even if they never name a specific test. Covers t-tests, ANOVA, chi-square, correlation, regression, non-parametric and Bayesian methods. For low-level model APIs, see the statsmodels and pymc skills.license: MIT license-metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}+metadata: {"version": "1.1", "skill-author": "K-Dense Inc."}---# Statistical Analysis## Overview-Statistical analysis is a systematic process for testing hypotheses and quantifying relationships. Conduct hypothesis tests (t-test, ANOVA, chi-square), regression, correlation, and Bayesian analyses with assumption checks and APA reporting. Apply this skill for academic research.+Conduct hypothesis tests (t-tests, ANOVA, chi-square), regression, correlation, and Bayesian analyses with systematic assumption checking, effect sizes, and APA-style reporting. The goal is an analysis a reviewer could not tear apart: the right test, verified assumptions, honest effect sizes, and a complete write-up.## When to Use This Skill-This skill should be used when:-- Conducting statistical hypothesis tests (t-tests, ANOVA, chi-square)+Use this skill when:+- Conducting statistical hypothesis tests (t-tests, ANOVA, chi-square, non-parametric)- Performing regression or correlation analyses- Running Bayesian statistical analyses- Checking statistical assumptions and diagnostics@@ -32,72 +32,33 @@ Use **uv** to install the libraries used in this skill. Pin versions in producti# Core frequentist stack (Python 3.10+; 3.12+ recommended for latest SciPy/ArviZ)uv pip install "pingouin>=0.6" "scipy>=1.11" "statsmodels>=0.14.6" pandas matplotlib seaborn-# Bayesian modeling (PyMC 5 + ArviZ; ArviZ 0.23+ requires Python 3.12+)-uv pip install "pymc>=5.0" "arviz>=0.17"+# Bayesian modeling (PyMC 5 + ArviZ)+uv pip install "pymc>=5.0" "arviz>=1.0"```-**Compatibility notes (2025–2026):**+**Compatibility notes (verified against pingouin 0.6.1, statsmodels 0.14.6, arviz 1.2, 2026):**-- **Pingouin 0.5+** renamed output columns (`p_val`, `cohen_d`, `CI95`, `p_unc`) — examples below use the current names.+- **Pingouin 0.6.0** renamed output columns to remove special characters: `p_val`, `cohen_d`, `CI95`, `p_unc` (previously `p-val`, `cohen-d`, `CI95%`, `p-unc` in 0.5.x). Examples below use the current names; if stuck on 0.5.x, use the hyphenated forms.- **statsmodels + SciPy**: use `statsmodels>=0.14.6` with `scipy>=1.11` to avoid `_lazywhere` import errors on SciPy 1.16+.-- **Pingouin Bayes Factors**: one-sided BF for t-tests was removed in 0.5+; use dedicated packages (e.g. JASP, BayesFactor via R) or PyMC for hypothesis testing.+- **ArviZ 1.x**: `az.summary()` now defaults to **89% intervals** (`eti89` columns) and the width parameter is `ci_prob` (not `hdi_prob`). To report a conventional 95% credible interval, pass `az.summary(trace, ci_prob=0.95)`.+- **One-sided Bayes Factors are gone from Pingouin**: `pg.ttest(..., alternative='greater')` silently drops the `BF10` column, and `pg.bayesfactor_ttest` raises on one-sided alternatives. For one-sided Bayesian tests, use PyMC directly (compute the posterior probability of the directional hypothesis) or JASP/R's BayesFactor.For model-specific APIs (OLS, GLM, ARIMA), see the **statsmodels** skill. For PyMC workflows, see the **pymc** skill.----## Core Capabilities+## Analysis Workflow-### 1. Test Selection and Planning-- Choose appropriate statistical tests based on research questions and data characteristics-- Conduct a priori power analyses to determine required sample sizes-- Plan analysis strategies including multiple comparison corrections+Every sound analysis follows the same arc. Skipping steps is how analyses end up retracted, so work through them in order and say what you did at each one.-### 2. Assumption Checking-- Automatically verify all relevant assumptions before running tests-- Provide diagnostic visualizations (Q-Q plots, residual plots, box plots)-- Recommend remedial actions when assumptions are violated+1. **Frame the question before touching the data.** State the hypothesis, the outcome and predictor variables, and the design (independent vs. paired, number of groups). Commit to a planned test now — choosing the test after peeking at results is p-hacking, even when done innocently.+2. **Inspect the data.** Per group: n, mean, SD, median, missing values. Plot the raw data (histograms or box plots) before any test. Unequal group sizes, missingness, floor/ceiling effects, and outliers all change what test is appropriate — surface them to the user rather than silently working around them.+3. **Select the test** using the quick reference below, or `references/test_selection_guide.md` for designs beyond the basics (counts, time-to-event, reliability, factorial).+4. **Check assumptions** with `scripts/assumption_checks.py`. If an assumption fails, switch to the remedial test (table below) and report both the plan and the change.+5. **Run the test** and always compute the effect size alongside it — a p-value says an effect exists; the effect size says whether anyone should care.+6. **Report** using the APA templates below, including descriptives, exact statistics, effect sizes with CIs, and the assumption checks performed.-### 3. Statistical Testing-- Hypothesis testing: t-tests, ANOVA, chi-square, non-parametric alternatives-- Regression: linear, multiple, logistic, with diagnostics-- Correlations: Pearson, Spearman, with confidence intervals-- Bayesian alternatives: Bayesian t-tests, ANOVA, regression with Bayes Factors--### 4. Effect Sizes and Interpretation-- Calculate and interpret appropriate effect sizes for all analyses-- Provide confidence intervals for effect estimates-- Distinguish statistical from practical significance--### 5. Professional Reporting-- Generate APA-style statistical reports-- Create publication-ready figures and tables-- Provide complete interpretation with all required statistics-------## Workflow Decision Tree--Use this decision tree to determine your analysis path:--```-START-│-├─ Need to SELECT a statistical test?-│ └─ YES → See "Test Selection Guide"-│ └─ NO → Continue-│-├─ Ready to check ASSUMPTIONS?-│ └─ YES → See "Assumption Checking"-│ └─ NO → Continue-│-├─ Ready to run ANALYSIS?-│ └─ YES → See "Running Statistical Tests"-│ └─ NO → Continue-│-└─ Need to REPORT results?- └─ YES → See "Reporting Results"-```+If the user only needs one step (e.g., "how many participants do I need?"), jump straight to that section — but still confirm the design assumptions the calculation rests on.---@@ -105,7 +66,7 @@ START### Quick Reference: Choosing the Right Test-Use `references/test_selection_guide.md` for comprehensive guidance. Quick reference:+Use `references/test_selection_guide.md` for comprehensive guidance (counts, survival, reliability, factorial designs). Quick reference:**Comparing Two Groups:**- Independent, continuous, normal → Independent t-test@@ -126,26 +87,20 @@ Use `references/test_selection_guide.md` for comprehensive guidance. Quick refer- Binary outcome with predictor(s) → Logistic regression**Bayesian Alternatives:**-All tests have Bayesian versions that provide:-- Direct probability statements about hypotheses-- Bayes Factors quantifying evidence-- Ability to support null hypothesis-- See `references/bayesian_statistics.md`+All tests have Bayesian versions providing direct probability statements about hypotheses, Bayes Factors quantifying evidence, and the ability to support the null. See `references/bayesian_statistics.md`.---## Assumption Checking-### Systematic Assumption Verification+**Always check assumptions before interpreting test results**, and report the checks — reviewers look for them.-**ALWAYS check assumptions before interpreting test results.**--Use the bundled `scripts/assumption_checks.py` module for automated checking. Run Python from the skill directory (`skills/statistical-analysis/`) or add `scripts/` to `sys.path`:+Use the bundled `scripts/assumption_checks.py` module. Run Python from the skill directory (`skills/statistical-analysis/`) or add `scripts/` to `sys.path`:```pythonfrom assumption_checks import comprehensive_assumption_check-# Comprehensive check with visualizations+# Outliers + normality (per group) + homogeneity of variance, with plotsresults = comprehensive_assumption_check(data=df,value_col='score',@@ -154,32 +109,19 @@ results = comprehensive_assumption_check()```-This performs:-1. **Outlier detection** (IQR and z-score methods)-2. **Normality testing** (Shapiro-Wilk test + Q-Q plots)-3. **Homogeneity of variance** (Levene's test + box plots)-4. **Interpretation and recommendations**--### Individual Assumption Checks--For targeted checks, use individual functions:+For targeted checks, import individual functions:```pythonfrom assumption_checks import (- check_normality,+ check_normality, # Shapiro-Wilk + Q-Q plot + histogramcheck_normality_per_group,- check_homogeneity_of_variance,- check_linearity,- detect_outliers+ check_homogeneity_of_variance, # Levene's test + box plots+ check_linearity, # scatter + residual plot for simple regression+ check_regression_diagnostics, # full OLS diagnostics (see Regression below)+ detect_outliers # IQR or z-score methods)-# Example: Check normality with visualization-result = check_normality(- data=df['score'],- name='Test Score',- alpha=0.05,- plot=True-)+result = check_normality(data=df['score'], name='Test Score', alpha=0.05, plot=True)print(result['interpretation'])print(result['recommendation'])```@@ -192,129 +134,80 @@ print(result['recommendation'])- Severe violation → Transform data or use non-parametric test**Homogeneity of variance violated:**-- For t-test → Use Welch's t-test-- For ANOVA → Use Welch's ANOVA or Brown-Forsythe ANOVA+- For t-test → Use Welch's t-test (`pg.ttest` applies it automatically with `correction='auto'`)+- For ANOVA → Use Welch's ANOVA (`pg.welch_anova`) or Brown-Forsythe- For regression → Use robust standard errors or weighted least squares**Linearity violated (regression):**-- Add polynomial terms-- Transform variables-- Use non-linear models or GAM+- Add polynomial terms, transform variables, or use non-linear models / GAM-See `references/assumptions_and_diagnostics.md` for comprehensive guidance.+Formal tests get oversensitive as n grows: for n ≥ 100, weigh the Q-Q plot more heavily than the Shapiro-Wilk p-value. See `references/assumptions_and_diagnostics.md` for comprehensive guidance.---## Running Statistical Tests-### Python Libraries+Primary libraries:+- **pingouin**: user-friendly tests that return effect sizes by default — prefer it for standard tests+- **scipy.stats**: core statistical tests+- **statsmodels**: regression, diagnostics, power analysis+- **pymc** + **arviz**: Bayesian modeling and diagnostics-Primary libraries for statistical analysis:-- **scipy.stats**: Core statistical tests-- **statsmodels**: Advanced regression and diagnostics-- **pingouin**: User-friendly statistical testing with effect sizes-- **pymc**: Bayesian statistical modeling-- **arviz**: Bayesian visualization and diagnostics--### Example Analyses--#### T-Test with Complete Reporting+### T-Test with Complete Reporting```pythonimport pingouin as pg-import numpy as np-# Run independent t-test+# correction='auto' applies Welch's correction when variances are unequalresult = pg.ttest(group_a, group_b, correction='auto')-# Extract results (Pingouin 0.5+ column names)+# Pingouin >= 0.6 column namest_stat = result['T'].values[0]df = result['dof'].values[0]p_value = result['p_val'].values[0]cohens_d = result['cohen_d'].values[0]-ci = result['CI95'].values[0]-ci_lower, ci_upper = ci[0], ci[1]+ci_lower, ci_upper = result['CI95'].values[0] # CI for the mean difference-# Report-print(f"t({df:.0f}) = {t_stat:.2f}, p = {p_value:.3f}")-print(f"Cohen's d = {cohens_d:.2f}, 95% CI [{ci_lower:.2f}, {ci_upper:.2f}]")+print(f"t({df:.0f}) = {t_stat:.2f}, p = {p_value:.3f}, d = {cohens_d:.2f}")```-#### ANOVA with Post-Hoc Tests+### ANOVA with Post-Hoc Tests```pythonimport pingouin as pg-# One-way ANOVAaov = pg.anova(dv='score', between='group', data=df, detailed=True)print(aov)-# If significant, conduct post-hoc tests+# Effect size: partial eta-squared+eta_p2 = aov['np2'].values[0]++# If significant, conduct post-hoc tests (Tukey HSD controls family-wise error)if aov['p_unc'].values[0] < 0.05:posthoc = pg.pairwise_tukey(dv='score', between='group', data=df)- print(posthoc)--# Effect size-eta_squared = aov['np2'].values[0] # Partial eta-squared-print(f"Partial η² = {eta_squared:.3f}")+ print(posthoc) # includes Hedges' g per pair```-#### Linear Regression with Diagnostics+### Linear Regression with Diagnostics```pythonimport statsmodels.api as sm-from statsmodels.stats.outliers_influence import variance_inflation_factor+from assumption_checks import check_regression_diagnostics-# Fit modelX = sm.add_constant(X_predictors) # Add interceptmodel = sm.OLS(y, X).fit()--# Summaryprint(model.summary())-# Check multicollinearity (VIF)-vif_data = pd.DataFrame()-vif_data["Variable"] = X.columns-vif_data["VIF"] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]-print(vif_data)--# Check assumptions-residuals = model.resid-fitted = model.fittedvalues--# Residual plots-import matplotlib.pyplot as plt-fig, axes = plt.subplots(2, 2, figsize=(12, 10))--# Residuals vs fitted-axes[0, 0].scatter(fitted, residuals, alpha=0.6)-axes[0, 0].axhline(y=0, color='r', linestyle='--')-axes[0, 0].set_xlabel('Fitted values')-axes[0, 0].set_ylabel('Residuals')-axes[0, 0].set_title('Residuals vs Fitted')--# Q-Q plot-from scipy import stats-stats.probplot(residuals, dist="norm", plot=axes[0, 1])-axes[0, 1].set_title('Normal Q-Q')--# Scale-Location-axes[1, 0].scatter(fitted, np.sqrt(np.abs(residuals / residuals.std())), alpha=0.6)-axes[1, 0].set_xlabel('Fitted values')-axes[1, 0].set_ylabel('√|Standardized residuals|')-axes[1, 0].set_title('Scale-Location')--# Residuals histogram-axes[1, 1].hist(residuals, bins=20, edgecolor='black', alpha=0.7)-axes[1, 1].set_xlabel('Residuals')-axes[1, 1].set_ylabel('Frequency')-axes[1, 1].set_title('Histogram of Residuals')--plt.tight_layout()-plt.show()+# 4-panel residual plot + Shapiro-Wilk, Breusch-Pagan, Durbin-Watson, VIF+diag = check_regression_diagnostics(model)+print(diag['interpretation'])+print(diag['vif'])++# If heteroscedasticity was flagged, report robust standard errors instead+robust = model.get_robustcov_results('HC3')```-#### Bayesian T-Test+### Bayesian T-Test```pythonimport pymc as pm@@ -334,29 +227,26 @@ with pm.Model() as model:# Derived quantitydiff = pm.Deterministic('difference', mu1 - mu2)- # Sample- trace = pm.sample(2000, tune=1000, return_inferencedata=True)+ trace = pm.sample(2000, tune=1000)-# Summarize-print(az.summary(trace, var_names=['difference']))+# ArviZ 1.x defaults to 89% intervals; request 95% explicitly for reporting+print(az.summary(trace, var_names=['difference'], ci_prob=0.95))-# Probability that group1 > group2+# Direct probability statement (this is what one-sided questions become)prob_greater = np.mean(trace.posterior['difference'].values > 0)-print(f"P(μ₁ > μ₂ | data) = {prob_greater:.3f}")+print(f"P(mu1 > mu2 | data) = {prob_greater:.3f}")-# Plot posterior-az.plot_posterior(trace, var_names=['difference'], ref_val=0)+# ArviZ 1.x removed az.plot_posterior; use plot_dist (on 0.x, plot_posterior still works)+az.plot_dist(trace, var_names=['difference'], ci_prob=0.95)```+Scale priors to the data (e.g., `sigma=10` suits outcomes with SD near 10; use the observed SD as a guide) and state the priors in the report.+---## Effect Sizes-### Always Calculate Effect Sizes--**Effect sizes quantify magnitude, while p-values only indicate existence of an effect.**--See `references/effect_sizes_and_power.md` for comprehensive guidance.+**Effect sizes quantify magnitude; p-values only indicate existence.** Report one for every test. See `references/effect_sizes_and_power.md` for the full guide.### Quick Reference: Common Effect Sizes@@ -368,41 +258,23 @@ See `references/effect_sizes_and_power.md` for comprehensive guidance.| Regression | R² | 0.02 | 0.13 | 0.26 || Chi-square | Cramér's V | 0.07 | 0.21 | 0.35 |-**Important**: Benchmarks are guidelines. Context matters!+Benchmarks are conventions, not laws — a "small" effect can matter enormously (drug side effects) and a "large" one can be trivial. Interpret in context.### Calculating Effect Sizes-Most effect sizes are automatically calculated by pingouin:--```python-# T-test returns Cohen's d-result = pg.ttest(x, y)-d = result['cohen_d'].values[0]--# ANOVA returns partial eta-squared-aov = pg.anova(dv='score', between='group', data=df)-eta_p2 = aov['np2'].values[0]--# Correlation: r is already an effect size-corr = pg.corr(x, y)-r = corr['r'].values[0]-```+Pingouin returns effect sizes with its tests (`cohen_d` from `pg.ttest`, `np2` from `pg.anova`, `hedges` from `pg.pairwise_tukey`; `r` from `pg.corr` is already an effect size).### Confidence Intervals for Effect Sizes-Always report CIs to show precision:+Report a CI for the effect size to show its precision. Use `pg.compute_esci` (note: `pg.compute_effsize_from_t` returns only the point estimate — it does **not** return a CI):```python-from pingouin import compute_effsize_from_t--# For t-test-d, ci = compute_effsize_from_t(- t_statistic,- nx=len(group1),- ny=len(group2),- eftype='cohen'-)-print(f"d = {d:.2f}, 95% CI [{ci[0]:.2f}, {ci[1]:.2f}]")+import pingouin as pg++d = pg.compute_effsize(group_a, group_b, eftype='cohen')+ci_lower, ci_upper = pg.compute_esci(stat=d, nx=len(group_a), ny=len(group_b),+ eftype='cohen', confidence=0.95)+print(f"d = {d:.2f}, 95% CI [{ci_lower:.2f}, {ci_upper:.2f}]")```---@@ -414,12 +286,9 @@ print(f"d = {d:.2f}, 95% CI [{ci[0]:.2f}, {ci[1]:.2f}]")Determine required sample size before data collection:```python-from statsmodels.stats.power import (- tt_ind_solve_power,- FTestAnovaPower-)+from statsmodels.stats.power import tt_ind_solve_power, FTestAnovaPower-# T-test: What n is needed to detect d = 0.5?+# T-test: What n per group is needed to detect d = 0.5?n_required = tt_ind_solve_power(effect_size=0.5,alpha=0.05,@@ -429,23 +298,26 @@ n_required = tt_ind_solve_power()print(f"Required n per group: {n_required:.0f}")-# ANOVA: What n is needed to detect f = 0.25?+# One-way ANOVA: What n is needed to detect Cohen's f = 0.25?+# Notes: the parameter is k_groups; effect_size is Cohen's f (f = sqrt(eta2/(1-eta2)));+# and solve_power returns the TOTAL sample size, not n per group.+import mathanova_power = FTestAnovaPower()-n_per_group = anova_power.solve_power(+n_total = anova_power.solve_power(effect_size=0.25,- ngroups=3,+ k_groups=3,alpha=0.05,power=0.80)-print(f"Required n per group: {n_per_group:.0f}")+print(f"Required total N: {math.ceil(n_total)} ({math.ceil(n_total / 3)} per group)")```### Sensitivity Analysis (Post-Study)-Determine what effect size you could detect:+Determine what effect size the study could detect:```python-# With n=50 per group, what effect could we detect?+# With n=50 per group, what effect could we detect at 80% power?detectable_d = tt_ind_solve_power(effect_size=None, # Solve for thisnobs1=50,@@ -454,10 +326,10 @@ detectable_d = tt_ind_solve_power(ratio=1.0,alternative='two-sided')-print(f"Study could detect d ≥ {detectable_d:.2f}")+print(f"Study could detect d >= {detectable_d:.2f}")```-**Note**: Post-hoc power analysis (calculating power after study) is generally not recommended. Use sensitivity analysis instead.+**Note**: Post-hoc "observed power" (computing power from the observed effect) is circular and misleading — it is a deterministic function of the p-value. If a study is done and someone asks about power, run a sensitivity analysis instead.See `references/effect_sizes_and_power.md` for detailed guidance.@@ -465,17 +337,13 @@ See `references/effect_sizes_and_power.md` for detailed guidance.## Reporting Results-### APA Style Statistical Reporting--Follow guidelines in `references/reporting_standards.md`.--### Essential Reporting Elements+Follow `references/reporting_standards.md` for APA style. Every report needs:1. **Descriptive statistics**: M, SD, n for all groups/variables-2. **Test statistics**: Test name, statistic, df, exact p-value+2. **Test statistics**: Test name, statistic, df, exact p-value (`p = .034`, not `p < .05`; use `p < .001` only below .001)3. **Effect sizes**: With confidence intervals-4. **Assumption checks**: Which tests were done, results, actions taken-5. **All planned analyses**: Including non-significant findings+4. **Assumption checks**: Which tests were run, results, and actions taken+5. **All planned analyses**: Including non-significant findings — omitting them is cherry-picking### Example Report Templates@@ -518,134 +386,59 @@ Multicollinearity was not a concern (all VIF < 1.5).```A Bayesian independent samples t-test was conducted using weakly-informative priors (Normal(0, 1) for mean difference). The posterior+informative priors (Normal(0, 10) for group means). The posteriordistribution indicated that Group A scored higher than Group B-(M_diff = 6.8, 95% credible interval [3.2, 10.4]). The Bayes Factor-BF₁₀ = 45.3 provided very strong evidence for a difference between-groups, with a 99.8% posterior probability that Group A's mean exceeded-Group B's mean. Convergence diagnostics were satisfactory (all R̂ < 1.01,-ESS > 1000).+(M_diff = 6.8, 95% credible interval [3.2, 10.4]), with a 99.8%+posterior probability that Group A's mean exceeded Group B's mean.+Convergence diagnostics were satisfactory (all R-hat < 1.01, ESS > 1000).```+If a non-parametric test was used, report medians rather than means, the U/W/H statistic, and a rank-based effect size (e.g., rank-biserial correlation, returned by `pg.mwu` as `RBC`).+---## Bayesian Statistics-### When to Use Bayesian Methods-Consider Bayesian approaches when:- You have prior information to incorporate-- You want direct probability statements about hypotheses-- Sample size is small or planning sequential data collection-- You need to quantify evidence for the null hypothesis-- The model is complex (hierarchical, missing data)--See `references/bayesian_statistics.md` for comprehensive guidance on:-- Bayes' theorem and interpretation-- Prior specification (informative, weakly informative, non-informative)-- Bayesian hypothesis testing with Bayes Factors-- Credible intervals vs. confidence intervals-- Bayesian t-tests, ANOVA, regression, and hierarchical models-- Model convergence checking and posterior predictive checks--### Key Advantages--1. **Intuitive interpretation**: "Given the data, there is a 95% probability the parameter is in this interval"-2. **Evidence for null**: Can quantify support for no effect-3. **Flexible**: No p-hacking concerns; can analyze data as it arrives-4. **Uncertainty quantification**: Full posterior distribution+- You want direct probability statements about hypotheses ("there is a 95% probability the effect lies in this interval")+- Sample size is small or data collection is sequential (no correction needed for optional stopping)+- You need to quantify evidence *for* the null hypothesis+- The model is complex (hierarchical structure, missing data)----+See `references/bayesian_statistics.md` for prior specification, Bayes Factors, credible intervals, hierarchical models, and convergence checking (R-hat < 1.01, sufficient ESS, posterior predictive checks).-## Resources+----This skill includes comprehensive reference materials:+## Bundled Resources-### References Directory+### References (`references/`)-- **test_selection_guide.md**: Decision tree for choosing appropriate statistical tests+- **test_selection_guide.md**: Decision tree covering group comparisons, relationships, counts, time-to-event, agreement/reliability, and categorical analysis- **assumptions_and_diagnostics.md**: Detailed guidance on checking and handling assumption violations-- **effect_sizes_and_power.md**: Calculating, interpreting, and reporting effect sizes; conducting power analyses-- **bayesian_statistics.md**: Complete guide to Bayesian analysis methods-- **reporting_standards.md**: APA-style reporting guidelines with examples+- **effect_sizes_and_power.md**: Calculating, interpreting, and reporting effect sizes; power analysis+- **bayesian_statistics.md**: Priors, Bayes Factors, credible intervals, hierarchical models, diagnostics+- **reporting_standards.md**: APA-style reporting guidelines with worked examples-### Scripts Directory+### Scripts (`scripts/`)- **assumption_checks.py**: Automated assumption checking with visualizations- - `comprehensive_assumption_check()`: Complete workflow- - `check_normality()`: Normality testing with Q-Q plots+ - `comprehensive_assumption_check()`: outliers + normality + variance homogeneity in one call+ - `check_normality()`, `check_normality_per_group()`: Shapiro-Wilk with Q-Q plots- `check_homogeneity_of_variance()`: Levene's test with box plots- - `check_linearity()`: Regression linearity checks- - `detect_outliers()`: IQR and z-score outlier detection-------## Best Practices--1. **Pre-register analyses** when possible to distinguish confirmatory from exploratory-2. **Always check assumptions** before interpreting results-3. **Report effect sizes** with confidence intervals-4. **Report all planned analyses** including non-significant results-5. **Distinguish statistical from practical significance**-6. **Visualize data** before and after analysis-7. **Check diagnostics** for regression/ANOVA (residual plots, VIF, etc.)-8. **Conduct sensitivity analyses** to assess robustness-9. **Share data and code** for reproducibility-10. **Be transparent** about violations, transformations, and decisions-------## Common Pitfalls to Avoid--1. **P-hacking**: Don't test multiple ways until something is significant-2. **HARKing**: Don't present exploratory findings as confirmatory-3. **Ignoring assumptions**: Check them and report violations-4. **Confusing significance with importance**: p < .05 ≠ meaningful effect-5. **Not reporting effect sizes**: Essential for interpretation-6. **Cherry-picking results**: Report all planned analyses-7. **Misinterpreting p-values**: They're NOT probability that hypothesis is true-8. **Multiple comparisons**: Correct for family-wise error when appropriate-9. **Ignoring missing data**: Understand mechanism (MCAR, MAR, MNAR)-10. **Overinterpreting non-significant results**: Absence of evidence ≠ evidence of absence+ - `check_regression_diagnostics()`: 4-panel residual plots + Shapiro-Wilk, Breusch-Pagan, Durbin-Watson, VIF for fitted OLS models+ - `check_linearity()`, `detect_outliers()`----## Getting Started Checklist--When beginning a statistical analysis:--- [ ] Define research question and hypotheses-- [ ] Determine appropriate statistical test (use test_selection_guide.md)-- [ ] Conduct power analysis to determine sample size-- [ ] Load and inspect data-- [ ] Check for missing data and outliers-- [ ] Verify assumptions using assumption_checks.py-- [ ] Run primary analysis-- [ ] Calculate effect sizes with confidence intervals-- [ ] Conduct post-hoc tests if needed (with corrections)-- [ ] Create visualizations-- [ ] Write results following reporting_standards.md-- [ ] Conduct sensitivity analyses-- [ ] Share data and code-------## Support and Further Reading--For questions about:-- **Test selection**: See references/test_selection_guide.md-- **Assumptions**: See references/assumptions_and_diagnostics.md-- **Effect sizes**: See references/effect_sizes_and_power.md-- **Bayesian methods**: See references/bayesian_statistics.md-- **Reporting**: See references/reporting_standards.md--**Key textbooks**:-- Cohen, J. (1988). *Statistical Power Analysis for the Behavioral Sciences*-- Field, A. (2013). *Discovering Statistics Using IBM SPSS Statistics*-- Gelman, A., & Hill, J. (2006). *Data Analysis Using Regression and Multilevel/Hierarchical Models*-- Kruschke, J. K. (2014). *Doing Bayesian Data Analysis*+## Statistical Integrity-**Online resources**:-- APA Style Guide: https://apastyle.apa.org/-- Statistical Consulting: Cross Validated (stats.stackexchange.com)+These are the practices that keep an analysis defensible. They matter because the most common statistical failures are not computational errors — they are silent flexibility (testing until something works) and selective reporting.+1. **Distinguish confirmatory from exploratory.** State the planned analysis before running it; label anything discovered along the way as exploratory.+2. **Don't shop for significance.** If the planned test is non-significant, that is the result. Trying alternative tests, subgroups, or outlier-removal schemes until p < .05 invalidates the p-value.+3. **Correct for multiple comparisons** when running families of tests (Tukey HSD for post-hoc ANOVA; Holm or Benjamini-Hochberg FDR for other families) and say which correction was used.+4. **A non-significant result is not evidence of no effect.** With small n, the study may simply have been underpowered — run a sensitivity analysis, or use a Bayesian analysis / equivalence test to actually quantify support for the null.+5. **Statistical significance is not practical importance.** With large n, trivial effects reach p < .001. Lead the interpretation with the effect size.+6. **Understand missing data before dropping rows.** Listwise deletion is only safe when data are missing completely at random; otherwise consider multiple imputation and say what was done.+7. **Make it reproducible.** Set random seeds, report library versions for simulation-based methods, and keep the analysis in a runnable script.diff --git a/skills/statistical-analysis/references/assumptions_and_diagnostics.md b/skills/statistical-analysis/references/assumptions_and_diagnostics.mdindex 9b1d2b46..62bf447a 100644--- a/skills/statistical-analysis/references/assumptions_and_diagnostics.md+++ b/skills/statistical-analysis/references/assumptions_and_diagnostics.md@@ -48,8 +48,8 @@ This document provides comprehensive guidance on checking and validating statist- Kernel density plot**Formal tests** (secondary):-- Shapiro-Wilk test (recommended for n < 50)-- Kolmogorov-Smirnov test+- Shapiro-Wilk test (good default; scipy handles n up to ~5000 and warns above that)+- Lilliefors test (`statsmodels.stats.diagnostic.lilliefors`) — use this instead of a plain Kolmogorov-Smirnov test, which is invalid when the mean/SD are estimated from the data- Anderson-Darling test**Python implementation**:@@ -71,7 +71,7 @@ stats.probplot(data, dist="norm", plot=plt)- Look for severe skewness, outliers, or bimodality**What to do if violated**:-- **Mild violations** (slight skewness): Proceed if n > 30 per group+- **Mild violations** (slight skewness): Proceed if n > 30 per group (this CLT heuristic assumes mild skewness; severely skewed or heavy-tailed data can require much larger samples)- **Moderate violations**: Use non-parametric alternatives (Mann-Whitney, Kruskal-Wallis, Wilcoxon)- **Severe violations**:- Transform data (log, square root, Box-Cox)@@ -115,6 +115,8 @@ statistic, p_value = stats.levene(group1, group2, group3)# For regression# Breusch-Pagan test+# Note: exog must include the constant column (e.g. exog = sm.add_constant(X),+# or pass the fitted model's model.exog)from statsmodels.stats.diagnostic import het_breuschpagan_, p_value, _, _ = het_breuschpagan(residuals, exog)```@@ -160,7 +162,9 @@ stats.levene(group1, group2)# If assumptions violated:# Option 1: Welch's t-test (unequal variances)-pg.ttest(group1, group2, correction=False) # Welch's+pg.ttest(group1, group2, correction=True) # correction=True applies Welch's+# (correction='auto' applies Welch only when variances/group sizes are unequal;+# correction=False forces Student's t-test)# Option 2: Non-parametric alternativepg.mwu(group1, group2) # Mann-Whitney U@@ -181,14 +185,16 @@ pg.mwu(group1, group2) # Mann-Whitney U**Diagnostic workflow**:```pythonimport pingouin as pg+from scipy import stats# Check normality per groupfor group in df['group'].unique():data = df[df['group'] == group]['value']- stats.shapiro(data)+ w, p = stats.shapiro(data)+ print(f"{group}: W = {w:.3f}, p = {p:.4f}")# Check homogeneity of variance-pg.homoscedasticity(df, dv='value', group='group')+print(pg.homoscedasticity(df, dv='value', group='group'))# For repeated measures: Check sphericity# Automatically tested in pingouin's rm_anova@@ -235,6 +241,7 @@ dw_statistic = durbin_watson(residuals)**3. Homoscedasticity**:```python# Breusch-Pagan test+# Note: exog must include the constant column (e.g. sm.add_constant(X))from statsmodels.stats.diagnostic import het_breuschpagan_, p_value, _, _ = het_breuschpagan(residuals, exog)@@ -295,18 +302,21 @@ vif_data["VIF"] = [variance_inflation_factor(X.values, i) for i in range(len(X.c**3. Influential observations**:```python-# Cook's distance, DFBetas, leverage-from statsmodels.stats.outliers_influence import OLSInfluence--influence = OLSInfluence(model)-cooks_d = influence.cooks_distance+# Cook's distance, DFBetas, leverage (statsmodels >= 0.10)+# Do NOT use OLSInfluence on Logit/GLM results; use get_influence(),+# which returns MLEInfluence (Logit) or GLMInfluence (GLM)+influence = model.get_influence()+cooks_d, cooks_p = influence.cooks_distance # returns a tuple: (distances, p_values)```-**4. Model fit**:+**4. Model fit / calibration**:```python-# Hosmer-Lemeshow test+# Calibration curve: compare predicted probabilities to observed event rates+# (e.g. sklearn.calibration.calibration_curve), plus the Brier score# Pseudo R-squared# Classification metrics (accuracy, AUC-ROC)+# Note: the Hosmer-Lemeshow test is not implemented in scipy/statsmodels+# and is sensitive to the choice of bins; prefer calibration curves```---@@ -341,7 +351,7 @@ cooks_d = influence.cooks_distance- **ANOVA**: n ≥ 30 per group- **Correlation**: n ≥ 30 for adequate power- **Simple regression**: n ≥ 50-- **Multiple regression**: n ≥ 10-20 per predictor (minimum 10 + k predictors)+- **Multiple regression**: 10-15 observations per predictor (or Green's rule: n ≥ 50 + 8k for testing the overall model with k predictors)- **Logistic regression**: n ≥ 10-20 events per predictor### Small Sample Considerationsdiff --git a/skills/statistical-analysis/references/bayesian_statistics.md b/skills/statistical-analysis/references/bayesian_statistics.mdindex 1e8b4594..2a1a84b3 100644--- a/skills/statistical-analysis/references/bayesian_statistics.md+++ b/skills/statistical-analysis/references/bayesian_statistics.md@@ -2,6 +2,22 @@This document provides guidance on conducting and interpreting Bayesian statistical analyses, which offer an alternative framework to frequentist (classical) statistics.+## Contents++- [Bayesian vs. Frequentist Philosophy](#bayesian-vs-frequentist-philosophy)+- [Bayes' Theorem](#bayes-theorem)+- [Prior Distributions](#prior-distributions)+- [Bayesian Hypothesis Testing](#bayesian-hypothesis-testing)+- [Bayesian Estimation](#bayesian-estimation)+- [Common Bayesian Analyses](#common-bayesian-analyses)+- [Hierarchical (Multilevel) Models](#hierarchical-multilevel-models)+- [Model Comparison](#model-comparison)+- [Checking Bayesian Models](#checking-bayesian-models)+- [Reporting Bayesian Results](#reporting-bayesian-results)+- [Advantages and Limitations](#advantages-and-limitations)+- [Key Python Packages](#key-python-packages)+- [When to Use Bayesian Methods](#when-to-use-bayesian-methods)+## Bayesian vs. Frequentist Philosophy### Fundamental Differences@@ -14,7 +30,7 @@ This document provides guidance on conducting and interpreting Bayesian statisti| **Primary output** | p-values, confidence intervals | Posterior probabilities, credible intervals || **Prior information** | Not formally incorporated | Explicitly incorporated via priors || **Hypothesis testing** | Reject/fail to reject null | Probability of hypotheses given data |-| **Sample size** | Often requires minimum | Can work with any sample size |+| **Sample size** | Often requires minimum | Works at any n, but small-n posteriors are prior-dominated — report a prior-sensitivity check || **Interpretation** | Indirect (probability of data given H₀) | Direct (probability of hypothesis given data) |### Key Question Difference@@ -88,7 +104,7 @@ Where:**Example priors**:- Effect size: Normal(0, 1) or Cauchy(0, 0.707)- Variance: Half-Cauchy(0, 1)-- Correlation: Uniform(-1, 1) or Beta(2, 2)+- Correlation: Uniform(-1, 1), a rescaled Beta on (-1, 1) (e.g. 2×Beta(2, 2)−1; plain Beta(2, 2) has support [0, 1]), or an LKJ prior for correlation matrices**Advantages**:- Balances objectivity and regularization@@ -142,7 +158,7 @@ for name, mu_prior, sigma_prior in prior_specs:with pm.Model() as model:effect = pm.Normal('effect', mu=mu_prior, sigma=sigma_prior)# ... likelihood and observed data- trace = pm.sample(2000, tune=1000, return_inferencedata=True)+ trace = pm.sample(2000, tune=1000)results[name] = trace```@@ -177,7 +193,7 @@ BF₁₀ = P(D|H₁) / P(D|H₀)**Advantages over p-values**:1. Can provide evidence for null hypothesis-2. Not dependent on sampling intentions (no "peeking" problem)+2. Less dependent on sampling intentions than p-values — but only Bayes factors with fixed priors are relatively insensitive to optional stopping; posterior-based decision rules are still affected, and transparency requires reporting the stopping rule3. Directly quantifies evidence4. Can be updated with more data@@ -252,8 +268,8 @@ import arviz as az# Equal-tailed intervaleti = np.percentile(posterior_samples, [2.5, 97.5])-# HDI-hdi = az.hdi(posterior_samples, hdi_prob=0.95)+# HDI (ArviZ 1.x renamed the keyword hdi_prob= to prob=)+hdi = az.hdi(posterior_samples, prob=0.95)```---@@ -281,8 +297,9 @@ hdi = az.hdi(posterior_samples, hdi_prob=0.95)import matplotlib.pyplot as pltimport arviz as az-# Posterior plot with HDI-az.plot_posterior(trace, hdi_prob=0.95)+# Posterior plot with 95% credible interval+# (ArviZ 1.x replaced plot_posterior with plot_dist and hdi_prob= with ci_prob=)+az.plot_dist(trace, ci_prob=0.95)# Trace plot (check convergence)az.plot_trace(trace)@@ -327,7 +344,7 @@ with pm.Model() as model:diff = pm.Deterministic('diff', mu1 - mu2)# Sample posterior- trace = pm.sample(2000, tune=1000, return_inferencedata=True)+ trace = pm.sample(2000, tune=1000)# Analyze resultsprint(az.summary(trace, var_names=['mu1', 'mu2', 'diff']))@@ -336,8 +353,9 @@ print(az.summary(trace, var_names=['mu1', 'mu2', 'diff']))prob_greater = np.mean(trace.posterior['diff'].values > 0)print(f"P(μ₁ > μ₂) = {prob_greater:.3f}")-# Plot posterior-az.plot_posterior(trace, var_names=['diff'], ref_val=0)+# Plot posterior (ArviZ 1.x: plot_posterior was replaced by plot_dist;+# add a reference line at 0 with matplotlib if needed)+az.plot_dist(trace, var_names=['diff'])```---@@ -368,7 +386,7 @@ with pm.Model() as anova_model:sigma=sigma_within,observed=data)- trace = pm.sample(2000, tune=1000, return_inferencedata=True)+ trace = pm.sample(2000, tune=1000)# Posterior contrastscontrast_1_2 = trace.posterior['group_means'][:,:,0] - trace.posterior['group_means'][:,:,1]@@ -384,23 +402,31 @@ contrast_1_2 = trace.posterior['group_means'][:,:,0] - trace.posterior['group_me**Python implementation**:```python+import numpy as npimport pymc as pm+# Standardize both variables first: with z-scored data the bivariate normal+# can fix mu = [0, 0] and unit variances, leaving rho as the only free+# parameter (correlation is unchanged by linear rescaling). Alternatively,+# model the means and SDs as parameters (or use pm.LKJCholeskyCov).+xz = (x - x.mean()) / x.std()+yz = (y - y.mean()) / y.std()+with pm.Model() as corr_model:# Prior on correlationrho = pm.Uniform('rho', lower=-1, upper=1)- # Convert to covariance matrix+ # Correlation (= covariance) matrix for standardized datacov_matrix = pm.math.stack([[1, rho],[rho, 1]])- # Likelihood (bivariate normal)+ # Likelihood (bivariate normal on standardized data)obs = pm.MvNormal('obs',mu=[0, 0],cov=cov_matrix,- observed=np.column_stack([x, y]))+ observed=np.column_stack([xz, yz]))- trace = pm.sample(2000, tune=1000, return_inferencedata=True)+ trace = pm.sample(2000, tune=1000)# Summarize correlationprint(az.summary(trace, var_names=['rho']))@@ -426,29 +452,33 @@ prob_positive = np.mean(trace.posterior['rho'].values > 0)import pymc as pmwith pm.Model() as regression_model:+ # Mutable data container: required for pm.set_data() to swap in new+ # predictors later (a raw array would make set_data fail)+ X_data = pm.Data('X', X)+# Priors for coefficientsalpha = pm.Normal('alpha', mu=0, sigma=10) # Interceptbeta = pm.Normal('beta', mu=0, sigma=10, shape=n_predictors)sigma = pm.HalfNormal('sigma', sigma=10)# Expected value- mu = alpha + pm.math.dot(X, beta)+ mu = alpha + pm.math.dot(X_data, beta)- # Likelihood- y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y)+ # Likelihood (shape=mu.shape lets predictions resize with new data)+ y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=y, shape=mu.shape)- trace = pm.sample(2000, tune=1000, return_inferencedata=True)+ trace = pm.sample(2000, tune=1000)# Posterior predictive checkswith regression_model:ppc = pm.sample_posterior_predictive(trace)-az.plot_ppc(ppc)+az.plot_ppc_dist(ppc) # ArviZ 1.x: plot_ppc was replaced by plot_ppc_dist# Predictions with uncertaintywith regression_model:pm.set_data({'X': X_new})- posterior_pred = pm.sample_posterior_predictive(trace)+ posterior_pred = pm.sample_posterior_predictive(trace, predictions=True)```---@@ -504,26 +534,28 @@ with pm.Model() as hierarchical_model:**WAIC (Widely Applicable Information Criterion)**:- Bayesian analog of AIC-- Lower is better+- Reported on the elpd (expected log pointwise predictive density) scale: HIGHER elpd is better (only on the deviance scale, −2 × elpd, is lower better)- Accounts for effective number of parameters+- `az.waic` was removed in ArviZ 1.x — use LOO**LOO (Leave-One-Out Cross-Validation)**:- Estimates out-of-sample prediction error-- Lower is better+- Also on the elpd scale: higher elpd is better- More robust than WAIC**Python calculation**:```pythonimport arviz as az+import pymc as pm-# Calculate WAIC and LOO-waic = az.waic(trace)-loo = az.loo(trace)+# LOO needs pointwise log-likelihoods+with model:+ pm.compute_log_likelihood(trace)-print(f"WAIC: {waic.elpd_waic:.2f}")-print(f"LOO: {loo.elpd_loo:.2f}")+loo = az.loo(trace)+print(f"LOO elpd: {loo.elpd:.2f}") # higher is better-# Compare multiple models+# Compare multiple models: az.compare ranks them correctly (rank 0 = best)comparison = az.compare({'model1': trace1,'model2': trace2,@@ -547,7 +579,7 @@ print(comparison)**Effective Sample Size (ESS)**:- Number of independent samples- Higher is better-- ESS > 400 per chain recommended+- Bulk-ESS > 400 in total across all chains recommended (Vehtari et al., 2021); also check tail-ESS**Trace plots**:- Should look like "fuzzy caterpillar"@@ -579,13 +611,16 @@ az.plot_rank(trace) # Rank plotswith model:ppc = pm.sample_posterior_predictive(trace)-# Visual check-az.plot_ppc(ppc, num_pp_samples=100)+# Visual check (ArviZ 1.x: plot_ppc was replaced by plot_ppc_dist)+az.plot_ppc_dist(ppc, num_samples=100)-# Quantitative checks+# Quantitative check: compute the statistic per posterior draw over the+# observation dimension (do NOT iterate the array directly - that loops+# over chains, not draws)obs_mean = np.mean(observed_data)-pred_means = [np.mean(sample) for sample in ppc.posterior_predictive['y_obs']]-p_value = np.mean(pred_means >= obs_mean) # Bayesian p-value+pp = ppc.posterior_predictive['y_obs'] # dims: (chain, draw, obs)+pred_means = pp.mean(dim=pp.dims[-1]).values.ravel() # one mean per draw+p_value = np.mean(pred_means >= obs_mean) # Bayesian (posterior predictive) p-value```---@@ -609,9 +644,9 @@ p_value = np.mean(pred_means >= obs_mean) # Bayesian p-value1. **Intuitive interpretation**: Direct probability statements about parameters2. **Incorporates prior knowledge**: Uses all available information3. **Flexible**: Handles complex models easily-4. **No p-hacking**: Can look at data as it arrives+4. **Less sensitive to optional stopping**: Bayes factors with fixed priors are relatively robust to analyzing data as it arrives, but posterior-based decision rules are still affected — always report the stopping rule5. **Quantifies uncertainty**: Full posterior distribution-6. **Small samples**: Works with any sample size+6. **Small samples**: Works at any sample size (but small-n posteriors are prior-dominated — report a prior-sensitivity check)### Limitations@@ -625,12 +660,12 @@ p_value = np.mean(pred_means >= obs_mean) # Bayesian p-value## Key Python Packages-Install with uv (see SKILL.md). ArviZ 0.23+ requires Python 3.12+.+Install with uv (see SKILL.md). ArviZ requires Python >= 3.10. ArviZ 1.x is the current line and is a breaking rewrite: `az.summary` defaults to 89% intervals and takes `ci_prob=` (the old `hdi_prob=` keyword is gone), `az.hdi` takes `prob=`, `az.plot_posterior`/`az.plot_ppc` were replaced by `az.plot_dist`/`az.plot_ppc_dist`, and `az.waic` was removed (use `az.loo`).- **PyMC** (`pymc>=5`): Full Bayesian modeling framework-- **ArviZ** (`arviz>=0.17`): Visualization and diagnostics ([docs](https://python.arviz.org))+- **ArviZ** (`arviz>=1.0`): Visualization and diagnostics ([docs](https://python.arviz.org))- **Bambi**: High-level interface for regression models (`uv pip install bambi`)-- **PyStan**: Python interface to Stan+- **cmdstanpy**: Python interface to Stan (use instead of the discontinued PyStan)- **TensorFlow Probability**: Bayesian inference with TensorFlow---diff --git a/skills/statistical-analysis/references/effect_sizes_and_power.md b/skills/statistical-analysis/references/effect_sizes_and_power.mdindex 14c47455..ad938113 100644--- a/skills/statistical-analysis/references/effect_sizes_and_power.md+++ b/skills/statistical-analysis/references/effect_sizes_and_power.md@@ -42,6 +42,7 @@ import numpy as np# Independent t-test with effect sizeresult = pg.ttest(group1, group2, correction=False)cohens_d = result['cohen_d'].values[0]+# (pingouin 0.6.0 renamed columns; on 0.5.x use 'p-val', 'cohen-d', 'CI95%', 'p-unc')# Manual calculationmean_diff = np.mean(group1) - np.mean(group2)@@ -55,9 +56,13 @@ cohens_d = result['cohen_d'].values[0]**Confidence intervals for d**:```python-from pingouin import compute_effsize_from_t+import pingouin as pg-d, ci = compute_effsize_from_t(t_statistic, nx=n1, ny=n2, eftype='cohen')+# compute_effsize_from_t returns only the point estimate;+# get the CI separately with compute_esci+d = pg.compute_effsize(group1, group2, eftype='cohen')+ci = pg.compute_esci(stat=d, nx=len(group1), ny=len(group2),+ eftype='cohen', confidence=0.95)```---@@ -70,8 +75,8 @@ d, ci = compute_effsize_from_t(t_statistic, nx=n1, ny=n2, eftype='cohen')**Python calculation**:```python-result = pg.ttest(group1, group2, correction=False)-hedges_g = result['hedges'].values[0]+# pg.ttest output has no Hedges' g column; compute it directly+hedges_g = pg.compute_effsize(group1, group2, eftype='hedges')```**Use Hedges' g when**:@@ -105,19 +110,19 @@ hedges_g = result['hedges'].values[0]- Medium: η² = 0.06 (6% of variance)- Large: η² = 0.14 (14% of variance)-**Limitation**: Biased with multiple factors (sums to > 1.0)+**Limitation**: In multi-factor designs each effect's η² shrinks as other factors are added (classical η² values sum to ≤ 1.0 by construction); it is partial η² that can sum to > 1.0 across factors**Python calculation**:```pythonimport pingouin as pg-# One-way ANOVA-aov = pg.anova(dv='value', between='group', data=df)+# One-way ANOVA (detailed=True is required for the SS column)+aov = pg.anova(dv='value', between='group', data=df, detailed=True)eta_squared = aov['SS'][0] / aov['SS'].sum()-# Or use pingouin directly-aov = pg.anova(dv='value', between='group', data=df, detailed=True)-eta_squared = aov['np2'][0] # Note: pingouin reports partial eta-squared+# Or read pingouin's np2 column, which is PARTIAL eta-squared:+partial_eta_sq = aov['np2'][0]+# np2 coincides with classical eta-squared only for one-way (single-factor) designs```---@@ -132,6 +137,8 @@ eta_squared = aov['np2'][0] # Note: pingouin reports partial eta-squared**When to use**: Multi-factor ANOVA (standard in factorial designs)+**Limitation**: Across factors, partial η² values can sum to > 1.0 — they are not additive shares of total variance+**Python calculation**:```pythonaov = pg.anova(dv='value', between=['factor1', 'factor2'], data=df)@@ -207,7 +214,7 @@ import pingouin as pg# Pearson correlation with CIresult = pg.corr(x, y, method='pearson')r = result['r'].values[0]-ci = result['CI95'].values[0] # Pingouin 0.5+: was CI95%+ci = result['CI95'].values[0] # pingouin 0.6.0 renamed CI95% to CI95# Spearman correlationresult = pg.corr(x, y, method='spearman')@@ -235,10 +242,10 @@ rho = result['r'].values[0]**Python calculation**:```pythonfrom sklearn.metrics import r2_score-from statsmodels.api import OLS+import statsmodels.api as sm-# Using statsmodels-model = OLS(y, X).fit()+# Using statsmodels (add_constant adds the intercept column)+model = sm.OLS(y, sm.add_constant(X)).fit()r_squared = model.rsquaredadjusted_r_squared = model.rsquared_adj@@ -285,7 +292,7 @@ beta = model.params**What it measures**: Effect size for individual predictors or model comparison-**Formula**: f² = R²_AB - R²_A / (1 - R²_AB)+**Formula**: f² = (R²_AB - R²_A) / (1 - R²_AB)Where:- R²_AB = R² for full model with predictor@@ -320,22 +327,28 @@ f_squared = (r2_full - r2_reduced) / (1 - r2_full)Where k = min(rows, columns)-**Interpretation** (for k > 2):-- Small: V = 0.07-- Medium: V = 0.21-- Large: V = 0.35+**Interpretation** (benchmarks depend on df* = min(rows, columns) − 1):++| df* | Small | Medium | Large |+|-----|-------|--------|-------|+| 1 (2×2) | 0.10 | 0.30 | 0.50 |+| 2 | 0.07 | 0.21 | 0.35 |+| 3 | 0.06 | 0.17 | 0.29 |**For 2×2 tables**: Use phi coefficient (φ)**Python calculation**:```python+import numpy as npfrom scipy.stats.contingency import association# Cramér's Vcramers_v = association(contingency_table, method='cramer')-# Phi coefficient (for 2x2)-phi = association(contingency_table, method='pearson')+# Phi coefficient (2x2): |phi| equals Cramér's V for a 2x2 table.+# Caution: method='pearson' is Pearson's contingency coefficient, NOT phi.+a, b, c, d = np.asarray(contingency_table).ravel()+phi = (a * d - b * c) / np.sqrt((a + b) * (c + d) * (a + c) * (b + d)) # signed phi```---@@ -367,15 +380,21 @@ phi = association(contingency_table, method='pearson')**Python calculation**:```python+import numpy as np+from scipy import statsimport statsmodels.api as sm# From contingency tableodds_ratio = (a * d) / (b * c)-# Confidence interval+# Fisher's exact test returns only the sample OR and a p-value (no CI)table = np.array([[a, b], [c, d]])oddsratio, pvalue = stats.fisher_exact(table)+# Odds-ratio confidence interval (scipy >= 1.10; conditional MLE estimate)+or_result = stats.contingency.odds_ratio(table)+ci = or_result.confidence_interval(confidence_level=0.95)+# From logistic regressionmodel = sm.Logit(y, X).fit()odds_ratios = np.exp(model.params) # Exponentiate coefficients@@ -384,6 +403,36 @@ ci = np.exp(model.conf_int()) # Exponentiate CIs---+### Nonparametric Effect Sizes++**Rank-biserial correlation (r_rb)**: Effect size for Mann-Whitney U and Wilcoxon signed-rank tests (range −1 to 1; interpret |r_rb| roughly like r). Returned by `pg.mwu` and `pg.wilcoxon` as the `RBC` column.++**Common-language effect size (CLES)**: Probability that a randomly sampled value from one group exceeds a randomly sampled value from the other (0.5 = no effect). Returned by `pg.mwu` as `CLES`.++**r = z / √N**: Classic effect size when a z approximation is reported for Mann-Whitney/Wilcoxon (small 0.10, medium 0.30, large 0.50).++**Epsilon-squared (ε²)**: Effect size for Kruskal-Wallis: ε² = H × (n + 1) / (n² − 1).++**Python calculation**:+```python+import numpy as np+import pandas as pd+import pingouin as pg++res = pg.mwu(group1, group2)+print(res[['U_val', 'p_val', 'RBC', 'CLES']])++# Kruskal-Wallis with epsilon-squared+df = pd.DataFrame({'value': np.concatenate([group1, group2, group3]),+ 'group': np.repeat(['a', 'b', 'c'],+ [len(group1), len(group2), len(group3)])})+kw = pg.kruskal(df, dv='value', between='group')+H, n = kw['H'].values[0], len(df)+epsilon_sq = H * (n + 1) / (n**2 - 1)+```++---+### Bayesian Effect Sizes#### Bayes Factor (BF)@@ -394,16 +443,11 @@ ci = np.exp(model.conf_int()) # Exponentiate CIs- BF₁₀ = 1: Equal evidence for H₁ and H₀- BF₁₀ = 3: H₁ is 3× more likely than H₀ (moderate evidence)- BF₁₀ = 10: H₁ is 10× more likely than H₀ (strong evidence)-- BF₁₀ = 100: H₁ is 100× more likely than H₀ (decisive evidence)+- BF₁₀ > 100: Decisive evidence for H₁ (30-100 counts as "very strong" on the Jeffreys scale)- BF₁₀ = 0.33: H₀ is 3× more likely than H₁- BF₁₀ = 0.10: H₀ is 10× more likely than H₁-**Classification** (Jeffreys, 1961):-- 1-3: Anecdotal evidence-- 3-10: Moderate evidence-- 10-30: Strong evidence-- 30-100: Very strong evidence-- >100: Decisive evidence+For the full Jeffreys interpretation table and BF reporting language, see `bayesian_statistics.md`.**Python calculation**:```python@@ -416,6 +460,29 @@ bf10 = result['BF10'].values[0]---+### Bootstrap Confidence Intervals++When no analytic CI exists for an effect size (or its assumptions are doubtful), bootstrap one:++```python+import numpy as np+from scipy import stats++def cohen_d(x, y):+ nx, ny = len(x), len(y)+ sp = np.sqrt(((nx - 1) * np.var(x, ddof=1) + (ny - 1) * np.var(y, ddof=1))+ / (nx + ny - 2))+ return (np.mean(x) - np.mean(y)) / sp++boot = stats.bootstrap((group1, group2), cohen_d, n_resamples=9999,+ method='BCa', rng=np.random.default_rng(42))+print(boot.confidence_interval) # 95% BCa CI by default+```++The same pattern works for any statistic (medians, correlations, rank-biserial, ...). Prefer `method='BCa'` and use at least 5000-10000 resamples.++---+## Power Analysis### Concepts@@ -462,14 +529,16 @@ n_required = tt_ind_solve_power(alternative='two-sided')-# ANOVA power analysis+# ANOVA power analysis (kwarg is k_groups, not ngroups)anova_power = FTestAnovaPower()-n_per_group = anova_power.solve_power(+n_total = anova_power.solve_power(effect_size=0.25, # Cohen's f- ngroups=3,+ k_groups=3,alpha=0.05,power=0.80)+# Returns the TOTAL sample size across all groups:+# f = 0.25, k = 3 -> ~158 total, i.e. ~53 per group# Correlation power analysisfrom pingouin import power_corr@@ -539,8 +608,7 @@ print(f"With n=50 per group, we could detect d ≥ {detectable_effect:.2f}")**Regression example**:> "The regression model significantly predicted exam scores, F(3, 146) = 45.2, p < .001, R² = .48. Study hours (β = .52, p < .001) and prior GPA (β = .31, p < .001) were significant predictors."-**Bayesian example**:-> "A Bayesian independent samples t-test provided strong evidence for a difference between groups, BF₁₀ = 23.5, indicating the data are 23.5 times more likely under H₁ than H₀."+**Bayesian example**: See `bayesian_statistics.md` (Reporting Bayesian Results) for Bayes Factor and posterior reporting templates.---@@ -566,8 +634,11 @@ print(f"With n=50 per group, we could detect d ≥ {detectable_effect:.2f}")| Correlation | r, ρ | 0.10 | 0.30 | 0.50 || Regression | R² | 0.02 | 0.13 | 0.26 || Regression | f² | 0.02 | 0.15 | 0.35 |-| Chi-square | Cramér's V | 0.07 | 0.21 | 0.35 |-| Chi-square (2×2) | φ | 0.10 | 0.30 | 0.50 |+| Chi-square (df* = 1, 2×2) | Cramér's V, φ | 0.10 | 0.30 | 0.50 |+| Chi-square (df* = 2) | Cramér's V | 0.07 | 0.21 | 0.35 |+| Chi-square (df* = 3) | Cramér's V | 0.06 | 0.17 | 0.29 |++*Note*: df* = min(rows, columns) − 1.---diff --git a/skills/statistical-analysis/references/reporting_standards.md b/skills/statistical-analysis/references/reporting_standards.mdindex 5ca231f5..59b685ad 100644--- a/skills/statistical-analysis/references/reporting_standards.md+++ b/skills/statistical-analysis/references/reporting_standards.md@@ -152,7 +152,7 @@ This document provides guidelines for reporting statistical analyses according t**What to report**:- Test statistic (t)- Degrees of freedom-- p-value (exact if p > .001, otherwise p < .001)+- p-value (exact if p ≥ .001, otherwise p < .001)- Effect size (Cohen's d or Hedges' g) with CI- Direction of effect- Whether test was one- or two-tailed@@ -192,7 +192,9 @@ This document provides guidelines for reporting statistical analyses according t> "A 2 (feedback: positive vs. negative) × 2 (timing: immediate vs. delayed) between-subjects ANOVA revealed a significant main effect of feedback, F(1, 146) = 12.34, p < .001, η²_p = .08, but no significant main effect of timing, F(1, 146) = 2.10, p = .15, η²_p = .01. Critically, the interaction was significant, F(1, 146) = 6.78, p = .01, η²_p = .04. Simple effects analysis showed that positive feedback improved performance for immediate timing (M_diff = 8.2, p < .001) but not for delayed timing (M_diff = 1.3, p = .42)."**Example (repeated measures ANOVA)**:-> "A one-way repeated measures ANOVA revealed a significant effect of time point on anxiety scores, F(2, 98) = 15.67, p < .001, η²_p = .24. Mauchly's test indicated that the assumption of sphericity was violated, χ²(2) = 8.45, p = .01, therefore Greenhouse-Geisser corrected values are reported (ε = 0.87). Pairwise comparisons with Bonferroni correction showed..."+> "Mauchly's test indicated that the assumption of sphericity was violated, χ²(2) = 8.45, p = .01, therefore Greenhouse-Geisser corrected degrees of freedom are reported (ε = 0.87). A one-way repeated measures ANOVA revealed a significant effect of time point on anxiety scores, F(1.74, 85.26) = 15.67, p < .001, η²_p = .24. Pairwise comparisons with Bonferroni correction showed..."++(Note: the corrected df are the uncorrected df multiplied by ε: 2 × 0.87 = 1.74 and 98 × 0.87 = 85.26.)---@@ -272,7 +274,7 @@ This document provides guidelines for reporting statistical analyses according t> "A Wilcoxon signed-rank test showed that scores increased significantly from pretest (Mdn = 65, IQR = 15) to posttest (Mdn = 72, IQR = 14), z = 3.89, p < .001, r = .39."**Kruskal-Wallis**:-> "A Kruskal-Wallis test revealed significant differences among the three conditions, H(2) = 15.7, p < .001, η² = .09. Follow-up pairwise comparisons with Bonferroni correction showed..."+> "A Kruskal-Wallis test revealed significant differences among the three conditions, H(2) = 15.7, p < .001, ε² = .09 (epsilon-squared). Follow-up pairwise comparisons with Bonferroni correction showed..."---@@ -289,7 +291,9 @@ This document provides guidelines for reporting statistical analyses according t> "A Bayesian independent samples t-test was conducted using weakly informative priors (Normal(0, 1) for mean difference). The posterior distribution of the mean difference had a mean of 6.8 (95% credible interval [3.2, 10.4]), indicating that Group A scored higher than Group B. The Bayes Factor BF₁₀ = 45.3 provided very strong evidence for a difference between groups. There was a 99.8% posterior probability that Group A's mean exceeded Group B's mean."**Example (Bayesian regression)**:-> "A Bayesian linear regression was fitted with weakly informative priors (Normal(0, 10) for coefficients, Half-Cauchy(0, 5) for residual SD). The model showed that study hours credibly predicted exam scores (β = 0.52, 95% CI [0.38, 0.66]; 0 not included in interval). All convergence diagnostics were satisfactory (R-hat < 1.01, ESS > 1000 for all parameters). Posterior predictive checks indicated adequate model fit."+> "A Bayesian linear regression was fitted with weakly informative priors (Normal(0, 10) for coefficients, Half-Cauchy(0, 5) for residual SD). The model showed that study hours credibly predicted exam scores (β = 0.52, 95% CrI [0.38, 0.66]; 0 not included in the credible interval). All convergence diagnostics were satisfactory (R-hat < 1.01, ESS > 1000 for all parameters). Posterior predictive checks indicated adequate model fit."++(Write "95% CrI" or "95% credible interval" for Bayesian intervals to distinguish them from frequentist confidence intervals.)---@@ -388,7 +392,7 @@ This document provides guidelines for reporting statistical analyses according t5. **Only reporting significant results**: Report all planned analyses6. **Using "prove" or "confirm"**: Use "support" or "consistent with"7. **Saying "marginally significant" for .05 < p < .10**: Either significant or not-8. **Reporting only one decimal for p-values**: Use two (p = .03, not p = .0)+8. **Reporting only one decimal for p-values**: APA style uses two or three decimals (p = .03 or p = .034, not p = .0)9. **Not specifying one- vs. two-tailed**: Always clarify10. **Inconsistent rounding**: Be consistent throughout@@ -414,6 +418,15 @@ This document provides guidelines for reporting statistical analyses according t- Confidence interval (may include meaningful values)- Power analysis (was study adequately powered?)+**To claim equivalence**: p > .05 is not evidence of equivalence. Run an equivalence test (TOST) against a pre-specified smallest effect size of interest, or a Bayesian ROPE analysis (see bayesian_statistics.md):++```python+import pingouin as pg++# TOST: is the group difference within +/- 0.5 raw units?+print(pg.tost(group_a, group_b, bound=0.5)) # significant pval -> equivalence+```+**Example**:> "Contrary to our hypothesis, there was no significant difference in creativity scores between the music (M = 72.1, SD = 8.3) and silence (M = 70.5, SD = 8.9) conditions, t(98) = 0.91, p = .36, d = 0.18, 95% CI [-0.21, 0.57]. A post hoc sensitivity analysis revealed that the study had 80% power to detect an effect of d = 0.57 or larger, suggesting the null finding may reflect insufficient power to detect small effects."diff --git a/skills/statistical-analysis/scripts/assumption_checks.py b/skills/statistical-analysis/scripts/assumption_checks.pyindex 72a55459..6c477f39 100644--- a/skills/statistical-analysis/scripts/assumption_checks.py+++ b/skills/statistical-analysis/scripts/assumption_checks.py@@ -406,6 +406,119 @@ def detect_outliers(}+def check_regression_diagnostics(+ model,+ alpha: float = 0.05,+ plot: bool = True+) -> Dict:+ """+ Run standard diagnostics on a fitted statsmodels OLS model.++ Produces the classic 4-panel diagnostic plot (residuals vs fitted,+ Q-Q, scale-location, residual histogram) plus formal tests:+ normality of residuals (Shapiro-Wilk), heteroscedasticity+ (Breusch-Pagan), autocorrelation (Durbin-Watson), and+ multicollinearity (VIF per predictor).++ Parameters+ ----------+ model : statsmodels regression results+ A fitted model from ``sm.OLS(y, X).fit()`` where X includes+ a constant (``sm.add_constant``).+ alpha : float+ Significance level for the formal tests.+ plot : bool+ Whether to create the 4-panel diagnostic figure.++ Returns+ -------+ dict+ Test results, VIF table, and per-assumption interpretations.+ """+ from statsmodels.stats.diagnostic import het_breuschpagan+ from statsmodels.stats.stattools import durbin_watson+ from statsmodels.stats.outliers_influence import variance_inflation_factor++ residuals = np.asarray(model.resid)+ fitted = np.asarray(model.fittedvalues)+ exog = model.model.exog+ exog_names = list(model.model.exog_names)++ # Normality of residuals+ sw_stat, sw_p = stats.shapiro(residuals)++ # Heteroscedasticity (Breusch-Pagan)+ bp_lm, bp_p, _, _ = het_breuschpagan(residuals, exog)++ # Autocorrelation (Durbin-Watson: ~2 = none, <1.5 or >2.5 = concern)+ dw = durbin_watson(residuals)++ # Multicollinearity (VIF, skipping the constant)+ vif_rows = []+ for i, name in enumerate(exog_names):+ if name.lower() in ("const", "intercept"):+ continue+ vif_rows.append({'Variable': name,+ 'VIF': variance_inflation_factor(exog, i)})+ vif_table = pd.DataFrame(vif_rows)+ max_vif = vif_table['VIF'].max() if not vif_table.empty else np.nan++ if plot:+ fig, axes = plt.subplots(2, 2, figsize=(12, 10))++ axes[0, 0].scatter(fitted, residuals, alpha=0.6, edgecolors='black', linewidths=0.5)+ axes[0, 0].axhline(y=0, color='r', linestyle='--')+ axes[0, 0].set_xlabel('Fitted values')+ axes[0, 0].set_ylabel('Residuals')+ axes[0, 0].set_title('Residuals vs Fitted')+ axes[0, 0].grid(alpha=0.3)++ stats.probplot(residuals, dist="norm", plot=axes[0, 1])+ axes[0, 1].set_title('Normal Q-Q')+ axes[0, 1].grid(alpha=0.3)++ std_resid = residuals / residuals.std()+ axes[1, 0].scatter(fitted, np.sqrt(np.abs(std_resid)), alpha=0.6,+ edgecolors='black', linewidths=0.5)+ axes[1, 0].set_xlabel('Fitted values')+ axes[1, 0].set_ylabel('√|Standardized residuals|')+ axes[1, 0].set_title('Scale-Location')+ axes[1, 0].grid(alpha=0.3)++ axes[1, 1].hist(residuals, bins='auto', edgecolor='black', alpha=0.7)+ axes[1, 1].set_xlabel('Residuals')+ axes[1, 1].set_ylabel('Frequency')+ axes[1, 1].set_title('Histogram of Residuals')+ axes[1, 1].grid(alpha=0.3, axis='y')++ plt.tight_layout()+ plt.show()++ issues = []+ if sw_p <= alpha:+ issues.append("non-normal residuals (consider transformation or robust/bootstrap inference)")+ if bp_p <= alpha:+ issues.append("heteroscedasticity (consider robust SEs, e.g. model.get_robustcov_results('HC3'), or WLS)")+ if dw < 1.5 or dw > 2.5:+ issues.append("possible autocorrelation (if data are ordered/temporal, use time-series methods or cluster-robust SEs)")+ if not np.isnan(max_vif) and max_vif > 5:+ issues.append("multicollinearity (VIF > 5; consider dropping/combining predictors)")++ return {+ 'residual_normality': {'test': 'Shapiro-Wilk', 'statistic': sw_stat,+ 'p_value': sw_p, 'ok': sw_p > alpha},+ 'heteroscedasticity': {'test': 'Breusch-Pagan', 'statistic': bp_lm,+ 'p_value': bp_p, 'ok': bp_p > alpha},+ 'autocorrelation': {'test': 'Durbin-Watson', 'statistic': dw,+ 'ok': 1.5 <= dw <= 2.5},+ 'vif': vif_table,+ 'max_vif': max_vif,+ 'issues': issues,+ 'interpretation': ("No assumption concerns detected." if not issues+ else "Concerns: " + "; ".join(issues))+ }++def comprehensive_assumption_check(data: pd.DataFrame,value_col: str,