Upload folder using huggingface_hub
Browse files- README.md +33 -0
- envs/pathway_analysis_env/README.md +109 -0
- envs/pathway_analysis_env/__init__.py +27 -0
- envs/pathway_analysis_env/agent_openai_tools.json +161 -0
- envs/pathway_analysis_env/agent_openai_tools.py +178 -0
- envs/pathway_analysis_env/client.py +116 -0
- envs/pathway_analysis_env/data/eval_manifest_geo.json +18 -0
- envs/pathway_analysis_env/data/eval_manifest_geo2.json +26 -0
- envs/pathway_analysis_env/data/eval_manifest_geo3.json +34 -0
- envs/pathway_analysis_env/data/geo_eval/gse111151_tamoxifen_benchmark/gse111151_case.json +49 -0
- envs/pathway_analysis_env/data/geo_eval/gse111151_tamoxifen_benchmark/gse111151_counts.csv.gz +3 -0
- envs/pathway_analysis_env/data/geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_case.json +43 -0
- envs/pathway_analysis_env/data/geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_dataset2_subset_counts.csv.gz +3 -0
- envs/pathway_analysis_env/data/geo_eval/gse216540_tpm_pseudo_benchmark/gse216540_case.json +114 -0
- envs/pathway_analysis_env/data/geo_eval/gse216540_tpm_pseudo_benchmark/gse216540_id_to_symbol.json +0 -0
- envs/pathway_analysis_env/data/geo_eval/gse216540_tpm_pseudo_benchmark/gse216540_pseudo_counts.csv.gz +3 -0
- envs/pathway_analysis_env/docs/AGENT_EVAL.md +100 -0
- envs/pathway_analysis_env/docs/FAILURE_CODES.md +63 -0
- envs/pathway_analysis_env/docs/LLM_JUDGE_EVAL.md +63 -0
- envs/pathway_analysis_env/models.py +80 -0
- envs/pathway_analysis_env/openenv.yaml +6 -0
- envs/pathway_analysis_env/pyproject.toml +42 -0
- envs/pathway_analysis_env/scripts/append_task_to_manifest.py +90 -0
- envs/pathway_analysis_env/scripts/create_geo_task.py +197 -0
- envs/pathway_analysis_env/scripts/export_agent_safe_cases.py +45 -0
- envs/pathway_analysis_env/scripts/run_agent_eval_suite.py +123 -0
- envs/pathway_analysis_env/scripts/run_llm_agent_eval.py +614 -0
- envs/pathway_analysis_env/scripts/run_llm_judge.py +260 -0
- envs/pathway_analysis_env/server/Dockerfile +55 -0
- envs/pathway_analysis_env/server/__init__.py +5 -0
- envs/pathway_analysis_env/server/analysis.py +624 -0
- envs/pathway_analysis_env/server/app.py +128 -0
- envs/pathway_analysis_env/server/case_loader.py +79 -0
- envs/pathway_analysis_env/server/eval_protocol.py +102 -0
- envs/pathway_analysis_env/server/failure_codes.py +49 -0
- envs/pathway_analysis_env/server/gradio_ui.py +573 -0
- envs/pathway_analysis_env/server/pathway_environment.py +1112 -0
- envs/pathway_analysis_env/server/scoring.py +159 -0
- examples/pathway_agent_loop.py +138 -0
- tests/envs/test_pathway_agent_tools.py +77 -0
- tests/envs/test_pathway_analysis_env.py +335 -0
- tests/envs/test_pathway_case_loader.py +49 -0
- tests/envs/test_pathway_scoring.py +100 -0
README.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: OpenEnv Pathway Analysis Environment
|
| 3 |
+
emoji: 🧬
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 8000
|
| 8 |
+
tags:
|
| 9 |
+
- openenv
|
| 10 |
+
- bioinformatics
|
| 11 |
+
- ai-agents
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
# OpenEnv Pathway Analysis Environment
|
| 15 |
+
|
| 16 |
+
This repository packages `pathway_analysis_env` for Hugging Face Hub publication.
|
| 17 |
+
|
| 18 |
+
## Contents
|
| 19 |
+
- `envs/pathway_analysis_env/` environment code
|
| 20 |
+
- reproducible GEO benchmark inputs for 3 tasks
|
| 21 |
+
- task expansion scripts:
|
| 22 |
+
- `create_geo_task.py`
|
| 23 |
+
- `append_task_to_manifest.py`
|
| 24 |
+
|
| 25 |
+
## Run locally
|
| 26 |
+
```bash
|
| 27 |
+
uv sync --all-extras
|
| 28 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_agent_eval_suite.py --manifest envs/pathway_analysis_env/data/eval_manifest_geo3.json
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
## Note on Spaces
|
| 32 |
+
Publishing as a Docker Space from a free user namespace may require Hugging Face PRO.
|
| 33 |
+
This repo is ready for maintainers to deploy under an entitled namespace.
|
envs/pathway_analysis_env/README.md
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pathway Analysis Environment
|
| 2 |
+
|
| 3 |
+
`pathway_analysis_env` is an OpenEnv environment for evaluating tool-using agents
|
| 4 |
+
on a realistic RNA-seq-style analysis loop.
|
| 5 |
+
|
| 6 |
+
Each task gives:
|
| 7 |
+
- a gene-expression matrix (`counts_file`)
|
| 8 |
+
- sample groups (`sample_metadata`)
|
| 9 |
+
- a default contrast (reference vs alternate condition)
|
| 10 |
+
|
| 11 |
+
The agent must execute:
|
| 12 |
+
1. inspect/understand design
|
| 13 |
+
2. differential expression (which genes changed)
|
| 14 |
+
3. pathway enrichment (which biological programs are implicated)
|
| 15 |
+
4. submit a final pathway hypothesis
|
| 16 |
+
|
| 17 |
+
## Quick start
|
| 18 |
+
|
| 19 |
+
From repo root:
|
| 20 |
+
|
| 21 |
+
```bash
|
| 22 |
+
uv sync --all-extras
|
| 23 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_agent_eval_suite.py \
|
| 24 |
+
--manifest envs/pathway_analysis_env/data/eval_manifest_geo3.json
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Run LLM eval:
|
| 28 |
+
|
| 29 |
+
```bash
|
| 30 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_llm_agent_eval.py \
|
| 31 |
+
--manifest envs/pathway_analysis_env/data/eval_manifest_geo3.json
|
| 32 |
+
```
|
| 33 |
+
|
| 34 |
+
Run LLM judge for one case:
|
| 35 |
+
|
| 36 |
+
```bash
|
| 37 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_llm_judge.py \
|
| 38 |
+
--case geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_case.json \
|
| 39 |
+
--agent-model gpt-5 \
|
| 40 |
+
--judge-model gpt-5
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
## Add a new GEO task (2 commands)
|
| 44 |
+
|
| 45 |
+
### Where to download public data
|
| 46 |
+
|
| 47 |
+
Use NCBI GEO as the primary source:
|
| 48 |
+
|
| 49 |
+
- GEO home: [https://www.ncbi.nlm.nih.gov/geo/](https://www.ncbi.nlm.nih.gov/geo/)
|
| 50 |
+
- GEO DataSets search: [https://www.ncbi.nlm.nih.gov/gds](https://www.ncbi.nlm.nih.gov/gds)
|
| 51 |
+
- Series record page pattern: `https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSEXXXX`
|
| 52 |
+
|
| 53 |
+
From each series page, use:
|
| 54 |
+
- **Series Matrix File(s)** for metadata/expression tables
|
| 55 |
+
- **Supplementary file** links for count tables
|
| 56 |
+
|
| 57 |
+
If you need raw sequencing reads instead of processed tables:
|
| 58 |
+
- SRA home: [https://www.ncbi.nlm.nih.gov/sra](https://www.ncbi.nlm.nih.gov/sra)
|
| 59 |
+
- GEO-to-SRA links are usually available from the GEO series page
|
| 60 |
+
|
| 61 |
+
### 1) Create case + copy counts
|
| 62 |
+
|
| 63 |
+
Prepare a metadata CSV with columns:
|
| 64 |
+
- `sample_id`
|
| 65 |
+
- `condition`
|
| 66 |
+
|
| 67 |
+
Then run:
|
| 68 |
+
|
| 69 |
+
```bash
|
| 70 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/create_geo_task.py \
|
| 71 |
+
--task-id gseXXXX_example \
|
| 72 |
+
--accession GSEXXXX \
|
| 73 |
+
--summary "One-line study summary" \
|
| 74 |
+
--counts-file /absolute/path/to/counts.csv.gz \
|
| 75 |
+
--metadata-csv /absolute/path/to/samples.csv \
|
| 76 |
+
--reference-condition control \
|
| 77 |
+
--alternate-condition treated
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
This creates:
|
| 81 |
+
- `data/geo_eval/gseXXXX_example/gsexxxx_case.json`
|
| 82 |
+
- `data/geo_eval/gseXXXX_example/<counts file>`
|
| 83 |
+
|
| 84 |
+
### 2) Add it to a manifest
|
| 85 |
+
|
| 86 |
+
```bash
|
| 87 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/append_task_to_manifest.py \
|
| 88 |
+
--manifest envs/pathway_analysis_env/data/eval_manifest_geo3.json \
|
| 89 |
+
--episode-id geo_gseXXXX_example \
|
| 90 |
+
--case-file geo_eval/gseXXXX_example/gsexxxx_case.json \
|
| 91 |
+
--hypothesis "expected biological theme"
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
Now rerun eval on that manifest.
|
| 95 |
+
|
| 96 |
+
## Scripts
|
| 97 |
+
|
| 98 |
+
- `scripts/create_geo_task.py` — create a GEO case from counts + metadata.
|
| 99 |
+
- `scripts/append_task_to_manifest.py` — append/update one episode in a manifest.
|
| 100 |
+
- `scripts/run_agent_eval_suite.py` — run scripted environment evaluation.
|
| 101 |
+
- `scripts/run_llm_agent_eval.py` — run tool-calling LLM evaluation.
|
| 102 |
+
- `scripts/run_llm_judge.py` — score report quality with an LLM judge.
|
| 103 |
+
- `scripts/export_agent_safe_cases.py` — export secret-stripped case files.
|
| 104 |
+
|
| 105 |
+
## Notes
|
| 106 |
+
|
| 107 |
+
- Keep large intermediate artifacts (`de_all.json`, `enrichment.json`, `work/`) out of commits unless required.
|
| 108 |
+
- For reproducibility, commit only case JSON + minimal raw inputs (counts/metadata mapping) needed to rerun.
|
| 109 |
+
- Eval defaults are documented in `docs/AGENT_EVAL.md`.
|
envs/pathway_analysis_env/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Pathway Analysis Environment for OpenEnv.
|
| 9 |
+
|
| 10 |
+
A toy computational-biology environment where an agent identifies the
|
| 11 |
+
activated signaling pathway from synthetic omics data.
|
| 12 |
+
|
| 13 |
+
Example:
|
| 14 |
+
>>> from pathway_analysis_env import PathwayEnv, PathwayAction
|
| 15 |
+
>>>
|
| 16 |
+
>>> with PathwayEnv(base_url="http://localhost:8000") as client:
|
| 17 |
+
... result = client.reset()
|
| 18 |
+
... result = client.step(PathwayAction(action_type="inspect_dataset"))
|
| 19 |
+
... result = client.step(PathwayAction(action_type="run_differential_expression"))
|
| 20 |
+
... result = client.step(PathwayAction(action_type="run_pathway_enrichment"))
|
| 21 |
+
... result = client.step(PathwayAction(action_type="submit_answer", hypothesis="MAPK signaling"))
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from .client import PathwayEnv
|
| 25 |
+
from .models import PathwayAction, PathwayObservation, PathwayState
|
| 26 |
+
|
| 27 |
+
__all__ = ["PathwayEnv", "PathwayAction", "PathwayObservation", "PathwayState"]
|
envs/pathway_analysis_env/agent_openai_tools.json
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "openai_chat_completions_tools_v1",
|
| 3 |
+
"notes": [
|
| 4 |
+
"One function per environment action (recommended). Map tool name -> PathwayAction.action_type in the harness.",
|
| 5 |
+
"Call env reset() before the tool loop; reset is not an OpenAI tool.",
|
| 6 |
+
"Compatible with Chat Completions tools= and Responses API function tools (same shape)."
|
| 7 |
+
],
|
| 8 |
+
"tools": [
|
| 9 |
+
{
|
| 10 |
+
"type": "function",
|
| 11 |
+
"function": {
|
| 12 |
+
"name": "understand_experiment_design",
|
| 13 |
+
"description": "Summarize experimental groups (conditions, sample counts, default contrast). Optionally validate a DESeq2 contrast by providing reference (condition_a) and alternate (condition_b). Does not run differential expression. Provide both condition fields or neither.",
|
| 14 |
+
"parameters": {
|
| 15 |
+
"type": "object",
|
| 16 |
+
"properties": {
|
| 17 |
+
"condition_a": {
|
| 18 |
+
"type": "string",
|
| 19 |
+
"description": "Reference / baseline condition name (denominator for log2FC). Must match a value in available_conditions."
|
| 20 |
+
},
|
| 21 |
+
"condition_b": {
|
| 22 |
+
"type": "string",
|
| 23 |
+
"description": "Alternate / comparison condition name. Must differ from condition_a."
|
| 24 |
+
}
|
| 25 |
+
},
|
| 26 |
+
"additionalProperties": false
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"type": "function",
|
| 32 |
+
"function": {
|
| 33 |
+
"name": "inspect_dataset",
|
| 34 |
+
"description": "Return sample IDs, per-sample condition metadata, and whether PyDESeq2 is available. Does not run DE or enrichment.",
|
| 35 |
+
"parameters": {
|
| 36 |
+
"type": "object",
|
| 37 |
+
"properties": {},
|
| 38 |
+
"additionalProperties": false
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"type": "function",
|
| 44 |
+
"function": {
|
| 45 |
+
"name": "run_differential_expression",
|
| 46 |
+
"description": "Run PyDESeq2 differential expression for reference vs alternate on the episode count matrix. Requires condition_a and condition_b unless a contrast was validated via understand_experiment_design or the case defines default_contrast.",
|
| 47 |
+
"parameters": {
|
| 48 |
+
"type": "object",
|
| 49 |
+
"properties": {
|
| 50 |
+
"condition_a": {
|
| 51 |
+
"type": "string",
|
| 52 |
+
"description": "Reference condition (baseline)."
|
| 53 |
+
},
|
| 54 |
+
"condition_b": {
|
| 55 |
+
"type": "string",
|
| 56 |
+
"description": "Alternate condition (comparison)."
|
| 57 |
+
}
|
| 58 |
+
},
|
| 59 |
+
"additionalProperties": false
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"type": "function",
|
| 65 |
+
"function": {
|
| 66 |
+
"name": "run_pathway_enrichment",
|
| 67 |
+
"description": "Run over-representation analysis (Fisher ORA) on DE genes against pathway gene sets in the case. In pipeline mode, run_differential_expression must succeed first.",
|
| 68 |
+
"parameters": {
|
| 69 |
+
"type": "object",
|
| 70 |
+
"properties": {
|
| 71 |
+
"gene_list": {
|
| 72 |
+
"type": "array",
|
| 73 |
+
"items": { "type": "string" },
|
| 74 |
+
"description": "Optional explicit gene list for ORA. If omitted, uses significant DE genes from the last DE step per case analysis_options."
|
| 75 |
+
}
|
| 76 |
+
},
|
| 77 |
+
"additionalProperties": false
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"type": "function",
|
| 83 |
+
"function": {
|
| 84 |
+
"name": "compare_pathways",
|
| 85 |
+
"description": "Compare exclusive vs shared differential-expression gene support between two named pathways from the case pathway_genes.",
|
| 86 |
+
"parameters": {
|
| 87 |
+
"type": "object",
|
| 88 |
+
"properties": {
|
| 89 |
+
"pathway_a": {
|
| 90 |
+
"type": "string",
|
| 91 |
+
"description": "First pathway name (exact string as in enrichment results or case pathway_genes keys)."
|
| 92 |
+
},
|
| 93 |
+
"pathway_b": {
|
| 94 |
+
"type": "string",
|
| 95 |
+
"description": "Second pathway name."
|
| 96 |
+
}
|
| 97 |
+
},
|
| 98 |
+
"required": ["pathway_a", "pathway_b"],
|
| 99 |
+
"additionalProperties": false
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"type": "function",
|
| 105 |
+
"function": {
|
| 106 |
+
"name": "submit_answer",
|
| 107 |
+
"description": "Submit final hypothesis: the activated signaling pathway name. Ends the episode. String must match case pathway naming exactly (case-insensitive match on server).",
|
| 108 |
+
"parameters": {
|
| 109 |
+
"type": "object",
|
| 110 |
+
"properties": {
|
| 111 |
+
"hypothesis": {
|
| 112 |
+
"type": "string",
|
| 113 |
+
"description": "Pathway name, e.g. 'MAPK signaling'."
|
| 114 |
+
}
|
| 115 |
+
},
|
| 116 |
+
"required": ["hypothesis"],
|
| 117 |
+
"additionalProperties": false
|
| 118 |
+
}
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
],
|
| 122 |
+
"unified_alternative": {
|
| 123 |
+
"description": "Single-tool variant that maps 1:1 to PathwayAction if you prefer one function with action_type enum.",
|
| 124 |
+
"tools": [
|
| 125 |
+
{
|
| 126 |
+
"type": "function",
|
| 127 |
+
"function": {
|
| 128 |
+
"name": "pathway_env_step",
|
| 129 |
+
"description": "Execute one step in the pathway analysis environment.",
|
| 130 |
+
"parameters": {
|
| 131 |
+
"type": "object",
|
| 132 |
+
"properties": {
|
| 133 |
+
"action_type": {
|
| 134 |
+
"type": "string",
|
| 135 |
+
"enum": [
|
| 136 |
+
"understand_experiment_design",
|
| 137 |
+
"inspect_dataset",
|
| 138 |
+
"run_differential_expression",
|
| 139 |
+
"run_pathway_enrichment",
|
| 140 |
+
"compare_pathways",
|
| 141 |
+
"submit_answer"
|
| 142 |
+
]
|
| 143 |
+
},
|
| 144 |
+
"condition_a": { "type": "string" },
|
| 145 |
+
"condition_b": { "type": "string" },
|
| 146 |
+
"gene_list": {
|
| 147 |
+
"type": "array",
|
| 148 |
+
"items": { "type": "string" }
|
| 149 |
+
},
|
| 150 |
+
"hypothesis": { "type": "string" },
|
| 151 |
+
"pathway_a": { "type": "string" },
|
| 152 |
+
"pathway_b": { "type": "string" }
|
| 153 |
+
},
|
| 154 |
+
"required": ["action_type"],
|
| 155 |
+
"additionalProperties": false
|
| 156 |
+
}
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
]
|
| 160 |
+
}
|
| 161 |
+
}
|
envs/pathway_analysis_env/agent_openai_tools.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
OpenAI-style tool definitions and mapping to PathwayAction.
|
| 9 |
+
|
| 10 |
+
Usage:
|
| 11 |
+
from pathway_analysis_env.agent_openai_tools import (
|
| 12 |
+
OPENAI_TOOLS,
|
| 13 |
+
tool_call_to_pathway_action,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Pass OPENAI_TOOLS to OpenAI Chat Completions `tools=` or Responses API.
|
| 17 |
+
# On tool_call, convert and step:
|
| 18 |
+
action = tool_call_to_pathway_action(
|
| 19 |
+
name=tool_call.function.name,
|
| 20 |
+
arguments_json=tool_call.function.arguments,
|
| 21 |
+
)
|
| 22 |
+
result = await client.step(action)
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import json
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any, Dict, List, Mapping, Optional, Set
|
| 30 |
+
|
| 31 |
+
from pathway_analysis_env.models import PathwayAction
|
| 32 |
+
|
| 33 |
+
_TOOL_NAMES: Set[str] = {
|
| 34 |
+
"understand_experiment_design",
|
| 35 |
+
"inspect_dataset",
|
| 36 |
+
"run_differential_expression",
|
| 37 |
+
"run_pathway_enrichment",
|
| 38 |
+
"compare_pathways",
|
| 39 |
+
"submit_answer",
|
| 40 |
+
"pathway_env_step",
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Per-action tools (recommended). Load from JSON to keep a single source of truth.
|
| 45 |
+
def _load_tools() -> List[Dict[str, Any]]:
|
| 46 |
+
path = Path(__file__).with_name("agent_openai_tools.json")
|
| 47 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 48 |
+
return list(data["tools"])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
OPENAI_TOOLS: List[Dict[str, Any]] = _load_tools()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _coerce_optional_str(value: Any) -> Optional[str]:
|
| 55 |
+
if value is None:
|
| 56 |
+
return None
|
| 57 |
+
s = str(value).strip()
|
| 58 |
+
return s if s else None
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _coerce_gene_list(value: Any) -> Optional[List[str]]:
|
| 62 |
+
if value is None:
|
| 63 |
+
return None
|
| 64 |
+
if not isinstance(value, list):
|
| 65 |
+
raise ValueError("gene_list must be an array of strings")
|
| 66 |
+
return [str(g).strip() for g in value if str(g).strip()]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def tool_call_to_pathway_action(
|
| 70 |
+
*,
|
| 71 |
+
name: str,
|
| 72 |
+
arguments_json: str | Mapping[str, Any],
|
| 73 |
+
) -> PathwayAction:
|
| 74 |
+
"""
|
| 75 |
+
Convert an OpenAI tool call into a PathwayAction for env.step().
|
| 76 |
+
|
| 77 |
+
Supports:
|
| 78 |
+
- Six named tools (name = action_type)
|
| 79 |
+
- Unified ``pathway_env_step`` with action_type inside arguments
|
| 80 |
+
"""
|
| 81 |
+
if isinstance(arguments_json, str):
|
| 82 |
+
parsed: Any = json.loads(arguments_json) if arguments_json.strip() else {}
|
| 83 |
+
else:
|
| 84 |
+
parsed = arguments_json
|
| 85 |
+
# Models occasionally emit ``null`` / non-object arguments (e.g. the JSON
|
| 86 |
+
# literal ``null`` parses to ``None``). Treat anything that is not a
|
| 87 |
+
# mapping as empty so callers fail gracefully instead of raising
|
| 88 |
+
# ``AttributeError`` on ``args.get(...)``.
|
| 89 |
+
args: Dict[str, Any] = dict(parsed) if isinstance(parsed, Mapping) else {}
|
| 90 |
+
|
| 91 |
+
if name == "pathway_env_step":
|
| 92 |
+
action_type = args.get("action_type")
|
| 93 |
+
if not action_type or action_type not in _TOOL_NAMES - {"pathway_env_step"}:
|
| 94 |
+
raise ValueError(
|
| 95 |
+
f"Invalid action_type in pathway_env_step: {action_type!r}"
|
| 96 |
+
)
|
| 97 |
+
elif name in _TOOL_NAMES:
|
| 98 |
+
action_type = name
|
| 99 |
+
else:
|
| 100 |
+
raise ValueError(f"Unknown tool name: {name!r}")
|
| 101 |
+
|
| 102 |
+
return PathwayAction(
|
| 103 |
+
action_type=action_type,
|
| 104 |
+
condition_a=_coerce_optional_str(args.get("condition_a")),
|
| 105 |
+
condition_b=_coerce_optional_str(args.get("condition_b")),
|
| 106 |
+
gene_list=_coerce_gene_list(args.get("gene_list")),
|
| 107 |
+
hypothesis=_coerce_optional_str(args.get("hypothesis")),
|
| 108 |
+
pathway_a=_coerce_optional_str(args.get("pathway_a")),
|
| 109 |
+
pathway_b=_coerce_optional_str(args.get("pathway_b")),
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# Default row caps for list-valued observation fields. Large omics tables
|
| 114 |
+
# (differential expression results, enrichment rows) otherwise balloon the LLM
|
| 115 |
+
# context and burn tokens; the agent only needs the top-ranked rows to reason,
|
| 116 |
+
# and the environment scores against its own full internal tables regardless.
|
| 117 |
+
_OBS_LIST_CAPS: Dict[str, int] = {
|
| 118 |
+
"de_genes": 30,
|
| 119 |
+
"pathway_enrichment": 20,
|
| 120 |
+
"top_genes": 30,
|
| 121 |
+
"top_pathways": 20,
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def truncate_observation_payload(
|
| 126 |
+
payload: Dict[str, Any],
|
| 127 |
+
*,
|
| 128 |
+
list_caps: Optional[Mapping[str, int]] = None,
|
| 129 |
+
) -> Dict[str, Any]:
|
| 130 |
+
"""
|
| 131 |
+
Cap long list-valued fields in an observation payload to control token use.
|
| 132 |
+
|
| 133 |
+
Returns a shallow copy with capped lists. A ``_truncation_note`` field is
|
| 134 |
+
added when anything was truncated so the agent knows results were trimmed.
|
| 135 |
+
The local ``trace_path`` is dropped (not useful to a remote agent).
|
| 136 |
+
"""
|
| 137 |
+
caps = dict(_OBS_LIST_CAPS)
|
| 138 |
+
if list_caps:
|
| 139 |
+
caps.update(list_caps)
|
| 140 |
+
out = dict(payload)
|
| 141 |
+
notes: List[str] = []
|
| 142 |
+
for key, cap in caps.items():
|
| 143 |
+
val = out.get(key)
|
| 144 |
+
if isinstance(val, list) and len(val) > cap:
|
| 145 |
+
notes.append(f"{key}: showing top {cap} of {len(val)}")
|
| 146 |
+
out[key] = val[:cap]
|
| 147 |
+
out.pop("trace_path", None)
|
| 148 |
+
if notes:
|
| 149 |
+
out["_truncation_note"] = "; ".join(notes)
|
| 150 |
+
return out
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def observation_to_tool_result_content(
|
| 154 |
+
observation: Any,
|
| 155 |
+
*,
|
| 156 |
+
truncate: bool = True,
|
| 157 |
+
list_caps: Optional[Mapping[str, int]] = None,
|
| 158 |
+
) -> str:
|
| 159 |
+
"""Serialize observation for OpenAI tool role message (truncation-friendly).
|
| 160 |
+
|
| 161 |
+
By default, long omics tables are capped (see ``truncate_observation_payload``)
|
| 162 |
+
to keep tool results within practical context/token budgets. Pass
|
| 163 |
+
``truncate=False`` to serialize the full payload.
|
| 164 |
+
"""
|
| 165 |
+
if hasattr(observation, "model_dump"):
|
| 166 |
+
payload = observation.model_dump()
|
| 167 |
+
elif isinstance(observation, dict):
|
| 168 |
+
payload = observation
|
| 169 |
+
else:
|
| 170 |
+
payload = {
|
| 171 |
+
"message": getattr(observation, "message", ""),
|
| 172 |
+
"reward": getattr(observation, "reward", 0.0),
|
| 173 |
+
"done": getattr(observation, "done", False),
|
| 174 |
+
"metadata": getattr(observation, "metadata", {}),
|
| 175 |
+
}
|
| 176 |
+
if truncate:
|
| 177 |
+
payload = truncate_observation_payload(payload, list_caps=list_caps)
|
| 178 |
+
return json.dumps(payload, default=str)
|
envs/pathway_analysis_env/client.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Pathway Analysis Environment Client.
|
| 9 |
+
|
| 10 |
+
Provides a WebSocket-based client for interacting with a running
|
| 11 |
+
Pathway Analysis server.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
from typing import Any, Dict
|
| 17 |
+
|
| 18 |
+
import httpx
|
| 19 |
+
|
| 20 |
+
from openenv.core.client_types import StepResult
|
| 21 |
+
from openenv.core.env_client import EnvClient
|
| 22 |
+
|
| 23 |
+
from .models import PathwayAction, PathwayObservation, PathwayState
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class PathwayEnv(EnvClient[PathwayAction, PathwayObservation, PathwayState]):
|
| 27 |
+
"""
|
| 28 |
+
Client for the Pathway Analysis Environment.
|
| 29 |
+
|
| 30 |
+
Example:
|
| 31 |
+
>>> with PathwayEnv(base_url="http://localhost:8000") as client:
|
| 32 |
+
... result = client.reset()
|
| 33 |
+
... result = client.step(PathwayAction(action_type="inspect_dataset"))
|
| 34 |
+
... print(result.observation.message)
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def _step_payload(self, action: PathwayAction) -> Dict[str, Any]:
|
| 38 |
+
return {
|
| 39 |
+
"action_type": action.action_type,
|
| 40 |
+
"condition_a": action.condition_a,
|
| 41 |
+
"condition_b": action.condition_b,
|
| 42 |
+
"gene_list": action.gene_list,
|
| 43 |
+
"hypothesis": action.hypothesis,
|
| 44 |
+
"pathway_a": action.pathway_a,
|
| 45 |
+
"pathway_b": action.pathway_b,
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
def _parse_result(self, payload: Dict[str, Any]) -> StepResult[PathwayObservation]:
|
| 49 |
+
obs_data = payload.get("observation", {})
|
| 50 |
+
observation = PathwayObservation(
|
| 51 |
+
message=obs_data.get("message", ""),
|
| 52 |
+
available_conditions=obs_data.get("available_conditions", []),
|
| 53 |
+
top_genes=obs_data.get("top_genes", []),
|
| 54 |
+
top_pathways=obs_data.get("top_pathways", []),
|
| 55 |
+
de_genes=obs_data.get("de_genes", []),
|
| 56 |
+
pathway_enrichment=obs_data.get("pathway_enrichment", []),
|
| 57 |
+
pathway_comparison=obs_data.get("pathway_comparison"),
|
| 58 |
+
overlap_summary=obs_data.get("overlap_summary"),
|
| 59 |
+
statistical_ambiguity=obs_data.get("statistical_ambiguity"),
|
| 60 |
+
trace_path=obs_data.get("trace_path"),
|
| 61 |
+
experiment_design=obs_data.get("experiment_design"),
|
| 62 |
+
done=obs_data.get("done", False),
|
| 63 |
+
reward=obs_data.get("reward", 0.0),
|
| 64 |
+
metadata=obs_data.get("metadata", {}),
|
| 65 |
+
)
|
| 66 |
+
return StepResult(
|
| 67 |
+
observation=observation,
|
| 68 |
+
reward=observation.reward,
|
| 69 |
+
done=observation.done,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def _parse_state(self, payload: Dict[str, Any]) -> PathwayState:
|
| 73 |
+
return PathwayState(
|
| 74 |
+
episode_id=payload.get("episode_id", ""),
|
| 75 |
+
step_count=payload.get("step_count", 0),
|
| 76 |
+
conditions=payload.get("conditions", []),
|
| 77 |
+
de_run=payload.get("de_run", False),
|
| 78 |
+
enrichment_run=payload.get("enrichment_run", False),
|
| 79 |
+
is_done=payload.get("is_done", False),
|
| 80 |
+
pipeline_mode=payload.get("pipeline_mode", False),
|
| 81 |
+
strict_mode=payload.get("strict_mode", False),
|
| 82 |
+
legacy_mode=payload.get("legacy_mode", False),
|
| 83 |
+
eval_mode=payload.get("eval_mode", True),
|
| 84 |
+
max_steps=payload.get("max_steps", 30),
|
| 85 |
+
design_understood=payload.get("design_understood", False),
|
| 86 |
+
validated_reference=payload.get("validated_reference"),
|
| 87 |
+
validated_alternate=payload.get("validated_alternate"),
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def _http_base_url(self) -> str:
|
| 91 |
+
ws = getattr(self, "_ws_url", "ws://localhost:8000/ws")
|
| 92 |
+
http = ws.replace("wss://", "https://").replace("ws://", "http://")
|
| 93 |
+
if http.endswith("/ws"):
|
| 94 |
+
http = http[:-3]
|
| 95 |
+
return http.rstrip("/")
|
| 96 |
+
|
| 97 |
+
def fetch_episode_outcome(self, timeout: float = 30.0) -> Dict[str, Any]:
|
| 98 |
+
"""
|
| 99 |
+
Fetch orchestrator episode score from a running pathway server.
|
| 100 |
+
|
| 101 |
+
Requires the server started with web interface (default). Only valid after
|
| 102 |
+
``submit_answer`` in the same session.
|
| 103 |
+
"""
|
| 104 |
+
base = self._http_base_url()
|
| 105 |
+
with httpx.Client(timeout=timeout) as client:
|
| 106 |
+
r = client.get(f"{base}/orchestrator/episode_outcome")
|
| 107 |
+
r.raise_for_status()
|
| 108 |
+
return r.json()
|
| 109 |
+
|
| 110 |
+
def fetch_eval_protocol(self, timeout: float = 30.0) -> Dict[str, Any]:
|
| 111 |
+
"""Fetch eval protocol summary from ``GET /orchestrator/eval_protocol``."""
|
| 112 |
+
base = self._http_base_url()
|
| 113 |
+
with httpx.Client(timeout=timeout) as client:
|
| 114 |
+
r = client.get(f"{base}/orchestrator/eval_protocol")
|
| 115 |
+
r.raise_for_status()
|
| 116 |
+
return r.json()
|
envs/pathway_analysis_env/data/eval_manifest_geo.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"description": "Real-world GEO task: GSE128911 fulvestrant vs DMSO.",
|
| 3 |
+
"defaults": {
|
| 4 |
+
"eval_mode": true,
|
| 5 |
+
"max_steps": 30,
|
| 6 |
+
"orchestrator_mode": true
|
| 7 |
+
},
|
| 8 |
+
"episodes": [
|
| 9 |
+
{
|
| 10 |
+
"id": "geo_gse128911_fulvestrant",
|
| 11 |
+
"case_file": "geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_case.json",
|
| 12 |
+
"hypothesis": "estrogen response",
|
| 13 |
+
"requires_pydeseq2": true,
|
| 14 |
+
"requires_gseapy": true,
|
| 15 |
+
"score_mode": "keywords"
|
| 16 |
+
}
|
| 17 |
+
]
|
| 18 |
+
}
|
envs/pathway_analysis_env/data/eval_manifest_geo2.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"description": "Two additional real-world GEO tasks: GSE111151 (tamoxifen resistance) and GSE216540 (fulvestrant pseudo-counts).",
|
| 3 |
+
"defaults": {
|
| 4 |
+
"eval_mode": true,
|
| 5 |
+
"max_steps": 30,
|
| 6 |
+
"orchestrator_mode": true
|
| 7 |
+
},
|
| 8 |
+
"episodes": [
|
| 9 |
+
{
|
| 10 |
+
"id": "geo_gse111151_tamoxifen_resistance",
|
| 11 |
+
"case_file": "geo_eval/gse111151_tamoxifen_benchmark/gse111151_case.json",
|
| 12 |
+
"hypothesis": "estrogen / tamoxifen resistance",
|
| 13 |
+
"requires_pydeseq2": true,
|
| 14 |
+
"requires_gseapy": true,
|
| 15 |
+
"score_mode": "keywords"
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"id": "geo_gse216540_fulvestrant_pseudo",
|
| 19 |
+
"case_file": "geo_eval/gse216540_tpm_pseudo_benchmark/gse216540_case.json",
|
| 20 |
+
"hypothesis": "interferon / immune response",
|
| 21 |
+
"requires_pydeseq2": true,
|
| 22 |
+
"requires_gseapy": true,
|
| 23 |
+
"score_mode": "keywords"
|
| 24 |
+
}
|
| 25 |
+
]
|
| 26 |
+
}
|
envs/pathway_analysis_env/data/eval_manifest_geo3.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"description": "Three real-world GEO tasks for capability comparison.",
|
| 3 |
+
"defaults": {
|
| 4 |
+
"eval_mode": true,
|
| 5 |
+
"max_steps": 30,
|
| 6 |
+
"orchestrator_mode": true
|
| 7 |
+
},
|
| 8 |
+
"episodes": [
|
| 9 |
+
{
|
| 10 |
+
"id": "geo_gse128911_fulvestrant",
|
| 11 |
+
"case_file": "geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_case.json",
|
| 12 |
+
"hypothesis": "estrogen response",
|
| 13 |
+
"requires_pydeseq2": true,
|
| 14 |
+
"requires_gseapy": true,
|
| 15 |
+
"score_mode": "keywords"
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"id": "geo_gse111151_tamoxifen_resistance",
|
| 19 |
+
"case_file": "geo_eval/gse111151_tamoxifen_benchmark/gse111151_case.json",
|
| 20 |
+
"hypothesis": "estrogen / tamoxifen resistance",
|
| 21 |
+
"requires_pydeseq2": true,
|
| 22 |
+
"requires_gseapy": true,
|
| 23 |
+
"score_mode": "keywords"
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"id": "geo_gse216540_fulvestrant_pseudo",
|
| 27 |
+
"case_file": "geo_eval/gse216540_tpm_pseudo_benchmark/gse216540_case.json",
|
| 28 |
+
"hypothesis": "interferon / immune response",
|
| 29 |
+
"requires_pydeseq2": true,
|
| 30 |
+
"requires_gseapy": true,
|
| 31 |
+
"score_mode": "keywords"
|
| 32 |
+
}
|
| 33 |
+
]
|
| 34 |
+
}
|
envs/pathway_analysis_env/data/geo_eval/gse111151_tamoxifen_benchmark/gse111151_case.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"case_id": "GSE111151_tamoxifen_resistance_parental",
|
| 3 |
+
"strict_mode": false,
|
| 4 |
+
"experiment_metadata": {
|
| 5 |
+
"accession": "GSE111151",
|
| 6 |
+
"reference": "https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE111151",
|
| 7 |
+
"summary": "Merged author per-sample raw counts (GEO legacy supplement files GSE111151_GSM1417177\u201384 \u2192 GSM3024053\u201360); 8/11 matrix columns (BT-474 arm not on this FTP mirror)."
|
| 8 |
+
},
|
| 9 |
+
"counts_file": "geo_eval/gse111151_tamoxifen_benchmark/gse111151_counts.csv.gz",
|
| 10 |
+
"sample_ids": [
|
| 11 |
+
"GSM3024053",
|
| 12 |
+
"GSM3024054",
|
| 13 |
+
"GSM3024055",
|
| 14 |
+
"GSM3024056",
|
| 15 |
+
"GSM3024057",
|
| 16 |
+
"GSM3024058",
|
| 17 |
+
"GSM3024059",
|
| 18 |
+
"GSM3024060"
|
| 19 |
+
],
|
| 20 |
+
"sample_metadata": {
|
| 21 |
+
"GSM3024053": "parental",
|
| 22 |
+
"GSM3024054": "tamoxifen_resistant",
|
| 23 |
+
"GSM3024055": "parental",
|
| 24 |
+
"GSM3024056": "tamoxifen_resistant",
|
| 25 |
+
"GSM3024057": "tamoxifen_resistant",
|
| 26 |
+
"GSM3024058": "parental",
|
| 27 |
+
"GSM3024059": "tamoxifen_resistant",
|
| 28 |
+
"GSM3024060": "tamoxifen_resistant"
|
| 29 |
+
},
|
| 30 |
+
"conditions": [
|
| 31 |
+
"parental",
|
| 32 |
+
"tamoxifen_resistant"
|
| 33 |
+
],
|
| 34 |
+
"default_contrast": {
|
| 35 |
+
"reference": "parental",
|
| 36 |
+
"alternate": "tamoxifen_resistant"
|
| 37 |
+
},
|
| 38 |
+
"analysis_options": {
|
| 39 |
+
"min_total_count": 10,
|
| 40 |
+
"padj_alpha": 0.05,
|
| 41 |
+
"de_query_direction": "both"
|
| 42 |
+
},
|
| 43 |
+
"enrichr_libraries": [
|
| 44 |
+
"MSigDB_Hallmark_2020",
|
| 45 |
+
"KEGG_2021_Human",
|
| 46 |
+
"Reactome_2022"
|
| 47 |
+
],
|
| 48 |
+
"true_pathway": "Unknown (GEO benchmark)"
|
| 49 |
+
}
|
envs/pathway_analysis_env/data/geo_eval/gse111151_tamoxifen_benchmark/gse111151_counts.csv.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6c4c9d087b82c73bf33b8a6a0aaaf9f80d5d8f30e4bb72d692bb864b594467a7
|
| 3 |
+
size 574584
|
envs/pathway_analysis_env/data/geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_case.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"case_id": "GSE128911_mda_mb_134_vi_fulvestrant_vs_dmso",
|
| 3 |
+
"strict_mode": false,
|
| 4 |
+
"experiment_metadata": {
|
| 5 |
+
"accession": "GSE128911",
|
| 6 |
+
"reference": "https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE128911",
|
| 7 |
+
"summary": "Dataset 2 count matrix subset (MDA-MB-134-VI; 2\u00d72 DMSO vs Fulvestrant)."
|
| 8 |
+
},
|
| 9 |
+
"counts_file": "geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_dataset2_subset_counts.csv.gz",
|
| 10 |
+
"sample_ids": [
|
| 11 |
+
"SAM24360838",
|
| 12 |
+
"SAM24360839",
|
| 13 |
+
"SAM24360844",
|
| 14 |
+
"SAM24360845"
|
| 15 |
+
],
|
| 16 |
+
"sample_metadata": {
|
| 17 |
+
"SAM24360838": "dmso",
|
| 18 |
+
"SAM24360839": "dmso",
|
| 19 |
+
"SAM24360844": "fulvestrant",
|
| 20 |
+
"SAM24360845": "fulvestrant"
|
| 21 |
+
},
|
| 22 |
+
"conditions": [
|
| 23 |
+
"dmso",
|
| 24 |
+
"fulvestrant"
|
| 25 |
+
],
|
| 26 |
+
"default_contrast": {
|
| 27 |
+
"reference": "dmso",
|
| 28 |
+
"alternate": "fulvestrant"
|
| 29 |
+
},
|
| 30 |
+
"analysis_options": {
|
| 31 |
+
"min_total_count": 10,
|
| 32 |
+
"padj_alpha": 0.05,
|
| 33 |
+
"de_query_direction": "both"
|
| 34 |
+
},
|
| 35 |
+
"enrichr_libraries": [
|
| 36 |
+
"MSigDB_Hallmark_2020",
|
| 37 |
+
"KEGG_2021_Human",
|
| 38 |
+
"Reactome_2022"
|
| 39 |
+
],
|
| 40 |
+
"true_pathway": "Unknown (GEO benchmark)",
|
| 41 |
+
"eval_mode": true,
|
| 42 |
+
"max_steps": 30
|
| 43 |
+
}
|
envs/pathway_analysis_env/data/geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_dataset2_subset_counts.csv.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bd8c97b666b6640046a506aa68afee80aa877ec12df46323a9865aafb1e6e855
|
| 3 |
+
size 236321
|
envs/pathway_analysis_env/data/geo_eval/gse216540_tpm_pseudo_benchmark/gse216540_case.json
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"case_id": "GSE216540_FULV_vs_DMSO_tpm_pseudo_full",
|
| 3 |
+
"strict_mode": false,
|
| 4 |
+
"experiment_metadata": {
|
| 5 |
+
"accession": "GSE216540",
|
| 6 |
+
"reference": "https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE216540",
|
| 7 |
+
"summary": "TPM matrix from GEO supplement; pseudo-counts = round(TPM * 100.0). For OpenEnv pipeline testing only, not DESeq2-ground-truth counts."
|
| 8 |
+
},
|
| 9 |
+
"counts_file": "geo_eval/gse216540_tpm_pseudo_benchmark/gse216540_pseudo_counts.csv.gz",
|
| 10 |
+
"sample_ids": [
|
| 11 |
+
"28_CM_DMSO_1",
|
| 12 |
+
"28_CM_DMSO_2",
|
| 13 |
+
"28_CM_DMSO_3",
|
| 14 |
+
"28_CM_DMSO_4",
|
| 15 |
+
"28_CM_FULV_1",
|
| 16 |
+
"28_CM_FULV_2",
|
| 17 |
+
"28_CM_FULV_3",
|
| 18 |
+
"28_CM_FULV_4",
|
| 19 |
+
"28_NC_DMSO_1",
|
| 20 |
+
"28_NC_DMSO_2",
|
| 21 |
+
"28_NC_DMSO_3",
|
| 22 |
+
"28_NC_DMSO_4",
|
| 23 |
+
"28_NC_FULV_1",
|
| 24 |
+
"28_NC_FULV_2",
|
| 25 |
+
"28_NC_FULV_3",
|
| 26 |
+
"28_NC_FULV_4",
|
| 27 |
+
"30_CM_DMSO_1",
|
| 28 |
+
"30_CM_DMSO_2",
|
| 29 |
+
"30_CM_DMSO_3",
|
| 30 |
+
"30_CM_DMSO_4",
|
| 31 |
+
"30_CM_FULV_1",
|
| 32 |
+
"30_CM_FULV_2",
|
| 33 |
+
"30_CM_FULV_3",
|
| 34 |
+
"30_CM_FULV_4",
|
| 35 |
+
"30_NC_DMSO_1",
|
| 36 |
+
"30_NC_DMSO_2",
|
| 37 |
+
"30_NC_DMSO_3",
|
| 38 |
+
"30_NC_DMSO_4",
|
| 39 |
+
"30_NC_FULV_1",
|
| 40 |
+
"30_NC_FULV_2",
|
| 41 |
+
"30_NC_FULV_3",
|
| 42 |
+
"30_NC_FULV_4",
|
| 43 |
+
"46_CM_DMSO_1",
|
| 44 |
+
"46_CM_DMSO_2",
|
| 45 |
+
"46_CM_FULV_1",
|
| 46 |
+
"46_CM_FULV_2",
|
| 47 |
+
"46_NC_DMSO_1",
|
| 48 |
+
"46_NC_DMSO_2",
|
| 49 |
+
"46_NC_FULV_1",
|
| 50 |
+
"46_NC_FULV_2"
|
| 51 |
+
],
|
| 52 |
+
"sample_metadata": {
|
| 53 |
+
"28_CM_DMSO_1": "DMSO",
|
| 54 |
+
"28_CM_DMSO_2": "DMSO",
|
| 55 |
+
"28_CM_DMSO_3": "DMSO",
|
| 56 |
+
"28_CM_DMSO_4": "DMSO",
|
| 57 |
+
"28_CM_FULV_1": "FULV",
|
| 58 |
+
"28_CM_FULV_2": "FULV",
|
| 59 |
+
"28_CM_FULV_3": "FULV",
|
| 60 |
+
"28_CM_FULV_4": "FULV",
|
| 61 |
+
"28_NC_DMSO_1": "DMSO",
|
| 62 |
+
"28_NC_DMSO_2": "DMSO",
|
| 63 |
+
"28_NC_DMSO_3": "DMSO",
|
| 64 |
+
"28_NC_DMSO_4": "DMSO",
|
| 65 |
+
"28_NC_FULV_1": "FULV",
|
| 66 |
+
"28_NC_FULV_2": "FULV",
|
| 67 |
+
"28_NC_FULV_3": "FULV",
|
| 68 |
+
"28_NC_FULV_4": "FULV",
|
| 69 |
+
"30_CM_DMSO_1": "DMSO",
|
| 70 |
+
"30_CM_DMSO_2": "DMSO",
|
| 71 |
+
"30_CM_DMSO_3": "DMSO",
|
| 72 |
+
"30_CM_DMSO_4": "DMSO",
|
| 73 |
+
"30_CM_FULV_1": "FULV",
|
| 74 |
+
"30_CM_FULV_2": "FULV",
|
| 75 |
+
"30_CM_FULV_3": "FULV",
|
| 76 |
+
"30_CM_FULV_4": "FULV",
|
| 77 |
+
"30_NC_DMSO_1": "DMSO",
|
| 78 |
+
"30_NC_DMSO_2": "DMSO",
|
| 79 |
+
"30_NC_DMSO_3": "DMSO",
|
| 80 |
+
"30_NC_DMSO_4": "DMSO",
|
| 81 |
+
"30_NC_FULV_1": "FULV",
|
| 82 |
+
"30_NC_FULV_2": "FULV",
|
| 83 |
+
"30_NC_FULV_3": "FULV",
|
| 84 |
+
"30_NC_FULV_4": "FULV",
|
| 85 |
+
"46_CM_DMSO_1": "DMSO",
|
| 86 |
+
"46_CM_DMSO_2": "DMSO",
|
| 87 |
+
"46_CM_FULV_1": "FULV",
|
| 88 |
+
"46_CM_FULV_2": "FULV",
|
| 89 |
+
"46_NC_DMSO_1": "DMSO",
|
| 90 |
+
"46_NC_DMSO_2": "DMSO",
|
| 91 |
+
"46_NC_FULV_1": "FULV",
|
| 92 |
+
"46_NC_FULV_2": "FULV"
|
| 93 |
+
},
|
| 94 |
+
"conditions": [
|
| 95 |
+
"DMSO",
|
| 96 |
+
"FULV"
|
| 97 |
+
],
|
| 98 |
+
"default_contrast": {
|
| 99 |
+
"reference": "DMSO",
|
| 100 |
+
"alternate": "FULV"
|
| 101 |
+
},
|
| 102 |
+
"analysis_options": {
|
| 103 |
+
"min_total_count": 10,
|
| 104 |
+
"padj_alpha": 0.05,
|
| 105 |
+
"de_query_direction": "both"
|
| 106 |
+
},
|
| 107 |
+
"enrichr_libraries": [
|
| 108 |
+
"MSigDB_Hallmark_2020",
|
| 109 |
+
"KEGG_2021_Human",
|
| 110 |
+
"Reactome_2022"
|
| 111 |
+
],
|
| 112 |
+
"gene_id_to_symbol_file": "geo_eval/gse216540_tpm_pseudo_benchmark/gse216540_id_to_symbol.json",
|
| 113 |
+
"true_pathway": "Unknown (GEO benchmark)"
|
| 114 |
+
}
|
envs/pathway_analysis_env/data/geo_eval/gse216540_tpm_pseudo_benchmark/gse216540_id_to_symbol.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
envs/pathway_analysis_env/data/geo_eval/gse216540_tpm_pseudo_benchmark/gse216540_pseudo_counts.csv.gz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cf7f9c931c3787d73b91bde371963cb1c40c73d62acffd038c8324339bcfb0d4
|
| 3 |
+
size 1485512
|
envs/pathway_analysis_env/docs/AGENT_EVAL.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agent evaluation guide — pathway_analysis_env
|
| 2 |
+
|
| 3 |
+
This guide covers how to evaluate tool-calling LLM agents in `pathway_analysis_env`.
|
| 4 |
+
|
| 5 |
+
## Eval defaults
|
| 6 |
+
|
| 7 |
+
`reset()` enables `eval_mode=True` by default.
|
| 8 |
+
|
| 9 |
+
In eval mode:
|
| 10 |
+
|
| 11 |
+
- `true_pathway` is hidden from agent-visible state
|
| 12 |
+
- `submit_answer` requires DE + ORA first
|
| 13 |
+
- custom ORA `gene_list` injection is blocked
|
| 14 |
+
- intermediate shaping rewards are flattened
|
| 15 |
+
- step budget is enforced (`max_steps`, default 30)
|
| 16 |
+
|
| 17 |
+
For local debugging only, set `eval_mode=False`.
|
| 18 |
+
|
| 19 |
+
## Standard environment eval
|
| 20 |
+
|
| 21 |
+
Run the manifest-driven harness:
|
| 22 |
+
|
| 23 |
+
```bash
|
| 24 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_agent_eval_suite.py
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Default manifest: `envs/pathway_analysis_env/data/eval_manifest.json`.
|
| 28 |
+
|
| 29 |
+
## LLM eval (tool-calling)
|
| 30 |
+
|
| 31 |
+
Set one provider credential in env or `.env`:
|
| 32 |
+
|
| 33 |
+
- `GROQ_API_KEY`
|
| 34 |
+
- `OPENAI_API_KEY`
|
| 35 |
+
- `OPENROUTER_API_KEY`
|
| 36 |
+
|
| 37 |
+
Then run:
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
export MPLCONFIGDIR=/tmp/mpl
|
| 41 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_llm_agent_eval.py
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
Useful flags:
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
# Choose provider explicitly
|
| 48 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_llm_agent_eval.py --provider groq
|
| 49 |
+
|
| 50 |
+
# Override models
|
| 51 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_llm_agent_eval.py --models gpt-5
|
| 52 |
+
|
| 53 |
+
# Use custom manifest
|
| 54 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_llm_agent_eval.py --manifest envs/pathway_analysis_env/data/eval_manifest_geo3.json
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
Reports are written to:
|
| 58 |
+
|
| 59 |
+
- `envs/pathway_analysis_env/outputs/llm_eval/latest.json`
|
| 60 |
+
- `envs/pathway_analysis_env/outputs/llm_eval/latest.md`
|
| 61 |
+
|
| 62 |
+
## LLM judge eval (report quality)
|
| 63 |
+
|
| 64 |
+
Run agent + judge against a single case:
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_llm_judge.py \
|
| 68 |
+
--case geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_case.json \
|
| 69 |
+
--agent-model gpt-5 \
|
| 70 |
+
--judge-model gpt-5 \
|
| 71 |
+
--out-json envs/pathway_analysis_env/outputs/llm_eval/live_judge_gse128911_gpt5_gpt5.json
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
## Scoring access (orchestrator side)
|
| 75 |
+
|
| 76 |
+
After submit:
|
| 77 |
+
|
| 78 |
+
```python
|
| 79 |
+
outcome = env.episode_outcome
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
With HTTP server:
|
| 83 |
+
|
| 84 |
+
- `GET /orchestrator/episode_outcome`
|
| 85 |
+
- `GET /orchestrator/eval_protocol`
|
| 86 |
+
|
| 87 |
+
## Agent-safe case export
|
| 88 |
+
|
| 89 |
+
Export sanitized cases for agent-facing deployments:
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
cd envs/pathway_analysis_env
|
| 93 |
+
PYTHONPATH=../../src:.. uv run python scripts/export_agent_safe_cases.py
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
Output path: `data/agent_safe/`.
|
| 97 |
+
|
| 98 |
+
## Failure codes
|
| 99 |
+
|
| 100 |
+
Failure code definitions are in `docs/FAILURE_CODES.md`.
|
envs/pathway_analysis_env/docs/FAILURE_CODES.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Pathway analysis env — failure codes (v1)
|
| 2 |
+
|
| 3 |
+
Observations use **`metadata["failure_code"]`** for stable, machine-readable failure labels. Success steps may omit this field or set it to `null` in future versions.
|
| 4 |
+
|
| 5 |
+
See `server/pathway_environment.py` for where each code is set.
|
| 6 |
+
|
| 7 |
+
## v1 taxonomy
|
| 8 |
+
|
| 9 |
+
| `failure_code` | When |
|
| 10 |
+
|----------------|------|
|
| 11 |
+
| `episode_already_done` | `step` after the episode ended (`submit` or strict failure). |
|
| 12 |
+
| `unknown_action_type` | `action_type` is not a recognized pathway action. |
|
| 13 |
+
| `design_partial_contrast` | `understand_experiment_design` with only one of reference/alternate. |
|
| 14 |
+
| `design_invalid_contrast_names` | Proposed reference/alternate not in `conditions`, or ref equals alt. |
|
| 15 |
+
| `design_insufficient_samples_per_arm` | Pipeline case: a contrast arm has no samples in `sample_metadata`. |
|
| 16 |
+
| `de_missing_contrast` | Pipeline DE: no reference/alternate from action, validated design, or `default_contrast`. |
|
| 17 |
+
| `de_pydeseq2_unavailable` | PyDESeq2 not installed (non-strict: recoverable; strict: episode ends). |
|
| 18 |
+
| `de_deseq2_failed` | `run_deseq2_contrast` returned an error string. |
|
| 19 |
+
| `de_invalid_counts_matrix` | `validate_counts_case` failed. |
|
| 20 |
+
| `de_too_few_genes_after_filter` | Prefilter leaves too few genes for stable DESeq2. |
|
| 21 |
+
| `case_sample_metadata_mismatch` | `build_sample_metadata` raised (e.g. sample id missing from metadata). |
|
| 22 |
+
| `ora_de_prerequisite` | Pipeline ORA before DE has been run. |
|
| 23 |
+
| `ora_no_pathway_definitions` | Case has no `pathway_genes` for ORA. |
|
| 24 |
+
| `compare_missing_pathway_names` | `compare_pathways` without both `pathway_a` and `pathway_b`. |
|
| 25 |
+
| `max_steps_exceeded` | Eval mode: step count exceeded case `max_steps`. |
|
| 26 |
+
| `submit_prerequisite_de` | Eval mode: submit before differential expression. |
|
| 27 |
+
| `submit_prerequisite_ora` | Eval mode: submit before pathway enrichment. |
|
| 28 |
+
| `ora_gene_list_blocked` | Eval mode: custom `gene_list` on ORA (must use DE output). |
|
| 29 |
+
| `compare_requires_ora` | Eval mode: compare before enrichment. |
|
| 30 |
+
| `submit_empty_hypothesis` | Submit with empty `hypothesis`. |
|
| 31 |
+
| `submit_incorrect_hypothesis` | `submit_answer` scored incorrect (orchestrator metadata when enabled). |
|
| 32 |
+
| `strict_termination` | Strict mode ended the episode; prefer the specific code above when also set. |
|
| 33 |
+
|
| 34 |
+
## Strict mode
|
| 35 |
+
|
| 36 |
+
When **`strict_mode`** ends an episode, observations include **`metadata["strict_failure"]: true`** and a specific **`failure_code`** (e.g. `de_missing_contrast`) when applicable, or `strict_termination` as a fallback.
|
| 37 |
+
|
| 38 |
+
## Implementation map (v1)
|
| 39 |
+
|
| 40 |
+
| Code | Where set in `pathway_environment.py` |
|
| 41 |
+
|------|----------------------------------------|
|
| 42 |
+
| `episode_already_done` | `step` when `s.is_done` |
|
| 43 |
+
| `unknown_action_type` | `step` fallback |
|
| 44 |
+
| `design_partial_contrast` | `_step_understand_experiment_design` (partial contrast) |
|
| 45 |
+
| `design_invalid_contrast_names` | `_validate_contrast_proposal` |
|
| 46 |
+
| `design_insufficient_samples_per_arm` | `_validate_contrast_proposal` |
|
| 47 |
+
| `de_missing_contrast` | `_step_de` (no ref/alt) |
|
| 48 |
+
| `de_pydeseq2_unavailable` | `_step_de` |
|
| 49 |
+
| `de_deseq2_failed` | `_step_de` after `run_deseq2_contrast` error |
|
| 50 |
+
| `de_invalid_counts_matrix` | `_step_de` after `validate_counts_case` |
|
| 51 |
+
| `de_too_few_genes_after_filter` | `_step_de` after prefilter |
|
| 52 |
+
| `case_sample_metadata_mismatch` | `_step_de` `build_sample_metadata` `ValueError` |
|
| 53 |
+
| `ora_de_prerequisite` | `_step_enrichment` (no DE rows, pipeline) |
|
| 54 |
+
| `ora_no_pathway_definitions` | `_step_enrichment` |
|
| 55 |
+
| `compare_missing_pathway_names` | `_step_compare` |
|
| 56 |
+
| `expert_disabled` | `_step_expert` |
|
| 57 |
+
| `expert_budget_exhausted` | `_step_expert` |
|
| 58 |
+
| `submit_incorrect_hypothesis` | `_step_submit` when `correct` is false |
|
| 59 |
+
| `strict_termination` | `_fail_strict` default only if no other code passed |
|
| 60 |
+
|
| 61 |
+
## Constants
|
| 62 |
+
|
| 63 |
+
Python constants live in **`server/failure_codes.py`** — import these instead of hard-coding strings in new code.
|
envs/pathway_analysis_env/docs/LLM_JUDGE_EVAL.md
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLM Judge Evaluation (Pure Report Comparison)
|
| 2 |
+
|
| 3 |
+
This document describes the non-training evaluation workflow for comparing an
|
| 4 |
+
agent's written analysis report against a reference report.
|
| 5 |
+
|
| 6 |
+
## What This Is
|
| 7 |
+
|
| 8 |
+
- **Purpose:** richer scientific assessment than keyword matching.
|
| 9 |
+
- **Scope:** eval-only (offline analysis), not environment reward shaping.
|
| 10 |
+
- **Judge input:** agent report + reference report.
|
| 11 |
+
- **Judge output:** 0-1 scores for:
|
| 12 |
+
- primary_biology
|
| 13 |
+
- supporting_pathways
|
| 14 |
+
- evidence_grounding
|
| 15 |
+
- mechanism
|
| 16 |
+
- overall
|
| 17 |
+
|
| 18 |
+
## Important Design Choice
|
| 19 |
+
|
| 20 |
+
The reference report is generated from the **same live episode outputs** (DE and
|
| 21 |
+
ORA) that the agent saw during that run. This avoids mismatches between:
|
| 22 |
+
|
| 23 |
+
- stale precomputed `enrichment.json` artifacts, and
|
| 24 |
+
- live Enrichr results at evaluation time.
|
| 25 |
+
|
| 26 |
+
## Scripts
|
| 27 |
+
|
| 28 |
+
- `scripts/run_llm_judge.py`
|
| 29 |
+
- Runs one case with a tool-calling agent model.
|
| 30 |
+
- Builds live reference from that same episode.
|
| 31 |
+
- Calls a judge model and writes JSON artifact.
|
| 32 |
+
- `scripts/build_judge_pdf.py`
|
| 33 |
+
- Builds a visual PDF from a judge artifact JSON.
|
| 34 |
+
|
| 35 |
+
## Example Commands
|
| 36 |
+
|
| 37 |
+
Run a single case:
|
| 38 |
+
|
| 39 |
+
```bash
|
| 40 |
+
MPLCONFIGDIR=/tmp/mpl PYTHONPATH=src:envs uv run python \
|
| 41 |
+
envs/pathway_analysis_env/scripts/run_llm_judge.py \
|
| 42 |
+
--case geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_case.json \
|
| 43 |
+
--agent-model gpt-5 \
|
| 44 |
+
--judge-model gpt-4o \
|
| 45 |
+
--out-json envs/pathway_analysis_env/outputs/llm_eval/live_judge_gse128911_gpt5.json
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
Build a PDF:
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
MPLCONFIGDIR=/tmp/mpl PYTHONPATH=src:envs uv run python \
|
| 52 |
+
envs/pathway_analysis_env/scripts/build_judge_pdf.py \
|
| 53 |
+
--artifact envs/pathway_analysis_env/outputs/llm_eval/live_judge_gse128911_gpt5.json \
|
| 54 |
+
--enrichment envs/pathway_analysis_env/data/geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/enrichment.json \
|
| 55 |
+
--out envs/pathway_analysis_env/outputs/llm_eval/live_judge_gse128911_gpt5.pdf
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
## Notes
|
| 59 |
+
|
| 60 |
+
- LLM judging is **non-deterministic** and should not replace deterministic
|
| 61 |
+
environment rewards for RL training.
|
| 62 |
+
- Keep judge model separate from agent model when possible (reduces self-bias).
|
| 63 |
+
- Do not commit secrets; keep API keys in `.env` (gitignored).
|
envs/pathway_analysis_env/models.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Data models for Pathway Analysis Environment.
|
| 9 |
+
|
| 10 |
+
Supports pipeline-style episodes (count matrix + sample metadata + gene sets)
|
| 11 |
+
with PyDESeq2 differential expression, Fisher ORA, overlap-aware summaries,
|
| 12 |
+
and HTML step traces.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from typing import Any, Dict, List, Optional
|
| 18 |
+
|
| 19 |
+
from openenv.core.env_server import Action, Observation, State
|
| 20 |
+
from pydantic import Field
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class PathwayAction(Action):
|
| 24 |
+
"""
|
| 25 |
+
Action for the Pathway Analysis environment.
|
| 26 |
+
|
| 27 |
+
action_type:
|
| 28 |
+
- ``inspect_dataset``: describe available samples and conditions.
|
| 29 |
+
- ``understand_experiment_design``: **(1)** Summarize groups (conditions, sample counts);
|
| 30 |
+
optionally **(2)** validate ``condition_a``/``condition_b`` as reference/alternate for
|
| 31 |
+
DGE (does not run DESeq2). Valid pairs feed ``run_differential_expression`` when DE omits
|
| 32 |
+
conditions. **(3)** Pathway steps follow DE.
|
| 33 |
+
- ``run_differential_expression``: PyDESeq2 contrast (needs ``condition_a`` /
|
| 34 |
+
``condition_b`` when using count-matrix cases).
|
| 35 |
+
- ``run_pathway_enrichment``: ORA on DE genes vs pathway gene sets.
|
| 36 |
+
- ``compare_pathways``: contrast exclusive vs shared DE support between two
|
| 37 |
+
pathways (``pathway_a``, ``pathway_b``).
|
| 38 |
+
- ``submit_answer``: submit ``hypothesis`` pathway name and end episode.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
action_type: str
|
| 42 |
+
condition_a: Optional[str] = None
|
| 43 |
+
condition_b: Optional[str] = None
|
| 44 |
+
gene_list: Optional[List[str]] = None
|
| 45 |
+
hypothesis: Optional[str] = None
|
| 46 |
+
pathway_a: Optional[str] = None
|
| 47 |
+
pathway_b: Optional[str] = None
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class PathwayObservation(Observation):
|
| 51 |
+
"""Observation with optional rich DE / ORA structures (JSON-serializable)."""
|
| 52 |
+
|
| 53 |
+
message: str = ""
|
| 54 |
+
available_conditions: List[str] = Field(default_factory=list)
|
| 55 |
+
top_genes: List[str] = Field(default_factory=list)
|
| 56 |
+
top_pathways: List[str] = Field(default_factory=list)
|
| 57 |
+
de_genes: List[Dict[str, Any]] = Field(default_factory=list)
|
| 58 |
+
pathway_enrichment: List[Dict[str, Any]] = Field(default_factory=list)
|
| 59 |
+
pathway_comparison: Optional[Dict[str, Any]] = None
|
| 60 |
+
overlap_summary: Optional[Dict[str, Any]] = None
|
| 61 |
+
statistical_ambiguity: Optional[Dict[str, Any]] = None
|
| 62 |
+
trace_path: Optional[str] = None
|
| 63 |
+
experiment_design: Optional[Dict[str, Any]] = None
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class PathwayState(State):
|
| 67 |
+
"""Agent-visible episode state (ground truth is never included)."""
|
| 68 |
+
|
| 69 |
+
conditions: List[str] = Field(default_factory=list)
|
| 70 |
+
de_run: bool = False
|
| 71 |
+
enrichment_run: bool = False
|
| 72 |
+
is_done: bool = False
|
| 73 |
+
pipeline_mode: bool = False
|
| 74 |
+
strict_mode: bool = False
|
| 75 |
+
legacy_mode: bool = False
|
| 76 |
+
eval_mode: bool = True
|
| 77 |
+
max_steps: int = 30
|
| 78 |
+
design_understood: bool = False
|
| 79 |
+
validated_reference: Optional[str] = None
|
| 80 |
+
validated_alternate: Optional[str] = None
|
envs/pathway_analysis_env/openenv.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
spec_version: 1
|
| 2 |
+
name: pathway_analysis_env
|
| 3 |
+
type: space
|
| 4 |
+
runtime: fastapi
|
| 5 |
+
app: server.app:app
|
| 6 |
+
port: 8000
|
envs/pathway_analysis_env/pyproject.toml
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
[build-system]
|
| 8 |
+
requires = ["setuptools>=45", "wheel"]
|
| 9 |
+
build-backend = "setuptools.build_meta"
|
| 10 |
+
|
| 11 |
+
[project]
|
| 12 |
+
name = "openenv-pathway-analysis-env"
|
| 13 |
+
version = "0.1.0"
|
| 14 |
+
description = "Toy pathway analysis environment for OpenEnv — identify activated signaling pathways from synthetic omics data"
|
| 15 |
+
requires-python = ">=3.10"
|
| 16 |
+
dependencies = [
|
| 17 |
+
"openenv-core[core]>=0.2.1",
|
| 18 |
+
"fastapi>=0.115.0",
|
| 19 |
+
"pydantic>=2.0.0",
|
| 20 |
+
"uvicorn>=0.24.0",
|
| 21 |
+
"requests>=2.31.0",
|
| 22 |
+
"numpy>=1.24.0",
|
| 23 |
+
"pandas>=2.0.0",
|
| 24 |
+
"scipy>=1.10.0",
|
| 25 |
+
"pydeseq2>=0.4.0",
|
| 26 |
+
"anndata>=0.10.0",
|
| 27 |
+
"gseapy>=1.1.3",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
[project.optional-dependencies]
|
| 31 |
+
dev = [
|
| 32 |
+
"pytest>=8.0.0",
|
| 33 |
+
"pytest-cov>=4.0.0",
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
[project.scripts]
|
| 37 |
+
server = "pathway_analysis_env.server.app:main"
|
| 38 |
+
|
| 39 |
+
[tool.setuptools]
|
| 40 |
+
include-package-data = true
|
| 41 |
+
packages = ["pathway_analysis_env", "pathway_analysis_env.server"]
|
| 42 |
+
package-dir = { "pathway_analysis_env" = ".", "pathway_analysis_env.server" = "server" }
|
envs/pathway_analysis_env/scripts/append_task_to_manifest.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Append or update one task episode in an eval manifest.
|
| 3 |
+
|
| 4 |
+
Example:
|
| 5 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/append_task_to_manifest.py \
|
| 6 |
+
--manifest envs/pathway_analysis_env/data/eval_manifest_geo3.json \
|
| 7 |
+
--episode-id geo_gseXXXX \
|
| 8 |
+
--case-file geo_eval/gseXXXX_example/gsexxxx_case.json \
|
| 9 |
+
--hypothesis "estrogen response"
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import json
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any, Dict, List
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _default_manifest() -> Dict[str, Any]:
|
| 21 |
+
return {
|
| 22 |
+
"description": "GEO evaluation tasks.",
|
| 23 |
+
"defaults": {
|
| 24 |
+
"eval_mode": True,
|
| 25 |
+
"max_steps": 30,
|
| 26 |
+
"orchestrator_mode": True,
|
| 27 |
+
},
|
| 28 |
+
"episodes": [],
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _load_manifest(path: Path) -> Dict[str, Any]:
|
| 33 |
+
if not path.exists():
|
| 34 |
+
return _default_manifest()
|
| 35 |
+
return json.loads(path.read_text(encoding="utf-8"))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _upsert_episode(episodes: List[Dict[str, Any]], episode: Dict[str, Any]) -> str:
|
| 39 |
+
episode_id = episode["id"]
|
| 40 |
+
for i, existing in enumerate(episodes):
|
| 41 |
+
if existing.get("id") == episode_id:
|
| 42 |
+
episodes[i] = episode
|
| 43 |
+
return "updated"
|
| 44 |
+
episodes.append(episode)
|
| 45 |
+
return "added"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def main() -> None:
|
| 49 |
+
parser = argparse.ArgumentParser(
|
| 50 |
+
description="Append or update a single episode in a manifest."
|
| 51 |
+
)
|
| 52 |
+
parser.add_argument("--manifest", type=Path, required=True)
|
| 53 |
+
parser.add_argument("--episode-id", required=True)
|
| 54 |
+
parser.add_argument("--case-file", required=True, help="Path relative to data/ (e.g. geo_eval/.../case.json)")
|
| 55 |
+
parser.add_argument("--hypothesis", default="pathway hypothesis")
|
| 56 |
+
parser.add_argument(
|
| 57 |
+
"--requires-pydeseq2",
|
| 58 |
+
action=argparse.BooleanOptionalAction,
|
| 59 |
+
default=True,
|
| 60 |
+
)
|
| 61 |
+
parser.add_argument(
|
| 62 |
+
"--requires-gseapy",
|
| 63 |
+
action=argparse.BooleanOptionalAction,
|
| 64 |
+
default=True,
|
| 65 |
+
)
|
| 66 |
+
parser.add_argument("--score-mode", default="keywords")
|
| 67 |
+
args = parser.parse_args()
|
| 68 |
+
|
| 69 |
+
manifest = _load_manifest(args.manifest)
|
| 70 |
+
episodes = manifest.setdefault("episodes", [])
|
| 71 |
+
|
| 72 |
+
episode = {
|
| 73 |
+
"id": args.episode_id,
|
| 74 |
+
"case_file": args.case_file,
|
| 75 |
+
"hypothesis": args.hypothesis,
|
| 76 |
+
"requires_pydeseq2": bool(args.requires_pydeseq2),
|
| 77 |
+
"requires_gseapy": bool(args.requires_gseapy),
|
| 78 |
+
"score_mode": args.score_mode,
|
| 79 |
+
}
|
| 80 |
+
action = _upsert_episode(episodes, episode)
|
| 81 |
+
args.manifest.parent.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
args.manifest.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
|
| 83 |
+
|
| 84 |
+
print(f"[ok] {action} episode '{args.episode_id}' in {args.manifest}")
|
| 85 |
+
print(f"[ok] total episodes: {len(episodes)}")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
main()
|
| 90 |
+
|
envs/pathway_analysis_env/scripts/create_geo_task.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Create a GEO-style task case from counts + sample metadata.
|
| 3 |
+
|
| 4 |
+
Example:
|
| 5 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/create_geo_task.py \
|
| 6 |
+
--task-id gseXXXX_example \
|
| 7 |
+
--accession GSEXXXX \
|
| 8 |
+
--summary "Short study summary" \
|
| 9 |
+
--counts-file /path/to/counts.csv.gz \
|
| 10 |
+
--metadata-csv /path/to/samples.csv \
|
| 11 |
+
--reference-condition control \
|
| 12 |
+
--alternate-condition treated
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import csv
|
| 19 |
+
import json
|
| 20 |
+
import shutil
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Dict, List, Tuple
|
| 23 |
+
|
| 24 |
+
DEFAULT_LIBRARIES = ["MSigDB_Hallmark_2020", "KEGG_2021_Human", "Reactome_2022"]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _read_metadata_csv(path: Path) -> Tuple[List[str], Dict[str, str], List[str]]:
|
| 28 |
+
with path.open("r", encoding="utf-8", newline="") as f:
|
| 29 |
+
reader = csv.DictReader(f)
|
| 30 |
+
fields = set(reader.fieldnames or [])
|
| 31 |
+
required = {"sample_id", "condition"}
|
| 32 |
+
missing = required - fields
|
| 33 |
+
if missing:
|
| 34 |
+
raise ValueError(
|
| 35 |
+
f"{path} is missing required columns: {sorted(missing)} "
|
| 36 |
+
"(required: sample_id, condition)"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
sample_ids: List[str] = []
|
| 40 |
+
sample_metadata: Dict[str, str] = {}
|
| 41 |
+
conditions: List[str] = []
|
| 42 |
+
seen_conditions = set()
|
| 43 |
+
|
| 44 |
+
for row in reader:
|
| 45 |
+
sample_id = (row.get("sample_id") or "").strip()
|
| 46 |
+
condition = (row.get("condition") or "").strip()
|
| 47 |
+
if not sample_id or not condition:
|
| 48 |
+
raise ValueError(
|
| 49 |
+
f"{path} has empty sample_id/condition row: {row!r}"
|
| 50 |
+
)
|
| 51 |
+
sample_ids.append(sample_id)
|
| 52 |
+
sample_metadata[sample_id] = condition
|
| 53 |
+
if condition not in seen_conditions:
|
| 54 |
+
seen_conditions.add(condition)
|
| 55 |
+
conditions.append(condition)
|
| 56 |
+
|
| 57 |
+
if not sample_ids:
|
| 58 |
+
raise ValueError(f"{path} has no sample rows")
|
| 59 |
+
return sample_ids, sample_metadata, conditions
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _counts_dest_name(src: Path) -> str:
|
| 63 |
+
name = src.name
|
| 64 |
+
if name.endswith(".csv") or name.endswith(".csv.gz"):
|
| 65 |
+
return name
|
| 66 |
+
return f"{src.stem}.csv.gz" if src.suffix == ".gz" else f"{src.name}.csv.gz"
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main() -> None:
|
| 70 |
+
parser = argparse.ArgumentParser(
|
| 71 |
+
description="Create a GEO task case JSON from counts + sample metadata."
|
| 72 |
+
)
|
| 73 |
+
parser.add_argument("--task-id", required=True, help="Folder id under data/geo_eval/")
|
| 74 |
+
parser.add_argument("--accession", required=True, help="Study accession (e.g. GSE216540)")
|
| 75 |
+
parser.add_argument("--summary", required=True, help="Short human-readable study summary")
|
| 76 |
+
parser.add_argument("--counts-file", type=Path, required=True, help="Path to counts .csv/.csv.gz")
|
| 77 |
+
parser.add_argument(
|
| 78 |
+
"--metadata-csv",
|
| 79 |
+
type=Path,
|
| 80 |
+
required=True,
|
| 81 |
+
help="CSV with columns: sample_id,condition",
|
| 82 |
+
)
|
| 83 |
+
parser.add_argument("--reference-condition", required=True, help="Reference group name")
|
| 84 |
+
parser.add_argument("--alternate-condition", required=True, help="Alternate group name")
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--geo-ref-url",
|
| 87 |
+
default="",
|
| 88 |
+
help="Optional GEO URL; default is generated from accession",
|
| 89 |
+
)
|
| 90 |
+
parser.add_argument(
|
| 91 |
+
"--libraries",
|
| 92 |
+
default=",".join(DEFAULT_LIBRARIES),
|
| 93 |
+
help="Comma-separated Enrichr libraries",
|
| 94 |
+
)
|
| 95 |
+
parser.add_argument(
|
| 96 |
+
"--out-dir",
|
| 97 |
+
type=Path,
|
| 98 |
+
default=Path("envs/pathway_analysis_env/data/geo_eval"),
|
| 99 |
+
help="Directory that stores task folders",
|
| 100 |
+
)
|
| 101 |
+
parser.add_argument(
|
| 102 |
+
"--copy-counts",
|
| 103 |
+
action="store_true",
|
| 104 |
+
help="Copy counts file into task folder (default behavior)",
|
| 105 |
+
)
|
| 106 |
+
parser.add_argument(
|
| 107 |
+
"--no-copy-counts",
|
| 108 |
+
action="store_true",
|
| 109 |
+
help="Do not copy counts file (use existing file under task folder)",
|
| 110 |
+
)
|
| 111 |
+
args = parser.parse_args()
|
| 112 |
+
|
| 113 |
+
if args.reference_condition == args.alternate_condition:
|
| 114 |
+
raise ValueError("reference-condition and alternate-condition must be different")
|
| 115 |
+
|
| 116 |
+
sample_ids, sample_metadata, conditions = _read_metadata_csv(args.metadata_csv)
|
| 117 |
+
if args.reference_condition not in conditions:
|
| 118 |
+
raise ValueError(
|
| 119 |
+
f"reference-condition '{args.reference_condition}' not found in metadata conditions {conditions}"
|
| 120 |
+
)
|
| 121 |
+
if args.alternate_condition not in conditions:
|
| 122 |
+
raise ValueError(
|
| 123 |
+
f"alternate-condition '{args.alternate_condition}' not found in metadata conditions {conditions}"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
task_dir = args.out_dir / args.task_id
|
| 127 |
+
task_dir.mkdir(parents=True, exist_ok=True)
|
| 128 |
+
|
| 129 |
+
counts_src = args.counts_file.resolve()
|
| 130 |
+
if not counts_src.exists():
|
| 131 |
+
raise FileNotFoundError(f"counts file not found: {counts_src}")
|
| 132 |
+
|
| 133 |
+
should_copy = not args.no_copy_counts
|
| 134 |
+
if args.copy_counts:
|
| 135 |
+
should_copy = True
|
| 136 |
+
|
| 137 |
+
if should_copy:
|
| 138 |
+
counts_name = _counts_dest_name(counts_src)
|
| 139 |
+
counts_dst = task_dir / counts_name
|
| 140 |
+
shutil.copy2(counts_src, counts_dst)
|
| 141 |
+
else:
|
| 142 |
+
counts_dst = counts_src
|
| 143 |
+
if task_dir not in counts_dst.parents:
|
| 144 |
+
raise ValueError(
|
| 145 |
+
"--no-copy-counts requires counts-file to already be inside task folder"
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
counts_rel = f"geo_eval/{args.task_id}/{counts_dst.name}"
|
| 149 |
+
case_name = f"{args.accession.lower()}_case.json"
|
| 150 |
+
case_path = task_dir / case_name
|
| 151 |
+
|
| 152 |
+
ref_url = args.geo_ref_url.strip() or f"https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc={args.accession}"
|
| 153 |
+
libraries = [s.strip() for s in args.libraries.split(",") if s.strip()]
|
| 154 |
+
if not libraries:
|
| 155 |
+
libraries = DEFAULT_LIBRARIES
|
| 156 |
+
|
| 157 |
+
case = {
|
| 158 |
+
"case_id": args.task_id,
|
| 159 |
+
"strict_mode": False,
|
| 160 |
+
"experiment_metadata": {
|
| 161 |
+
"accession": args.accession,
|
| 162 |
+
"reference": ref_url,
|
| 163 |
+
"summary": args.summary,
|
| 164 |
+
},
|
| 165 |
+
"counts_file": counts_rel,
|
| 166 |
+
"sample_ids": sample_ids,
|
| 167 |
+
"sample_metadata": sample_metadata,
|
| 168 |
+
"conditions": conditions,
|
| 169 |
+
"default_contrast": {
|
| 170 |
+
"reference": args.reference_condition,
|
| 171 |
+
"alternate": args.alternate_condition,
|
| 172 |
+
},
|
| 173 |
+
"analysis_options": {
|
| 174 |
+
"min_total_count": 10,
|
| 175 |
+
"padj_alpha": 0.05,
|
| 176 |
+
"de_query_direction": "both",
|
| 177 |
+
},
|
| 178 |
+
"enrichr_libraries": libraries,
|
| 179 |
+
"true_pathway": "Unknown (GEO benchmark)",
|
| 180 |
+
}
|
| 181 |
+
case_path.write_text(json.dumps(case, indent=2) + "\n", encoding="utf-8")
|
| 182 |
+
|
| 183 |
+
print(f"[ok] wrote case: {case_path}")
|
| 184 |
+
print(f"[ok] counts file: {counts_dst}")
|
| 185 |
+
print(
|
| 186 |
+
"[next] append to manifest:\n"
|
| 187 |
+
" PYTHONPATH=src:envs uv run python "
|
| 188 |
+
"envs/pathway_analysis_env/scripts/append_task_to_manifest.py "
|
| 189 |
+
f"--manifest envs/pathway_analysis_env/data/eval_manifest_geo3.json "
|
| 190 |
+
f"--episode-id {args.task_id} --case-file {counts_rel.rsplit('/', 1)[0]}/{case_name} "
|
| 191 |
+
'--hypothesis "your expected theme"'
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
main()
|
| 197 |
+
|
envs/pathway_analysis_env/scripts/export_agent_safe_cases.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Export agent-safe case JSON files (no ground-truth fields) under data/agent_safe/."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
from pathway_analysis_env.server.case_loader import export_agent_safe_case
|
| 10 |
+
from pathway_analysis_env.server.pathway_environment import DATA_DIR
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def main() -> None:
|
| 14 |
+
parser = argparse.ArgumentParser()
|
| 15 |
+
parser.add_argument(
|
| 16 |
+
"--out-dir",
|
| 17 |
+
type=Path,
|
| 18 |
+
default=DATA_DIR / "agent_safe",
|
| 19 |
+
help="Output root (mirrors relative paths from data/).",
|
| 20 |
+
)
|
| 21 |
+
parser.add_argument(
|
| 22 |
+
"cases",
|
| 23 |
+
nargs="*",
|
| 24 |
+
default=[
|
| 25 |
+
"toy_case_001.json",
|
| 26 |
+
"toy_case_002.json",
|
| 27 |
+
"toy_case_legacy.json",
|
| 28 |
+
"toy_case_no_default.json",
|
| 29 |
+
"geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_case.json",
|
| 30 |
+
],
|
| 31 |
+
)
|
| 32 |
+
args = parser.parse_args()
|
| 33 |
+
out_root: Path = args.out_dir
|
| 34 |
+
for rel in args.cases:
|
| 35 |
+
src = DATA_DIR / rel
|
| 36 |
+
if not src.is_file():
|
| 37 |
+
print(f"skip missing {src}")
|
| 38 |
+
continue
|
| 39 |
+
dst = out_root / rel
|
| 40 |
+
export_agent_safe_case(src, dst)
|
| 41 |
+
print(f"wrote {dst}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
main()
|
envs/pathway_analysis_env/scripts/run_agent_eval_suite.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Run the standard pathway agent eval manifest (fixed policy baseline).
|
| 4 |
+
|
| 5 |
+
Scores via ``env.episode_outcome`` (orchestrator mode). Writes JSON summary.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Any, Dict, List
|
| 14 |
+
|
| 15 |
+
from pathway_analysis_env.models import PathwayAction
|
| 16 |
+
from pathway_analysis_env.server.analysis import gseapy_available, pydeseq2_available
|
| 17 |
+
from pathway_analysis_env.server.pathway_environment import (
|
| 18 |
+
DATA_DIR,
|
| 19 |
+
PathwayEnvironment,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _run_episode(spec: Dict[str, Any], *, strict: bool) -> Dict[str, Any]:
|
| 24 |
+
case_file = spec["case_file"]
|
| 25 |
+
if spec.get("requires_pydeseq2") and not pydeseq2_available():
|
| 26 |
+
return {
|
| 27 |
+
"id": spec["id"],
|
| 28 |
+
"skipped": True,
|
| 29 |
+
"reason": "pydeseq2_unavailable",
|
| 30 |
+
}
|
| 31 |
+
if spec.get("requires_gseapy") and not gseapy_available():
|
| 32 |
+
return {
|
| 33 |
+
"id": spec["id"],
|
| 34 |
+
"skipped": True,
|
| 35 |
+
"reason": "gseapy_unavailable",
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
from pathway_analysis_env.server.pathway_environment import load_case
|
| 39 |
+
|
| 40 |
+
case = load_case(case_file)
|
| 41 |
+
ref = (case.get("default_contrast") or {}).get("reference")
|
| 42 |
+
alt = (case.get("default_contrast") or {}).get("alternate")
|
| 43 |
+
|
| 44 |
+
env = PathwayEnvironment(case_file=case_file)
|
| 45 |
+
env.reset(strict=strict, orchestrator_mode=True)
|
| 46 |
+
|
| 47 |
+
actions: List[str] = []
|
| 48 |
+
|
| 49 |
+
def go(kind: str, **kw: Any):
|
| 50 |
+
actions.append(kind)
|
| 51 |
+
return env.step(PathwayAction(action_type=kind, **kw))
|
| 52 |
+
|
| 53 |
+
go("understand_experiment_design")
|
| 54 |
+
go("inspect_dataset")
|
| 55 |
+
o_de = go(
|
| 56 |
+
"run_differential_expression",
|
| 57 |
+
condition_a=ref,
|
| 58 |
+
condition_b=alt,
|
| 59 |
+
)
|
| 60 |
+
if o_de.metadata and o_de.metadata.get("failure_code"):
|
| 61 |
+
return {
|
| 62 |
+
"id": spec["id"],
|
| 63 |
+
"case_file": case_file,
|
| 64 |
+
"passed": False,
|
| 65 |
+
"stage": "de",
|
| 66 |
+
"failure_code": o_de.metadata.get("failure_code"),
|
| 67 |
+
"actions": actions,
|
| 68 |
+
}
|
| 69 |
+
o_ora = go("run_pathway_enrichment")
|
| 70 |
+
if o_ora.metadata and o_ora.metadata.get("failure_code"):
|
| 71 |
+
return {
|
| 72 |
+
"id": spec["id"],
|
| 73 |
+
"case_file": case_file,
|
| 74 |
+
"passed": False,
|
| 75 |
+
"stage": "ora",
|
| 76 |
+
"failure_code": o_ora.metadata.get("failure_code"),
|
| 77 |
+
"actions": actions,
|
| 78 |
+
}
|
| 79 |
+
hyp = spec.get("hypothesis", "")
|
| 80 |
+
go("submit_answer", hypothesis=hyp)
|
| 81 |
+
outcome = env.episode_outcome or {}
|
| 82 |
+
return {
|
| 83 |
+
"id": spec["id"],
|
| 84 |
+
"case_file": case_file,
|
| 85 |
+
"passed": bool(outcome.get("correct")),
|
| 86 |
+
"episode_outcome": outcome,
|
| 87 |
+
"actions": actions,
|
| 88 |
+
"steps": env.state.step_count,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def main() -> None:
|
| 93 |
+
parser = argparse.ArgumentParser()
|
| 94 |
+
parser.add_argument(
|
| 95 |
+
"--manifest",
|
| 96 |
+
type=Path,
|
| 97 |
+
default=DATA_DIR / "eval_manifest.json",
|
| 98 |
+
)
|
| 99 |
+
parser.add_argument("--strict", action="store_true")
|
| 100 |
+
parser.add_argument("--json-out", type=Path, default=None)
|
| 101 |
+
args = parser.parse_args()
|
| 102 |
+
|
| 103 |
+
manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
|
| 104 |
+
results = [_run_episode(ep, strict=args.strict) for ep in manifest.get("episodes", [])]
|
| 105 |
+
n_pass = sum(1 for r in results if r.get("passed"))
|
| 106 |
+
n_run = sum(1 for r in results if not r.get("skipped"))
|
| 107 |
+
summary = {
|
| 108 |
+
"manifest": str(args.manifest),
|
| 109 |
+
"passed": n_pass,
|
| 110 |
+
"run": n_run,
|
| 111 |
+
"total": len(results),
|
| 112 |
+
"pass_rate": (n_pass / n_run) if n_run else 0.0,
|
| 113 |
+
"results": results,
|
| 114 |
+
}
|
| 115 |
+
text = json.dumps(summary, indent=2)
|
| 116 |
+
if args.json_out:
|
| 117 |
+
args.json_out.parent.mkdir(parents=True, exist_ok=True)
|
| 118 |
+
args.json_out.write_text(text + "\n", encoding="utf-8")
|
| 119 |
+
print(text)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
main()
|
envs/pathway_analysis_env/scripts/run_llm_agent_eval.py
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Tool-calling LLM agent evaluation for pathway_analysis_env.
|
| 4 |
+
|
| 5 |
+
Runs a tool-calling LLM agent over ``data/eval_manifest.json``. The agent is
|
| 6 |
+
given the pathway tools and decides which to call and when to submit_answer.
|
| 7 |
+
Writes JSON + Markdown reports.
|
| 8 |
+
|
| 9 |
+
Free providers (no credit card):
|
| 10 |
+
Groq: export GROQ_API_KEY=... (https://console.groq.com)
|
| 11 |
+
OpenRouter: export OPENROUTER_API_KEY=... (model openrouter/free)
|
| 12 |
+
Ollama: ollama serve && ollama pull llama3.1:8b (--provider ollama)
|
| 13 |
+
|
| 14 |
+
Usage:
|
| 15 |
+
export GROQ_API_KEY=...
|
| 16 |
+
export MPLCONFIGDIR=/tmp/mpl
|
| 17 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_llm_agent_eval.py
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import asyncio
|
| 24 |
+
import json
|
| 25 |
+
import os
|
| 26 |
+
import time
|
| 27 |
+
import traceback
|
| 28 |
+
from dataclasses import dataclass, field
|
| 29 |
+
from datetime import datetime, timezone
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 32 |
+
|
| 33 |
+
from pathway_analysis_env.agent_openai_tools import (
|
| 34 |
+
OPENAI_TOOLS,
|
| 35 |
+
observation_to_tool_result_content,
|
| 36 |
+
tool_call_to_pathway_action,
|
| 37 |
+
)
|
| 38 |
+
from pathway_analysis_env.server.analysis import gseapy_available, pydeseq2_available
|
| 39 |
+
from pathway_analysis_env.server.pathway_environment import DATA_DIR, PathwayEnvironment
|
| 40 |
+
|
| 41 |
+
DEFAULT_SYSTEM_PROMPT = """You are a computational biologist agent operating a pathway analysis environment.
|
| 42 |
+
|
| 43 |
+
Required workflow (eval mode):
|
| 44 |
+
1. understand_experiment_design and/or inspect_dataset — learn groups and sample layout.
|
| 45 |
+
2. run_differential_expression — set reference (baseline) vs alternate (treatment) conditions.
|
| 46 |
+
3. run_pathway_enrichment — ORA on DE genes (do not pass a custom gene_list).
|
| 47 |
+
4. Optionally compare_pathways between two top pathway names.
|
| 48 |
+
5. submit_answer — one pathway hypothesis string supported by ORA.
|
| 49 |
+
|
| 50 |
+
Rules:
|
| 51 |
+
- Never guess without running DE and ORA first.
|
| 52 |
+
- Use condition names exactly as returned in available_conditions.
|
| 53 |
+
- For submit_answer, name a specific pathway (e.g. from top_pathways), not a long essay.
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
MINIMAL_SYSTEM_PROMPT = """Run pathway workflow: design/inspect → DE (reference vs alternate) → ORA → submit_answer with one pathway from ORA. Use exact condition names."""
|
| 57 |
+
|
| 58 |
+
# OpenAI-compatible providers (Groq is free — no credit card).
|
| 59 |
+
LLM_PROVIDERS: Dict[str, Dict[str, Any]] = {
|
| 60 |
+
"groq": {
|
| 61 |
+
"api_key_env": "GROQ_API_KEY",
|
| 62 |
+
"base_url": "https://api.groq.com/openai/v1",
|
| 63 |
+
"default_models": ["llama-3.3-70b-versatile"],
|
| 64 |
+
},
|
| 65 |
+
"openrouter": {
|
| 66 |
+
"api_key_env": "OPENROUTER_API_KEY",
|
| 67 |
+
"base_url": "https://openrouter.ai/api/v1",
|
| 68 |
+
"default_models": ["openrouter/free"],
|
| 69 |
+
},
|
| 70 |
+
"openai": {
|
| 71 |
+
"api_key_env": "OPENAI_API_KEY",
|
| 72 |
+
"base_url": None,
|
| 73 |
+
"default_models": ["gpt-4o-mini", "gpt-4o"],
|
| 74 |
+
},
|
| 75 |
+
"ollama": {
|
| 76 |
+
"api_key_env": None,
|
| 77 |
+
"base_url": "http://127.0.0.1:11434/v1",
|
| 78 |
+
"default_models": ["llama3.1:8b"],
|
| 79 |
+
},
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@dataclass
|
| 84 |
+
class LLMProvider:
|
| 85 |
+
name: str
|
| 86 |
+
api_key: str
|
| 87 |
+
base_url: Optional[str]
|
| 88 |
+
default_models: List[str]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@dataclass
|
| 92 |
+
class EpisodeResult:
|
| 93 |
+
agent_id: str
|
| 94 |
+
model: str
|
| 95 |
+
episode_id: str
|
| 96 |
+
case_file: str
|
| 97 |
+
passed: bool
|
| 98 |
+
score: float
|
| 99 |
+
steps: int
|
| 100 |
+
turns: int
|
| 101 |
+
wall_time_s: float
|
| 102 |
+
done: bool
|
| 103 |
+
hypothesis: Optional[str] = None
|
| 104 |
+
match_mode: Optional[str] = None
|
| 105 |
+
failure_code: Optional[str] = None
|
| 106 |
+
action_trace: List[str] = field(default_factory=list)
|
| 107 |
+
error: Optional[str] = None
|
| 108 |
+
skipped: bool = False
|
| 109 |
+
skip_reason: Optional[str] = None
|
| 110 |
+
|
| 111 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 112 |
+
return {
|
| 113 |
+
"agent_id": self.agent_id,
|
| 114 |
+
"model": self.model,
|
| 115 |
+
"episode_id": self.episode_id,
|
| 116 |
+
"case_file": self.case_file,
|
| 117 |
+
"passed": self.passed,
|
| 118 |
+
"score": self.score,
|
| 119 |
+
"steps": self.steps,
|
| 120 |
+
"turns": self.turns,
|
| 121 |
+
"wall_time_s": round(self.wall_time_s, 2),
|
| 122 |
+
"done": self.done,
|
| 123 |
+
"hypothesis": self.hypothesis,
|
| 124 |
+
"match_mode": self.match_mode,
|
| 125 |
+
"failure_code": self.failure_code,
|
| 126 |
+
"action_trace": self.action_trace,
|
| 127 |
+
"error": self.error,
|
| 128 |
+
"skipped": self.skipped,
|
| 129 |
+
"skip_reason": self.skip_reason,
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _load_dotenv() -> None:
|
| 134 |
+
root = Path(__file__).resolve().parents[3]
|
| 135 |
+
env_path = root / ".env"
|
| 136 |
+
if not env_path.is_file():
|
| 137 |
+
return
|
| 138 |
+
for line in env_path.read_text(encoding="utf-8").splitlines():
|
| 139 |
+
line = line.strip()
|
| 140 |
+
if not line or line.startswith("#") or "=" not in line:
|
| 141 |
+
continue
|
| 142 |
+
key, _, val = line.partition("=")
|
| 143 |
+
key, val = key.strip(), val.strip().strip('"').strip("'")
|
| 144 |
+
if key and val and key not in os.environ:
|
| 145 |
+
os.environ[key] = val
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _ollama_reachable() -> bool:
|
| 149 |
+
try:
|
| 150 |
+
import urllib.request
|
| 151 |
+
|
| 152 |
+
with urllib.request.urlopen(
|
| 153 |
+
"http://127.0.0.1:11434/api/tags", timeout=1.5
|
| 154 |
+
) as resp:
|
| 155 |
+
return resp.status == 200
|
| 156 |
+
except Exception:
|
| 157 |
+
return False
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def resolve_llm_provider(explicit: str = "auto") -> Optional[LLMProvider]:
|
| 161 |
+
"""Pick an LLM backend from env vars or an explicit --provider flag."""
|
| 162 |
+
order = ["groq", "openrouter", "openai", "ollama"]
|
| 163 |
+
names = [explicit] if explicit != "auto" else order
|
| 164 |
+
|
| 165 |
+
for name in names:
|
| 166 |
+
if name not in LLM_PROVIDERS:
|
| 167 |
+
raise SystemExit(
|
| 168 |
+
f"Unknown provider {name!r}. Choose: auto, {', '.join(order)}"
|
| 169 |
+
)
|
| 170 |
+
spec = LLM_PROVIDERS[name]
|
| 171 |
+
key_env = spec.get("api_key_env")
|
| 172 |
+
if key_env:
|
| 173 |
+
api_key = os.environ.get(key_env, "")
|
| 174 |
+
if not api_key:
|
| 175 |
+
continue
|
| 176 |
+
elif name == "ollama":
|
| 177 |
+
if not _ollama_reachable():
|
| 178 |
+
continue
|
| 179 |
+
api_key = "ollama"
|
| 180 |
+
else:
|
| 181 |
+
continue
|
| 182 |
+
return LLMProvider(
|
| 183 |
+
name=name,
|
| 184 |
+
api_key=api_key,
|
| 185 |
+
base_url=spec.get("base_url"),
|
| 186 |
+
default_models=list(spec["default_models"]),
|
| 187 |
+
)
|
| 188 |
+
return None
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def make_llm_client(provider: LLMProvider):
|
| 192 |
+
from openai import AsyncOpenAI
|
| 193 |
+
|
| 194 |
+
kwargs: Dict[str, Any] = {"api_key": provider.api_key}
|
| 195 |
+
if provider.base_url:
|
| 196 |
+
kwargs["base_url"] = provider.base_url
|
| 197 |
+
return AsyncOpenAI(**kwargs)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _episode_skipped(spec: Dict[str, Any]) -> Optional[str]:
|
| 201 |
+
if spec.get("requires_pydeseq2") and not pydeseq2_available():
|
| 202 |
+
return "pydeseq2_unavailable"
|
| 203 |
+
if spec.get("requires_gseapy") and not gseapy_available():
|
| 204 |
+
return "gseapy_unavailable"
|
| 205 |
+
return None
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def _skipped_result(
|
| 209 |
+
agent_id: str, model: str, spec: Dict[str, Any], reason: str
|
| 210 |
+
) -> EpisodeResult:
|
| 211 |
+
return EpisodeResult(
|
| 212 |
+
agent_id=agent_id,
|
| 213 |
+
model=model,
|
| 214 |
+
episode_id=spec["id"],
|
| 215 |
+
case_file=spec["case_file"],
|
| 216 |
+
passed=False,
|
| 217 |
+
score=0.0,
|
| 218 |
+
steps=0,
|
| 219 |
+
turns=0,
|
| 220 |
+
wall_time_s=0.0,
|
| 221 |
+
done=False,
|
| 222 |
+
skipped=True,
|
| 223 |
+
skip_reason=reason,
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _retry_after_seconds(exc: Exception) -> Optional[float]:
|
| 228 |
+
"""Parse a provider 'try again in Xs' hint from a rate-limit error."""
|
| 229 |
+
import re
|
| 230 |
+
|
| 231 |
+
text = str(exc)
|
| 232 |
+
m = re.search(r"try again in\s*(?:(\d+)m)?\s*([\d.]+)s", text)
|
| 233 |
+
if not m:
|
| 234 |
+
return None
|
| 235 |
+
minutes = float(m.group(1)) if m.group(1) else 0.0
|
| 236 |
+
seconds = float(m.group(2)) if m.group(2) else 0.0
|
| 237 |
+
return minutes * 60.0 + seconds
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _supports_temperature_override(model: str) -> bool:
|
| 241 |
+
"""Some models (e.g. gpt-5) only support default temperature."""
|
| 242 |
+
return not model.startswith("gpt-5")
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
async def _chat_with_retry(
|
| 246 |
+
client,
|
| 247 |
+
*,
|
| 248 |
+
model: str,
|
| 249 |
+
messages: List[Dict[str, Any]],
|
| 250 |
+
max_retries: int,
|
| 251 |
+
):
|
| 252 |
+
"""Call chat.completions with backoff on rate limits / transient errors.
|
| 253 |
+
|
| 254 |
+
Honors the provider's "try again in Xs" hint when present; otherwise uses
|
| 255 |
+
exponential backoff. Tool-use parser hiccups (Groq ``tool_use_failed``) are
|
| 256 |
+
also retried since they are non-deterministic.
|
| 257 |
+
"""
|
| 258 |
+
attempt = 0
|
| 259 |
+
tool_hiccups = 0
|
| 260 |
+
while True:
|
| 261 |
+
# Base call is deterministic (T=0). On a provider tool-call parser
|
| 262 |
+
# failure, nudge temperature up so retries are not identical (and thus
|
| 263 |
+
# not guaranteed to fail the same way).
|
| 264 |
+
temperature = min(0.2 * tool_hiccups, 0.8)
|
| 265 |
+
try:
|
| 266 |
+
kwargs: Dict[str, Any] = {
|
| 267 |
+
"model": model,
|
| 268 |
+
"messages": messages,
|
| 269 |
+
"tools": OPENAI_TOOLS,
|
| 270 |
+
"tool_choice": "auto",
|
| 271 |
+
}
|
| 272 |
+
if _supports_temperature_override(model):
|
| 273 |
+
kwargs["temperature"] = temperature
|
| 274 |
+
return await client.chat.completions.create(**kwargs)
|
| 275 |
+
except Exception as exc: # noqa: BLE001 - provider-agnostic retry
|
| 276 |
+
text = str(exc)
|
| 277 |
+
is_rate_limit = "429" in text or "rate_limit" in text.lower()
|
| 278 |
+
is_tool_hiccup = "tool_use_failed" in text
|
| 279 |
+
if attempt >= max_retries or not (is_rate_limit or is_tool_hiccup):
|
| 280 |
+
raise
|
| 281 |
+
if is_tool_hiccup:
|
| 282 |
+
tool_hiccups += 1
|
| 283 |
+
hinted = _retry_after_seconds(exc) if is_rate_limit else None
|
| 284 |
+
if hinted is not None:
|
| 285 |
+
delay = hinted + 1.0 # cushion past the rate-limit window
|
| 286 |
+
elif is_tool_hiccup:
|
| 287 |
+
delay = 1.0 # parser hiccup: retry quickly with new temperature
|
| 288 |
+
else:
|
| 289 |
+
delay = min(2.0 * (2**attempt), 60.0)
|
| 290 |
+
print(
|
| 291 |
+
f" retry {attempt + 1}/{max_retries} after "
|
| 292 |
+
f"{'rate limit' if is_rate_limit else 'tool_use_failed'} "
|
| 293 |
+
f"(sleeping {delay:.1f}s, temp->{min(0.2 * tool_hiccups, 0.8):.1f})...",
|
| 294 |
+
flush=True,
|
| 295 |
+
)
|
| 296 |
+
await asyncio.sleep(delay)
|
| 297 |
+
attempt += 1
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
async def run_llm_episode(
|
| 301 |
+
*,
|
| 302 |
+
agent_id: str,
|
| 303 |
+
model: str,
|
| 304 |
+
case_file: str,
|
| 305 |
+
episode_id: str,
|
| 306 |
+
system_prompt: str,
|
| 307 |
+
max_turns: int,
|
| 308 |
+
strict: bool,
|
| 309 |
+
provider: LLMProvider,
|
| 310 |
+
max_retries: int = 6,
|
| 311 |
+
) -> EpisodeResult:
|
| 312 |
+
t0 = time.perf_counter()
|
| 313 |
+
action_trace: List[str] = []
|
| 314 |
+
client = make_llm_client(provider)
|
| 315 |
+
env = PathwayEnvironment(case_file=case_file)
|
| 316 |
+
try:
|
| 317 |
+
obs = env.reset(orchestrator_mode=True, strict=strict)
|
| 318 |
+
messages: List[Dict[str, Any]] = [
|
| 319 |
+
{"role": "system", "content": system_prompt},
|
| 320 |
+
{
|
| 321 |
+
"role": "user",
|
| 322 |
+
"content": (
|
| 323 |
+
f"Episode {episode_id}. Case: {case_file}. "
|
| 324 |
+
f"Conditions: {obs.available_conditions}. {obs.message}"
|
| 325 |
+
),
|
| 326 |
+
},
|
| 327 |
+
]
|
| 328 |
+
last_failure: Optional[str] = None
|
| 329 |
+
turn = 0
|
| 330 |
+
for turn in range(max_turns):
|
| 331 |
+
response = await _chat_with_retry(
|
| 332 |
+
client,
|
| 333 |
+
model=model,
|
| 334 |
+
messages=messages,
|
| 335 |
+
max_retries=max_retries,
|
| 336 |
+
)
|
| 337 |
+
msg = response.choices[0].message
|
| 338 |
+
if not msg.tool_calls:
|
| 339 |
+
messages.append({"role": "assistant", "content": msg.content or ""})
|
| 340 |
+
if env.state.is_done:
|
| 341 |
+
break
|
| 342 |
+
continue
|
| 343 |
+
# Reconstruct a clean assistant message with only fields that
|
| 344 |
+
# OpenAI-compatible providers universally accept. The OpenAI SDK
|
| 345 |
+
# adds extra fields (e.g. ``annotations``) that strict providers
|
| 346 |
+
# such as Groq reject with a 400 error on the next request.
|
| 347 |
+
messages.append(
|
| 348 |
+
{
|
| 349 |
+
"role": "assistant",
|
| 350 |
+
"content": msg.content or "",
|
| 351 |
+
"tool_calls": [
|
| 352 |
+
{
|
| 353 |
+
"id": tc.id,
|
| 354 |
+
"type": "function",
|
| 355 |
+
"function": {
|
| 356 |
+
"name": tc.function.name,
|
| 357 |
+
"arguments": tc.function.arguments,
|
| 358 |
+
},
|
| 359 |
+
}
|
| 360 |
+
for tc in msg.tool_calls
|
| 361 |
+
],
|
| 362 |
+
}
|
| 363 |
+
)
|
| 364 |
+
for tc in msg.tool_calls:
|
| 365 |
+
action = tool_call_to_pathway_action(
|
| 366 |
+
name=tc.function.name,
|
| 367 |
+
arguments_json=tc.function.arguments,
|
| 368 |
+
)
|
| 369 |
+
action_trace.append(action.action_type)
|
| 370 |
+
step_obs = env.step(action)
|
| 371 |
+
meta = step_obs.metadata or {}
|
| 372 |
+
if meta.get("failure_code"):
|
| 373 |
+
last_failure = str(meta["failure_code"])
|
| 374 |
+
messages.append(
|
| 375 |
+
{
|
| 376 |
+
"role": "tool",
|
| 377 |
+
"tool_call_id": tc.id,
|
| 378 |
+
"content": observation_to_tool_result_content(step_obs),
|
| 379 |
+
}
|
| 380 |
+
)
|
| 381 |
+
if step_obs.done:
|
| 382 |
+
break
|
| 383 |
+
if env.state.is_done:
|
| 384 |
+
break
|
| 385 |
+
outcome = env.episode_outcome or {}
|
| 386 |
+
return EpisodeResult(
|
| 387 |
+
agent_id=agent_id,
|
| 388 |
+
model=model,
|
| 389 |
+
episode_id=episode_id,
|
| 390 |
+
case_file=case_file,
|
| 391 |
+
passed=bool(outcome.get("correct")),
|
| 392 |
+
score=float(outcome.get("score") or 0.0),
|
| 393 |
+
steps=env.state.step_count,
|
| 394 |
+
turns=turn + 1,
|
| 395 |
+
wall_time_s=time.perf_counter() - t0,
|
| 396 |
+
done=env.state.is_done,
|
| 397 |
+
hypothesis=outcome.get("hypothesis"),
|
| 398 |
+
match_mode=outcome.get("match_mode"),
|
| 399 |
+
failure_code=last_failure if not outcome.get("correct") else None,
|
| 400 |
+
action_trace=action_trace,
|
| 401 |
+
)
|
| 402 |
+
except Exception as exc:
|
| 403 |
+
return EpisodeResult(
|
| 404 |
+
agent_id=agent_id,
|
| 405 |
+
model=model,
|
| 406 |
+
episode_id=episode_id,
|
| 407 |
+
case_file=case_file,
|
| 408 |
+
passed=False,
|
| 409 |
+
score=0.0,
|
| 410 |
+
steps=0,
|
| 411 |
+
turns=0,
|
| 412 |
+
wall_time_s=time.perf_counter() - t0,
|
| 413 |
+
done=False,
|
| 414 |
+
error=f"{type(exc).__name__}: {exc}",
|
| 415 |
+
action_trace=action_trace,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def aggregate(results: List[EpisodeResult]) -> Dict[str, Any]:
|
| 420 |
+
by_agent: Dict[str, List[EpisodeResult]] = {}
|
| 421 |
+
for r in results:
|
| 422 |
+
by_agent.setdefault(r.agent_id, []).append(r)
|
| 423 |
+
agents_summary = []
|
| 424 |
+
for agent_id, rows in sorted(by_agent.items()):
|
| 425 |
+
run_rows = [x for x in rows if not x.skipped]
|
| 426 |
+
passed = sum(1 for x in run_rows if x.passed)
|
| 427 |
+
agents_summary.append(
|
| 428 |
+
{
|
| 429 |
+
"agent_id": agent_id,
|
| 430 |
+
"model": rows[0].model if rows else "",
|
| 431 |
+
"episodes_run": len(run_rows),
|
| 432 |
+
"episodes_passed": passed,
|
| 433 |
+
"pass_rate": passed / len(run_rows) if run_rows else 0.0,
|
| 434 |
+
"avg_score": (
|
| 435 |
+
sum(x.score for x in run_rows) / len(run_rows) if run_rows else 0.0
|
| 436 |
+
),
|
| 437 |
+
"avg_steps": (
|
| 438 |
+
sum(x.steps for x in run_rows) / len(run_rows) if run_rows else 0.0
|
| 439 |
+
),
|
| 440 |
+
"avg_wall_time_s": (
|
| 441 |
+
sum(x.wall_time_s for x in run_rows) / len(run_rows)
|
| 442 |
+
if run_rows
|
| 443 |
+
else 0.0
|
| 444 |
+
),
|
| 445 |
+
}
|
| 446 |
+
)
|
| 447 |
+
return {"agents": agents_summary}
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def write_markdown_report(summary: Dict[str, Any], path: Path) -> None:
|
| 451 |
+
lines = [
|
| 452 |
+
"# Pathway Agent Evaluation Report",
|
| 453 |
+
"",
|
| 454 |
+
f"Generated: {summary.get('generated_at', '')}",
|
| 455 |
+
"",
|
| 456 |
+
"## Eval plan",
|
| 457 |
+
"",
|
| 458 |
+
summary.get("eval_plan", ""),
|
| 459 |
+
"",
|
| 460 |
+
"## Leaderboard",
|
| 461 |
+
"",
|
| 462 |
+
"| Agent | Model | Pass rate | Avg score | Avg steps | Avg time (s) |",
|
| 463 |
+
"|-------|-------|-----------|-----------|-----------|--------------|",
|
| 464 |
+
]
|
| 465 |
+
for a in summary.get("aggregate", {}).get("agents", []):
|
| 466 |
+
lines.append(
|
| 467 |
+
f"| {a['agent_id']} | {a['model']} | {a['pass_rate']:.0%} "
|
| 468 |
+
f"({a['episodes_passed']}/{a['episodes_run']}) | {a['avg_score']:.2f} | "
|
| 469 |
+
f"{a['avg_steps']:.1f} | {a['avg_wall_time_s']:.1f} |"
|
| 470 |
+
)
|
| 471 |
+
lines.extend(["", "## Per-episode results", ""])
|
| 472 |
+
for r in summary.get("results", []):
|
| 473 |
+
status = "SKIP" if r.get("skipped") else ("PASS" if r.get("passed") else "FAIL")
|
| 474 |
+
lines.append(
|
| 475 |
+
f"- **{status}** `{r.get('agent_id')}` / `{r.get('episode_id')}` "
|
| 476 |
+
f"— score={r.get('score')} steps={r.get('steps')} "
|
| 477 |
+
f"hypothesis={r.get('hypothesis')!r} "
|
| 478 |
+
f"failure={r.get('failure_code') or r.get('error') or '—'}"
|
| 479 |
+
)
|
| 480 |
+
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
async def main_async(
|
| 484 |
+
args: argparse.Namespace,
|
| 485 |
+
) -> Tuple[Dict[str, Any], Optional[LLMProvider]]:
|
| 486 |
+
manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
|
| 487 |
+
episodes = manifest.get("episodes", [])
|
| 488 |
+
provider = resolve_llm_provider(args.provider)
|
| 489 |
+
models = [m.strip() for m in args.models.split(",") if m.strip()]
|
| 490 |
+
if not models and provider:
|
| 491 |
+
models = list(provider.default_models)
|
| 492 |
+
|
| 493 |
+
eval_plan = (
|
| 494 |
+
"Tool-calling LLM agent at T=0 over the manifest episodes "
|
| 495 |
+
"(provider: Groq/OpenRouter/OpenAI/Ollama). The agent is given the "
|
| 496 |
+
"pathway tools and decides which to call and when to submit_answer. "
|
| 497 |
+
"Metrics: pass rate, avg score, steps, wall time, action trace, failure codes."
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
results: List[EpisodeResult] = []
|
| 501 |
+
|
| 502 |
+
if provider is None:
|
| 503 |
+
print(
|
| 504 |
+
"No LLM API key found — cannot run the agent.\n"
|
| 505 |
+
" Free option: export GROQ_API_KEY=... (sign up at https://console.groq.com)\n"
|
| 506 |
+
" Or: ollama serve && --provider ollama\n"
|
| 507 |
+
" Or add GROQ_API_KEY to repo-root .env",
|
| 508 |
+
flush=True,
|
| 509 |
+
)
|
| 510 |
+
else:
|
| 511 |
+
print(f"LLM provider: {provider.name} models: {', '.join(models)}", flush=True)
|
| 512 |
+
prompt_variants = [("llm_default", DEFAULT_SYSTEM_PROMPT)]
|
| 513 |
+
if args.prompt_ablation:
|
| 514 |
+
prompt_variants.append(("llm_minimal", MINIMAL_SYSTEM_PROMPT))
|
| 515 |
+
for model in models:
|
| 516 |
+
for prompt_name, prompt_text in prompt_variants:
|
| 517 |
+
agent_id = f"{prompt_name}__{model.replace('/', '_').replace(':', '_')}"
|
| 518 |
+
for spec in episodes:
|
| 519 |
+
skip = _episode_skipped(spec)
|
| 520 |
+
if skip:
|
| 521 |
+
results.append(_skipped_result(agent_id, model, spec, skip))
|
| 522 |
+
continue
|
| 523 |
+
print(f"Running {agent_id} on {spec['id']}...", flush=True)
|
| 524 |
+
r = await run_llm_episode(
|
| 525 |
+
agent_id=agent_id,
|
| 526 |
+
model=model,
|
| 527 |
+
case_file=spec["case_file"],
|
| 528 |
+
episode_id=spec["id"],
|
| 529 |
+
system_prompt=prompt_text,
|
| 530 |
+
max_turns=args.max_turns,
|
| 531 |
+
strict=args.strict,
|
| 532 |
+
provider=provider,
|
| 533 |
+
max_retries=args.max_retries,
|
| 534 |
+
)
|
| 535 |
+
results.append(r)
|
| 536 |
+
print(
|
| 537 |
+
f" -> {'PASS' if r.passed else 'FAIL'} score={r.score} steps={r.steps}",
|
| 538 |
+
flush=True,
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
summary = {
|
| 542 |
+
"generated_at": datetime.now(timezone.utc).isoformat(),
|
| 543 |
+
"eval_plan": eval_plan,
|
| 544 |
+
"manifest": str(args.manifest),
|
| 545 |
+
"llm_provider": provider.name if provider else None,
|
| 546 |
+
"models": models if provider else [],
|
| 547 |
+
"aggregate": aggregate(results),
|
| 548 |
+
"results": [r.to_dict() for r in results],
|
| 549 |
+
}
|
| 550 |
+
return summary, provider
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def main() -> None:
|
| 554 |
+
parser = argparse.ArgumentParser(
|
| 555 |
+
description="Tool-calling LLM agent eval for pathway env"
|
| 556 |
+
)
|
| 557 |
+
parser.add_argument(
|
| 558 |
+
"--manifest", type=Path, default=DATA_DIR / "eval_manifest.json"
|
| 559 |
+
)
|
| 560 |
+
parser.add_argument(
|
| 561 |
+
"--provider",
|
| 562 |
+
default="auto",
|
| 563 |
+
choices=["auto", "groq", "openrouter", "openai", "ollama"],
|
| 564 |
+
help="LLM backend (auto tries Groq, OpenRouter, OpenAI, then Ollama)",
|
| 565 |
+
)
|
| 566 |
+
parser.add_argument(
|
| 567 |
+
"--models",
|
| 568 |
+
default="",
|
| 569 |
+
help="Comma-separated model IDs (defaults per provider if omitted)",
|
| 570 |
+
)
|
| 571 |
+
parser.add_argument("--max-turns", type=int, default=20)
|
| 572 |
+
parser.add_argument(
|
| 573 |
+
"--max-retries",
|
| 574 |
+
type=int,
|
| 575 |
+
default=6,
|
| 576 |
+
help="Retries per LLM call on rate-limit / transient tool errors",
|
| 577 |
+
)
|
| 578 |
+
parser.add_argument("--strict", action="store_true")
|
| 579 |
+
parser.add_argument("--prompt-ablation", action="store_true")
|
| 580 |
+
parser.add_argument(
|
| 581 |
+
"--json-out",
|
| 582 |
+
type=Path,
|
| 583 |
+
default=Path("envs/pathway_analysis_env/outputs/llm_eval/latest.json"),
|
| 584 |
+
)
|
| 585 |
+
parser.add_argument(
|
| 586 |
+
"--md-out",
|
| 587 |
+
type=Path,
|
| 588 |
+
default=Path("envs/pathway_analysis_env/outputs/llm_eval/latest.md"),
|
| 589 |
+
)
|
| 590 |
+
args = parser.parse_args()
|
| 591 |
+
|
| 592 |
+
_load_dotenv()
|
| 593 |
+
|
| 594 |
+
try:
|
| 595 |
+
summary, _provider = asyncio.run(main_async(args))
|
| 596 |
+
except Exception:
|
| 597 |
+
traceback.print_exc()
|
| 598 |
+
raise
|
| 599 |
+
|
| 600 |
+
args.json_out.parent.mkdir(parents=True, exist_ok=True)
|
| 601 |
+
args.json_out.write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
|
| 602 |
+
write_markdown_report(summary, args.md_out)
|
| 603 |
+
print(f"\nWrote {args.json_out}")
|
| 604 |
+
print(f"Wrote {args.md_out}")
|
| 605 |
+
print("\nLeaderboard:")
|
| 606 |
+
for a in summary["aggregate"]["agents"]:
|
| 607 |
+
print(
|
| 608 |
+
f" {a['agent_id']:40s} pass={a['pass_rate']:.0%} "
|
| 609 |
+
f"avg_score={a['avg_score']:.2f} avg_steps={a['avg_steps']:.1f}"
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
if __name__ == "__main__":
|
| 614 |
+
main()
|
envs/pathway_analysis_env/scripts/run_llm_judge.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
LLM-judge evaluation for pathway_analysis_env (eval-only, non-deterministic).
|
| 4 |
+
|
| 5 |
+
Runs a tool-calling agent on one GEO case, asks it to produce a findings
|
| 6 |
+
report, builds a *reference* report from the same live episode outputs (DE/ORA)
|
| 7 |
+
that the agent saw, then asks a judge model to rate the agent report.
|
| 8 |
+
|
| 9 |
+
This is an EVALUATION aid only. It is deliberately NOT wired into the
|
| 10 |
+
environment reward (which must stay deterministic for RL training).
|
| 11 |
+
|
| 12 |
+
Usage:
|
| 13 |
+
export OPENAI_API_KEY=...
|
| 14 |
+
PYTHONPATH=src:envs uv run python envs/pathway_analysis_env/scripts/run_llm_judge.py \
|
| 15 |
+
--case geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso/gse128911_case.json \
|
| 16 |
+
--reference-dir envs/pathway_analysis_env/data/geo_eval/gse128911_mda_mb_134_vi_fulvestrant_vs_dmso \
|
| 17 |
+
--agent-model gpt-4o-mini --judge-model gpt-4o-mini
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import asyncio
|
| 24 |
+
import json
|
| 25 |
+
import os
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
from typing import Any, Dict, List
|
| 28 |
+
|
| 29 |
+
from openai import AsyncOpenAI
|
| 30 |
+
|
| 31 |
+
from pathway_analysis_env.agent_openai_tools import (
|
| 32 |
+
OPENAI_TOOLS,
|
| 33 |
+
observation_to_tool_result_content,
|
| 34 |
+
tool_call_to_pathway_action,
|
| 35 |
+
)
|
| 36 |
+
from pathway_analysis_env.server.pathway_environment import DATA_DIR, PathwayEnvironment
|
| 37 |
+
|
| 38 |
+
AGENT_SYSTEM_PROMPT = """You are a computational biologist agent operating a pathway analysis environment.
|
| 39 |
+
|
| 40 |
+
Workflow: understand_experiment_design / inspect_dataset -> run_differential_expression
|
| 41 |
+
(reference vs alternate) -> run_pathway_enrichment -> optionally compare_pathways ->
|
| 42 |
+
submit_answer with the activated pathway. Never guess before running DE and ORA.
|
| 43 |
+
After you submit, you will be asked to write a short findings report."""
|
| 44 |
+
|
| 45 |
+
REPORT_REQUEST = """The episode is complete. Write a concise findings report (5-8 sentences)
|
| 46 |
+
of what you discovered: the contrast you ran, the most significant differentially
|
| 47 |
+
expressed genes/direction, the top enriched pathways, and your biological interpretation
|
| 48 |
+
of what program is activated/repressed in this experiment."""
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _chat_kwargs_for_model(model: str) -> Dict[str, Any]:
|
| 52 |
+
"""
|
| 53 |
+
Some models (e.g. gpt-5) do not accept non-default temperature values.
|
| 54 |
+
Return a safe kwargs dict for chat.completions.create.
|
| 55 |
+
"""
|
| 56 |
+
if model.startswith("gpt-5"):
|
| 57 |
+
return {}
|
| 58 |
+
return {"temperature": 0.0}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _load_dotenv() -> None:
|
| 62 |
+
root = Path(__file__).resolve().parents[3]
|
| 63 |
+
env_path = root / ".env"
|
| 64 |
+
if not env_path.is_file():
|
| 65 |
+
return
|
| 66 |
+
for line in env_path.read_text(encoding="utf-8").splitlines():
|
| 67 |
+
line = line.strip()
|
| 68 |
+
if not line or line.startswith("#") or "=" not in line:
|
| 69 |
+
continue
|
| 70 |
+
key, _, val = line.partition("=")
|
| 71 |
+
key, val = key.strip(), val.strip().strip('"').strip("'")
|
| 72 |
+
if key and val and key not in os.environ:
|
| 73 |
+
os.environ[key] = val
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def build_reference_report_from_live(
|
| 77 |
+
case: Dict[str, Any],
|
| 78 |
+
*,
|
| 79 |
+
de_rows: List[Dict[str, Any]],
|
| 80 |
+
ora_rows: List[Dict[str, Any]],
|
| 81 |
+
contrast: str,
|
| 82 |
+
) -> str:
|
| 83 |
+
"""Build reference report from the same live outputs seen by the agent."""
|
| 84 |
+
top = []
|
| 85 |
+
for row in ora_rows[:10]:
|
| 86 |
+
name = row.get("pathway")
|
| 87 |
+
q = row.get("q_value")
|
| 88 |
+
q_txt = f"{q:.2e}" if isinstance(q, (int, float)) else str(q)
|
| 89 |
+
genes = ", ".join((row.get("overlap_genes") or [])[:8])
|
| 90 |
+
top.append(f" - {name} (q={q_txt}); key genes: {genes}")
|
| 91 |
+
top_block = "\n".join(top) if top else " - (none)"
|
| 92 |
+
|
| 93 |
+
sig_n = sum(1 for r in de_rows if bool(r.get("significant")))
|
| 94 |
+
meta = case.get("experiment_metadata", {})
|
| 95 |
+
return (
|
| 96 |
+
f"STUDY: {meta.get('accession')} - {meta.get('summary')}\n"
|
| 97 |
+
f"CONTRAST: {contrast}\n"
|
| 98 |
+
f"SIGNIFICANT GENES (padj<0.05): {sig_n}\n"
|
| 99 |
+
f"TOP ENRICHED PATHWAYS (ground-truth, from same live episode outputs):\n"
|
| 100 |
+
f"{top_block}\n"
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
async def run_agent_report(
|
| 105 |
+
client: AsyncOpenAI, model: str, case_file: str
|
| 106 |
+
) -> tuple[str, str]:
|
| 107 |
+
env = PathwayEnvironment(case_file=case_file)
|
| 108 |
+
obs = env.reset(orchestrator_mode=True)
|
| 109 |
+
messages: List[Dict[str, Any]] = [
|
| 110 |
+
{"role": "system", "content": AGENT_SYSTEM_PROMPT},
|
| 111 |
+
{
|
| 112 |
+
"role": "user",
|
| 113 |
+
"content": f"Case: {case_file}. Conditions: {obs.available_conditions}. {obs.message}",
|
| 114 |
+
},
|
| 115 |
+
]
|
| 116 |
+
for _ in range(20):
|
| 117 |
+
resp = await client.chat.completions.create(
|
| 118 |
+
model=model,
|
| 119 |
+
messages=messages,
|
| 120 |
+
tools=OPENAI_TOOLS,
|
| 121 |
+
tool_choice="auto",
|
| 122 |
+
**_chat_kwargs_for_model(model),
|
| 123 |
+
)
|
| 124 |
+
msg = resp.choices[0].message
|
| 125 |
+
if not msg.tool_calls:
|
| 126 |
+
messages.append({"role": "assistant", "content": msg.content or ""})
|
| 127 |
+
if env.state.is_done:
|
| 128 |
+
break
|
| 129 |
+
continue
|
| 130 |
+
messages.append({
|
| 131 |
+
"role": "assistant", "content": msg.content or "",
|
| 132 |
+
"tool_calls": [
|
| 133 |
+
{"id": tc.id, "type": "function",
|
| 134 |
+
"function": {"name": tc.function.name, "arguments": tc.function.arguments}}
|
| 135 |
+
for tc in msg.tool_calls
|
| 136 |
+
],
|
| 137 |
+
})
|
| 138 |
+
for tc in msg.tool_calls:
|
| 139 |
+
action = tool_call_to_pathway_action(
|
| 140 |
+
name=tc.function.name, arguments_json=tc.function.arguments)
|
| 141 |
+
step_obs = env.step(action)
|
| 142 |
+
messages.append({
|
| 143 |
+
"role": "tool", "tool_call_id": tc.id,
|
| 144 |
+
"content": observation_to_tool_result_content(step_obs),
|
| 145 |
+
})
|
| 146 |
+
if env.state.is_done:
|
| 147 |
+
break
|
| 148 |
+
|
| 149 |
+
# Build reference from exactly the outputs this episode produced.
|
| 150 |
+
de_rows = list(getattr(env, "_de_rows", []) or [])
|
| 151 |
+
ora_rows = list(getattr(env, "_ora_rows", []) or [])
|
| 152 |
+
c_ref = getattr(env._state, "validated_reference", None) or (
|
| 153 |
+
(env._case.get("default_contrast") or {}).get("reference")
|
| 154 |
+
)
|
| 155 |
+
c_alt = getattr(env._state, "validated_alternate", None) or (
|
| 156 |
+
(env._case.get("default_contrast") or {}).get("alternate")
|
| 157 |
+
)
|
| 158 |
+
contrast = (
|
| 159 |
+
f"{c_alt} vs {c_ref} (reference={c_ref})" if c_ref and c_alt else "unknown"
|
| 160 |
+
)
|
| 161 |
+
reference = build_reference_report_from_live(
|
| 162 |
+
env._case, de_rows=de_rows, ora_rows=ora_rows, contrast=contrast
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
messages.append({"role": "user", "content": REPORT_REQUEST})
|
| 166 |
+
resp = await client.chat.completions.create(
|
| 167 |
+
model=model, messages=messages, **_chat_kwargs_for_model(model)
|
| 168 |
+
)
|
| 169 |
+
return resp.choices[0].message.content or "", reference
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
JUDGE_SYSTEM = """You are a strict scientific reviewer. Compare an AGENT REPORT against a
|
| 173 |
+
REFERENCE (ground-truth pathway-analysis result). Score how well the agent recovered the
|
| 174 |
+
correct biology. Return STRICT JSON only."""
|
| 175 |
+
|
| 176 |
+
JUDGE_RUBRIC = """Score 0.0-1.0 on each criterion, then an overall 0.0-1.0:
|
| 177 |
+
- primary_biology: did the agent identify the correct dominant program?
|
| 178 |
+
- supporting_pathways: did it mention the secondary/related pathways?
|
| 179 |
+
- evidence_grounding: are claims tied to the actual DE/enrichment results (not generic priors)?
|
| 180 |
+
- mechanism: correct biological interpretation of the experiment?
|
| 181 |
+
Return JSON: {"primary_biology":x,"supporting_pathways":x,"evidence_grounding":x,
|
| 182 |
+
"mechanism":x,"overall":x,"justification":"2-3 sentences"}"""
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
async def judge(client: AsyncOpenAI, model: str, agent_report: str, reference: str) -> Dict[str, Any]:
|
| 186 |
+
resp = await client.chat.completions.create(
|
| 187 |
+
model=model,
|
| 188 |
+
messages=[
|
| 189 |
+
{"role": "system", "content": JUDGE_SYSTEM},
|
| 190 |
+
{
|
| 191 |
+
"role": "user",
|
| 192 |
+
"content": f"{JUDGE_RUBRIC}\n\n=== REFERENCE ===\n{reference}\n\n=== AGENT REPORT ===\n{agent_report}",
|
| 193 |
+
},
|
| 194 |
+
],
|
| 195 |
+
response_format={"type": "json_object"},
|
| 196 |
+
**_chat_kwargs_for_model(model),
|
| 197 |
+
)
|
| 198 |
+
return json.loads(resp.choices[0].message.content or "{}")
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
async def main_async(args: argparse.Namespace) -> None:
|
| 202 |
+
client = AsyncOpenAI(api_key=os.environ["OPENAI_API_KEY"])
|
| 203 |
+
case_path = DATA_DIR / args.case
|
| 204 |
+
case = json.loads(case_path.read_text())
|
| 205 |
+
|
| 206 |
+
print("Running agent and generating report...", flush=True)
|
| 207 |
+
agent_report, reference = await run_agent_report(client, args.agent_model, args.case)
|
| 208 |
+
print("Judging...", flush=True)
|
| 209 |
+
verdict = await judge(client, args.judge_model, agent_report, reference)
|
| 210 |
+
|
| 211 |
+
print("\n" + "=" * 70)
|
| 212 |
+
print("REFERENCE REPORT\n" + "-" * 70)
|
| 213 |
+
print(reference)
|
| 214 |
+
print("=" * 70)
|
| 215 |
+
print(f"AGENT REPORT ({args.agent_model})\n" + "-" * 70)
|
| 216 |
+
print(agent_report)
|
| 217 |
+
print("=" * 70)
|
| 218 |
+
print(f"JUDGE VERDICT ({args.judge_model})\n" + "-" * 70)
|
| 219 |
+
print(json.dumps(verdict, indent=2))
|
| 220 |
+
|
| 221 |
+
if args.out_json:
|
| 222 |
+
out = Path(args.out_json)
|
| 223 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 224 |
+
out.write_text(
|
| 225 |
+
json.dumps(
|
| 226 |
+
{
|
| 227 |
+
"case": args.case,
|
| 228 |
+
"agent_model": args.agent_model,
|
| 229 |
+
"judge_model": args.judge_model,
|
| 230 |
+
"reference": reference,
|
| 231 |
+
"agent_report": agent_report,
|
| 232 |
+
"verdict": verdict,
|
| 233 |
+
"experiment_metadata": case.get("experiment_metadata", {}),
|
| 234 |
+
},
|
| 235 |
+
indent=2,
|
| 236 |
+
),
|
| 237 |
+
encoding="utf-8",
|
| 238 |
+
)
|
| 239 |
+
print(f"\nWrote {out}")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def main() -> None:
|
| 243 |
+
p = argparse.ArgumentParser(description="LLM-judge eval for pathway env")
|
| 244 |
+
p.add_argument("--case", required=True, help="Case file path relative to data dir")
|
| 245 |
+
p.add_argument(
|
| 246 |
+
"--reference-dir",
|
| 247 |
+
required=False,
|
| 248 |
+
default=None,
|
| 249 |
+
help="Deprecated: reference is now built from live episode outputs",
|
| 250 |
+
)
|
| 251 |
+
p.add_argument("--agent-model", default="gpt-4o-mini")
|
| 252 |
+
p.add_argument("--judge-model", default="gpt-4o-mini")
|
| 253 |
+
p.add_argument("--out-json", default=None, help="Optional path to save artifacts")
|
| 254 |
+
args = p.parse_args()
|
| 255 |
+
_load_dotenv()
|
| 256 |
+
asyncio.run(main_async(args))
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
if __name__ == "__main__":
|
| 260 |
+
main()
|
envs/pathway_analysis_env/server/Dockerfile
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
|
| 8 |
+
FROM ${BASE_IMAGE} AS builder
|
| 9 |
+
|
| 10 |
+
WORKDIR /app
|
| 11 |
+
|
| 12 |
+
ARG BUILD_MODE=in-repo
|
| 13 |
+
|
| 14 |
+
COPY . /app/env
|
| 15 |
+
|
| 16 |
+
WORKDIR /app/env
|
| 17 |
+
|
| 18 |
+
RUN if ! command -v uv >/dev/null 2>&1; then \
|
| 19 |
+
curl -LsSf https://astral.sh/uv/install.sh | sh && \
|
| 20 |
+
mv /root/.local/bin/uv /usr/local/bin/uv && \
|
| 21 |
+
mv /root/.local/bin/uvx /usr/local/bin/uvx; \
|
| 22 |
+
fi
|
| 23 |
+
|
| 24 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 25 |
+
git \
|
| 26 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 27 |
+
|
| 28 |
+
RUN --mount=type=cache,target=/root/.cache/uv \
|
| 29 |
+
if [ -f uv.lock ]; then \
|
| 30 |
+
uv sync --frozen --no-install-project --no-editable; \
|
| 31 |
+
else \
|
| 32 |
+
uv sync --no-install-project --no-editable; \
|
| 33 |
+
fi
|
| 34 |
+
|
| 35 |
+
RUN --mount=type=cache,target=/root/.cache/uv \
|
| 36 |
+
if [ -f uv.lock ]; then \
|
| 37 |
+
uv sync --frozen --no-editable; \
|
| 38 |
+
else \
|
| 39 |
+
uv sync --no-editable; \
|
| 40 |
+
fi
|
| 41 |
+
|
| 42 |
+
FROM ${BASE_IMAGE}
|
| 43 |
+
|
| 44 |
+
WORKDIR /app
|
| 45 |
+
|
| 46 |
+
COPY --from=builder /app/env/.venv /app/.venv
|
| 47 |
+
COPY --from=builder /app/env /app/env
|
| 48 |
+
|
| 49 |
+
ENV PATH="/app/.venv/bin:$PATH"
|
| 50 |
+
ENV PYTHONPATH="/app/env:$PYTHONPATH"
|
| 51 |
+
|
| 52 |
+
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
| 53 |
+
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1
|
| 54 |
+
|
| 55 |
+
CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
|
envs/pathway_analysis_env/server/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
envs/pathway_analysis_env/server/analysis.py
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Differential expression (PyDESeq2) and over-representation analysis (ORA).
|
| 9 |
+
|
| 10 |
+
Counts matrices use **samples × genes** layout for PyDESeq2 ≥ 0.5.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import io
|
| 16 |
+
import math
|
| 17 |
+
from contextlib import redirect_stderr, redirect_stdout
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Dict, List, Optional, Sequence, Set, Tuple
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import pandas as pd
|
| 23 |
+
from scipy.stats import false_discovery_control, fisher_exact
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
from pydeseq2.dds import DeseqDataSet
|
| 27 |
+
from pydeseq2.ds import DeseqStats
|
| 28 |
+
|
| 29 |
+
_PYDESQ2_AVAILABLE = True
|
| 30 |
+
except ImportError: # pragma: no cover - optional heavy dep
|
| 31 |
+
DeseqDataSet = None # type: ignore[misc, assignment]
|
| 32 |
+
DeseqStats = None # type: ignore[misc, assignment]
|
| 33 |
+
_PYDESQ2_AVAILABLE = False
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
import gseapy as gp
|
| 37 |
+
|
| 38 |
+
_GSEAPY_AVAILABLE = True
|
| 39 |
+
except ImportError: # pragma: no cover - optional extra dep
|
| 40 |
+
gp = None # type: ignore[assignment]
|
| 41 |
+
_GSEAPY_AVAILABLE = False
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def pydeseq2_available() -> bool:
|
| 45 |
+
return _PYDESQ2_AVAILABLE
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def gseapy_available() -> bool:
|
| 49 |
+
return _GSEAPY_AVAILABLE
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def default_analysis_options() -> Dict[str, Any]:
|
| 53 |
+
"""Defaults aligned with common RNA-seq practice (DESeq2 prefilter, directional ORA)."""
|
| 54 |
+
return {
|
| 55 |
+
"min_total_count": 10,
|
| 56 |
+
"padj_alpha": 0.05,
|
| 57 |
+
"ora_min_pathway_genes": 3,
|
| 58 |
+
# Use "up" for treated-vs-control activation screens; "both" is the safe default.
|
| 59 |
+
"de_query_direction": "both",
|
| 60 |
+
"min_abs_log2fc": 0.0,
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def merge_analysis_options(case: Dict[str, Any]) -> Dict[str, Any]:
|
| 65 |
+
out = default_analysis_options()
|
| 66 |
+
raw = case.get("analysis_options")
|
| 67 |
+
if not isinstance(raw, dict):
|
| 68 |
+
return out
|
| 69 |
+
for k, v in raw.items():
|
| 70 |
+
if k not in out or v is None:
|
| 71 |
+
continue
|
| 72 |
+
if k in ("min_total_count", "ora_min_pathway_genes"):
|
| 73 |
+
out[k] = int(v)
|
| 74 |
+
elif k in ("padj_alpha", "min_abs_log2fc"):
|
| 75 |
+
out[k] = float(v)
|
| 76 |
+
elif k == "de_query_direction":
|
| 77 |
+
out[k] = str(v).lower().strip()
|
| 78 |
+
else:
|
| 79 |
+
out[k] = v
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def filter_counts_by_minimum_total(
|
| 84 |
+
counts_df: pd.DataFrame,
|
| 85 |
+
min_total: int,
|
| 86 |
+
) -> Tuple[pd.DataFrame, int, int]:
|
| 87 |
+
"""
|
| 88 |
+
Remove genes with summed counts below ``min_total`` (DESeq2-style prefilter).
|
| 89 |
+
|
| 90 |
+
Returns:
|
| 91 |
+
(filtered_df, n_before, n_after)
|
| 92 |
+
"""
|
| 93 |
+
if min_total <= 0:
|
| 94 |
+
return counts_df, counts_df.shape[1], counts_df.shape[1]
|
| 95 |
+
totals = counts_df.sum(axis=0)
|
| 96 |
+
keep = totals >= min_total
|
| 97 |
+
n_before = int(counts_df.shape[1])
|
| 98 |
+
filtered = counts_df.loc[:, keep]
|
| 99 |
+
n_after = int(filtered.shape[1])
|
| 100 |
+
return filtered, n_before, n_after
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def normalize_gene_ids(raw: Sequence[str]) -> List[str]:
|
| 104 |
+
"""
|
| 105 |
+
Normalize gene identifiers for downstream gene set matching.
|
| 106 |
+
|
| 107 |
+
GEO count tables often use a combined key like ``ENSG...__TP53``.
|
| 108 |
+
We keep the symbol suffix when present.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
out: List[str] = []
|
| 112 |
+
for g in raw:
|
| 113 |
+
s = str(g)
|
| 114 |
+
if "__" in s:
|
| 115 |
+
s = s.split("__", 1)[1]
|
| 116 |
+
out.append(s)
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def load_counts_csv_as_samples_by_genes(
|
| 121 |
+
path: str | Path,
|
| 122 |
+
*,
|
| 123 |
+
sample_ids: Optional[Sequence[str]] = None,
|
| 124 |
+
) -> pd.DataFrame:
|
| 125 |
+
"""
|
| 126 |
+
Load a counts table from CSV/CSV.GZ and return **samples × genes** DataFrame.
|
| 127 |
+
|
| 128 |
+
Expected file layout:
|
| 129 |
+
- rows: genes
|
| 130 |
+
- columns: sample IDs
|
| 131 |
+
- first column: gene identifier (may be unnamed)
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
p = Path(path)
|
| 135 |
+
df = pd.read_csv(p, index_col=0)
|
| 136 |
+
if df.empty:
|
| 137 |
+
raise ValueError(f"Counts file is empty: {p}")
|
| 138 |
+
|
| 139 |
+
df.index = normalize_gene_ids(df.index.tolist())
|
| 140 |
+
df = df.apply(pd.to_numeric, errors="coerce").fillna(0).astype(int)
|
| 141 |
+
|
| 142 |
+
# Aggregate duplicate symbols (common when collapsing Ensembl->symbol).
|
| 143 |
+
if df.index.has_duplicates:
|
| 144 |
+
df = df.groupby(df.index).sum()
|
| 145 |
+
|
| 146 |
+
# genes × samples -> samples × genes
|
| 147 |
+
counts_df = df.T
|
| 148 |
+
|
| 149 |
+
if sample_ids is not None:
|
| 150 |
+
missing = [s for s in sample_ids if s not in counts_df.index]
|
| 151 |
+
if missing:
|
| 152 |
+
raise ValueError(
|
| 153 |
+
f"Counts file missing sample columns/rows for: {missing[:10]}"
|
| 154 |
+
+ (" ..." if len(missing) > 10 else "")
|
| 155 |
+
)
|
| 156 |
+
counts_df = counts_df.loc[list(sample_ids)]
|
| 157 |
+
|
| 158 |
+
return counts_df
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def counts_dict_to_samples_by_genes(
|
| 162 |
+
counts: Dict[str, Sequence[int]],
|
| 163 |
+
sample_ids: Sequence[str],
|
| 164 |
+
) -> pd.DataFrame:
|
| 165 |
+
"""Build a samples × genes count matrix from gene → per-sample counts."""
|
| 166 |
+
sid_to_i = {sid: i for i, sid in enumerate(sample_ids)}
|
| 167 |
+
rows = []
|
| 168 |
+
for sid in sample_ids:
|
| 169 |
+
j = sid_to_i[sid]
|
| 170 |
+
rows.append([int(counts[g][j]) for g in counts])
|
| 171 |
+
return pd.DataFrame(rows, index=list(sample_ids), columns=list(counts.keys()))
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def build_sample_metadata(
|
| 175 |
+
sample_ids: Sequence[str],
|
| 176 |
+
condition_by_sample: Dict[str, str],
|
| 177 |
+
) -> pd.DataFrame:
|
| 178 |
+
missing = [s for s in sample_ids if s not in condition_by_sample]
|
| 179 |
+
if missing:
|
| 180 |
+
raise ValueError(
|
| 181 |
+
f"sample_metadata missing entries for sample_ids: {missing[:10]}"
|
| 182 |
+
+ (" ..." if len(missing) > 10 else "")
|
| 183 |
+
)
|
| 184 |
+
conds = [condition_by_sample[s] for s in sample_ids]
|
| 185 |
+
return pd.DataFrame({"condition": conds}, index=list(sample_ids))
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def validate_counts_case(case: Dict[str, Any]) -> Optional[str]:
|
| 189 |
+
"""Return an error message if pipeline case JSON is inconsistent, else None."""
|
| 190 |
+
counts = case.get("counts")
|
| 191 |
+
sample_ids = case.get("sample_ids")
|
| 192 |
+
if not isinstance(counts, dict) or not sample_ids:
|
| 193 |
+
return None
|
| 194 |
+
n = len(sample_ids)
|
| 195 |
+
for gene, vals in counts.items():
|
| 196 |
+
if len(vals) != n:
|
| 197 |
+
return (
|
| 198 |
+
f"Gene {gene!r} has {len(vals)} count values but "
|
| 199 |
+
f"sample_ids has length {n}."
|
| 200 |
+
)
|
| 201 |
+
return None
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def load_author_de_table_csv(
|
| 205 |
+
path: str | Path,
|
| 206 |
+
*,
|
| 207 |
+
gene_column: str | None = None,
|
| 208 |
+
log2fc_column: str = "log2FoldChange",
|
| 209 |
+
pvalue_column: str = "pvalue",
|
| 210 |
+
padj_column: str = "padj",
|
| 211 |
+
) -> List[Dict[str, Any]]:
|
| 212 |
+
"""
|
| 213 |
+
Load a precomputed differential expression (DE) table (author-provided).
|
| 214 |
+
|
| 215 |
+
Supports the common GEO supplement format used in GSE227102:
|
| 216 |
+
- semicolon-delimited
|
| 217 |
+
- decimal comma in numeric columns (e.g. ``0,12``) and scientific like ``1,47E-18``
|
| 218 |
+
- gene symbol in a column like ``Gene,name`` and/or an Ensembl ``ID``
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
DE rows in the same schema as ``run_deseq2_contrast`` output, sorted by ascending padj.
|
| 222 |
+
"""
|
| 223 |
+
|
| 224 |
+
p = Path(path)
|
| 225 |
+
if not p.is_file():
|
| 226 |
+
raise ValueError(f"DE table file not found: {p}")
|
| 227 |
+
|
| 228 |
+
df = pd.read_csv(p, sep=";")
|
| 229 |
+
if df.empty:
|
| 230 |
+
raise ValueError(f"DE table is empty: {p}")
|
| 231 |
+
|
| 232 |
+
# Pick gene column.
|
| 233 |
+
if gene_column is None:
|
| 234 |
+
for cand in ("Gene,name", "gene", "symbol", "Gene", "gene_name"):
|
| 235 |
+
if cand in df.columns:
|
| 236 |
+
gene_column = cand
|
| 237 |
+
break
|
| 238 |
+
if gene_column is None or gene_column not in df.columns:
|
| 239 |
+
raise ValueError(
|
| 240 |
+
"Could not infer gene column. Available columns: "
|
| 241 |
+
+ ", ".join(map(str, df.columns.tolist()))
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
# Normalize numeric strings (decimal commas).
|
| 245 |
+
for c in (log2fc_column, pvalue_column, padj_column):
|
| 246 |
+
if c not in df.columns:
|
| 247 |
+
raise ValueError(f"Missing required column {c!r} in DE table: {p}")
|
| 248 |
+
df[c] = df[c].astype(str).str.replace(",", ".", regex=False)
|
| 249 |
+
df[c] = pd.to_numeric(df[c], errors="coerce")
|
| 250 |
+
|
| 251 |
+
df[gene_column] = df[gene_column].astype(str)
|
| 252 |
+
|
| 253 |
+
rows: List[Dict[str, Any]] = []
|
| 254 |
+
for _, r in df.iterrows():
|
| 255 |
+
gene = str(r.get(gene_column, "")).strip()
|
| 256 |
+
if not gene or gene.lower() in ("nan", "none"):
|
| 257 |
+
continue
|
| 258 |
+
padj = float(r.get(padj_column)) if pd.notna(r.get(padj_column)) else 1.0
|
| 259 |
+
rows.append(
|
| 260 |
+
{
|
| 261 |
+
"gene": gene,
|
| 262 |
+
"baseMean": float("nan"), # unknown for author tables; kept for schema compat
|
| 263 |
+
"log2FoldChange": float(r.get(log2fc_column, 0.0))
|
| 264 |
+
if pd.notna(r.get(log2fc_column))
|
| 265 |
+
else 0.0,
|
| 266 |
+
"lfcSE": None,
|
| 267 |
+
"pvalue": float(r.get(pvalue_column, 1.0))
|
| 268 |
+
if pd.notna(r.get(pvalue_column))
|
| 269 |
+
else 1.0,
|
| 270 |
+
"padj": padj,
|
| 271 |
+
"significant": False, # filled by caller using chosen alpha
|
| 272 |
+
}
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
rows.sort(
|
| 276 |
+
key=lambda x: (
|
| 277 |
+
_safe_padj_value(x.get("padj")),
|
| 278 |
+
-abs(float(x.get("log2FoldChange") or 0.0)),
|
| 279 |
+
)
|
| 280 |
+
)
|
| 281 |
+
return rows
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def run_deseq2_contrast(
|
| 285 |
+
counts_df: pd.DataFrame,
|
| 286 |
+
metadata_df: pd.DataFrame,
|
| 287 |
+
alt_level: str,
|
| 288 |
+
ref_level: str,
|
| 289 |
+
*,
|
| 290 |
+
padj_alpha: float = 0.05,
|
| 291 |
+
min_replicates: int = 2,
|
| 292 |
+
) -> Tuple[List[Dict[str, Any]], Optional[str]]:
|
| 293 |
+
"""
|
| 294 |
+
Run PyDESeq2 Wald test for ``alt_level`` vs ``ref_level`` on column ``condition``.
|
| 295 |
+
|
| 296 |
+
Returns:
|
| 297 |
+
(de_rows, error_message). ``de_rows`` are sorted by ascending adjusted p-value.
|
| 298 |
+
"""
|
| 299 |
+
if not _PYDESQ2_AVAILABLE:
|
| 300 |
+
return [], "PyDESeq2 is not installed."
|
| 301 |
+
|
| 302 |
+
levels = set(metadata_df["condition"].tolist())
|
| 303 |
+
if ref_level not in levels or alt_level not in levels:
|
| 304 |
+
return [], (
|
| 305 |
+
f"Contrast invalid: need both reference {ref_level!r} and "
|
| 306 |
+
f"alternate {alt_level!r} in sample metadata; got {sorted(levels)}."
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
try:
|
| 310 |
+
dds = DeseqDataSet(
|
| 311 |
+
counts=counts_df,
|
| 312 |
+
metadata=metadata_df,
|
| 313 |
+
design="~condition",
|
| 314 |
+
refit_cooks=True,
|
| 315 |
+
min_replicates=min_replicates,
|
| 316 |
+
quiet=True,
|
| 317 |
+
)
|
| 318 |
+
buf_out, buf_err = io.StringIO(), io.StringIO()
|
| 319 |
+
with redirect_stdout(buf_out), redirect_stderr(buf_err):
|
| 320 |
+
dds.deseq2()
|
| 321 |
+
stat_res = DeseqStats(dds, contrast=["condition", alt_level, ref_level])
|
| 322 |
+
stat_res.summary()
|
| 323 |
+
res = stat_res.results_df
|
| 324 |
+
except Exception as exc: # pragma: no cover - fitting failures
|
| 325 |
+
return [], f"DESeq2 failed: {exc}"
|
| 326 |
+
|
| 327 |
+
de_rows: List[Dict[str, Any]] = []
|
| 328 |
+
for gene, row in res.iterrows():
|
| 329 |
+
padj = float(row["padj"]) if pd.notna(row["padj"]) else 1.0
|
| 330 |
+
de_rows.append(
|
| 331 |
+
{
|
| 332 |
+
"gene": str(gene),
|
| 333 |
+
"baseMean": float(row.get("baseMean", 0.0)),
|
| 334 |
+
"log2FoldChange": float(row.get("log2FoldChange", 0.0)),
|
| 335 |
+
"lfcSE": float(row.get("lfcSE", 0.0))
|
| 336 |
+
if pd.notna(row.get("lfcSE"))
|
| 337 |
+
else None,
|
| 338 |
+
"pvalue": float(row.get("pvalue", 1.0))
|
| 339 |
+
if pd.notna(row.get("pvalue"))
|
| 340 |
+
else 1.0,
|
| 341 |
+
"padj": padj,
|
| 342 |
+
"significant": padj <= padj_alpha,
|
| 343 |
+
}
|
| 344 |
+
)
|
| 345 |
+
de_rows.sort(key=lambda r: (r["padj"], -abs(r["log2FoldChange"])))
|
| 346 |
+
return de_rows, None
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def benjamini_hochberg(p_values: Sequence[float]) -> List[float]:
|
| 350 |
+
"""Benjamini–Hochberg FDR; returns q-values in original order (fallback)."""
|
| 351 |
+
m = len(p_values)
|
| 352 |
+
if m == 0:
|
| 353 |
+
return []
|
| 354 |
+
p_arr = np.nan_to_num(np.asarray(p_values, dtype=float), nan=1.0)
|
| 355 |
+
order = np.argsort(p_arr)
|
| 356 |
+
sorted_p = p_arr[order]
|
| 357 |
+
adj_sorted = np.empty(m)
|
| 358 |
+
running = 1.0
|
| 359 |
+
for i in range(m - 1, -1, -1):
|
| 360 |
+
running = min(sorted_p[i] * m / (i + 1), running)
|
| 361 |
+
adj_sorted[i] = running
|
| 362 |
+
out = np.empty(m)
|
| 363 |
+
out[order] = adj_sorted
|
| 364 |
+
return np.clip(out, 0.0, 1.0).tolist()
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def adjust_pvalues_bh(p_values: Sequence[float]) -> List[float]:
|
| 368 |
+
"""Benjamini–Hochberg adjusted p-values using SciPy (preferred)."""
|
| 369 |
+
m = len(p_values)
|
| 370 |
+
if m == 0:
|
| 371 |
+
return []
|
| 372 |
+
p_arr = np.clip(
|
| 373 |
+
np.nan_to_num(np.asarray(p_values, dtype=float), nan=1.0), 1e-300, 1.0
|
| 374 |
+
)
|
| 375 |
+
try:
|
| 376 |
+
adj = false_discovery_control(p_arr, method="bh")
|
| 377 |
+
return np.clip(adj, 0.0, 1.0).tolist()
|
| 378 |
+
except Exception:
|
| 379 |
+
return benjamini_hochberg(p_values)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def ora_fisher(
|
| 383 |
+
de_genes: Sequence[str],
|
| 384 |
+
pathway_genes: Dict[str, Sequence[str]],
|
| 385 |
+
universe_genes: Sequence[str],
|
| 386 |
+
*,
|
| 387 |
+
min_pathway_genes: int = 3,
|
| 388 |
+
) -> List[Dict[str, Any]]:
|
| 389 |
+
"""
|
| 390 |
+
Over-representation analysis (one-sided Fisher exact, greater overlap).
|
| 391 |
+
|
| 392 |
+
``universe_genes`` should be the **same gene set** used for DESeq2 (prefiltered).
|
| 393 |
+
|
| 394 |
+
Pathways smaller than ``min_pathway_genes`` in the universe are skipped (reduces
|
| 395 |
+
noise from tiny sets).
|
| 396 |
+
"""
|
| 397 |
+
u: Set[str] = set(universe_genes)
|
| 398 |
+
de: Set[str] = {g for g in de_genes if g in u}
|
| 399 |
+
results: List[Dict[str, Any]] = []
|
| 400 |
+
de_n = len(de)
|
| 401 |
+
|
| 402 |
+
for pname, pgenes in pathway_genes.items():
|
| 403 |
+
pset = {g for g in pgenes if g in u}
|
| 404 |
+
if len(pset) < min_pathway_genes:
|
| 405 |
+
continue
|
| 406 |
+
overlap = sorted(de & pset)
|
| 407 |
+
a = len(overlap)
|
| 408 |
+
b = len(de - pset)
|
| 409 |
+
c = len(pset - de)
|
| 410 |
+
d = len(u) - a - b - c
|
| 411 |
+
if d < 0:
|
| 412 |
+
d = 0
|
| 413 |
+
oddsr, p_raw = fisher_exact([[a, b], [c, d]], alternative="greater")
|
| 414 |
+
p_f = float(p_raw) if math.isfinite(float(p_raw)) else 1.0
|
| 415 |
+
results.append(
|
| 416 |
+
{
|
| 417 |
+
"pathway": pname,
|
| 418 |
+
"p_value": p_f,
|
| 419 |
+
"odds_ratio": float(oddsr) if np.isfinite(oddsr) else None,
|
| 420 |
+
"overlap_genes": overlap,
|
| 421 |
+
"overlap_count": a,
|
| 422 |
+
"pathway_size": len(pset),
|
| 423 |
+
"de_in_universe": de_n,
|
| 424 |
+
"gene_ratio": f"{a}/{len(pset)}",
|
| 425 |
+
}
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
qvals = adjust_pvalues_bh([r["p_value"] for r in results])
|
| 429 |
+
for r, q in zip(results, qvals):
|
| 430 |
+
r["q_value"] = q
|
| 431 |
+
results.sort(key=lambda x: (x["p_value"], -x["overlap_count"]))
|
| 432 |
+
return results
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def enrichr_ora(
|
| 436 |
+
query_genes: Sequence[str],
|
| 437 |
+
*,
|
| 438 |
+
libraries: Sequence[str],
|
| 439 |
+
background: Optional[Sequence[str]] = None,
|
| 440 |
+
top_k: int = 50,
|
| 441 |
+
) -> tuple[List[Dict[str, Any]], Optional[str]]:
|
| 442 |
+
"""
|
| 443 |
+
Enrichr-based ORA using gseapy (requires network for most libraries).
|
| 444 |
+
|
| 445 |
+
Returns:
|
| 446 |
+
(rows, error_message)
|
| 447 |
+
"""
|
| 448 |
+
|
| 449 |
+
if not _GSEAPY_AVAILABLE:
|
| 450 |
+
return [], "gseapy is not installed."
|
| 451 |
+
q = [str(g) for g in query_genes if g]
|
| 452 |
+
if not q:
|
| 453 |
+
return [], "Empty query gene list."
|
| 454 |
+
libs = [str(x) for x in libraries if x]
|
| 455 |
+
if not libs:
|
| 456 |
+
return [], "No Enrichr libraries configured."
|
| 457 |
+
|
| 458 |
+
rows: List[Dict[str, Any]] = []
|
| 459 |
+
try:
|
| 460 |
+
for lib in libs:
|
| 461 |
+
enr = gp.enrichr( # type: ignore[union-attr]
|
| 462 |
+
gene_list=q,
|
| 463 |
+
gene_sets=lib,
|
| 464 |
+
background=list(background) if background is not None else None,
|
| 465 |
+
outdir=None,
|
| 466 |
+
no_plot=True,
|
| 467 |
+
)
|
| 468 |
+
res = getattr(enr, "results", None)
|
| 469 |
+
if res is None or res.empty:
|
| 470 |
+
continue
|
| 471 |
+
for _, r in res.head(top_k).iterrows():
|
| 472 |
+
genes = []
|
| 473 |
+
raw = r.get("Genes")
|
| 474 |
+
if isinstance(raw, str):
|
| 475 |
+
genes = [g.strip() for g in raw.replace(";", ",").split(",") if g.strip()]
|
| 476 |
+
rows.append(
|
| 477 |
+
{
|
| 478 |
+
"pathway": f"{lib}: {r.get('Term')}",
|
| 479 |
+
"p_value": float(r.get("P-value", 1.0)),
|
| 480 |
+
"q_value": float(r.get("Adjusted P-value", 1.0)),
|
| 481 |
+
"odds_ratio": float(r.get("Odds Ratio"))
|
| 482 |
+
if pd.notna(r.get("Odds Ratio"))
|
| 483 |
+
else None,
|
| 484 |
+
"overlap_genes": genes,
|
| 485 |
+
"overlap_count": int(r.get("Overlap", "0/0").split("/")[0])
|
| 486 |
+
if isinstance(r.get("Overlap"), str)
|
| 487 |
+
else None,
|
| 488 |
+
"pathway_size": int(r.get("Overlap", "0/0").split("/")[1])
|
| 489 |
+
if isinstance(r.get("Overlap"), str)
|
| 490 |
+
else None,
|
| 491 |
+
}
|
| 492 |
+
)
|
| 493 |
+
except Exception as exc: # pragma: no cover
|
| 494 |
+
return [], f"Enrichr failed: {exc}"
|
| 495 |
+
|
| 496 |
+
rows.sort(key=lambda x: (x.get("q_value", 1.0), x.get("p_value", 1.0)))
|
| 497 |
+
return rows, None
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def _safe_padj_value(v: Any) -> float:
|
| 501 |
+
try:
|
| 502 |
+
x = float(v)
|
| 503 |
+
except (TypeError, ValueError):
|
| 504 |
+
return 1.0
|
| 505 |
+
return 1.0 if math.isnan(x) else x
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def pick_de_query_genes(
|
| 509 |
+
de_rows: Sequence[Dict[str, Any]],
|
| 510 |
+
*,
|
| 511 |
+
padj_alpha: float = 0.05,
|
| 512 |
+
max_genes: int = 200,
|
| 513 |
+
direction: str = "both",
|
| 514 |
+
min_abs_log2fc: float = 0.0,
|
| 515 |
+
) -> List[str]:
|
| 516 |
+
"""
|
| 517 |
+
Genes for ORA query: significant by ``padj`` and optional **direction** (activation).
|
| 518 |
+
|
| 519 |
+
``direction``: ``\"up\"`` (alt > ref), ``\"down\"`` (alt < ref), or ``\"both\"``.
|
| 520 |
+
"""
|
| 521 |
+
dir_norm = direction.lower().strip()
|
| 522 |
+
if dir_norm not in ("up", "down", "both"):
|
| 523 |
+
dir_norm = "both"
|
| 524 |
+
|
| 525 |
+
def lfc_ok(r: Dict[str, Any]) -> bool:
|
| 526 |
+
try:
|
| 527 |
+
lfc = float(r.get("log2FoldChange", 0.0))
|
| 528 |
+
except (TypeError, ValueError):
|
| 529 |
+
return False
|
| 530 |
+
if math.isnan(lfc):
|
| 531 |
+
return False
|
| 532 |
+
if dir_norm == "both":
|
| 533 |
+
return abs(lfc) >= min_abs_log2fc
|
| 534 |
+
if dir_norm == "up":
|
| 535 |
+
return lfc >= min_abs_log2fc
|
| 536 |
+
return lfc <= -min_abs_log2fc
|
| 537 |
+
|
| 538 |
+
sig: List[str] = []
|
| 539 |
+
for r in de_rows:
|
| 540 |
+
if _safe_padj_value(r.get("padj", 1.0)) > padj_alpha:
|
| 541 |
+
continue
|
| 542 |
+
if not lfc_ok(r):
|
| 543 |
+
continue
|
| 544 |
+
sig.append(r["gene"])
|
| 545 |
+
|
| 546 |
+
if not sig:
|
| 547 |
+
for r in de_rows[:max_genes]:
|
| 548 |
+
if lfc_ok(r):
|
| 549 |
+
sig.append(r["gene"])
|
| 550 |
+
if not sig:
|
| 551 |
+
sig = [r["gene"] for r in de_rows[:max_genes]]
|
| 552 |
+
return sig[:max_genes]
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def compare_pathways_detail(
|
| 556 |
+
pathway_a: str,
|
| 557 |
+
pathway_b: str,
|
| 558 |
+
pathway_genes: Dict[str, Sequence[str]],
|
| 559 |
+
de_genes: Sequence[str],
|
| 560 |
+
) -> Dict[str, Any]:
|
| 561 |
+
"""Exclusive vs shared DE support between two pathways."""
|
| 562 |
+
pa = set(pathway_genes.get(pathway_a, []))
|
| 563 |
+
pb = set(pathway_genes.get(pathway_b, []))
|
| 564 |
+
de = set(de_genes)
|
| 565 |
+
only_a = sorted((pa - pb) & de)
|
| 566 |
+
only_b = sorted((pb - pa) & de)
|
| 567 |
+
shared = sorted((pa & pb) & de)
|
| 568 |
+
return {
|
| 569 |
+
"pathway_a": pathway_a,
|
| 570 |
+
"pathway_b": pathway_b,
|
| 571 |
+
"exclusive_to_a": only_a,
|
| 572 |
+
"exclusive_to_b": only_b,
|
| 573 |
+
"shared_de_support": shared,
|
| 574 |
+
"pathway_a_size": len(pa),
|
| 575 |
+
"pathway_b_size": len(pb),
|
| 576 |
+
"overlap_pathway_genes": sorted(pa & pb),
|
| 577 |
+
}
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def overlap_genes_across_top_pathways(
|
| 581 |
+
ora_rows: Sequence[Dict[str, Any]],
|
| 582 |
+
top_k: int = 5,
|
| 583 |
+
) -> Dict[str, Any]:
|
| 584 |
+
"""DE genes that appear in more than one of the top-k pathways by p-value."""
|
| 585 |
+
top = [r for r in ora_rows[:top_k] if r.get("overlap_genes")]
|
| 586 |
+
gene_to_paths: Dict[str, List[str]] = {}
|
| 587 |
+
for row in top:
|
| 588 |
+
p = row["pathway"]
|
| 589 |
+
for g in row.get("overlap_genes", []):
|
| 590 |
+
gene_to_paths.setdefault(g, []).append(p)
|
| 591 |
+
multi = {g: paths for g, paths in gene_to_paths.items() if len(paths) > 1}
|
| 592 |
+
return {
|
| 593 |
+
"genes_supporting_multiple_top_pathways": sorted(multi.keys()),
|
| 594 |
+
"gene_to_pathways": {g: multi[g] for g in sorted(multi)},
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def top_hits_statistically_close(
|
| 599 |
+
ora_rows: Sequence[Dict[str, Any]],
|
| 600 |
+
*,
|
| 601 |
+
ratio_threshold: float = 10.0,
|
| 602 |
+
top_k: int = 3,
|
| 603 |
+
) -> Dict[str, Any]:
|
| 604 |
+
"""Flag when the top two enriched pathways have similar p-values (ratio bound)."""
|
| 605 |
+
if len(ora_rows) < 2:
|
| 606 |
+
return {
|
| 607 |
+
"close_top_hits": False,
|
| 608 |
+
"p_ratio": None,
|
| 609 |
+
"note": "fewer than 2 pathways",
|
| 610 |
+
}
|
| 611 |
+
p1 = ora_rows[0]["p_value"]
|
| 612 |
+
p2 = ora_rows[1]["p_value"]
|
| 613 |
+
if p1 <= 0 or p2 <= 0:
|
| 614 |
+
ratio = None
|
| 615 |
+
close = False
|
| 616 |
+
else:
|
| 617 |
+
ratio = max(p1, p2) / min(p1, p2)
|
| 618 |
+
close = ratio <= ratio_threshold
|
| 619 |
+
return {
|
| 620 |
+
"close_top_hits": close,
|
| 621 |
+
"p_ratio": ratio,
|
| 622 |
+
"p_top1": p1,
|
| 623 |
+
"p_top2": p2,
|
| 624 |
+
}
|
envs/pathway_analysis_env/server/app.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""FastAPI application for the Pathway Analysis Environment."""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import inspect
|
| 12 |
+
import logging
|
| 13 |
+
import os
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from typing import Any, Dict, Optional
|
| 16 |
+
|
| 17 |
+
# Pathway lab is meant to be used at /web; OpenEnv defaults web off unless set.
|
| 18 |
+
if "ENABLE_WEB_INTERFACE" not in os.environ:
|
| 19 |
+
os.environ["ENABLE_WEB_INTERFACE"] = "true"
|
| 20 |
+
|
| 21 |
+
# Some dependencies (e.g. gseapy) import matplotlib, which tries to write a font/cache
|
| 22 |
+
# directory under the user's home. In sandboxed / CI contexts this can be unwritable.
|
| 23 |
+
if "MPLCONFIGDIR" not in os.environ:
|
| 24 |
+
cache_dir = Path(__file__).resolve().parent.parent / "outputs" / ".mplcache"
|
| 25 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 26 |
+
os.environ["MPLCONFIGDIR"] = str(cache_dir)
|
| 27 |
+
|
| 28 |
+
from openenv.core.env_server.http_server import create_app
|
| 29 |
+
|
| 30 |
+
from ..models import PathwayAction, PathwayObservation
|
| 31 |
+
from .gradio_ui import build_pathway_gradio_app
|
| 32 |
+
from .pathway_environment import PathwayEnvironment
|
| 33 |
+
|
| 34 |
+
_logger = logging.getLogger(__name__)
|
| 35 |
+
|
| 36 |
+
# Populated when the Gradio / web UI is built (single shared env instance).
|
| 37 |
+
_WEB_MANAGER: Dict[str, Any] = {}
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _pathway_env_factory() -> PathwayEnvironment:
|
| 41 |
+
return PathwayEnvironment()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _gradio_builder_with_manager(web_manager, *args, **kwargs):
|
| 45 |
+
_WEB_MANAGER["manager"] = web_manager
|
| 46 |
+
return build_pathway_gradio_app(web_manager, *args, **kwargs)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
_sig = inspect.signature(create_app)
|
| 50 |
+
_kw: dict = {
|
| 51 |
+
"env": _pathway_env_factory,
|
| 52 |
+
"action_cls": PathwayAction,
|
| 53 |
+
"observation_cls": PathwayObservation,
|
| 54 |
+
"env_name": "pathway_analysis_env",
|
| 55 |
+
}
|
| 56 |
+
if "gradio_builder" in _sig.parameters:
|
| 57 |
+
_kw["gradio_builder"] = _gradio_builder_with_manager
|
| 58 |
+
else:
|
| 59 |
+
_logger.warning(
|
| 60 |
+
"openenv-core does not support gradio_builder; Pathway lab tab will be unavailable."
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
app = create_app(**_kw)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _active_pathway_env() -> Optional[PathwayEnvironment]:
|
| 67 |
+
mgr = _WEB_MANAGER.get("manager")
|
| 68 |
+
if mgr is None:
|
| 69 |
+
return None
|
| 70 |
+
env = getattr(mgr, "env", None)
|
| 71 |
+
return env if isinstance(env, PathwayEnvironment) else None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@app.get(
|
| 75 |
+
"/orchestrator/episode_outcome",
|
| 76 |
+
tags=["Orchestrator"],
|
| 77 |
+
summary="Episode score (orchestrator only)",
|
| 78 |
+
)
|
| 79 |
+
async def orchestrator_episode_outcome() -> Dict[str, Any]:
|
| 80 |
+
"""
|
| 81 |
+
Return ``episode_outcome`` for the active web-session environment.
|
| 82 |
+
|
| 83 |
+
Not for untrusted agents — use after ``submit_answer`` when running benchmarks
|
| 84 |
+
against the local server. Returns ``{}`` if no episode has been scored yet.
|
| 85 |
+
"""
|
| 86 |
+
env = _active_pathway_env()
|
| 87 |
+
if env is None:
|
| 88 |
+
return {"error": "web_interface_not_initialized"}
|
| 89 |
+
return dict(env.episode_outcome or {})
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@app.get(
|
| 93 |
+
"/orchestrator/eval_protocol",
|
| 94 |
+
tags=["Orchestrator"],
|
| 95 |
+
summary="Eval protocol summary",
|
| 96 |
+
)
|
| 97 |
+
async def orchestrator_eval_protocol() -> Dict[str, Any]:
|
| 98 |
+
"""Describe eval-mode guarantees for the active environment instance."""
|
| 99 |
+
env = _active_pathway_env()
|
| 100 |
+
if env is None:
|
| 101 |
+
return {"error": "web_interface_not_initialized"}
|
| 102 |
+
st = env.state
|
| 103 |
+
return {
|
| 104 |
+
"eval_mode": st.eval_mode,
|
| 105 |
+
"max_steps": st.max_steps,
|
| 106 |
+
"pipeline_mode": st.pipeline_mode,
|
| 107 |
+
"legacy_mode": st.legacy_mode,
|
| 108 |
+
"de_run": st.de_run,
|
| 109 |
+
"enrichment_run": st.enrichment_run,
|
| 110 |
+
"step_count": st.step_count,
|
| 111 |
+
"required_workflow": [
|
| 112 |
+
"understand_experiment_design or inspect_dataset",
|
| 113 |
+
"run_differential_expression",
|
| 114 |
+
"run_pathway_enrichment",
|
| 115 |
+
"submit_answer",
|
| 116 |
+
],
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def main():
|
| 121 |
+
"""Entry point for ``uv run --project . server``."""
|
| 122 |
+
import uvicorn
|
| 123 |
+
|
| 124 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
if __name__ == "__main__":
|
| 128 |
+
main()
|
envs/pathway_analysis_env/server/case_loader.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Load pathway cases with optional separation of agent-visible vs orchestrator secrets."""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
from copy import deepcopy
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Any, Dict, List, Tuple
|
| 15 |
+
|
| 16 |
+
# Keys that must not ship to untrusted agent runtimes (orchestrator keeps full case).
|
| 17 |
+
CASE_SECRET_KEYS = frozenset(
|
| 18 |
+
{
|
| 19 |
+
"true_pathway",
|
| 20 |
+
"true_pathway_aliases",
|
| 21 |
+
"expected_keywords",
|
| 22 |
+
"expert_hint",
|
| 23 |
+
"expert_penalty",
|
| 24 |
+
"expert_budget",
|
| 25 |
+
}
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def strip_case_secrets(case: Dict[str, Any]) -> Dict[str, Any]:
|
| 30 |
+
"""Return a copy of ``case`` without orchestrator-only fields."""
|
| 31 |
+
out = deepcopy(case)
|
| 32 |
+
for key in CASE_SECRET_KEYS:
|
| 33 |
+
out.pop(key, None)
|
| 34 |
+
return out
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def extract_case_secrets(case: Dict[str, Any]) -> Dict[str, Any]:
|
| 38 |
+
return {
|
| 39 |
+
"true_pathway": str(case.get("true_pathway", "")),
|
| 40 |
+
"true_pathway_aliases": list(case.get("true_pathway_aliases") or []),
|
| 41 |
+
"expected_keywords": list(case.get("expected_keywords") or []),
|
| 42 |
+
"expert_hint": case.get("expert_hint"),
|
| 43 |
+
"expert_budget": case.get("expert_budget"),
|
| 44 |
+
"expert_penalty": case.get("expert_penalty"),
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_case_file(
|
| 49 |
+
data_dir: Path,
|
| 50 |
+
case_name: str,
|
| 51 |
+
*,
|
| 52 |
+
agent_safe: bool = False,
|
| 53 |
+
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
| 54 |
+
"""
|
| 55 |
+
Load case JSON from ``data_dir``.
|
| 56 |
+
|
| 57 |
+
Returns ``(case_dict, secrets)``. When ``agent_safe`` is True, ``case_dict`` has
|
| 58 |
+
secret keys removed (for agent containers); secrets are still returned for the server.
|
| 59 |
+
"""
|
| 60 |
+
path = data_dir / case_name
|
| 61 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 62 |
+
raw: Dict[str, Any] = json.load(f)
|
| 63 |
+
secrets = extract_case_secrets(raw)
|
| 64 |
+
if agent_safe:
|
| 65 |
+
return strip_case_secrets(raw), secrets
|
| 66 |
+
return raw, secrets
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def export_agent_safe_case(
|
| 70 |
+
source: Path,
|
| 71 |
+
destination: Path,
|
| 72 |
+
) -> None:
|
| 73 |
+
"""Write an agent-safe case JSON (no ground-truth fields)."""
|
| 74 |
+
with open(source, "r", encoding="utf-8") as f:
|
| 75 |
+
raw = json.load(f)
|
| 76 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 77 |
+
with open(destination, "w", encoding="utf-8") as f:
|
| 78 |
+
json.dump(strip_case_secrets(raw), f, indent=2)
|
| 79 |
+
f.write("\n")
|
envs/pathway_analysis_env/server/eval_protocol.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Agent-safe evaluation protocol helpers for pathway_analysis_env."""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from copy import deepcopy
|
| 12 |
+
from typing import Any, Dict, List, Optional
|
| 13 |
+
|
| 14 |
+
from ..models import PathwayObservation
|
| 15 |
+
|
| 16 |
+
# Keys never sent to agents when eval_mode is on.
|
| 17 |
+
_AGENT_METADATA_BLOCKLIST = frozenset(
|
| 18 |
+
{
|
| 19 |
+
"correct",
|
| 20 |
+
"static_top_genes",
|
| 21 |
+
"static_top_pathways",
|
| 22 |
+
"true_pathway",
|
| 23 |
+
"ground_truth",
|
| 24 |
+
"episode_score",
|
| 25 |
+
}
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def default_max_steps(case: Dict[str, Any]) -> int:
|
| 30 |
+
return max(5, int(case.get("max_steps", 30)))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def resolve_eval_mode(case: Dict[str, Any], reset_kwargs: Dict[str, Any]) -> bool:
|
| 34 |
+
"""Eval mode is on unless reset(eval_mode=False) or case sets eval_mode: false."""
|
| 35 |
+
if "eval_mode" in reset_kwargs:
|
| 36 |
+
return bool(reset_kwargs["eval_mode"])
|
| 37 |
+
return bool(case.get("eval_mode", True))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def resolve_orchestrator_mode(case: Dict[str, Any], reset_kwargs: Dict[str, Any]) -> bool:
|
| 41 |
+
"""Expose scoring details in metadata (for in-repo harnesses only)."""
|
| 42 |
+
if "orchestrator_mode" in reset_kwargs:
|
| 43 |
+
return bool(reset_kwargs["orchestrator_mode"])
|
| 44 |
+
return bool(case.get("orchestrator_mode", False))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def shaping_reward(eval_mode: bool, nominal: float) -> float:
|
| 48 |
+
"""Zero intermediate shaping in eval mode; terminal scoring is separate."""
|
| 49 |
+
if eval_mode:
|
| 50 |
+
return 0.0
|
| 51 |
+
return nominal
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def sanitize_metadata_for_agent(
|
| 55 |
+
metadata: Optional[Dict[str, Any]], *, eval_mode: bool
|
| 56 |
+
) -> Dict[str, Any]:
|
| 57 |
+
if not metadata:
|
| 58 |
+
return {}
|
| 59 |
+
if not eval_mode:
|
| 60 |
+
return dict(metadata)
|
| 61 |
+
out = {k: v for k, v in metadata.items() if k not in _AGENT_METADATA_BLOCKLIST}
|
| 62 |
+
return out
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def sanitize_observation_for_agent(
|
| 66 |
+
obs: PathwayObservation,
|
| 67 |
+
*,
|
| 68 |
+
eval_mode: bool,
|
| 69 |
+
orchestrator_mode: bool,
|
| 70 |
+
reward_override: Optional[float] = None,
|
| 71 |
+
) -> PathwayObservation:
|
| 72 |
+
if not eval_mode:
|
| 73 |
+
return obs
|
| 74 |
+
meta = sanitize_metadata_for_agent(obs.metadata, eval_mode=True)
|
| 75 |
+
if orchestrator_mode and obs.metadata and "correct" in obs.metadata:
|
| 76 |
+
meta["correct"] = obs.metadata["correct"]
|
| 77 |
+
if orchestrator_mode and obs.metadata and "episode_score" in obs.metadata:
|
| 78 |
+
meta["episode_score"] = obs.metadata["episode_score"]
|
| 79 |
+
reward = obs.reward if reward_override is None else reward_override
|
| 80 |
+
if eval_mode and not orchestrator_mode:
|
| 81 |
+
# Hide reward signal except strict terminal failures (negative).
|
| 82 |
+
if obs.done and reward and reward > 0:
|
| 83 |
+
reward = 0.0
|
| 84 |
+
elif not obs.done:
|
| 85 |
+
reward = 0.0
|
| 86 |
+
return obs.model_copy(
|
| 87 |
+
update={
|
| 88 |
+
"metadata": meta,
|
| 89 |
+
"reward": reward,
|
| 90 |
+
}
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def strip_legacy_answer_leaks(
|
| 95 |
+
inspect_meta: Dict[str, Any], *, eval_mode: bool
|
| 96 |
+
) -> Dict[str, Any]:
|
| 97 |
+
if not eval_mode:
|
| 98 |
+
return inspect_meta
|
| 99 |
+
out = dict(inspect_meta)
|
| 100 |
+
out.pop("static_top_genes", None)
|
| 101 |
+
out.pop("static_top_pathways", None)
|
| 102 |
+
return out
|
envs/pathway_analysis_env/server/failure_codes.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Stable ``failure_code`` strings for observation metadata (pathway_analysis_env v1)."""
|
| 8 |
+
|
| 9 |
+
# Session / episode
|
| 10 |
+
EPISODE_ALREADY_DONE = "episode_already_done"
|
| 11 |
+
UNKNOWN_ACTION_TYPE = "unknown_action_type"
|
| 12 |
+
MAX_STEPS_EXCEEDED = "max_steps_exceeded"
|
| 13 |
+
|
| 14 |
+
# eval protocol
|
| 15 |
+
SUBMIT_PREREQUISITE_DE = "submit_prerequisite_de"
|
| 16 |
+
SUBMIT_PREREQUISITE_ORA = "submit_prerequisite_ora"
|
| 17 |
+
ORA_GENE_LIST_BLOCKED = "ora_gene_list_blocked"
|
| 18 |
+
COMPARE_REQUIRES_ORA = "compare_requires_ora"
|
| 19 |
+
SUBMIT_EMPTY_HYPOTHESIS = "submit_empty_hypothesis"
|
| 20 |
+
|
| 21 |
+
# understand_experiment_design
|
| 22 |
+
DESIGN_PARTIAL_CONTRAST = "design_partial_contrast"
|
| 23 |
+
DESIGN_INVALID_CONTRAST_NAMES = "design_invalid_contrast_names"
|
| 24 |
+
DESIGN_INSUFFICIENT_SAMPLES_PER_ARM = "design_insufficient_samples_per_arm"
|
| 25 |
+
|
| 26 |
+
# run_differential_expression
|
| 27 |
+
DE_MISSING_CONTRAST = "de_missing_contrast"
|
| 28 |
+
DE_PYDESeq2_UNAVAILABLE = "de_pydeseq2_unavailable"
|
| 29 |
+
DE_DESEQ2_FAILED = "de_deseq2_failed"
|
| 30 |
+
DE_INVALID_COUNTS_MATRIX = "de_invalid_counts_matrix"
|
| 31 |
+
DE_TOO_FEW_GENES_AFTER_FILTER = "de_too_few_genes_after_filter"
|
| 32 |
+
CASE_SAMPLE_METADATA_MISMATCH = "case_sample_metadata_mismatch"
|
| 33 |
+
|
| 34 |
+
# run_pathway_enrichment
|
| 35 |
+
ORA_DE_PREREQUISITE = "ora_de_prerequisite"
|
| 36 |
+
ORA_NO_PATHWAY_DEFINITIONS = "ora_no_pathway_definitions"
|
| 37 |
+
|
| 38 |
+
# compare_pathways
|
| 39 |
+
COMPARE_MISSING_PATHWAY_NAMES = "compare_missing_pathway_names"
|
| 40 |
+
|
| 41 |
+
# ask_expert
|
| 42 |
+
EXPERT_DISABLED = "expert_disabled"
|
| 43 |
+
EXPERT_BUDGET_EXHAUSTED = "expert_budget_exhausted"
|
| 44 |
+
|
| 45 |
+
# submit (analytics)
|
| 46 |
+
SUBMIT_INCORRECT_HYPOTHESIS = "submit_incorrect_hypothesis"
|
| 47 |
+
|
| 48 |
+
# strict mode umbrella (specific code still preferred when set)
|
| 49 |
+
STRICT_TERMINATION = "strict_termination"
|
envs/pathway_analysis_env/server/gradio_ui.py
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Gradio **Pathway lab** tab: case selection, guided RNA-seq / ORA workflow, tables.
|
| 9 |
+
|
| 10 |
+
Mount when ``ENABLE_WEB_INTERFACE=true`` and ``create_app(..., gradio_builder=...)``.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 18 |
+
|
| 19 |
+
import gradio as gr
|
| 20 |
+
import pandas as pd
|
| 21 |
+
from openenv.core.env_server.types import EnvironmentMetadata
|
| 22 |
+
|
| 23 |
+
_DATA_DIR = Path(__file__).resolve().parent.parent / "data"
|
| 24 |
+
_OUTPUTS_DIR = Path(__file__).resolve().parent.parent / "outputs"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _list_case_files() -> List[str]:
|
| 28 |
+
if not _DATA_DIR.is_dir():
|
| 29 |
+
return ["toy_case_001.json"]
|
| 30 |
+
names = sorted(p.name for p in _DATA_DIR.glob("*.json"))
|
| 31 |
+
return names if names else ["toy_case_001.json"]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _list_saved_runs() -> List[str]:
|
| 35 |
+
"""Folders under outputs/ that contain summary.json."""
|
| 36 |
+
if not _OUTPUTS_DIR.is_dir():
|
| 37 |
+
return []
|
| 38 |
+
runs = []
|
| 39 |
+
for p in sorted(_OUTPUTS_DIR.iterdir()):
|
| 40 |
+
if not p.is_dir():
|
| 41 |
+
continue
|
| 42 |
+
if (p / "summary.json").is_file():
|
| 43 |
+
runs.append(p.name)
|
| 44 |
+
return runs
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _load_saved_run(run_name: str) -> Dict[str, Any]:
|
| 48 |
+
base = _OUTPUTS_DIR / run_name
|
| 49 |
+
out: Dict[str, Any] = {"run": run_name}
|
| 50 |
+
try:
|
| 51 |
+
out["summary"] = json.loads((base / "summary.json").read_text(encoding="utf-8"))
|
| 52 |
+
except Exception as e:
|
| 53 |
+
out["summary_error"] = str(e)
|
| 54 |
+
out["summary"] = {}
|
| 55 |
+
try:
|
| 56 |
+
out["de"] = json.loads((base / "de_top200.json").read_text(encoding="utf-8"))
|
| 57 |
+
except Exception as e:
|
| 58 |
+
out["de_error"] = str(e)
|
| 59 |
+
out["de"] = []
|
| 60 |
+
try:
|
| 61 |
+
out["enrichment"] = json.loads(
|
| 62 |
+
(base / "enrichment_top50.json").read_text(encoding="utf-8")
|
| 63 |
+
)
|
| 64 |
+
except Exception as e:
|
| 65 |
+
out["enrichment_error"] = str(e)
|
| 66 |
+
out["enrichment"] = []
|
| 67 |
+
return out
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _saved_run_to_tables(run: Dict[str, Any]) -> Tuple[str, pd.DataFrame, pd.DataFrame]:
|
| 71 |
+
s = run.get("summary") or {}
|
| 72 |
+
md_lines = [
|
| 73 |
+
f"**Run:** `{run.get('run','')}`",
|
| 74 |
+
f"**Case:** `{s.get('case_id','')}`",
|
| 75 |
+
f"**Contrast:** `{s.get('contrast')}`",
|
| 76 |
+
f"**Genes:** in matrix `{s.get('genes_in_matrix')}` → after prefilter `{s.get('genes_after_prefilter')}`",
|
| 77 |
+
f"**Trace:** `{s.get('trace_path','')}`",
|
| 78 |
+
]
|
| 79 |
+
md = "\n\n".join(md_lines)
|
| 80 |
+
|
| 81 |
+
de = run.get("de") or []
|
| 82 |
+
df_de = pd.DataFrame(de) if isinstance(de, list) and de else pd.DataFrame({"info": ["No DE export found."]})
|
| 83 |
+
|
| 84 |
+
enr = run.get("enrichment") or []
|
| 85 |
+
if isinstance(enr, list) and enr:
|
| 86 |
+
df_enr = pd.DataFrame(
|
| 87 |
+
[
|
| 88 |
+
{
|
| 89 |
+
"pathway": r.get("pathway"),
|
| 90 |
+
"p_value": r.get("p_value"),
|
| 91 |
+
"q_value": r.get("q_value"),
|
| 92 |
+
"odds_ratio": r.get("odds_ratio"),
|
| 93 |
+
"overlap_genes": ", ".join((r.get("overlap_genes") or [])[:40]),
|
| 94 |
+
}
|
| 95 |
+
for r in enr
|
| 96 |
+
if isinstance(r, dict)
|
| 97 |
+
]
|
| 98 |
+
)
|
| 99 |
+
else:
|
| 100 |
+
df_enr = pd.DataFrame({"info": ["No enrichment export found."]})
|
| 101 |
+
|
| 102 |
+
return md, df_de, df_enr
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _pathway_comparison_df(obs: Dict[str, Any]) -> pd.DataFrame:
|
| 106 |
+
pc = obs.get("pathway_comparison")
|
| 107 |
+
if not isinstance(pc, dict) or not pc:
|
| 108 |
+
return pd.DataFrame(
|
| 109 |
+
{
|
| 110 |
+
"": [
|
| 111 |
+
"Run **Compare pathways** with two pathway names to see exclusive vs shared DE support."
|
| 112 |
+
]
|
| 113 |
+
}
|
| 114 |
+
)
|
| 115 |
+
a = pc.get("pathway_a", "")
|
| 116 |
+
b = pc.get("pathway_b", "")
|
| 117 |
+
rows = [
|
| 118 |
+
{
|
| 119 |
+
"pathway": f"A only ({a})",
|
| 120 |
+
"count": len(pc.get("exclusive_to_a") or []),
|
| 121 |
+
"genes (preview)": ", ".join((pc.get("exclusive_to_a") or [])[:40]),
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"pathway": f"B only ({b})",
|
| 125 |
+
"count": len(pc.get("exclusive_to_b") or []),
|
| 126 |
+
"genes (preview)": ", ".join((pc.get("exclusive_to_b") or [])[:40]),
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"pathway": "Shared DE support",
|
| 130 |
+
"count": len(pc.get("shared_de_support") or []),
|
| 131 |
+
"genes (preview)": ", ".join((pc.get("shared_de_support") or [])[:40]),
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"pathway": "Pathway gene-set sizes",
|
| 135 |
+
"count": pc.get("pathway_a_size", 0) + pc.get("pathway_b_size", 0),
|
| 136 |
+
"genes (preview)": f"A size={pc.get('pathway_a_size')} · B size={pc.get('pathway_b_size')}",
|
| 137 |
+
},
|
| 138 |
+
]
|
| 139 |
+
return pd.DataFrame(rows)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _state_markdown(
|
| 143 |
+
st: Dict[str, Any], episode_outcome: Optional[Dict[str, Any]] = None
|
| 144 |
+
) -> str:
|
| 145 |
+
"""Episode banner from ``WebInterfaceManager.get_state()`` (PathwayState fields)."""
|
| 146 |
+
if not st:
|
| 147 |
+
return "*No state yet — reset an episode.*"
|
| 148 |
+
eid = str(st.get("episode_id") or "")
|
| 149 |
+
eid_short = f"`{eid[:10]}…`" if len(eid) > 10 else f"`{eid}`"
|
| 150 |
+
pipe = "counts + PyDESeq2" if st.get("pipeline_mode") else "legacy lists"
|
| 151 |
+
strict = "strict" if st.get("strict_mode") else "lenient"
|
| 152 |
+
de_ok = "✓" if st.get("de_run") else "○"
|
| 153 |
+
ora_ok = "✓" if st.get("enrichment_run") else "○"
|
| 154 |
+
done = "**Episode ended.** Reset to start over." if st.get("is_done") else ""
|
| 155 |
+
score_line = ""
|
| 156 |
+
if st.get("is_done") and episode_outcome:
|
| 157 |
+
score_line = (
|
| 158 |
+
f"\n\n**Episode score:** correct={episode_outcome.get('correct')} "
|
| 159 |
+
f"· mode={episode_outcome.get('match_mode')} "
|
| 160 |
+
f"· score={episode_outcome.get('score')}"
|
| 161 |
+
)
|
| 162 |
+
conds = st.get("conditions") or []
|
| 163 |
+
cond_line = ", ".join(f"`{c}`" for c in conds[:12]) if conds else "—"
|
| 164 |
+
vref = st.get("validated_reference")
|
| 165 |
+
valt = st.get("validated_alternate")
|
| 166 |
+
val_line = ""
|
| 167 |
+
if vref and valt:
|
| 168 |
+
val_line = f"\n\n**Validated contrast (for DE if fields empty):** `{vref}` → `{valt}`"
|
| 169 |
+
des = "✓" if st.get("design_understood") else "○"
|
| 170 |
+
eval_on = st.get("eval_mode", True)
|
| 171 |
+
max_s = st.get("max_steps", 30)
|
| 172 |
+
return (
|
| 173 |
+
f"**Episode** {eid_short} · step **{st.get('step_count', 0)}** / {max_s} · {pipe} · {strict}"
|
| 174 |
+
f" · eval **{'on' if eval_on else 'off'}**\n\n"
|
| 175 |
+
f"**Conditions in case:** {cond_line}\n\n"
|
| 176 |
+
f"**Pipeline:** Design {des} · DE {de_ok} · ORA {ora_ok}"
|
| 177 |
+
f"{val_line}\n\n"
|
| 178 |
+
f"{done}{score_line}"
|
| 179 |
+
).strip()
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _observation_to_tables(
|
| 183 |
+
data: Dict[str, Any],
|
| 184 |
+
) -> Tuple[str, pd.DataFrame, pd.DataFrame, pd.DataFrame, str, str, str]:
|
| 185 |
+
"""Markdown summary, DE df, ORA df, compare df, overlap/ambiguity, trace, raw JSON."""
|
| 186 |
+
obs = data.get("observation") or {}
|
| 187 |
+
if not isinstance(obs, dict):
|
| 188 |
+
obs = {}
|
| 189 |
+
|
| 190 |
+
msg = obs.get("message", "") or ""
|
| 191 |
+
reward = obs.get("reward")
|
| 192 |
+
done = obs.get("done")
|
| 193 |
+
lines = [
|
| 194 |
+
f"**Message:** {msg}",
|
| 195 |
+
f"**Reward:** `{reward}` · **Done:** `{done}`",
|
| 196 |
+
]
|
| 197 |
+
ac = obs.get("available_conditions") or []
|
| 198 |
+
if ac:
|
| 199 |
+
lines.append("**Conditions (from last step):** " + ", ".join(f"`{c}`" for c in ac[:20]))
|
| 200 |
+
|
| 201 |
+
ed = obs.get("experiment_design")
|
| 202 |
+
if isinstance(ed, dict) and ed:
|
| 203 |
+
lines.append(
|
| 204 |
+
"**Experiment design (structured):**\n```json\n"
|
| 205 |
+
+ json.dumps(ed, indent=2, default=str)[:8000]
|
| 206 |
+
+ "\n```"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
md = "\n\n".join(lines)
|
| 210 |
+
|
| 211 |
+
de_rows = obs.get("de_genes") or []
|
| 212 |
+
if de_rows and isinstance(de_rows, list):
|
| 213 |
+
df_de = pd.DataFrame(de_rows[:200])
|
| 214 |
+
else:
|
| 215 |
+
top = obs.get("top_genes") or []
|
| 216 |
+
if top:
|
| 217 |
+
df_de = pd.DataFrame({"gene": top})
|
| 218 |
+
else:
|
| 219 |
+
df_de = pd.DataFrame(
|
| 220 |
+
{"info": ["No DE table yet — run differential expression."]}
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
pe = obs.get("pathway_enrichment") or []
|
| 224 |
+
if pe and isinstance(pe, list):
|
| 225 |
+
rows_flat = []
|
| 226 |
+
for r in pe[:80]:
|
| 227 |
+
if not isinstance(r, dict):
|
| 228 |
+
continue
|
| 229 |
+
rows_flat.append(
|
| 230 |
+
{
|
| 231 |
+
"pathway": r.get("pathway", ""),
|
| 232 |
+
"p_value": r.get("p_value"),
|
| 233 |
+
"q_value": r.get("q_value"),
|
| 234 |
+
"overlap_count": r.get("overlap_count"),
|
| 235 |
+
"pathway_size": r.get("pathway_size"),
|
| 236 |
+
"gene_ratio": r.get("gene_ratio", ""),
|
| 237 |
+
}
|
| 238 |
+
)
|
| 239 |
+
df_pe = (
|
| 240 |
+
pd.DataFrame(rows_flat)
|
| 241 |
+
if rows_flat
|
| 242 |
+
else pd.DataFrame({"info": ["No ORA results — run pathway enrichment."]})
|
| 243 |
+
)
|
| 244 |
+
else:
|
| 245 |
+
tp = obs.get("top_pathways") or []
|
| 246 |
+
if tp:
|
| 247 |
+
df_pe = pd.DataFrame({"pathway": tp})
|
| 248 |
+
else:
|
| 249 |
+
df_pe = pd.DataFrame(
|
| 250 |
+
{"info": ["No ORA table yet — run pathway enrichment."]}
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
df_cmp = _pathway_comparison_df(obs)
|
| 254 |
+
|
| 255 |
+
ov = obs.get("overlap_summary") or {}
|
| 256 |
+
amb = obs.get("statistical_ambiguity") or {}
|
| 257 |
+
extra = []
|
| 258 |
+
if ov:
|
| 259 |
+
extra.append(
|
| 260 |
+
"**Overlap across top pathways:**\n```json\n"
|
| 261 |
+
+ json.dumps(ov, indent=2)[:4000]
|
| 262 |
+
+ "\n```"
|
| 263 |
+
)
|
| 264 |
+
if amb:
|
| 265 |
+
extra.append(
|
| 266 |
+
"**Statistical ambiguity:**\n```json\n"
|
| 267 |
+
+ json.dumps(amb, indent=2)[:2000]
|
| 268 |
+
+ "\n```"
|
| 269 |
+
)
|
| 270 |
+
extra_txt = "\n\n".join(extra) if extra else "*No overlap / ambiguity data yet.*"
|
| 271 |
+
|
| 272 |
+
trace = obs.get("trace_path") or ""
|
| 273 |
+
trace_md = (
|
| 274 |
+
f"**HTML episode trace:** `{trace}`\n\n"
|
| 275 |
+
f"Open the file locally to audit each step in a browser."
|
| 276 |
+
if trace
|
| 277 |
+
else "*Trace file path appears after environment steps.*"
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
raw = json.dumps(data, indent=2, default=str)
|
| 281 |
+
return md, df_de, df_pe, df_cmp, extra_txt, trace_md, raw
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _response(
|
| 285 |
+
data: Dict[str, Any],
|
| 286 |
+
web_manager: Any,
|
| 287 |
+
status: str,
|
| 288 |
+
update_contrast: bool,
|
| 289 |
+
) -> Tuple[Any, ...]:
|
| 290 |
+
"""Shared outputs for all steps; optionally refresh contrast textboxes from state."""
|
| 291 |
+
md, df_de, df_pe, df_cmp, extra, trace_md, raw = _observation_to_tables(data)
|
| 292 |
+
st = web_manager.get_state()
|
| 293 |
+
env = getattr(web_manager, "env", None)
|
| 294 |
+
outcome = getattr(env, "episode_outcome", None) if env is not None else None
|
| 295 |
+
state_md = _state_markdown(
|
| 296 |
+
st if isinstance(st, dict) else {},
|
| 297 |
+
outcome if isinstance(outcome, dict) else None,
|
| 298 |
+
)
|
| 299 |
+
conds = (st or {}).get("conditions") or []
|
| 300 |
+
if update_contrast and conds:
|
| 301 |
+
ref_v = str(conds[0])
|
| 302 |
+
alt_v = str(conds[1]) if len(conds) > 1 else ref_v
|
| 303 |
+
cref, calt = gr.update(value=ref_v), gr.update(value=alt_v)
|
| 304 |
+
else:
|
| 305 |
+
cref, calt = gr.update(), gr.update()
|
| 306 |
+
return (
|
| 307 |
+
md,
|
| 308 |
+
df_de,
|
| 309 |
+
df_pe,
|
| 310 |
+
df_cmp,
|
| 311 |
+
extra,
|
| 312 |
+
trace_md,
|
| 313 |
+
raw,
|
| 314 |
+
state_md,
|
| 315 |
+
status,
|
| 316 |
+
cref,
|
| 317 |
+
calt,
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def build_pathway_gradio_app(
|
| 322 |
+
web_manager: Any,
|
| 323 |
+
action_fields: List[Dict[str, Any]],
|
| 324 |
+
metadata: Optional[EnvironmentMetadata],
|
| 325 |
+
is_chat_env: bool,
|
| 326 |
+
title: str,
|
| 327 |
+
quick_start_md: str,
|
| 328 |
+
) -> gr.Blocks:
|
| 329 |
+
"""
|
| 330 |
+
Second tab (**Visualization**) for pathway_analysis_env: interactive pathway lab.
|
| 331 |
+
|
| 332 |
+
Uses ``web_manager.env.set_case_file`` before reset, and ``step_environment`` with
|
| 333 |
+
structured ``PathwayAction`` payloads.
|
| 334 |
+
"""
|
| 335 |
+
case_choices = _list_case_files()
|
| 336 |
+
saved_runs = _list_saved_runs()
|
| 337 |
+
display = metadata.name if metadata else title
|
| 338 |
+
|
| 339 |
+
async def do_reset(case_file: str):
|
| 340 |
+
try:
|
| 341 |
+
if hasattr(web_manager.env, "set_case_file"):
|
| 342 |
+
web_manager.env.set_case_file(case_file)
|
| 343 |
+
data = await web_manager.reset_environment()
|
| 344 |
+
return _response(
|
| 345 |
+
data,
|
| 346 |
+
web_manager,
|
| 347 |
+
f"Loaded case `{case_file}` and reset.",
|
| 348 |
+
update_contrast=True,
|
| 349 |
+
)
|
| 350 |
+
except Exception as e:
|
| 351 |
+
empty = pd.DataFrame({"error": [str(e)]})
|
| 352 |
+
z = gr.update()
|
| 353 |
+
return (
|
| 354 |
+
"",
|
| 355 |
+
empty,
|
| 356 |
+
empty,
|
| 357 |
+
empty,
|
| 358 |
+
"",
|
| 359 |
+
"",
|
| 360 |
+
"",
|
| 361 |
+
f"*Error:* `{e}`",
|
| 362 |
+
str(e),
|
| 363 |
+
z,
|
| 364 |
+
z,
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
async def step_inspect():
|
| 368 |
+
data = await web_manager.step_environment({"action_type": "inspect_dataset"})
|
| 369 |
+
return _response(
|
| 370 |
+
data,
|
| 371 |
+
web_manager,
|
| 372 |
+
"Inspect complete.",
|
| 373 |
+
update_contrast=False,
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
async def step_understand(cond_a: str, cond_b: str):
|
| 377 |
+
payload: Dict[str, Any] = {
|
| 378 |
+
"action_type": "understand_experiment_design",
|
| 379 |
+
"condition_a": (cond_a or "").strip() or None,
|
| 380 |
+
"condition_b": (cond_b or "").strip() or None,
|
| 381 |
+
}
|
| 382 |
+
data = await web_manager.step_environment(payload)
|
| 383 |
+
return _response(
|
| 384 |
+
data,
|
| 385 |
+
web_manager,
|
| 386 |
+
"Understand experiment design complete.",
|
| 387 |
+
update_contrast=False,
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
async def step_de(cond_a: str, cond_b: str):
|
| 391 |
+
payload: Dict[str, Any] = {
|
| 392 |
+
"action_type": "run_differential_expression",
|
| 393 |
+
"condition_a": (cond_a or "").strip() or None,
|
| 394 |
+
"condition_b": (cond_b or "").strip() or None,
|
| 395 |
+
}
|
| 396 |
+
data = await web_manager.step_environment(payload)
|
| 397 |
+
return _response(
|
| 398 |
+
data,
|
| 399 |
+
web_manager,
|
| 400 |
+
"Differential expression complete.",
|
| 401 |
+
update_contrast=False,
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
async def step_ora():
|
| 405 |
+
data = await web_manager.step_environment(
|
| 406 |
+
{"action_type": "run_pathway_enrichment"}
|
| 407 |
+
)
|
| 408 |
+
return _response(
|
| 409 |
+
data,
|
| 410 |
+
web_manager,
|
| 411 |
+
"ORA complete.",
|
| 412 |
+
update_contrast=False,
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
async def step_compare(pa: str, pb: str):
|
| 416 |
+
data = await web_manager.step_environment(
|
| 417 |
+
{
|
| 418 |
+
"action_type": "compare_pathways",
|
| 419 |
+
"pathway_a": (pa or "").strip(),
|
| 420 |
+
"pathway_b": (pb or "").strip(),
|
| 421 |
+
}
|
| 422 |
+
)
|
| 423 |
+
return _response(
|
| 424 |
+
data,
|
| 425 |
+
web_manager,
|
| 426 |
+
"Compare complete.",
|
| 427 |
+
update_contrast=False,
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
async def step_submit(hyp: str):
|
| 431 |
+
data = await web_manager.step_environment(
|
| 432 |
+
{"action_type": "submit_answer", "hypothesis": (hyp or "").strip()}
|
| 433 |
+
)
|
| 434 |
+
return _response(
|
| 435 |
+
data,
|
| 436 |
+
web_manager,
|
| 437 |
+
"Answer submitted.",
|
| 438 |
+
update_contrast=False,
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
with gr.Blocks(title=f"{display} — Pathway lab") as blocks:
|
| 442 |
+
gr.Markdown(
|
| 443 |
+
f"# Pathway lab\n\n"
|
| 444 |
+
f"**Agent-style flow:** **(1) Groups & design** — how many conditions and samples per group. "
|
| 445 |
+
f"**(2) DGE** — pick reference vs alternate, then differential expression. "
|
| 446 |
+
f"**(3) Pathways** — ORA, compare, submit hypothesis. "
|
| 447 |
+
f"Buttons: Understand design → Inspect → Run DE → Run ORA → … Use **Playground** for raw actions.\n\n"
|
| 448 |
+
f"---"
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
with gr.Row(equal_height=True):
|
| 452 |
+
with gr.Column(scale=2):
|
| 453 |
+
gr.Markdown("**Case & episode**")
|
| 454 |
+
with gr.Row():
|
| 455 |
+
case_dd = gr.Dropdown(
|
| 456 |
+
choices=case_choices,
|
| 457 |
+
value=case_choices[0] if case_choices else None,
|
| 458 |
+
label="Case JSON (`data/`)",
|
| 459 |
+
scale=2,
|
| 460 |
+
)
|
| 461 |
+
reset_btn = gr.Button("Reset episode", variant="primary", scale=1)
|
| 462 |
+
with gr.Column(scale=3):
|
| 463 |
+
out_state = gr.Markdown(label="Episode state")
|
| 464 |
+
out_status = gr.Textbox(label="Last action", max_lines=2)
|
| 465 |
+
|
| 466 |
+
gr.Markdown("### Contrast (PyDESeq2 pipeline cases)")
|
| 467 |
+
gr.Markdown(
|
| 468 |
+
"*Reference* = baseline condition, *alternate* = treatment. "
|
| 469 |
+
"Reset fills these from the case when possible; edit if needed. "
|
| 470 |
+
"**Understand design:** leave both empty for a structured summary only, or fill both to validate the contrast (used by **Run DE** when those fields are left empty)."
|
| 471 |
+
)
|
| 472 |
+
with gr.Row():
|
| 473 |
+
cond_ref = gr.Textbox(
|
| 474 |
+
label="Reference condition",
|
| 475 |
+
placeholder="e.g. control",
|
| 476 |
+
lines=1,
|
| 477 |
+
)
|
| 478 |
+
cond_alt = gr.Textbox(
|
| 479 |
+
label="Alternate condition",
|
| 480 |
+
placeholder="e.g. treated",
|
| 481 |
+
lines=1,
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
gr.Markdown("#### Workflow")
|
| 485 |
+
with gr.Row():
|
| 486 |
+
btn_ud = gr.Button("0 · Understand design", variant="secondary")
|
| 487 |
+
btn_ins = gr.Button("1 · Inspect", variant="secondary")
|
| 488 |
+
btn_de = gr.Button("2 · Run DE", variant="primary")
|
| 489 |
+
btn_ora = gr.Button("3 · Run ORA", variant="primary")
|
| 490 |
+
with gr.Row():
|
| 491 |
+
pw_a = gr.Textbox(label="Pathway A", placeholder="MAPK signaling", scale=1)
|
| 492 |
+
pw_b = gr.Textbox(label="Pathway B", placeholder="PI3K-Akt", scale=1)
|
| 493 |
+
btn_cmp = gr.Button("4 · Compare", scale=0, min_width=120)
|
| 494 |
+
with gr.Row():
|
| 495 |
+
hyp = gr.Textbox(
|
| 496 |
+
label="Hypothesis (pathway name)",
|
| 497 |
+
placeholder="True activated pathway",
|
| 498 |
+
scale=2,
|
| 499 |
+
)
|
| 500 |
+
btn_sub = gr.Button("5 · Submit", variant="stop", scale=0, min_width=120)
|
| 501 |
+
|
| 502 |
+
gr.Markdown("### Results")
|
| 503 |
+
out_md = gr.Markdown()
|
| 504 |
+
with gr.Tabs():
|
| 505 |
+
with gr.Tab("DE genes"):
|
| 506 |
+
out_de = gr.Dataframe(
|
| 507 |
+
label="Differential expression",
|
| 508 |
+
interactive=False,
|
| 509 |
+
wrap=True,
|
| 510 |
+
)
|
| 511 |
+
with gr.Tab("ORA"):
|
| 512 |
+
out_ora = gr.Dataframe(
|
| 513 |
+
label="Pathway enrichment",
|
| 514 |
+
interactive=False,
|
| 515 |
+
wrap=True,
|
| 516 |
+
)
|
| 517 |
+
with gr.Tab("Compare"):
|
| 518 |
+
out_cmp = gr.Dataframe(
|
| 519 |
+
label="Pathway vs pathway",
|
| 520 |
+
interactive=False,
|
| 521 |
+
wrap=True,
|
| 522 |
+
)
|
| 523 |
+
with gr.Tab("Saved run (GSE235417)"):
|
| 524 |
+
gr.Markdown(
|
| 525 |
+
"Browse exported run artifacts under `envs/pathway_analysis_env/outputs/<run>/` "
|
| 526 |
+
"(e.g. `gse235417`). This view does **not** re-run DESeq2; it only loads saved JSON."
|
| 527 |
+
)
|
| 528 |
+
run_dd = gr.Dropdown(
|
| 529 |
+
choices=saved_runs,
|
| 530 |
+
value="gse235417" if "gse235417" in saved_runs else (saved_runs[0] if saved_runs else None),
|
| 531 |
+
label="Saved run folder (`outputs/`)",
|
| 532 |
+
)
|
| 533 |
+
load_btn = gr.Button("Load saved results", variant="primary")
|
| 534 |
+
run_md = gr.Markdown()
|
| 535 |
+
run_de = gr.Dataframe(label="Saved DE (top 200)", interactive=False, wrap=True)
|
| 536 |
+
run_enr = gr.Dataframe(label="Saved enrichment (top 50)", interactive=False, wrap=True)
|
| 537 |
+
with gr.Tab("Overlap & ambiguity"):
|
| 538 |
+
out_extra = gr.Markdown()
|
| 539 |
+
with gr.Tab("Trace"):
|
| 540 |
+
out_trace = gr.Markdown()
|
| 541 |
+
with gr.Tab("Raw JSON"):
|
| 542 |
+
out_raw = gr.Code(label="Wire payload", language="json", interactive=False)
|
| 543 |
+
|
| 544 |
+
ui_outputs = [
|
| 545 |
+
out_md,
|
| 546 |
+
out_de,
|
| 547 |
+
out_ora,
|
| 548 |
+
out_cmp,
|
| 549 |
+
out_extra,
|
| 550 |
+
out_trace,
|
| 551 |
+
out_raw,
|
| 552 |
+
out_state,
|
| 553 |
+
out_status,
|
| 554 |
+
cond_ref,
|
| 555 |
+
cond_alt,
|
| 556 |
+
]
|
| 557 |
+
|
| 558 |
+
reset_btn.click(fn=do_reset, inputs=[case_dd], outputs=ui_outputs)
|
| 559 |
+
btn_ud.click(fn=step_understand, inputs=[cond_ref, cond_alt], outputs=ui_outputs)
|
| 560 |
+
btn_ins.click(fn=step_inspect, outputs=ui_outputs)
|
| 561 |
+
btn_de.click(fn=step_de, inputs=[cond_ref, cond_alt], outputs=ui_outputs)
|
| 562 |
+
btn_ora.click(fn=step_ora, outputs=ui_outputs)
|
| 563 |
+
btn_cmp.click(fn=step_compare, inputs=[pw_a, pw_b], outputs=ui_outputs)
|
| 564 |
+
btn_sub.click(fn=step_submit, inputs=[hyp], outputs=ui_outputs)
|
| 565 |
+
|
| 566 |
+
def do_load_saved(run_name: str):
|
| 567 |
+
run = _load_saved_run(run_name or "")
|
| 568 |
+
md, df_de, df_enr = _saved_run_to_tables(run)
|
| 569 |
+
return md, df_de, df_enr
|
| 570 |
+
|
| 571 |
+
load_btn.click(fn=do_load_saved, inputs=[run_dd], outputs=[run_md, run_de, run_enr])
|
| 572 |
+
|
| 573 |
+
return blocks
|
envs/pathway_analysis_env/server/pathway_environment.py
ADDED
|
@@ -0,0 +1,1112 @@
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
Pathway analysis environment: PyDESeq2 DE, Fisher ORA, overlap-aware tools,
|
| 9 |
+
HTML episode trace.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import html
|
| 15 |
+
import json
|
| 16 |
+
import uuid
|
| 17 |
+
from datetime import datetime, timezone
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 20 |
+
|
| 21 |
+
from openenv.core.env_server import Environment
|
| 22 |
+
|
| 23 |
+
from ..models import PathwayAction, PathwayObservation, PathwayState
|
| 24 |
+
from . import failure_codes as FC
|
| 25 |
+
from .case_loader import load_case_file, strip_case_secrets
|
| 26 |
+
from .eval_protocol import (
|
| 27 |
+
default_max_steps,
|
| 28 |
+
resolve_eval_mode,
|
| 29 |
+
resolve_orchestrator_mode,
|
| 30 |
+
sanitize_observation_for_agent,
|
| 31 |
+
shaping_reward,
|
| 32 |
+
strip_legacy_answer_leaks,
|
| 33 |
+
)
|
| 34 |
+
from .scoring import score_submission
|
| 35 |
+
from .analysis import (
|
| 36 |
+
build_sample_metadata,
|
| 37 |
+
compare_pathways_detail,
|
| 38 |
+
counts_dict_to_samples_by_genes,
|
| 39 |
+
filter_counts_by_minimum_total,
|
| 40 |
+
gseapy_available,
|
| 41 |
+
load_counts_csv_as_samples_by_genes,
|
| 42 |
+
load_author_de_table_csv,
|
| 43 |
+
merge_analysis_options,
|
| 44 |
+
enrichr_ora,
|
| 45 |
+
ora_fisher,
|
| 46 |
+
overlap_genes_across_top_pathways,
|
| 47 |
+
pick_de_query_genes,
|
| 48 |
+
pydeseq2_available,
|
| 49 |
+
run_deseq2_contrast,
|
| 50 |
+
top_hits_statistically_close,
|
| 51 |
+
validate_counts_case,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
DATA_DIR = Path(__file__).resolve().parent.parent / "data"
|
| 55 |
+
OUTPUT_TRACE_DIR = Path(__file__).resolve().parent.parent / "outputs" / "pathway_traces"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def load_case(
|
| 59 |
+
case_name: str = "toy_case_001.json", *, agent_safe: bool = False
|
| 60 |
+
) -> Dict[str, Any]:
|
| 61 |
+
"""Load a case JSON. Set ``agent_safe=True`` to omit orchestrator secret fields."""
|
| 62 |
+
case, _secrets = load_case_file(DATA_DIR, case_name, agent_safe=agent_safe)
|
| 63 |
+
return case
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _legacy_de_rows(top_names: List[str]) -> List[Dict[str, Any]]:
|
| 67 |
+
"""Synthetic DE rows for legacy JSON-only cases."""
|
| 68 |
+
rows: List[Dict[str, Any]] = []
|
| 69 |
+
for i, name in enumerate(top_names):
|
| 70 |
+
rows.append(
|
| 71 |
+
{
|
| 72 |
+
"gene": name,
|
| 73 |
+
"baseMean": 500.0,
|
| 74 |
+
"log2FoldChange": 2.0 - i * 0.1,
|
| 75 |
+
"lfcSE": 0.2,
|
| 76 |
+
"pvalue": 1e-6,
|
| 77 |
+
"padj": 0.01,
|
| 78 |
+
"significant": True,
|
| 79 |
+
}
|
| 80 |
+
)
|
| 81 |
+
return rows
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _write_html_trace(
|
| 85 |
+
episode_id: str,
|
| 86 |
+
steps: List[Dict[str, Any]],
|
| 87 |
+
case_id: str,
|
| 88 |
+
) -> str:
|
| 89 |
+
OUTPUT_TRACE_DIR.mkdir(parents=True, exist_ok=True)
|
| 90 |
+
path = OUTPUT_TRACE_DIR / f"{episode_id}.html"
|
| 91 |
+
rows_html = []
|
| 92 |
+
for s in steps:
|
| 93 |
+
rows_html.append(
|
| 94 |
+
"<tr><td>{}</td><td><pre>{}</pre></td><td>{}</td></tr>".format(
|
| 95 |
+
html.escape(str(s.get("step", ""))),
|
| 96 |
+
html.escape(json.dumps(s.get("detail", {}), indent=2)[:8000]),
|
| 97 |
+
html.escape(str(s.get("message", ""))[:2000]),
|
| 98 |
+
)
|
| 99 |
+
)
|
| 100 |
+
body = f"""<!DOCTYPE html>
|
| 101 |
+
<html><head><meta charset="utf-8"/><title>Pathway trace {html.escape(episode_id)}</title>
|
| 102 |
+
<style>body{{font-family:system-ui,sans-serif;margin:1rem;}} table{{border-collapse:collapse;width:100%;}}
|
| 103 |
+
td,th{{border:1px solid #ccc;padding:0.4rem;vertical-align:top;}} pre{{white-space:pre-wrap;}}</style>
|
| 104 |
+
</head><body>
|
| 105 |
+
<h1>Pathway analysis episode</h1>
|
| 106 |
+
<p><b>case</b>: {html.escape(case_id)} <b>episode</b>: {html.escape(episode_id)}</p>
|
| 107 |
+
<p>Generated {html.escape(datetime.now(timezone.utc).isoformat())}</p>
|
| 108 |
+
<table><thead><tr><th>Step</th><th>Detail</th><th>Message</th></tr></thead>
|
| 109 |
+
<tbody>{"".join(rows_html)}</tbody></table>
|
| 110 |
+
</body></html>"""
|
| 111 |
+
path.write_text(body, encoding="utf-8")
|
| 112 |
+
return str(path)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _safe_case_id(case: Dict[str, Any]) -> str:
|
| 116 |
+
"""Best-effort case identifier for trace rendering."""
|
| 117 |
+
try:
|
| 118 |
+
cid = case.get("case_id")
|
| 119 |
+
except Exception:
|
| 120 |
+
cid = None
|
| 121 |
+
return str(cid or "unknown_case")
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class PathwayEnvironment(Environment):
|
| 125 |
+
"""
|
| 126 |
+
Pathway inference with optional **pipeline Mode A** (counts + metadata in JSON),
|
| 127 |
+
or **legacy** toy fixtures (static gene/pathway lists).
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
def __init__(
|
| 131 |
+
self,
|
| 132 |
+
case_file: str = "toy_case_001.json",
|
| 133 |
+
*,
|
| 134 |
+
agent_safe_cases: bool = False,
|
| 135 |
+
):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self._case_file = case_file
|
| 138 |
+
self._agent_safe_cases = agent_safe_cases
|
| 139 |
+
self._case: Dict[str, Any] = {}
|
| 140 |
+
self._state = PathwayState()
|
| 141 |
+
self._true_pathway: str = ""
|
| 142 |
+
self._true_pathway_aliases: List[str] = []
|
| 143 |
+
self._expected_keywords: List[str] = []
|
| 144 |
+
self._eval_mode: bool = True
|
| 145 |
+
self._orchestrator_mode: bool = False
|
| 146 |
+
self._max_steps: int = 30
|
| 147 |
+
self._episode_outcome: Optional[Dict[str, Any]] = None
|
| 148 |
+
self._de_rows: List[Dict[str, Any]] = []
|
| 149 |
+
self._ora_rows: List[Dict[str, Any]] = []
|
| 150 |
+
self._query_genes: List[str] = []
|
| 151 |
+
self._trace_steps: List[Dict[str, Any]] = []
|
| 152 |
+
self._universe_genes: List[str] = []
|
| 153 |
+
self.reset()
|
| 154 |
+
|
| 155 |
+
def set_case_file(self, case_file: str) -> None:
|
| 156 |
+
"""Switch JSON case before ``reset()`` (used by the Gradio Pathway lab tab)."""
|
| 157 |
+
self._case_file = case_file
|
| 158 |
+
|
| 159 |
+
@property
|
| 160 |
+
def episode_outcome(self) -> Optional[Dict[str, Any]]:
|
| 161 |
+
"""Orchestrator-only score after ``submit_answer`` (not exposed via agent state)."""
|
| 162 |
+
return self._episode_outcome
|
| 163 |
+
|
| 164 |
+
def _emit(self, obs: PathwayObservation) -> PathwayObservation:
|
| 165 |
+
if obs.trace_path is None and self._state.episode_id:
|
| 166 |
+
obs = obs.model_copy(update={"trace_path": self._refresh_trace_file()})
|
| 167 |
+
return sanitize_observation_for_agent(
|
| 168 |
+
obs,
|
| 169 |
+
eval_mode=self._eval_mode,
|
| 170 |
+
orchestrator_mode=self._orchestrator_mode,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
def reset(
|
| 174 |
+
self,
|
| 175 |
+
seed: Optional[int] = None,
|
| 176 |
+
episode_id: Optional[str] = None,
|
| 177 |
+
**kwargs: Any,
|
| 178 |
+
) -> PathwayObservation:
|
| 179 |
+
use_agent_safe = bool(
|
| 180 |
+
kwargs.get("agent_safe_cases", self._agent_safe_cases)
|
| 181 |
+
)
|
| 182 |
+
full_case, secrets = load_case_file(
|
| 183 |
+
DATA_DIR, self._case_file, agent_safe=False
|
| 184 |
+
)
|
| 185 |
+
self._eval_mode = resolve_eval_mode(full_case, kwargs)
|
| 186 |
+
self._orchestrator_mode = resolve_orchestrator_mode(full_case, kwargs)
|
| 187 |
+
if use_agent_safe or (
|
| 188 |
+
self._eval_mode and not self._orchestrator_mode
|
| 189 |
+
):
|
| 190 |
+
self._case = strip_case_secrets(full_case)
|
| 191 |
+
else:
|
| 192 |
+
self._case = full_case
|
| 193 |
+
eid = episode_id or str(uuid.uuid4())
|
| 194 |
+
strict = bool(kwargs.get("strict", full_case.get("strict_mode", False)))
|
| 195 |
+
self._max_steps = default_max_steps(full_case)
|
| 196 |
+
self._true_pathway = str(secrets.get("true_pathway", ""))
|
| 197 |
+
self._true_pathway_aliases = list(secrets.get("true_pathway_aliases") or [])
|
| 198 |
+
self._expected_keywords = list(secrets.get("expected_keywords") or [])
|
| 199 |
+
self._episode_outcome = None
|
| 200 |
+
pipeline = (
|
| 201 |
+
(
|
| 202 |
+
"counts" in self._case
|
| 203 |
+
or "counts_file" in self._case
|
| 204 |
+
or "de_table_file" in self._case
|
| 205 |
+
)
|
| 206 |
+
and "sample_ids" in self._case
|
| 207 |
+
and "sample_metadata" in self._case
|
| 208 |
+
)
|
| 209 |
+
self._de_rows = []
|
| 210 |
+
self._ora_rows = []
|
| 211 |
+
self._query_genes = []
|
| 212 |
+
self._trace_steps = []
|
| 213 |
+
self._universe_genes = []
|
| 214 |
+
self._state = PathwayState(
|
| 215 |
+
episode_id=eid,
|
| 216 |
+
step_count=0,
|
| 217 |
+
conditions=list(self._case.get("conditions", [])),
|
| 218 |
+
pipeline_mode=pipeline,
|
| 219 |
+
strict_mode=strict,
|
| 220 |
+
legacy_mode=not pipeline,
|
| 221 |
+
eval_mode=self._eval_mode,
|
| 222 |
+
max_steps=self._max_steps,
|
| 223 |
+
)
|
| 224 |
+
mode = "legacy"
|
| 225 |
+
if pipeline:
|
| 226 |
+
if "de_table_file" in self._case:
|
| 227 |
+
mode = "author_de_table"
|
| 228 |
+
elif "counts_file" in self._case or "counts" in self._case:
|
| 229 |
+
mode = "counts_matrix"
|
| 230 |
+
else:
|
| 231 |
+
mode = "pipeline_unknown"
|
| 232 |
+
msg = (
|
| 233 |
+
"Dataset loaded (pipeline: counts/metadata)."
|
| 234 |
+
if mode == "counts_matrix"
|
| 235 |
+
else (
|
| 236 |
+
"Dataset loaded (pipeline: author DE table; enrichment only, not DESeq2-from-counts)."
|
| 237 |
+
if mode == "author_de_table"
|
| 238 |
+
else "Toy dataset loaded (legacy static lists)."
|
| 239 |
+
)
|
| 240 |
+
)
|
| 241 |
+
self._trace(
|
| 242 |
+
"reset",
|
| 243 |
+
{
|
| 244 |
+
"case_id": self._case.get("case_id"),
|
| 245 |
+
"pipeline": pipeline,
|
| 246 |
+
"mode": mode,
|
| 247 |
+
"strict": strict,
|
| 248 |
+
},
|
| 249 |
+
msg,
|
| 250 |
+
)
|
| 251 |
+
trace_path = _write_html_trace(
|
| 252 |
+
eid, self._trace_steps, _safe_case_id(self._case)
|
| 253 |
+
)
|
| 254 |
+
obs = PathwayObservation(
|
| 255 |
+
message=msg
|
| 256 |
+
+ " Use understand_experiment_design, inspect, run DE, enrichment, compare, or submit.",
|
| 257 |
+
available_conditions=self._state.conditions,
|
| 258 |
+
metadata={
|
| 259 |
+
"case_id": self._case["case_id"],
|
| 260 |
+
"pipeline_mode": pipeline,
|
| 261 |
+
"pipeline_data_mode": mode,
|
| 262 |
+
"eval_mode": self._eval_mode,
|
| 263 |
+
"max_steps": self._max_steps,
|
| 264 |
+
},
|
| 265 |
+
trace_path=trace_path,
|
| 266 |
+
)
|
| 267 |
+
return self._emit(obs)
|
| 268 |
+
|
| 269 |
+
def _trace(self, kind: str, detail: Dict[str, Any], message: str) -> None:
|
| 270 |
+
s = self._state
|
| 271 |
+
self._trace_steps.append(
|
| 272 |
+
{
|
| 273 |
+
"step": s.step_count,
|
| 274 |
+
"kind": kind,
|
| 275 |
+
"detail": detail,
|
| 276 |
+
"message": message,
|
| 277 |
+
}
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
def _refresh_trace_file(self) -> str:
|
| 281 |
+
eid = self._state.episode_id or "unknown"
|
| 282 |
+
return _write_html_trace(
|
| 283 |
+
eid, self._trace_steps, _safe_case_id(self._case)
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
def _fail_strict(
|
| 287 |
+
self, reason: str, failure_code: str = FC.STRICT_TERMINATION
|
| 288 |
+
) -> PathwayObservation:
|
| 289 |
+
self._state.is_done = True
|
| 290 |
+
self._trace(
|
| 291 |
+
"strict_failure",
|
| 292 |
+
{"reason": reason, "failure_code": failure_code},
|
| 293 |
+
reason,
|
| 294 |
+
)
|
| 295 |
+
tp = self._refresh_trace_file()
|
| 296 |
+
return PathwayObservation(
|
| 297 |
+
message=reason,
|
| 298 |
+
done=True,
|
| 299 |
+
reward=-3.0,
|
| 300 |
+
metadata={
|
| 301 |
+
"strict_failure": True,
|
| 302 |
+
"reason": reason,
|
| 303 |
+
"failure_code": failure_code,
|
| 304 |
+
},
|
| 305 |
+
trace_path=tp,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
def step(
|
| 309 |
+
self,
|
| 310 |
+
action: PathwayAction,
|
| 311 |
+
timeout_s: Optional[float] = None,
|
| 312 |
+
**kwargs: Any,
|
| 313 |
+
) -> PathwayObservation:
|
| 314 |
+
return self._emit(self._step_inner(action))
|
| 315 |
+
|
| 316 |
+
def _step_inner(self, action: PathwayAction) -> PathwayObservation:
|
| 317 |
+
s = self._state
|
| 318 |
+
|
| 319 |
+
if s.is_done:
|
| 320 |
+
obs = PathwayObservation(
|
| 321 |
+
message="Episode already finished; call reset() for a new episode.",
|
| 322 |
+
done=True,
|
| 323 |
+
reward=0.0,
|
| 324 |
+
metadata={
|
| 325 |
+
"error": "episode_done",
|
| 326 |
+
"failure_code": FC.EPISODE_ALREADY_DONE,
|
| 327 |
+
"step_count": s.step_count,
|
| 328 |
+
},
|
| 329 |
+
)
|
| 330 |
+
obs.trace_path = self._refresh_trace_file()
|
| 331 |
+
return obs
|
| 332 |
+
|
| 333 |
+
s.step_count += 1
|
| 334 |
+
|
| 335 |
+
if self._eval_mode and s.step_count > self._max_steps:
|
| 336 |
+
s.is_done = True
|
| 337 |
+
self._trace(
|
| 338 |
+
"max_steps",
|
| 339 |
+
{"max_steps": self._max_steps},
|
| 340 |
+
"Step budget exhausted.",
|
| 341 |
+
)
|
| 342 |
+
return PathwayObservation(
|
| 343 |
+
message="Maximum steps exceeded for this episode.",
|
| 344 |
+
done=True,
|
| 345 |
+
reward=-1.0 if not self._eval_mode else 0.0,
|
| 346 |
+
metadata={
|
| 347 |
+
"failure_code": FC.MAX_STEPS_EXCEEDED,
|
| 348 |
+
"max_steps": self._max_steps,
|
| 349 |
+
},
|
| 350 |
+
trace_path=self._refresh_trace_file(),
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
if action.action_type == "inspect_dataset":
|
| 354 |
+
meta = self._case.get("sample_metadata") or {}
|
| 355 |
+
sample_ids = list(self._case.get("sample_ids") or [])
|
| 356 |
+
sample_level = bool(sample_ids and meta)
|
| 357 |
+
if s.legacy_mode:
|
| 358 |
+
msg = (
|
| 359 |
+
"Legacy fixture: conditions are listed; per-sample metadata and counts "
|
| 360 |
+
"are not modeled. DE and ORA return static curated outputs."
|
| 361 |
+
)
|
| 362 |
+
elif sample_level:
|
| 363 |
+
msg = (
|
| 364 |
+
"Sample metadata and conditions are available for contrast specification."
|
| 365 |
+
)
|
| 366 |
+
else:
|
| 367 |
+
msg = (
|
| 368 |
+
"Conditions are available; sample_ids or sample_metadata are incomplete "
|
| 369 |
+
"in this case."
|
| 370 |
+
)
|
| 371 |
+
inspect_meta: Dict[str, Any] = {
|
| 372 |
+
"step_count": s.step_count,
|
| 373 |
+
"legacy_mode": s.legacy_mode,
|
| 374 |
+
"pipeline_mode": s.pipeline_mode,
|
| 375 |
+
"sample_level_metadata_available": sample_level,
|
| 376 |
+
"sample_metadata": meta,
|
| 377 |
+
"sample_ids": sample_ids,
|
| 378 |
+
"pydeseq2_available": pydeseq2_available(),
|
| 379 |
+
"experiment_metadata": self._case.get("experiment_metadata"),
|
| 380 |
+
}
|
| 381 |
+
if s.legacy_mode and not self._eval_mode:
|
| 382 |
+
inspect_meta["static_top_genes"] = list(
|
| 383 |
+
self._case.get("top_genes") or []
|
| 384 |
+
)
|
| 385 |
+
inspect_meta["static_top_pathways"] = list(
|
| 386 |
+
self._case.get("top_pathways") or []
|
| 387 |
+
)
|
| 388 |
+
inspect_meta = strip_legacy_answer_leaks(
|
| 389 |
+
inspect_meta, eval_mode=self._eval_mode
|
| 390 |
+
)
|
| 391 |
+
obs = PathwayObservation(
|
| 392 |
+
message=msg,
|
| 393 |
+
available_conditions=s.conditions,
|
| 394 |
+
reward=shaping_reward(self._eval_mode, 0.05),
|
| 395 |
+
metadata=inspect_meta,
|
| 396 |
+
)
|
| 397 |
+
self._trace(
|
| 398 |
+
"inspect_dataset",
|
| 399 |
+
{"conditions": s.conditions, "legacy": s.legacy_mode},
|
| 400 |
+
obs.message,
|
| 401 |
+
)
|
| 402 |
+
obs.trace_path = self._refresh_trace_file()
|
| 403 |
+
return obs
|
| 404 |
+
|
| 405 |
+
if action.action_type == "understand_experiment_design":
|
| 406 |
+
return self._step_understand_experiment_design(action)
|
| 407 |
+
|
| 408 |
+
if action.action_type == "run_differential_expression":
|
| 409 |
+
return self._step_de(action)
|
| 410 |
+
|
| 411 |
+
if action.action_type == "run_pathway_enrichment":
|
| 412 |
+
return self._step_enrichment(action)
|
| 413 |
+
|
| 414 |
+
if action.action_type == "compare_pathways":
|
| 415 |
+
return self._step_compare(action)
|
| 416 |
+
|
| 417 |
+
if action.action_type == "submit_answer":
|
| 418 |
+
return self._step_submit(action)
|
| 419 |
+
|
| 420 |
+
obs = PathwayObservation(
|
| 421 |
+
message=f"Unknown action_type: {action.action_type}",
|
| 422 |
+
reward=shaping_reward(self._eval_mode, -0.2),
|
| 423 |
+
metadata={
|
| 424 |
+
"step_count": s.step_count,
|
| 425 |
+
"failure_code": FC.UNKNOWN_ACTION_TYPE,
|
| 426 |
+
"action_type": action.action_type,
|
| 427 |
+
},
|
| 428 |
+
)
|
| 429 |
+
obs.trace_path = self._refresh_trace_file()
|
| 430 |
+
return obs
|
| 431 |
+
|
| 432 |
+
def _experiment_design_dict(self) -> Dict[str, Any]:
|
| 433 |
+
case = self._case
|
| 434 |
+
s = self._state
|
| 435 |
+
sample_ids = list(case.get("sample_ids") or [])
|
| 436 |
+
smd = case.get("sample_metadata") or {}
|
| 437 |
+
per: Dict[str, int] = {}
|
| 438 |
+
for sid in sample_ids:
|
| 439 |
+
c = smd.get(sid)
|
| 440 |
+
if c is not None:
|
| 441 |
+
per[c] = per.get(c, 0) + 1
|
| 442 |
+
conds = list(s.conditions)
|
| 443 |
+
sample_level = bool(sample_ids and smd)
|
| 444 |
+
design: Dict[str, Any] = {
|
| 445 |
+
"case_id": case.get("case_id"),
|
| 446 |
+
"pipeline_mode": s.pipeline_mode,
|
| 447 |
+
"legacy_mode": s.legacy_mode,
|
| 448 |
+
"conditions": conds,
|
| 449 |
+
"n_groups": len(conds),
|
| 450 |
+
"n_samples": len(sample_ids) if sample_level else None,
|
| 451 |
+
"sample_ids": sample_ids,
|
| 452 |
+
"sample_level_metadata_available": sample_level,
|
| 453 |
+
"default_contrast": case.get("default_contrast"),
|
| 454 |
+
"experiment_metadata": case.get("experiment_metadata"),
|
| 455 |
+
}
|
| 456 |
+
if sample_level:
|
| 457 |
+
design["samples_per_condition"] = per
|
| 458 |
+
workflow = (
|
| 459 |
+
"(1) Groups: use conditions + samples_per_condition to see how many groups and "
|
| 460 |
+
"replicates exist. (2) DGE: pick reference vs alternate for DESeq2 "
|
| 461 |
+
"(validate via understand_experiment_design or pass to run_differential_expression). "
|
| 462 |
+
"(3) Pathways: run_pathway_enrichment then compare/submit."
|
| 463 |
+
)
|
| 464 |
+
note = (
|
| 465 |
+
"Reference = baseline (denominator of log2 fold change); alternate = comparison arm "
|
| 466 |
+
"for DGE. Optionally set condition_a / condition_b here to validate before "
|
| 467 |
+
"run_differential_expression."
|
| 468 |
+
)
|
| 469 |
+
elif s.legacy_mode:
|
| 470 |
+
design["samples_per_condition"] = None
|
| 471 |
+
design["legacy_fixture"] = True
|
| 472 |
+
workflow = (
|
| 473 |
+
"(1) Groups: conditions are named only (no per-sample counts in this legacy fixture). "
|
| 474 |
+
"(2) DGE / ORA return static curated gene and pathway lists. "
|
| 475 |
+
"(3) Submit the pathway hypothesis."
|
| 476 |
+
)
|
| 477 |
+
note = (
|
| 478 |
+
"Legacy mode does not run DESeq2 on counts. Contrast validation checks condition "
|
| 479 |
+
"names only. Use run_differential_expression and run_pathway_enrichment for "
|
| 480 |
+
"fixture outputs, then submit_answer."
|
| 481 |
+
)
|
| 482 |
+
else:
|
| 483 |
+
design["samples_per_condition"] = per if per else None
|
| 484 |
+
workflow = (
|
| 485 |
+
"(1) Groups: conditions are listed; sample-level metadata may be incomplete. "
|
| 486 |
+
"(2) DGE: pick reference vs alternate when counts/metadata are available. "
|
| 487 |
+
"(3) Pathways: enrichment then submit."
|
| 488 |
+
)
|
| 489 |
+
note = (
|
| 490 |
+
"Reference = baseline; alternate = comparison arm. Sample counts per condition "
|
| 491 |
+
"are unavailable until sample_ids and sample_metadata are present in the case."
|
| 492 |
+
)
|
| 493 |
+
design["agent_workflow"] = workflow
|
| 494 |
+
design["design_note"] = note
|
| 495 |
+
return design
|
| 496 |
+
|
| 497 |
+
def _validate_contrast_proposal(
|
| 498 |
+
self, ref: str, alt: str
|
| 499 |
+
) -> Optional[Tuple[str, str]]:
|
| 500 |
+
"""Return (error_message, failure_code) if invalid; None if valid for DESeq2."""
|
| 501 |
+
conds = set(self._state.conditions)
|
| 502 |
+
if ref not in conds or alt not in conds:
|
| 503 |
+
return (
|
| 504 |
+
"Reference and alternate must be among the case `conditions`.",
|
| 505 |
+
FC.DESIGN_INVALID_CONTRAST_NAMES,
|
| 506 |
+
)
|
| 507 |
+
if ref == alt:
|
| 508 |
+
return (
|
| 509 |
+
"Reference and alternate must be two different conditions.",
|
| 510 |
+
FC.DESIGN_INVALID_CONTRAST_NAMES,
|
| 511 |
+
)
|
| 512 |
+
sample_ids = list(self._case.get("sample_ids") or [])
|
| 513 |
+
smd = self._case.get("sample_metadata") or {}
|
| 514 |
+
if not sample_ids:
|
| 515 |
+
return None
|
| 516 |
+
per: Dict[str, int] = {}
|
| 517 |
+
for sid in sample_ids:
|
| 518 |
+
c = smd.get(sid)
|
| 519 |
+
if c is not None:
|
| 520 |
+
per[c] = per.get(c, 0) + 1
|
| 521 |
+
if per.get(ref, 0) < 1 or per.get(alt, 0) < 1:
|
| 522 |
+
return (
|
| 523 |
+
"Each contrast arm must have at least one sample in `sample_metadata`.",
|
| 524 |
+
FC.DESIGN_INSUFFICIENT_SAMPLES_PER_ARM,
|
| 525 |
+
)
|
| 526 |
+
return None
|
| 527 |
+
|
| 528 |
+
def _step_understand_experiment_design(
|
| 529 |
+
self, action: PathwayAction
|
| 530 |
+
) -> PathwayObservation:
|
| 531 |
+
s = self._state
|
| 532 |
+
design = self._experiment_design_dict()
|
| 533 |
+
ref_in = (action.condition_a or "").strip()
|
| 534 |
+
alt_in = (action.condition_b or "").strip()
|
| 535 |
+
has_both = bool(ref_in and alt_in)
|
| 536 |
+
has_partial = bool(ref_in or alt_in) and not has_both
|
| 537 |
+
|
| 538 |
+
if has_partial:
|
| 539 |
+
obs = PathwayObservation(
|
| 540 |
+
message=(
|
| 541 |
+
"Provide both reference (condition_a) and alternate (condition_b) to "
|
| 542 |
+
"validate a contrast, or leave both empty for a design summary only."
|
| 543 |
+
),
|
| 544 |
+
available_conditions=s.conditions,
|
| 545 |
+
experiment_design=design,
|
| 546 |
+
reward=shaping_reward(self._eval_mode, -0.02),
|
| 547 |
+
metadata={
|
| 548 |
+
"step_count": s.step_count,
|
| 549 |
+
"validation": "incomplete",
|
| 550 |
+
"failure_code": FC.DESIGN_PARTIAL_CONTRAST,
|
| 551 |
+
},
|
| 552 |
+
)
|
| 553 |
+
self._trace(
|
| 554 |
+
"understand_experiment_design",
|
| 555 |
+
{"validation": "incomplete"},
|
| 556 |
+
obs.message,
|
| 557 |
+
)
|
| 558 |
+
obs.trace_path = self._refresh_trace_file()
|
| 559 |
+
return obs
|
| 560 |
+
|
| 561 |
+
if not has_both:
|
| 562 |
+
s.design_understood = True
|
| 563 |
+
if s.legacy_mode:
|
| 564 |
+
msg = (
|
| 565 |
+
"Design summary (legacy fixture): condition names are available; per-sample "
|
| 566 |
+
"replicate counts are not modeled. DE and ORA use static outputs. You may still "
|
| 567 |
+
"validate a contrast by naming reference vs alternate, then run DE → ORA → submit."
|
| 568 |
+
)
|
| 569 |
+
elif design.get("sample_level_metadata_available"):
|
| 570 |
+
msg = (
|
| 571 |
+
"Design summary: you have the groups (conditions) and sample counts per group. "
|
| 572 |
+
"Next, choose reference vs alternate for DGE (differential expression), then "
|
| 573 |
+
"pathway steps. Re-run this action with both conditions set to validate your "
|
| 574 |
+
"contrast."
|
| 575 |
+
)
|
| 576 |
+
else:
|
| 577 |
+
msg = (
|
| 578 |
+
"Design summary: condition names are listed; sample counts per group are not "
|
| 579 |
+
"available in this case. Re-run with both conditions set to validate a contrast "
|
| 580 |
+
"when supported, then run DGE and pathway steps."
|
| 581 |
+
)
|
| 582 |
+
obs = PathwayObservation(
|
| 583 |
+
message=msg,
|
| 584 |
+
available_conditions=s.conditions,
|
| 585 |
+
experiment_design=design,
|
| 586 |
+
reward=shaping_reward(self._eval_mode, 0.05),
|
| 587 |
+
metadata={"step_count": s.step_count, "validation": "summary_only"},
|
| 588 |
+
)
|
| 589 |
+
self._trace("understand_experiment_design", {"mode": "summary"}, msg)
|
| 590 |
+
obs.trace_path = self._refresh_trace_file()
|
| 591 |
+
return obs
|
| 592 |
+
|
| 593 |
+
invalid = self._validate_contrast_proposal(ref_in, alt_in)
|
| 594 |
+
if invalid:
|
| 595 |
+
err, fcode = invalid
|
| 596 |
+
s.validated_reference = None
|
| 597 |
+
s.validated_alternate = None
|
| 598 |
+
s.design_understood = True
|
| 599 |
+
obs = PathwayObservation(
|
| 600 |
+
message=err,
|
| 601 |
+
available_conditions=s.conditions,
|
| 602 |
+
experiment_design=design,
|
| 603 |
+
reward=shaping_reward(self._eval_mode, -0.05),
|
| 604 |
+
metadata={
|
| 605 |
+
"step_count": s.step_count,
|
| 606 |
+
"validation": "invalid",
|
| 607 |
+
"failure_code": fcode,
|
| 608 |
+
},
|
| 609 |
+
)
|
| 610 |
+
self._trace(
|
| 611 |
+
"understand_experiment_design",
|
| 612 |
+
{"validation": "invalid", "proposal": [ref_in, alt_in]},
|
| 613 |
+
err,
|
| 614 |
+
)
|
| 615 |
+
obs.trace_path = self._refresh_trace_file()
|
| 616 |
+
return obs
|
| 617 |
+
|
| 618 |
+
s.validated_reference = ref_in
|
| 619 |
+
s.validated_alternate = alt_in
|
| 620 |
+
s.design_understood = True
|
| 621 |
+
design["validated_contrast"] = {"reference": ref_in, "alternate": alt_in}
|
| 622 |
+
msg = (
|
| 623 |
+
f"DGE contrast chosen: reference=`{ref_in}`, alternate=`{alt_in}` "
|
| 624 |
+
f"({len(s.conditions)} groups in study). "
|
| 625 |
+
"run_differential_expression will use this pair when DE omits conditions; "
|
| 626 |
+
"explicit DE fields override. Then run pathway enrichment."
|
| 627 |
+
)
|
| 628 |
+
obs = PathwayObservation(
|
| 629 |
+
message=msg,
|
| 630 |
+
available_conditions=s.conditions,
|
| 631 |
+
experiment_design=design,
|
| 632 |
+
reward=shaping_reward(self._eval_mode, 0.08),
|
| 633 |
+
metadata={"step_count": s.step_count, "validation": "valid"},
|
| 634 |
+
)
|
| 635 |
+
self._trace(
|
| 636 |
+
"understand_experiment_design",
|
| 637 |
+
{"validation": "valid", "contrast": [ref_in, alt_in]},
|
| 638 |
+
msg,
|
| 639 |
+
)
|
| 640 |
+
obs.trace_path = self._refresh_trace_file()
|
| 641 |
+
return obs
|
| 642 |
+
|
| 643 |
+
def _resolve_de_contrast(
|
| 644 |
+
self, action: PathwayAction
|
| 645 |
+
) -> tuple[Optional[str], Optional[str]]:
|
| 646 |
+
"""DESeq2 contrast: explicit action fields beat validated design, then default_contrast."""
|
| 647 |
+
dc = self._case.get("default_contrast") or {}
|
| 648 |
+
ar = (action.condition_a or "").strip()
|
| 649 |
+
ab = (action.condition_b or "").strip()
|
| 650 |
+
ref = ar or self._state.validated_reference or dc.get("reference")
|
| 651 |
+
alt = ab or self._state.validated_alternate or dc.get("alternate")
|
| 652 |
+
return ref, alt
|
| 653 |
+
|
| 654 |
+
def _step_de(self, action: PathwayAction) -> PathwayObservation:
|
| 655 |
+
s = self._state
|
| 656 |
+
if s.legacy_mode:
|
| 657 |
+
names = list(self._case.get("top_genes", []))
|
| 658 |
+
self._de_rows = _legacy_de_rows(names)
|
| 659 |
+
self._query_genes = names
|
| 660 |
+
s.de_run = True
|
| 661 |
+
self._trace("de", {"legacy": True, "genes": names}, "Legacy DE")
|
| 662 |
+
obs = PathwayObservation(
|
| 663 |
+
message="Differential expression complete (legacy fixture).",
|
| 664 |
+
top_genes=names,
|
| 665 |
+
de_genes=self._de_rows,
|
| 666 |
+
reward=shaping_reward(self._eval_mode, 0.25),
|
| 667 |
+
metadata={"step_count": s.step_count, "legacy": True},
|
| 668 |
+
)
|
| 669 |
+
obs.trace_path = self._refresh_trace_file()
|
| 670 |
+
return obs
|
| 671 |
+
|
| 672 |
+
if not pydeseq2_available():
|
| 673 |
+
if s.strict_mode:
|
| 674 |
+
return self._fail_strict(
|
| 675 |
+
"PyDESeq2 is not installed; strict mode terminates.",
|
| 676 |
+
FC.DE_PYDESeq2_UNAVAILABLE,
|
| 677 |
+
)
|
| 678 |
+
return PathwayObservation(
|
| 679 |
+
message="PyDESeq2 is not installed; cannot run DE on counts.",
|
| 680 |
+
reward=shaping_reward(self._eval_mode, -0.5),
|
| 681 |
+
metadata={
|
| 682 |
+
"error": "missing_pydeseq2",
|
| 683 |
+
"failure_code": FC.DE_PYDESeq2_UNAVAILABLE,
|
| 684 |
+
},
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
ref, alt = self._resolve_de_contrast(action)
|
| 688 |
+
if not ref or not alt:
|
| 689 |
+
msg = "Specify condition_a (reference) and condition_b (alternate) for DESeq2."
|
| 690 |
+
if s.strict_mode:
|
| 691 |
+
return self._fail_strict(msg, FC.DE_MISSING_CONTRAST)
|
| 692 |
+
return PathwayObservation(
|
| 693 |
+
message=msg,
|
| 694 |
+
reward=shaping_reward(self._eval_mode, -0.3),
|
| 695 |
+
metadata={"error": "contrast", "failure_code": FC.DE_MISSING_CONTRAST},
|
| 696 |
+
)
|
| 697 |
+
|
| 698 |
+
sample_ids = self._case["sample_ids"]
|
| 699 |
+
smd = self._case["sample_metadata"]
|
| 700 |
+
try:
|
| 701 |
+
if "de_table_file" in self._case:
|
| 702 |
+
# Author-provided DE (no counts available). We treat this as a precomputed DE run.
|
| 703 |
+
opts = merge_analysis_options(self._case)
|
| 704 |
+
de_rows = load_author_de_table_csv(
|
| 705 |
+
DATA_DIR / str(self._case["de_table_file"]),
|
| 706 |
+
gene_column=str(self._case.get("de_table_gene_column") or "Gene,name"),
|
| 707 |
+
log2fc_column=str(self._case.get("de_table_log2fc_column") or "log2FoldChange"),
|
| 708 |
+
pvalue_column=str(self._case.get("de_table_pvalue_column") or "pvalue"),
|
| 709 |
+
padj_column=str(self._case.get("de_table_padj_column") or "padj"),
|
| 710 |
+
)
|
| 711 |
+
padj_alpha = float(opts["padj_alpha"])
|
| 712 |
+
for r in de_rows:
|
| 713 |
+
try:
|
| 714 |
+
pv = float(r.get("padj"))
|
| 715 |
+
except (TypeError, ValueError):
|
| 716 |
+
pv = 1.0
|
| 717 |
+
r["significant"] = bool(pv <= padj_alpha)
|
| 718 |
+
self._de_rows = de_rows
|
| 719 |
+
self._query_genes = pick_de_query_genes(
|
| 720 |
+
de_rows,
|
| 721 |
+
padj_alpha=padj_alpha,
|
| 722 |
+
direction=str(opts["de_query_direction"]),
|
| 723 |
+
min_abs_log2fc=float(opts["min_abs_log2fc"]),
|
| 724 |
+
)
|
| 725 |
+
self._universe_genes = [] # unknown without counts
|
| 726 |
+
s.de_run = True
|
| 727 |
+
top_names = [r["gene"] for r in de_rows[:50]]
|
| 728 |
+
self._trace(
|
| 729 |
+
"de",
|
| 730 |
+
{
|
| 731 |
+
"precomputed": True,
|
| 732 |
+
"source": "author_de_table",
|
| 733 |
+
"contrast": [ref, alt],
|
| 734 |
+
"n_sig": sum(1 for r in de_rows if r.get("significant")),
|
| 735 |
+
"n_rows": len(de_rows),
|
| 736 |
+
},
|
| 737 |
+
"Differential expression loaded (author-provided table).",
|
| 738 |
+
)
|
| 739 |
+
obs = PathwayObservation(
|
| 740 |
+
message="Differential expression loaded from author table.",
|
| 741 |
+
top_genes=top_names,
|
| 742 |
+
de_genes=self._de_rows,
|
| 743 |
+
reward=shaping_reward(self._eval_mode, 0.25),
|
| 744 |
+
metadata={
|
| 745 |
+
"step_count": s.step_count,
|
| 746 |
+
"precomputed": True,
|
| 747 |
+
"source": "author_de_table",
|
| 748 |
+
},
|
| 749 |
+
)
|
| 750 |
+
obs.trace_path = self._refresh_trace_file()
|
| 751 |
+
return obs
|
| 752 |
+
|
| 753 |
+
if "counts_file" in self._case:
|
| 754 |
+
counts_df = load_counts_csv_as_samples_by_genes(
|
| 755 |
+
DATA_DIR / str(self._case["counts_file"]),
|
| 756 |
+
sample_ids=sample_ids,
|
| 757 |
+
)
|
| 758 |
+
else:
|
| 759 |
+
counts = self._case["counts"]
|
| 760 |
+
v_err = validate_counts_case(self._case)
|
| 761 |
+
if v_err:
|
| 762 |
+
raise ValueError(v_err)
|
| 763 |
+
counts_df = counts_dict_to_samples_by_genes(counts, sample_ids)
|
| 764 |
+
meta_df = build_sample_metadata(sample_ids, smd)
|
| 765 |
+
except ValueError as exc:
|
| 766 |
+
if s.strict_mode:
|
| 767 |
+
return self._fail_strict(str(exc), FC.DE_INVALID_COUNTS_MATRIX)
|
| 768 |
+
return PathwayObservation(
|
| 769 |
+
message=str(exc),
|
| 770 |
+
reward=shaping_reward(self._eval_mode, -0.5),
|
| 771 |
+
metadata={
|
| 772 |
+
"error": "counts_or_metadata_invalid",
|
| 773 |
+
"failure_code": FC.DE_INVALID_COUNTS_MATRIX,
|
| 774 |
+
},
|
| 775 |
+
)
|
| 776 |
+
|
| 777 |
+
opts = merge_analysis_options(self._case)
|
| 778 |
+
counts_df, n_genes_in, n_genes_filt = filter_counts_by_minimum_total(
|
| 779 |
+
counts_df, int(opts["min_total_count"])
|
| 780 |
+
)
|
| 781 |
+
if n_genes_filt < 5:
|
| 782 |
+
msg = (
|
| 783 |
+
f"After min_total_count={opts['min_total_count']} prefilter, "
|
| 784 |
+
f"only {n_genes_filt} genes remain (need ≥5 for stable DESeq2)."
|
| 785 |
+
)
|
| 786 |
+
if s.strict_mode:
|
| 787 |
+
return self._fail_strict(msg, FC.DE_TOO_FEW_GENES_AFTER_FILTER)
|
| 788 |
+
return PathwayObservation(
|
| 789 |
+
message=msg,
|
| 790 |
+
reward=shaping_reward(self._eval_mode, -0.5),
|
| 791 |
+
metadata={
|
| 792 |
+
"error": "too_few_genes_after_filter",
|
| 793 |
+
"failure_code": FC.DE_TOO_FEW_GENES_AFTER_FILTER,
|
| 794 |
+
},
|
| 795 |
+
)
|
| 796 |
+
|
| 797 |
+
rows, err = run_deseq2_contrast(
|
| 798 |
+
counts_df,
|
| 799 |
+
meta_df,
|
| 800 |
+
alt,
|
| 801 |
+
ref,
|
| 802 |
+
padj_alpha=float(opts["padj_alpha"]),
|
| 803 |
+
)
|
| 804 |
+
if err:
|
| 805 |
+
if s.strict_mode:
|
| 806 |
+
return self._fail_strict(err, FC.DE_DESEQ2_FAILED)
|
| 807 |
+
return PathwayObservation(
|
| 808 |
+
message=err,
|
| 809 |
+
reward=shaping_reward(self._eval_mode, -0.5),
|
| 810 |
+
metadata={"error": err, "failure_code": FC.DE_DESEQ2_FAILED},
|
| 811 |
+
)
|
| 812 |
+
|
| 813 |
+
self._universe_genes = list(counts_df.columns)
|
| 814 |
+
self._de_rows = rows
|
| 815 |
+
self._query_genes = pick_de_query_genes(
|
| 816 |
+
rows,
|
| 817 |
+
padj_alpha=float(opts["padj_alpha"]),
|
| 818 |
+
direction=str(opts["de_query_direction"]),
|
| 819 |
+
min_abs_log2fc=float(opts["min_abs_log2fc"]),
|
| 820 |
+
)
|
| 821 |
+
s.de_run = True
|
| 822 |
+
top_names = [r["gene"] for r in rows[:50]]
|
| 823 |
+
self._trace(
|
| 824 |
+
"de",
|
| 825 |
+
{
|
| 826 |
+
"contrast": [ref, alt],
|
| 827 |
+
"n_sig": sum(1 for r in rows if r["significant"]),
|
| 828 |
+
"genes_in_matrix": n_genes_in,
|
| 829 |
+
"genes_after_prefilter": n_genes_filt,
|
| 830 |
+
},
|
| 831 |
+
"DESeq2 complete",
|
| 832 |
+
)
|
| 833 |
+
obs = PathwayObservation(
|
| 834 |
+
message="Differential expression complete (PyDESeq2).",
|
| 835 |
+
top_genes=top_names,
|
| 836 |
+
de_genes=rows[:200],
|
| 837 |
+
reward=shaping_reward(self._eval_mode, 0.35),
|
| 838 |
+
metadata={
|
| 839 |
+
"step_count": s.step_count,
|
| 840 |
+
"contrast": [ref, alt],
|
| 841 |
+
"genes_in_matrix": n_genes_in,
|
| 842 |
+
"genes_after_prefilter": n_genes_filt,
|
| 843 |
+
"analysis_options": {
|
| 844 |
+
k: opts[k]
|
| 845 |
+
for k in (
|
| 846 |
+
"min_total_count",
|
| 847 |
+
"padj_alpha",
|
| 848 |
+
"de_query_direction",
|
| 849 |
+
"min_abs_log2fc",
|
| 850 |
+
)
|
| 851 |
+
},
|
| 852 |
+
},
|
| 853 |
+
)
|
| 854 |
+
obs.trace_path = self._refresh_trace_file()
|
| 855 |
+
return obs
|
| 856 |
+
|
| 857 |
+
def _step_enrichment(self, action: PathwayAction) -> PathwayObservation:
|
| 858 |
+
s = self._state
|
| 859 |
+
if self._eval_mode and action.gene_list:
|
| 860 |
+
return PathwayObservation(
|
| 861 |
+
message=(
|
| 862 |
+
"Custom gene_list is disabled in eval mode; run differential "
|
| 863 |
+
"expression and use the resulting DE gene set for ORA."
|
| 864 |
+
),
|
| 865 |
+
reward=shaping_reward(self._eval_mode, -0.2),
|
| 866 |
+
metadata={"failure_code": FC.ORA_GENE_LIST_BLOCKED},
|
| 867 |
+
)
|
| 868 |
+
if not self._de_rows and not s.legacy_mode:
|
| 869 |
+
msg = "Run differential expression before enrichment."
|
| 870 |
+
return PathwayObservation(
|
| 871 |
+
message=msg,
|
| 872 |
+
reward=shaping_reward(self._eval_mode, -0.2),
|
| 873 |
+
metadata={"failure_code": FC.ORA_DE_PREREQUISITE},
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
pathways = self._case.get("pathway_genes") or {}
|
| 877 |
+
if s.legacy_mode:
|
| 878 |
+
names = list(self._case.get("top_pathways", []))
|
| 879 |
+
s.enrichment_run = True
|
| 880 |
+
fake = [
|
| 881 |
+
{
|
| 882 |
+
"pathway": n,
|
| 883 |
+
"p_value": 0.001,
|
| 884 |
+
"q_value": 0.01,
|
| 885 |
+
"overlap_genes": list(self._case.get("top_genes", []))[:2],
|
| 886 |
+
"overlap_count": 2,
|
| 887 |
+
"pathway_size": 10,
|
| 888 |
+
"de_in_universe": len(self._query_genes),
|
| 889 |
+
"gene_ratio": "2/10",
|
| 890 |
+
}
|
| 891 |
+
for n in names
|
| 892 |
+
]
|
| 893 |
+
self._ora_rows = fake
|
| 894 |
+
amb = top_hits_statistically_close(fake)
|
| 895 |
+
ov = overlap_genes_across_top_pathways(fake)
|
| 896 |
+
self._trace("ora", {"legacy": True}, "Legacy ORA")
|
| 897 |
+
obs = PathwayObservation(
|
| 898 |
+
message="Pathway enrichment complete (legacy fixture).",
|
| 899 |
+
top_pathways=names,
|
| 900 |
+
pathway_enrichment=fake,
|
| 901 |
+
statistical_ambiguity=amb,
|
| 902 |
+
overlap_summary=ov,
|
| 903 |
+
reward=shaping_reward(self._eval_mode, 0.45),
|
| 904 |
+
metadata={"legacy": True},
|
| 905 |
+
)
|
| 906 |
+
obs.trace_path = self._refresh_trace_file()
|
| 907 |
+
return obs
|
| 908 |
+
|
| 909 |
+
opts = merge_analysis_options(self._case)
|
| 910 |
+
universe = self._universe_genes
|
| 911 |
+
if not universe:
|
| 912 |
+
if "counts" in self._case:
|
| 913 |
+
universe = list(self._case["counts"].keys())
|
| 914 |
+
else:
|
| 915 |
+
universe = []
|
| 916 |
+
query = action.gene_list if action.gene_list else self._query_genes
|
| 917 |
+
if not query:
|
| 918 |
+
query = pick_de_query_genes(
|
| 919 |
+
self._de_rows,
|
| 920 |
+
padj_alpha=float(opts["padj_alpha"]),
|
| 921 |
+
direction=str(opts["de_query_direction"]),
|
| 922 |
+
min_abs_log2fc=float(opts["min_abs_log2fc"]),
|
| 923 |
+
)
|
| 924 |
+
if not query and self._de_rows:
|
| 925 |
+
query = [r["gene"] for r in self._de_rows[:50]]
|
| 926 |
+
|
| 927 |
+
enrichr_libs = self._case.get("enrichr_libraries")
|
| 928 |
+
if enrichr_libs:
|
| 929 |
+
if not gseapy_available():
|
| 930 |
+
msg = "gseapy not installed; cannot run Enrichr enrichment."
|
| 931 |
+
if s.strict_mode:
|
| 932 |
+
return self._fail_strict(msg, FC.ORA_NO_PATHWAY_DEFINITIONS)
|
| 933 |
+
return PathwayObservation(
|
| 934 |
+
message=msg,
|
| 935 |
+
reward=shaping_reward(self._eval_mode, -0.3),
|
| 936 |
+
metadata={
|
| 937 |
+
"error": "missing_gseapy",
|
| 938 |
+
"failure_code": FC.ORA_NO_PATHWAY_DEFINITIONS,
|
| 939 |
+
},
|
| 940 |
+
)
|
| 941 |
+
ora, err = enrichr_ora(
|
| 942 |
+
query,
|
| 943 |
+
libraries=list(enrichr_libs),
|
| 944 |
+
background=universe or None,
|
| 945 |
+
top_k=100,
|
| 946 |
+
)
|
| 947 |
+
if err:
|
| 948 |
+
if s.strict_mode:
|
| 949 |
+
return self._fail_strict(err, FC.ORA_NO_PATHWAY_DEFINITIONS)
|
| 950 |
+
return PathwayObservation(
|
| 951 |
+
message=err,
|
| 952 |
+
reward=shaping_reward(self._eval_mode, -0.3),
|
| 953 |
+
metadata={
|
| 954 |
+
"error": "enrichr_failed",
|
| 955 |
+
"failure_code": FC.ORA_NO_PATHWAY_DEFINITIONS,
|
| 956 |
+
},
|
| 957 |
+
)
|
| 958 |
+
else:
|
| 959 |
+
if not pathways:
|
| 960 |
+
msg = "Case has no pathway_genes (and no enrichr_libraries); cannot run ORA."
|
| 961 |
+
if s.strict_mode:
|
| 962 |
+
return self._fail_strict(msg, FC.ORA_NO_PATHWAY_DEFINITIONS)
|
| 963 |
+
return PathwayObservation(
|
| 964 |
+
message=msg,
|
| 965 |
+
reward=shaping_reward(self._eval_mode, -0.3),
|
| 966 |
+
metadata={
|
| 967 |
+
"error": "no_pathways",
|
| 968 |
+
"failure_code": FC.ORA_NO_PATHWAY_DEFINITIONS,
|
| 969 |
+
},
|
| 970 |
+
)
|
| 971 |
+
ora = ora_fisher(
|
| 972 |
+
query,
|
| 973 |
+
pathways,
|
| 974 |
+
universe,
|
| 975 |
+
min_pathway_genes=int(opts["ora_min_pathway_genes"]),
|
| 976 |
+
)
|
| 977 |
+
self._ora_rows = ora
|
| 978 |
+
s.enrichment_run = True
|
| 979 |
+
top_names = [r["pathway"] for r in ora[:20]]
|
| 980 |
+
amb = top_hits_statistically_close(ora)
|
| 981 |
+
ov = overlap_genes_across_top_pathways(ora)
|
| 982 |
+
self._trace("ora", {"n_pathways": len(ora)}, "ORA complete")
|
| 983 |
+
obs = PathwayObservation(
|
| 984 |
+
message="Over-representation analysis complete.",
|
| 985 |
+
top_pathways=top_names,
|
| 986 |
+
pathway_enrichment=ora[:50],
|
| 987 |
+
statistical_ambiguity=amb,
|
| 988 |
+
overlap_summary=ov,
|
| 989 |
+
reward=shaping_reward(self._eval_mode, 0.5),
|
| 990 |
+
metadata={
|
| 991 |
+
"query_genes": len(query),
|
| 992 |
+
"ora_universe_size": len(universe),
|
| 993 |
+
"ora_min_pathway_genes": int(opts["ora_min_pathway_genes"]),
|
| 994 |
+
},
|
| 995 |
+
)
|
| 996 |
+
obs.trace_path = self._refresh_trace_file()
|
| 997 |
+
return obs
|
| 998 |
+
|
| 999 |
+
def _step_compare(self, action: PathwayAction) -> PathwayObservation:
|
| 1000 |
+
s = self._state
|
| 1001 |
+
if self._eval_mode and not s.enrichment_run:
|
| 1002 |
+
return PathwayObservation(
|
| 1003 |
+
message="Run pathway enrichment before compare_pathways.",
|
| 1004 |
+
reward=shaping_reward(self._eval_mode, -0.1),
|
| 1005 |
+
metadata={"failure_code": FC.COMPARE_REQUIRES_ORA},
|
| 1006 |
+
)
|
| 1007 |
+
a = (action.pathway_a or "").strip()
|
| 1008 |
+
b = (action.pathway_b or "").strip()
|
| 1009 |
+
if not a or not b:
|
| 1010 |
+
return PathwayObservation(
|
| 1011 |
+
message="Provide pathway_a and pathway_b.",
|
| 1012 |
+
reward=shaping_reward(self._eval_mode, -0.1),
|
| 1013 |
+
metadata={
|
| 1014 |
+
"error": "missing_names",
|
| 1015 |
+
"failure_code": FC.COMPARE_MISSING_PATHWAY_NAMES,
|
| 1016 |
+
},
|
| 1017 |
+
)
|
| 1018 |
+
pathways = self._case.get("pathway_genes") or {}
|
| 1019 |
+
if s.legacy_mode:
|
| 1020 |
+
# infer dummy pathways from top_pathways list
|
| 1021 |
+
pathways = {
|
| 1022 |
+
p: self._case.get("top_genes", [])
|
| 1023 |
+
for p in self._case.get("top_pathways", [])
|
| 1024 |
+
}
|
| 1025 |
+
detail = compare_pathways_detail(
|
| 1026 |
+
a, b, pathways, self._query_genes or list(self._case.get("top_genes", []))
|
| 1027 |
+
)
|
| 1028 |
+
self._trace("compare_pathways", detail, f"Compared {a} vs {b}")
|
| 1029 |
+
obs = PathwayObservation(
|
| 1030 |
+
message=f"Pathway comparison: {a} vs {b}.",
|
| 1031 |
+
pathway_comparison=detail,
|
| 1032 |
+
reward=shaping_reward(self._eval_mode, 0.15),
|
| 1033 |
+
metadata={"step_count": s.step_count},
|
| 1034 |
+
)
|
| 1035 |
+
obs.trace_path = self._refresh_trace_file()
|
| 1036 |
+
return obs
|
| 1037 |
+
|
| 1038 |
+
def _step_submit(self, action: PathwayAction) -> PathwayObservation:
|
| 1039 |
+
s = self._state
|
| 1040 |
+
hypothesis = (action.hypothesis or "").strip()
|
| 1041 |
+
if not hypothesis:
|
| 1042 |
+
return PathwayObservation(
|
| 1043 |
+
message="Provide a non-empty pathway hypothesis.",
|
| 1044 |
+
reward=shaping_reward(self._eval_mode, -0.1),
|
| 1045 |
+
metadata={"failure_code": FC.SUBMIT_EMPTY_HYPOTHESIS},
|
| 1046 |
+
)
|
| 1047 |
+
if self._eval_mode:
|
| 1048 |
+
if not s.de_run:
|
| 1049 |
+
return PathwayObservation(
|
| 1050 |
+
message="Run differential expression before submitting.",
|
| 1051 |
+
reward=0.0,
|
| 1052 |
+
metadata={"failure_code": FC.SUBMIT_PREREQUISITE_DE},
|
| 1053 |
+
)
|
| 1054 |
+
if not s.enrichment_run:
|
| 1055 |
+
return PathwayObservation(
|
| 1056 |
+
message="Run pathway enrichment before submitting.",
|
| 1057 |
+
reward=0.0,
|
| 1058 |
+
metadata={"failure_code": FC.SUBMIT_PREREQUISITE_ORA},
|
| 1059 |
+
)
|
| 1060 |
+
|
| 1061 |
+
top_ora = [r.get("pathway", "") for r in self._ora_rows[:20] if r.get("pathway")]
|
| 1062 |
+
outcome = score_submission(
|
| 1063 |
+
hypothesis,
|
| 1064 |
+
true_pathway=self._true_pathway,
|
| 1065 |
+
expected_keywords=self._expected_keywords,
|
| 1066 |
+
pathway_gene_set_names=list((self._case.get("pathway_genes") or {}).keys()),
|
| 1067 |
+
true_pathway_aliases=self._true_pathway_aliases,
|
| 1068 |
+
top_ora_pathways=top_ora,
|
| 1069 |
+
)
|
| 1070 |
+
correct = bool(outcome.get("correct"))
|
| 1071 |
+
self._episode_outcome = {
|
| 1072 |
+
**outcome,
|
| 1073 |
+
"hypothesis": hypothesis,
|
| 1074 |
+
"step_count": s.step_count,
|
| 1075 |
+
"case_id": self._case.get("case_id"),
|
| 1076 |
+
}
|
| 1077 |
+
s.is_done = True
|
| 1078 |
+
self._trace(
|
| 1079 |
+
"submit",
|
| 1080 |
+
{
|
| 1081 |
+
"hypothesis": hypothesis,
|
| 1082 |
+
"correct": correct,
|
| 1083 |
+
"match_mode": outcome.get("match_mode"),
|
| 1084 |
+
},
|
| 1085 |
+
"Episode end",
|
| 1086 |
+
)
|
| 1087 |
+
meta: Dict[str, Any] = {
|
| 1088 |
+
"correct": correct,
|
| 1089 |
+
"episode_score": outcome,
|
| 1090 |
+
"step_count": s.step_count,
|
| 1091 |
+
}
|
| 1092 |
+
if not correct:
|
| 1093 |
+
meta["failure_code"] = FC.SUBMIT_INCORRECT_HYPOTHESIS
|
| 1094 |
+
nominal_reward = 2.0 if correct else -1.0
|
| 1095 |
+
obs = PathwayObservation(
|
| 1096 |
+
message=(
|
| 1097 |
+
"Answer submitted. Episode complete."
|
| 1098 |
+
if self._eval_mode
|
| 1099 |
+
else ("Correct pathway." if correct else "Incorrect pathway.")
|
| 1100 |
+
),
|
| 1101 |
+
done=True,
|
| 1102 |
+
reward=shaping_reward(self._eval_mode, nominal_reward)
|
| 1103 |
+
if not self._eval_mode
|
| 1104 |
+
else 0.0,
|
| 1105 |
+
metadata=meta,
|
| 1106 |
+
)
|
| 1107 |
+
obs.trace_path = self._refresh_trace_file()
|
| 1108 |
+
return obs
|
| 1109 |
+
|
| 1110 |
+
@property
|
| 1111 |
+
def state(self) -> PathwayState:
|
| 1112 |
+
return self._state
|
envs/pathway_analysis_env/server/scoring.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Ground-truth scoring for pathway submissions (orchestrator-only)."""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
from typing import Any, Dict, List, Optional, Sequence
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def normalize_label(text: str) -> str:
|
| 16 |
+
"""Lowercase alphanumeric tokens for fuzzy pathway / keyword matching."""
|
| 17 |
+
s = (text or "").strip().lower()
|
| 18 |
+
s = re.sub(r"[_\-/]+", " ", s)
|
| 19 |
+
s = re.sub(r"[^a-z0-9\s]+", " ", s)
|
| 20 |
+
return " ".join(s.split())
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def is_unknown_ground_truth(true_pathway: str) -> bool:
|
| 24 |
+
t = normalize_label(true_pathway)
|
| 25 |
+
return not t or t.startswith("unknown")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _token_set(text: str) -> set[str]:
|
| 29 |
+
return {t for t in normalize_label(text).split() if len(t) > 2}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def labels_match(a: str, b: str) -> bool:
|
| 33 |
+
na, nb = normalize_label(a), normalize_label(b)
|
| 34 |
+
if not na or not nb:
|
| 35 |
+
return False
|
| 36 |
+
if na == nb:
|
| 37 |
+
return True
|
| 38 |
+
if na in nb or nb in na:
|
| 39 |
+
return True
|
| 40 |
+
ta, tb = _token_set(a), _token_set(b)
|
| 41 |
+
if not ta or not tb:
|
| 42 |
+
return False
|
| 43 |
+
overlap = len(ta & tb) / min(len(ta), len(tb))
|
| 44 |
+
return overlap >= 0.6
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def keyword_hits(text: str, keywords: Sequence[str]) -> List[str]:
|
| 48 |
+
joined = normalize_label(text)
|
| 49 |
+
hits: List[str] = []
|
| 50 |
+
for kw in keywords:
|
| 51 |
+
k = normalize_label(kw)
|
| 52 |
+
if k and k in joined:
|
| 53 |
+
hits.append(kw)
|
| 54 |
+
return hits
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# Base score awarded for a correct keyword-rubric (GEO) identification. The
|
| 58 |
+
# remaining ``1 - KEYWORD_BASE_SCORE`` is distributed by how many expected
|
| 59 |
+
# keywords the hypothesis hits. This keeps a correct GEO answer on a scale
|
| 60 |
+
# comparable to a correct exact-label answer (1.0) instead of collapsing to a
|
| 61 |
+
# small fraction such as 1/5 = 0.2, which otherwise biases leaderboards and
|
| 62 |
+
# RL advantage estimates across heterogeneous cases.
|
| 63 |
+
KEYWORD_BASE_SCORE = 0.7
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def score_submission(
|
| 67 |
+
hypothesis: str,
|
| 68 |
+
*,
|
| 69 |
+
true_pathway: str,
|
| 70 |
+
expected_keywords: Optional[Sequence[str]] = None,
|
| 71 |
+
pathway_gene_set_names: Optional[Sequence[str]] = None,
|
| 72 |
+
true_pathway_aliases: Optional[Sequence[str]] = None,
|
| 73 |
+
top_ora_pathways: Optional[Sequence[str]] = None,
|
| 74 |
+
) -> Dict[str, Any]:
|
| 75 |
+
"""
|
| 76 |
+
Score a submitted pathway hypothesis without exposing labels to agents.
|
| 77 |
+
|
| 78 |
+
Returns dict with ``correct``, ``score`` (0–1), ``match_mode``, and details.
|
| 79 |
+
|
| 80 |
+
Scoring is intentionally strict about *which* label earns full credit:
|
| 81 |
+
|
| 82 |
+
* With a known ``true_pathway``, only that label (and any explicit
|
| 83 |
+
``true_pathway_aliases``) scores 1.0. Distractor pathways present in the
|
| 84 |
+
case (``pathway_gene_set_names``) and arbitrary top ORA hits do NOT earn
|
| 85 |
+
credit — naming a distractor that happens to be defined in the case is a
|
| 86 |
+
reward-hacking surface, not a correct answer.
|
| 87 |
+
* With keyword rubrics (GEO / theme-based cases), any keyword hit is
|
| 88 |
+
correct, scored on a normalized scale (see ``KEYWORD_BASE_SCORE``).
|
| 89 |
+
* Only when ground truth is genuinely unknown is the top ORA hit accepted.
|
| 90 |
+
|
| 91 |
+
``pathway_gene_set_names`` is retained for telemetry/back-compat but no
|
| 92 |
+
longer grants credit on its own.
|
| 93 |
+
"""
|
| 94 |
+
hyp = (hypothesis or "").strip()
|
| 95 |
+
if not hyp:
|
| 96 |
+
return {
|
| 97 |
+
"correct": False,
|
| 98 |
+
"score": 0.0,
|
| 99 |
+
"match_mode": "empty_hypothesis",
|
| 100 |
+
"matched_label": None,
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
keywords = list(expected_keywords or [])
|
| 104 |
+
ora_names = list(top_ora_pathways or [])
|
| 105 |
+
|
| 106 |
+
# Keyword rubric (GEO / theme-based cases).
|
| 107 |
+
if keywords:
|
| 108 |
+
hits = keyword_hits(hyp, keywords)
|
| 109 |
+
if hits:
|
| 110 |
+
extra_fraction = len(hits) / max(1, len(keywords))
|
| 111 |
+
score = KEYWORD_BASE_SCORE + (1.0 - KEYWORD_BASE_SCORE) * extra_fraction
|
| 112 |
+
return {
|
| 113 |
+
"correct": True,
|
| 114 |
+
"score": round(min(1.0, score), 4),
|
| 115 |
+
"match_mode": "expected_keywords",
|
| 116 |
+
"matched_label": hits[0],
|
| 117 |
+
"keyword_hits": hits,
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
# Known ground truth: credit only the true pathway (and explicit aliases).
|
| 121 |
+
if not is_unknown_ground_truth(true_pathway):
|
| 122 |
+
candidates = [true_pathway, *(true_pathway_aliases or [])]
|
| 123 |
+
seen: set[str] = set()
|
| 124 |
+
for label in candidates:
|
| 125 |
+
key = normalize_label(label)
|
| 126 |
+
if not key or key in seen:
|
| 127 |
+
continue
|
| 128 |
+
seen.add(key)
|
| 129 |
+
if labels_match(hyp, label):
|
| 130 |
+
return {
|
| 131 |
+
"correct": True,
|
| 132 |
+
"score": 1.0,
|
| 133 |
+
"match_mode": "pathway_label",
|
| 134 |
+
"matched_label": label,
|
| 135 |
+
}
|
| 136 |
+
# Known truth but no match: incorrect. Do not credit distractor
|
| 137 |
+
# pathways or top ORA hits.
|
| 138 |
+
return {
|
| 139 |
+
"correct": False,
|
| 140 |
+
"score": 0.0,
|
| 141 |
+
"match_mode": "no_match",
|
| 142 |
+
"matched_label": None,
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
# Unknown ground truth: accept top ORA hit if agent names it exactly.
|
| 146 |
+
if ora_names and labels_match(hyp, ora_names[0]):
|
| 147 |
+
return {
|
| 148 |
+
"correct": True,
|
| 149 |
+
"score": 0.85,
|
| 150 |
+
"match_mode": "top_ora_pathway",
|
| 151 |
+
"matched_label": ora_names[0],
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
return {
|
| 155 |
+
"correct": False,
|
| 156 |
+
"score": 0.0,
|
| 157 |
+
"match_mode": "no_match",
|
| 158 |
+
"matched_label": None,
|
| 159 |
+
}
|
examples/pathway_agent_loop.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 3 |
+
# All rights reserved.
|
| 4 |
+
#
|
| 5 |
+
# OpenAI tool-calling agent for pathway_analysis_env (in-process orchestrator).
|
| 6 |
+
#
|
| 7 |
+
# Usage:
|
| 8 |
+
# export OPENAI_API_KEY=...
|
| 9 |
+
# PYTHONPATH=src:envs uv run python examples/pathway_agent_loop.py \
|
| 10 |
+
# --case toy_case_001.json
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import asyncio
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
from pathway_analysis_env.agent_openai_tools import (
|
| 21 |
+
OPENAI_TOOLS,
|
| 22 |
+
observation_to_tool_result_content,
|
| 23 |
+
tool_call_to_pathway_action,
|
| 24 |
+
)
|
| 25 |
+
from pathway_analysis_env.models import PathwayAction
|
| 26 |
+
from pathway_analysis_env.server.pathway_environment import PathwayEnvironment
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
SYSTEM_PROMPT = """You are a computational biologist agent operating a pathway analysis environment.
|
| 30 |
+
|
| 31 |
+
Required workflow (eval mode):
|
| 32 |
+
1. understand_experiment_design and/or inspect_dataset — learn groups and sample layout.
|
| 33 |
+
2. run_differential_expression — set reference (baseline) vs alternate (treatment) conditions.
|
| 34 |
+
3. run_pathway_enrichment — ORA on DE genes (do not pass a custom gene_list).
|
| 35 |
+
4. Optionally compare_pathways between two top pathway names.
|
| 36 |
+
5. submit_answer — one pathway hypothesis string supported by ORA.
|
| 37 |
+
|
| 38 |
+
Rules:
|
| 39 |
+
- Never guess without running DE and ORA first.
|
| 40 |
+
- Use condition names exactly as returned in available_conditions.
|
| 41 |
+
- For submit_answer, name a specific pathway (e.g. from top_pathways), not a long essay.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
async def run_episode(
|
| 46 |
+
case_file: str,
|
| 47 |
+
model: str,
|
| 48 |
+
max_turns: int,
|
| 49 |
+
*,
|
| 50 |
+
strict: bool,
|
| 51 |
+
) -> dict:
|
| 52 |
+
try:
|
| 53 |
+
from openai import AsyncOpenAI
|
| 54 |
+
except ImportError as exc:
|
| 55 |
+
raise SystemExit("Install openai: uv add openai") from exc
|
| 56 |
+
|
| 57 |
+
if not os.environ.get("OPENAI_API_KEY"):
|
| 58 |
+
print("Warning: OPENAI_API_KEY not set", file=sys.stderr)
|
| 59 |
+
|
| 60 |
+
client = AsyncOpenAI()
|
| 61 |
+
env = PathwayEnvironment(case_file=case_file)
|
| 62 |
+
obs = env.reset(orchestrator_mode=True, strict=strict)
|
| 63 |
+
messages = [
|
| 64 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 65 |
+
{
|
| 66 |
+
"role": "user",
|
| 67 |
+
"content": (
|
| 68 |
+
f"Episode started for case {case_file}. "
|
| 69 |
+
f"Conditions: {obs.available_conditions}. "
|
| 70 |
+
f"{obs.message}"
|
| 71 |
+
),
|
| 72 |
+
},
|
| 73 |
+
]
|
| 74 |
+
|
| 75 |
+
for turn in range(max_turns):
|
| 76 |
+
response = await client.chat.completions.create(
|
| 77 |
+
model=model,
|
| 78 |
+
messages=messages,
|
| 79 |
+
tools=OPENAI_TOOLS,
|
| 80 |
+
tool_choice="auto",
|
| 81 |
+
)
|
| 82 |
+
msg = response.choices[0].message
|
| 83 |
+
if not msg.tool_calls:
|
| 84 |
+
messages.append({"role": "assistant", "content": msg.content or ""})
|
| 85 |
+
if env.state.is_done:
|
| 86 |
+
break
|
| 87 |
+
continue
|
| 88 |
+
|
| 89 |
+
messages.append(msg.model_dump())
|
| 90 |
+
for tc in msg.tool_calls:
|
| 91 |
+
action = tool_call_to_pathway_action(
|
| 92 |
+
name=tc.function.name,
|
| 93 |
+
arguments_json=tc.function.arguments,
|
| 94 |
+
)
|
| 95 |
+
step_obs = env.step(action)
|
| 96 |
+
messages.append(
|
| 97 |
+
{
|
| 98 |
+
"role": "tool",
|
| 99 |
+
"tool_call_id": tc.id,
|
| 100 |
+
"content": observation_to_tool_result_content(step_obs),
|
| 101 |
+
}
|
| 102 |
+
)
|
| 103 |
+
if step_obs.done:
|
| 104 |
+
return {
|
| 105 |
+
"turns": turn + 1,
|
| 106 |
+
"done": True,
|
| 107 |
+
"episode_outcome": env.episode_outcome,
|
| 108 |
+
"last_message": step_obs.message,
|
| 109 |
+
"steps": env.state.step_count,
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
return {
|
| 113 |
+
"turns": max_turns,
|
| 114 |
+
"done": env.state.is_done,
|
| 115 |
+
"episode_outcome": env.episode_outcome,
|
| 116 |
+
"steps": env.state.step_count,
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def main() -> None:
|
| 121 |
+
parser = argparse.ArgumentParser(description="LLM agent on pathway_analysis_env")
|
| 122 |
+
parser.add_argument("--case", default="toy_case_001.json")
|
| 123 |
+
parser.add_argument("--model", default="gpt-4o-mini")
|
| 124 |
+
parser.add_argument("--max-turns", type=int, default=24)
|
| 125 |
+
parser.add_argument("--strict", action="store_true")
|
| 126 |
+
args = parser.parse_args()
|
| 127 |
+
result = asyncio.run(
|
| 128 |
+
run_episode(args.case, args.model, args.max_turns, strict=args.strict)
|
| 129 |
+
)
|
| 130 |
+
print(json.dumps(result, indent=2))
|
| 131 |
+
outcome = result.get("episode_outcome") or {}
|
| 132 |
+
if outcome.get("correct"):
|
| 133 |
+
sys.exit(0)
|
| 134 |
+
sys.exit(1 if result.get("done") else 2)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
main()
|
tests/envs/test_pathway_agent_tools.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
|
| 6 |
+
from pathway_analysis_env.agent_openai_tools import (
|
| 7 |
+
observation_to_tool_result_content,
|
| 8 |
+
tool_call_to_pathway_action,
|
| 9 |
+
truncate_observation_payload,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_tool_call_with_null_arguments_does_not_crash():
|
| 14 |
+
"""Models sometimes emit the JSON literal ``null`` for tool arguments.
|
| 15 |
+
|
| 16 |
+
``json.loads("null")`` returns ``None``; the mapper must treat that as
|
| 17 |
+
empty args instead of raising ``AttributeError`` on ``args.get(...)``.
|
| 18 |
+
"""
|
| 19 |
+
action = tool_call_to_pathway_action(
|
| 20 |
+
name="run_differential_expression", arguments_json="null"
|
| 21 |
+
)
|
| 22 |
+
assert action.action_type == "run_differential_expression"
|
| 23 |
+
assert action.condition_a is None
|
| 24 |
+
assert action.condition_b is None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_tool_call_with_empty_arguments():
|
| 28 |
+
action = tool_call_to_pathway_action(name="inspect_dataset", arguments_json="")
|
| 29 |
+
assert action.action_type == "inspect_dataset"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_tool_call_with_mapping_arguments():
|
| 33 |
+
action = tool_call_to_pathway_action(
|
| 34 |
+
name="submit_answer", arguments_json={"hypothesis": "MAPK signaling"}
|
| 35 |
+
)
|
| 36 |
+
assert action.action_type == "submit_answer"
|
| 37 |
+
assert action.hypothesis == "MAPK signaling"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_tool_call_normal_json_arguments():
|
| 41 |
+
action = tool_call_to_pathway_action(
|
| 42 |
+
name="run_differential_expression",
|
| 43 |
+
arguments_json='{"condition_a": "control", "condition_b": "treated"}',
|
| 44 |
+
)
|
| 45 |
+
assert action.condition_a == "control"
|
| 46 |
+
assert action.condition_b == "treated"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_truncate_observation_payload_caps_long_lists():
|
| 50 |
+
payload = {
|
| 51 |
+
"message": "ok",
|
| 52 |
+
"de_genes": [{"gene": f"G{i}"} for i in range(100)],
|
| 53 |
+
"pathway_enrichment": [{"pathway": f"P{i}"} for i in range(50)],
|
| 54 |
+
"trace_path": "/tmp/some/local/trace.html",
|
| 55 |
+
}
|
| 56 |
+
out = truncate_observation_payload(payload)
|
| 57 |
+
assert len(out["de_genes"]) == 30
|
| 58 |
+
assert len(out["pathway_enrichment"]) == 20
|
| 59 |
+
assert "trace_path" not in out
|
| 60 |
+
assert "_truncation_note" in out
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_truncate_observation_payload_keeps_short_lists():
|
| 64 |
+
payload = {"de_genes": [{"gene": "G1"}], "message": "ok"}
|
| 65 |
+
out = truncate_observation_payload(payload)
|
| 66 |
+
assert len(out["de_genes"]) == 1
|
| 67 |
+
assert "_truncation_note" not in out
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def test_observation_serialization_truncates_by_default():
|
| 71 |
+
payload = {"de_genes": [{"gene": f"G{i}"} for i in range(100)], "message": "ok"}
|
| 72 |
+
serialized = observation_to_tool_result_content(payload)
|
| 73 |
+
restored = json.loads(serialized)
|
| 74 |
+
assert len(restored["de_genes"]) == 30
|
| 75 |
+
|
| 76 |
+
full = observation_to_tool_result_content(payload, truncate=False)
|
| 77 |
+
assert len(json.loads(full)["de_genes"]) == 100
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
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# This source code is licensed under the BSD-style license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
"""Tests for pathway_analysis_env (DE, ORA, compare, expert, trace)."""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
|
| 13 |
+
import pytest
|
| 14 |
+
|
| 15 |
+
from pathway_analysis_env.models import PathwayAction
|
| 16 |
+
from pathway_analysis_env.server.analysis import (
|
| 17 |
+
adjust_pvalues_bh,
|
| 18 |
+
build_sample_metadata,
|
| 19 |
+
ora_fisher,
|
| 20 |
+
overlap_genes_across_top_pathways,
|
| 21 |
+
pydeseq2_available,
|
| 22 |
+
run_deseq2_contrast,
|
| 23 |
+
validate_counts_case,
|
| 24 |
+
)
|
| 25 |
+
from pathway_analysis_env.server.pathway_environment import (
|
| 26 |
+
DATA_DIR,
|
| 27 |
+
PathwayEnvironment,
|
| 28 |
+
load_case,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
requires_pydeseq2 = pytest.mark.skipif(
|
| 32 |
+
not pydeseq2_available(),
|
| 33 |
+
reason="PyDESeq2 required for pathway pipeline tests",
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_set_case_file():
|
| 38 |
+
env = PathwayEnvironment(case_file="toy_case_001.json")
|
| 39 |
+
env.set_case_file("toy_case_legacy.json")
|
| 40 |
+
assert env._case_file == "toy_case_legacy.json"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_load_pipeline_case():
|
| 44 |
+
case = load_case("toy_case_001.json")
|
| 45 |
+
assert "counts" in case
|
| 46 |
+
assert "pathway_genes" in case
|
| 47 |
+
assert case["true_pathway"] == "MAPK signaling"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def test_load_gse235417_case_is_pipeline_mode():
|
| 51 |
+
case = load_case("gse235417_case.json")
|
| 52 |
+
assert "counts_file" in case
|
| 53 |
+
assert "sample_ids" in case
|
| 54 |
+
assert "sample_metadata" in case
|
| 55 |
+
assert case["default_contrast"]["reference"] == "baseline"
|
| 56 |
+
assert case["default_contrast"]["alternate"] == "resistant"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@requires_pydeseq2
|
| 60 |
+
def test_deseq2_mapk_case():
|
| 61 |
+
case = json.loads((DATA_DIR / "toy_case_001.json").read_text(encoding="utf-8"))
|
| 62 |
+
from pathway_analysis_env.server.analysis import (
|
| 63 |
+
build_sample_metadata,
|
| 64 |
+
counts_dict_to_samples_by_genes,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
cdf = counts_dict_to_samples_by_genes(case["counts"], case["sample_ids"])
|
| 68 |
+
meta = build_sample_metadata(case["sample_ids"], case["sample_metadata"])
|
| 69 |
+
rows, err = run_deseq2_contrast(
|
| 70 |
+
cdf,
|
| 71 |
+
meta,
|
| 72 |
+
case["default_contrast"]["alternate"],
|
| 73 |
+
case["default_contrast"]["reference"],
|
| 74 |
+
)
|
| 75 |
+
assert err is None
|
| 76 |
+
top = [r["gene"] for r in rows[:5]]
|
| 77 |
+
assert "DUSP6" in top or "FOS" in top
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def test_ora_fisher_structure():
|
| 81 |
+
universe = ["A", "B", "C", "D", "E", "F"]
|
| 82 |
+
pathways = {"P1": ["A", "B", "C"], "P2": ["C", "D"]}
|
| 83 |
+
de = ["A", "B", "C"]
|
| 84 |
+
ora = ora_fisher(de, pathways, universe, min_pathway_genes=2)
|
| 85 |
+
assert len(ora) == 2
|
| 86 |
+
assert ora[0]["pathway"] in ("P1", "P2")
|
| 87 |
+
assert "q_value" in ora[0]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def test_adjust_pvalues_bh_matches_scipy():
|
| 91 |
+
ps = [0.01, 0.05, 0.1]
|
| 92 |
+
q = adjust_pvalues_bh(ps)
|
| 93 |
+
assert len(q) == 3
|
| 94 |
+
assert all(0.0 <= x <= 1.0 for x in q)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def test_validate_counts_case():
|
| 98 |
+
assert validate_counts_case({}) is None
|
| 99 |
+
bad = {
|
| 100 |
+
"counts": {"G1": [1, 2], "G2": [1]},
|
| 101 |
+
"sample_ids": ["a", "b"],
|
| 102 |
+
}
|
| 103 |
+
assert validate_counts_case(bad) is not None
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_build_sample_metadata_missing_sample():
|
| 107 |
+
with pytest.raises(ValueError, match="missing"):
|
| 108 |
+
build_sample_metadata(["S1", "S2"], {"S1": "a"})
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def test_understand_experiment_design_summary():
|
| 112 |
+
env = PathwayEnvironment(case_file="toy_case_001.json")
|
| 113 |
+
env.reset()
|
| 114 |
+
obs = env.step(PathwayAction(action_type="understand_experiment_design"))
|
| 115 |
+
assert obs.experiment_design
|
| 116 |
+
assert obs.experiment_design.get("samples_per_condition")
|
| 117 |
+
assert env.state.design_understood is True
|
| 118 |
+
assert env.state.validated_reference is None
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def test_understand_experiment_design_legacy_graceful():
|
| 122 |
+
env = PathwayEnvironment(case_file="toy_case_legacy.json")
|
| 123 |
+
env.reset()
|
| 124 |
+
obs = env.step(PathwayAction(action_type="understand_experiment_design"))
|
| 125 |
+
design = obs.experiment_design or {}
|
| 126 |
+
assert design.get("legacy_mode") is True
|
| 127 |
+
assert design.get("sample_level_metadata_available") is False
|
| 128 |
+
assert design.get("samples_per_condition") is None
|
| 129 |
+
assert design.get("conditions") == ["control", "treated"]
|
| 130 |
+
assert "legacy" in obs.message.lower()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_inspect_dataset_legacy_graceful():
|
| 134 |
+
env = PathwayEnvironment(case_file="toy_case_legacy.json")
|
| 135 |
+
env.reset()
|
| 136 |
+
obs = env.step(PathwayAction(action_type="inspect_dataset"))
|
| 137 |
+
meta = obs.metadata or {}
|
| 138 |
+
assert meta.get("legacy_mode") is True
|
| 139 |
+
assert meta.get("sample_level_metadata_available") is False
|
| 140 |
+
assert meta.get("sample_ids") == []
|
| 141 |
+
assert "static_top_genes" not in meta
|
| 142 |
+
assert "static_top_pathways" not in meta
|
| 143 |
+
assert "legacy" in obs.message.lower()
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def test_inspect_legacy_debug_mode_shows_static_lists():
|
| 147 |
+
env = PathwayEnvironment(case_file="toy_case_legacy.json")
|
| 148 |
+
env.reset(eval_mode=False)
|
| 149 |
+
obs = env.step(PathwayAction(action_type="inspect_dataset"))
|
| 150 |
+
meta = obs.metadata or {}
|
| 151 |
+
assert meta.get("static_top_genes")
|
| 152 |
+
assert meta.get("static_top_pathways")
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_state_never_exposes_true_pathway():
|
| 156 |
+
env = PathwayEnvironment(case_file="toy_case_001.json")
|
| 157 |
+
env.reset()
|
| 158 |
+
assert "true_pathway" not in env.state.model_dump()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_submit_blocked_without_de_in_eval_mode():
|
| 162 |
+
env = PathwayEnvironment(case_file="toy_case_001.json")
|
| 163 |
+
env.reset()
|
| 164 |
+
obs = env.step(
|
| 165 |
+
PathwayAction(action_type="submit_answer", hypothesis="MAPK signaling")
|
| 166 |
+
)
|
| 167 |
+
assert obs.metadata.get("failure_code") == "submit_prerequisite_de"
|
| 168 |
+
assert obs.done is False
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def test_gene_list_blocked_in_eval_mode():
|
| 172 |
+
env = PathwayEnvironment(case_file="toy_case_legacy.json")
|
| 173 |
+
env.reset()
|
| 174 |
+
env.step(PathwayAction(action_type="run_differential_expression"))
|
| 175 |
+
obs = env.step(
|
| 176 |
+
PathwayAction(
|
| 177 |
+
action_type="run_pathway_enrichment",
|
| 178 |
+
gene_list=["DUSP6", "FOS"],
|
| 179 |
+
)
|
| 180 |
+
)
|
| 181 |
+
assert obs.metadata.get("failure_code") == "ora_gene_list_blocked"
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
@requires_pydeseq2
|
| 185 |
+
def test_understand_validated_contrast_matches_explicit_de():
|
| 186 |
+
env = PathwayEnvironment(case_file="toy_case_001.json")
|
| 187 |
+
env.reset()
|
| 188 |
+
u = env.step(
|
| 189 |
+
PathwayAction(
|
| 190 |
+
action_type="understand_experiment_design",
|
| 191 |
+
condition_a="control",
|
| 192 |
+
condition_b="treated",
|
| 193 |
+
)
|
| 194 |
+
)
|
| 195 |
+
assert u.experiment_design and u.experiment_design.get("validated_contrast")
|
| 196 |
+
assert env.state.validated_reference == "control"
|
| 197 |
+
assert env.state.validated_alternate == "treated"
|
| 198 |
+
a = env.step(
|
| 199 |
+
PathwayAction(
|
| 200 |
+
action_type="run_differential_expression",
|
| 201 |
+
condition_a="control",
|
| 202 |
+
condition_b="treated",
|
| 203 |
+
)
|
| 204 |
+
)
|
| 205 |
+
env2 = PathwayEnvironment(case_file="toy_case_001.json")
|
| 206 |
+
env2.reset()
|
| 207 |
+
env2.step(
|
| 208 |
+
PathwayAction(
|
| 209 |
+
action_type="understand_experiment_design",
|
| 210 |
+
condition_a="control",
|
| 211 |
+
condition_b="treated",
|
| 212 |
+
)
|
| 213 |
+
)
|
| 214 |
+
b = env2.step(PathwayAction(action_type="run_differential_expression"))
|
| 215 |
+
assert a.de_genes and b.de_genes
|
| 216 |
+
assert [r.get("gene") for r in a.de_genes[:10]] == [r.get("gene") for r in b.de_genes[:10]]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def test_no_step_after_episode_done():
|
| 220 |
+
env = PathwayEnvironment(case_file="toy_case_legacy.json")
|
| 221 |
+
env.reset()
|
| 222 |
+
env.step(PathwayAction(action_type="run_differential_expression"))
|
| 223 |
+
env.step(PathwayAction(action_type="run_pathway_enrichment"))
|
| 224 |
+
env.step(PathwayAction(action_type="submit_answer", hypothesis="MAPK signaling"))
|
| 225 |
+
late = env.step(PathwayAction(action_type="inspect_dataset"))
|
| 226 |
+
assert late.done
|
| 227 |
+
assert late.metadata.get("error") == "episode_done"
|
| 228 |
+
assert late.metadata.get("failure_code") == "episode_already_done"
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def test_overlap_summary():
|
| 232 |
+
ora = [
|
| 233 |
+
{
|
| 234 |
+
"pathway": "a",
|
| 235 |
+
"p_value": 0.01,
|
| 236 |
+
"overlap_genes": ["G1", "G2"],
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"pathway": "b",
|
| 240 |
+
"p_value": 0.02,
|
| 241 |
+
"overlap_genes": ["G2", "G3"],
|
| 242 |
+
},
|
| 243 |
+
]
|
| 244 |
+
ov = overlap_genes_across_top_pathways(ora, top_k=2)
|
| 245 |
+
assert "G2" in ov["genes_supporting_multiple_top_pathways"]
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
@requires_pydeseq2
|
| 249 |
+
def test_episode_pipeline_success():
|
| 250 |
+
env = PathwayEnvironment(case_file="toy_case_001.json")
|
| 251 |
+
obs0 = env.reset(episode_id="ep-test-1")
|
| 252 |
+
assert obs0.metadata.get("pipeline_mode") is True
|
| 253 |
+
assert obs0.trace_path
|
| 254 |
+
|
| 255 |
+
a = PathwayAction(
|
| 256 |
+
action_type="run_differential_expression",
|
| 257 |
+
condition_a="control",
|
| 258 |
+
condition_b="treated",
|
| 259 |
+
)
|
| 260 |
+
obs1 = env.step(a)
|
| 261 |
+
assert obs1.de_genes
|
| 262 |
+
assert obs1.top_genes
|
| 263 |
+
|
| 264 |
+
b = PathwayAction(action_type="run_pathway_enrichment")
|
| 265 |
+
obs2 = env.step(b)
|
| 266 |
+
assert obs2.pathway_enrichment
|
| 267 |
+
assert "MAPK signaling" in obs2.top_pathways[:3]
|
| 268 |
+
assert obs2.overlap_summary is not None
|
| 269 |
+
|
| 270 |
+
c = PathwayAction(
|
| 271 |
+
action_type="compare_pathways",
|
| 272 |
+
pathway_a="MAPK signaling",
|
| 273 |
+
pathway_b="ERK cascade",
|
| 274 |
+
)
|
| 275 |
+
obs3 = env.step(c)
|
| 276 |
+
assert obs3.pathway_comparison
|
| 277 |
+
assert "shared_de_support" in obs3.pathway_comparison
|
| 278 |
+
|
| 279 |
+
obs4 = env.step(
|
| 280 |
+
PathwayAction(action_type="submit_answer", hypothesis="MAPK signaling")
|
| 281 |
+
)
|
| 282 |
+
assert obs4.done
|
| 283 |
+
assert obs4.metadata.get("correct") is None
|
| 284 |
+
assert env.episode_outcome is not None
|
| 285 |
+
assert env.episode_outcome.get("correct") is True
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def test_legacy_fixture():
|
| 289 |
+
env = PathwayEnvironment(case_file="toy_case_legacy.json")
|
| 290 |
+
obs0 = env.reset()
|
| 291 |
+
assert obs0.metadata.get("pipeline_mode") is False
|
| 292 |
+
env.step(PathwayAction(action_type="run_differential_expression"))
|
| 293 |
+
env.step(PathwayAction(action_type="run_pathway_enrichment"))
|
| 294 |
+
fin = env.step(
|
| 295 |
+
PathwayAction(action_type="submit_answer", hypothesis="MAPK signaling")
|
| 296 |
+
)
|
| 297 |
+
assert fin.done
|
| 298 |
+
assert env.episode_outcome and env.episode_outcome.get("correct") is True
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def test_orchestrator_mode_exposes_correct_metadata():
|
| 302 |
+
env = PathwayEnvironment(case_file="toy_case_legacy.json")
|
| 303 |
+
env.reset(orchestrator_mode=True)
|
| 304 |
+
env.step(PathwayAction(action_type="run_differential_expression"))
|
| 305 |
+
env.step(PathwayAction(action_type="run_pathway_enrichment"))
|
| 306 |
+
fin = env.step(
|
| 307 |
+
PathwayAction(action_type="submit_answer", hypothesis="MAPK signaling")
|
| 308 |
+
)
|
| 309 |
+
assert fin.metadata.get("correct") is True
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@requires_pydeseq2
|
| 313 |
+
def test_strict_invalid_counts_matrix():
|
| 314 |
+
env = PathwayEnvironment(case_file="toy_case_001.json")
|
| 315 |
+
env.reset(strict=True)
|
| 316 |
+
env._case["counts"]["DUSP6"] = [1, 2]
|
| 317 |
+
obs = env.step(
|
| 318 |
+
PathwayAction(
|
| 319 |
+
action_type="run_differential_expression",
|
| 320 |
+
condition_a="control",
|
| 321 |
+
condition_b="treated",
|
| 322 |
+
)
|
| 323 |
+
)
|
| 324 |
+
assert obs.done and obs.metadata.get("strict_failure") is True
|
| 325 |
+
assert obs.metadata.get("failure_code") == "de_invalid_counts_matrix"
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@requires_pydeseq2
|
| 329 |
+
def test_strict_mode_missing_contrast():
|
| 330 |
+
env = PathwayEnvironment(case_file="toy_case_no_default.json")
|
| 331 |
+
env.reset(strict=True)
|
| 332 |
+
obs = env.step(PathwayAction(action_type="run_differential_expression"))
|
| 333 |
+
assert obs.done is True
|
| 334 |
+
assert obs.metadata.get("strict_failure") is True
|
| 335 |
+
assert obs.metadata.get("failure_code") == "de_missing_contrast"
|
tests/envs/test_pathway_case_loader.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
from pathway_analysis_env.server.case_loader import (
|
| 6 |
+
CASE_SECRET_KEYS,
|
| 7 |
+
load_case_file,
|
| 8 |
+
strip_case_secrets,
|
| 9 |
+
)
|
| 10 |
+
from pathway_analysis_env.server.pathway_environment import DATA_DIR, PathwayEnvironment
|
| 11 |
+
from pathway_analysis_env.models import PathwayAction
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def test_strip_case_secrets():
|
| 15 |
+
raw = {
|
| 16 |
+
"case_id": "x",
|
| 17 |
+
"true_pathway": "MAPK signaling",
|
| 18 |
+
"expected_keywords": ["mapk"],
|
| 19 |
+
"counts": {"G1": [1, 2]},
|
| 20 |
+
}
|
| 21 |
+
pub = strip_case_secrets(raw)
|
| 22 |
+
for k in CASE_SECRET_KEYS:
|
| 23 |
+
assert k not in pub
|
| 24 |
+
assert "counts" in pub
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def test_reset_agent_safe_case_has_no_secrets_in_memory():
|
| 28 |
+
env = PathwayEnvironment(case_file="toy_case_001.json")
|
| 29 |
+
env.reset(eval_mode=True, orchestrator_mode=False)
|
| 30 |
+
dumped = json.dumps(env._case)
|
| 31 |
+
assert "true_pathway" not in dumped
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_episode_observation_no_correct_without_orchestrator():
|
| 35 |
+
env = PathwayEnvironment(case_file="toy_case_legacy.json")
|
| 36 |
+
env.reset()
|
| 37 |
+
env.step(PathwayAction(action_type="run_differential_expression"))
|
| 38 |
+
env.step(PathwayAction(action_type="run_pathway_enrichment"))
|
| 39 |
+
fin = env.step(
|
| 40 |
+
PathwayAction(action_type="submit_answer", hypothesis="MAPK signaling")
|
| 41 |
+
)
|
| 42 |
+
assert fin.metadata.get("correct") is None
|
| 43 |
+
assert env.episode_outcome.get("correct") is True
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_load_case_file_roundtrip():
|
| 47 |
+
case, secrets = load_case_file(DATA_DIR, "toy_case_001.json", agent_safe=False)
|
| 48 |
+
assert secrets["true_pathway"] == "MAPK signaling"
|
| 49 |
+
assert case["case_id"]
|
tests/envs/test_pathway_scoring.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
|
| 4 |
+
from pathway_analysis_env.server.scoring import (
|
| 5 |
+
is_unknown_ground_truth,
|
| 6 |
+
KEYWORD_BASE_SCORE,
|
| 7 |
+
labels_match,
|
| 8 |
+
score_submission,
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_labels_match_fuzzy():
|
| 13 |
+
assert labels_match("MAPK signaling", "mapk signaling")
|
| 14 |
+
assert labels_match(
|
| 15 |
+
"Estrogen Response Early",
|
| 16 |
+
"MSigDB_Hallmark_2020: Estrogen Response Early",
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_score_exact_pathway():
|
| 21 |
+
out = score_submission(
|
| 22 |
+
"MAPK signaling",
|
| 23 |
+
true_pathway="MAPK signaling",
|
| 24 |
+
pathway_gene_set_names=["MAPK signaling", "PI3K-Akt signaling"],
|
| 25 |
+
top_ora_pathways=["ERK cascade"],
|
| 26 |
+
)
|
| 27 |
+
assert out["correct"] is True
|
| 28 |
+
assert out["match_mode"] == "pathway_label"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_score_keywords_geo():
|
| 32 |
+
out = score_submission(
|
| 33 |
+
"Strong estrogen response hallmark",
|
| 34 |
+
true_pathway="Unknown (GEO benchmark)",
|
| 35 |
+
expected_keywords=["estrogen", "ESR1"],
|
| 36 |
+
top_ora_pathways=[],
|
| 37 |
+
)
|
| 38 |
+
assert out["correct"] is True
|
| 39 |
+
assert out["match_mode"] == "expected_keywords"
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_unknown_ground_truth():
|
| 43 |
+
assert is_unknown_ground_truth("Unknown (GEO benchmark)")
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_distractor_pathway_label_not_credited():
|
| 47 |
+
"""Naming a distractor pathway defined in the case must not score 1.0.
|
| 48 |
+
|
| 49 |
+
Regression guard for a reward-hacking surface: previously any pathway
|
| 50 |
+
gene-set name present in the case (or any top ORA hit) matched as a
|
| 51 |
+
``pathway_label`` and earned full credit.
|
| 52 |
+
"""
|
| 53 |
+
out = score_submission(
|
| 54 |
+
"PI3K-Akt signaling",
|
| 55 |
+
true_pathway="MAPK signaling",
|
| 56 |
+
pathway_gene_set_names=["MAPK signaling", "ERK cascade", "PI3K-Akt signaling"],
|
| 57 |
+
top_ora_pathways=["MAPK signaling", "ERK cascade", "PI3K-Akt signaling"],
|
| 58 |
+
)
|
| 59 |
+
assert out["correct"] is False
|
| 60 |
+
assert out["score"] == 0.0
|
| 61 |
+
assert out["match_mode"] == "no_match"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_top_ora_hit_not_credited_when_truth_known():
|
| 65 |
+
"""A top ORA hit that is not the true pathway must not earn credit."""
|
| 66 |
+
out = score_submission(
|
| 67 |
+
"ERK cascade",
|
| 68 |
+
true_pathway="MAPK signaling",
|
| 69 |
+
top_ora_pathways=["ERK cascade", "MAPK signaling"],
|
| 70 |
+
)
|
| 71 |
+
assert out["correct"] is False
|
| 72 |
+
assert out["score"] == 0.0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_true_pathway_alias_credited():
|
| 76 |
+
"""Explicit aliases of the true pathway earn full credit."""
|
| 77 |
+
out = score_submission(
|
| 78 |
+
"MAPK/ERK pathway",
|
| 79 |
+
true_pathway="MAPK signaling",
|
| 80 |
+
true_pathway_aliases=["MAPK/ERK pathway", "RAS-MAPK"],
|
| 81 |
+
)
|
| 82 |
+
assert out["correct"] is True
|
| 83 |
+
assert out["score"] == 1.0
|
| 84 |
+
assert out["match_mode"] == "pathway_label"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_keyword_score_normalized_above_base():
|
| 88 |
+
"""A correct GEO answer scores on a scale comparable to exact matches.
|
| 89 |
+
|
| 90 |
+
A single keyword hit out of several should land at or above the base
|
| 91 |
+
score, not collapse to a small fraction like 1/5 = 0.2.
|
| 92 |
+
"""
|
| 93 |
+
out = score_submission(
|
| 94 |
+
"estrogen response",
|
| 95 |
+
true_pathway="Unknown (GEO benchmark)",
|
| 96 |
+
expected_keywords=["estrogen", "ESR1", "fulvestrant", "ER", "hormone"],
|
| 97 |
+
)
|
| 98 |
+
assert out["correct"] is True
|
| 99 |
+
assert out["score"] >= KEYWORD_BASE_SCORE
|
| 100 |
+
assert out["match_mode"] == "expected_keywords"
|