czty commited on
Commit
3f8ed95
·
verified ·
1 Parent(s): 6f44bb0

BioOcto code and data release (snapshot 2026-11-27)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +4 -0
  2. BioScientist/.env.example +12 -0
  3. BioScientist/.gitignore +11 -0
  4. BioScientist/GIT_INFO.txt +6 -0
  5. BioScientist/LICENSE +21 -0
  6. BioScientist/README.md +237 -0
  7. BioScientist/UNCOMMITTED_CHANGES.patch +45 -0
  8. BioScientist/UNCOMMITTED_STATUS.txt +2 -0
  9. BioScientist/UNTRACKED_FILES.txt +1 -0
  10. BioScientist/agent_system/__init__.py +11 -0
  11. BioScientist/agent_system/bioinfomcp_converter.py +254 -0
  12. BioScientist/agent_system/engines/__init__.py +5 -0
  13. BioScientist/agent_system/engines/bioinfo_platform_pipleline.svg +34 -0
  14. BioScientist/agent_system/engines/e1_v1_sequence.svg +99 -0
  15. BioScientist/agent_system/engines/e1_validator.py +1400 -0
  16. BioScientist/agent_system/engines/t1_consultant.py +625 -0
  17. BioScientist/agent_system/engines/test_gemini.py +25 -0
  18. BioScientist/agent_system/engines/v1_executor.py +1348 -0
  19. BioScientist/agent_system/engines/v1_executor_backup/__init__.py +3 -0
  20. BioScientist/agent_system/engines/v1_executor_backup/agent/__init__.py +1 -0
  21. BioScientist/agent_system/engines/v1_executor_backup/agent/a1.py +0 -0
  22. BioScientist/agent_system/engines/v1_executor_backup/agent/env_collection.py +313 -0
  23. BioScientist/agent_system/engines/v1_executor_backup/agent/function_generator.py +119 -0
  24. BioScientist/agent_system/engines/v1_executor_backup/agent/qa_llm.py +50 -0
  25. BioScientist/agent_system/engines/v1_executor_backup/agent/react.py +465 -0
  26. BioScientist/agent_system/engines/v1_executor_backup/biorxiv_scripts/extract_biorxiv_tasks.py +404 -0
  27. BioScientist/agent_system/engines/v1_executor_backup/biorxiv_scripts/generate_function.py +72 -0
  28. BioScientist/agent_system/engines/v1_executor_backup/biorxiv_scripts/process_all_subjects.py +315 -0
  29. BioScientist/agent_system/engines/v1_executor_backup/config.py +99 -0
  30. BioScientist/agent_system/engines/v1_executor_backup/env_desc.py +221 -0
  31. BioScientist/agent_system/engines/v1_executor_backup/env_desc_cm.py +219 -0
  32. BioScientist/agent_system/engines/v1_executor_backup/eval/__init__.py +3 -0
  33. BioScientist/agent_system/engines/v1_executor_backup/eval/biomni_eval1.py +324 -0
  34. BioScientist/agent_system/engines/v1_executor_backup/know_how/__init__.py +9 -0
  35. BioScientist/agent_system/engines/v1_executor_backup/know_how/loader.py +348 -0
  36. BioScientist/agent_system/engines/v1_executor_backup/know_how/resource/CRISPick_download_links.txt +238 -0
  37. BioScientist/agent_system/engines/v1_executor_backup/know_how/resource/addgene_grna_sequences.csv +322 -0
  38. BioScientist/agent_system/engines/v1_executor_backup/know_how/sgRNA_design_guide.md +419 -0
  39. BioScientist/agent_system/engines/v1_executor_backup/know_how/single_cell_annotation.md +223 -0
  40. BioScientist/agent_system/engines/v1_executor_backup/llm.py +276 -0
  41. BioScientist/agent_system/engines/v1_executor_backup/mcp_config_bioscientist_generated.yaml +0 -0
  42. BioScientist/agent_system/engines/v1_executor_backup/model/__init__.py +0 -0
  43. BioScientist/agent_system/engines/v1_executor_backup/model/retriever.py +203 -0
  44. BioScientist/agent_system/engines/v1_executor_backup/task/__init__.py +0 -0
  45. BioScientist/agent_system/engines/v1_executor_backup/task/base_task.py +18 -0
  46. BioScientist/agent_system/engines/v1_executor_backup/task/hle.py +146 -0
  47. BioScientist/agent_system/engines/v1_executor_backup/task/lab_bench.py +115 -0
  48. BioScientist/agent_system/engines/v1_executor_backup/tool/__init__.py +1 -0
  49. BioScientist/agent_system/engines/v1_executor_backup/tool/biochemistry.py +1026 -0
  50. BioScientist/agent_system/engines/v1_executor_backup/tool/bioengineering.py +1387 -0
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ .DS_Store
BioScientist/.env.example ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ AZURE_OPENAI_API_VERSION = "2024-12-01-preview" # or the latest version available
2
+ MODEL_NAME = "<model-name>" # e.g., "gpt-4o", "gpt-4o-mini", "gpt-4.1-turbo", "gpt-4.1-mini"
3
+
4
+ # If you are using Azure OpenAI, set the following variables
5
+ AZURE_OPENAI_ENDPOINT='https://<azure-endpoint>.cognitiveservices.azure.com/'
6
+ AZURE_OPENAI_KEY='<azure-key>'
7
+
8
+ # If you are using OpenAI, set the following variable
9
+ OPENAI_API_KEY = '<openai-key>'
10
+
11
+ # If you want to test it into an Anthropic Environment, set the following variable
12
+ ANTHROPIC_API_KEY = '<anthropic-key>'
BioScientist/.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .env
2
+ agent_system/toolbase/output/
3
+ agent_system/toolbase/mcp_batch_from_help_txt/
4
+ agent_system/toolbase/mcp_batch_from_manual_txt/
5
+ shared_knowledge/
6
+ data/
7
+ agent_system/toolbase/output/benchmark/outputs/
8
+ *.safetensors
9
+ *.pt
10
+ *.bin
11
+ *.pth
BioScientist/GIT_INFO.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ repo_path_on_source_server: /225040511/project/Beyond_Prompt-Based_Planning/BioScientist
2
+ remote: git@github.com:healme-225040511/BioScientist.git
3
+ branch: main
4
+ head: f7c7d276244e61fc6407c779b477245b87e47c2e
5
+ head_date: 2026-05-01 08:48:52 +0000
6
+ uncommitted_entries: 2
BioScientist/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 florensiawidjaja
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
BioScientist/README.md ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # BioScientist Agent System
2
+
3
+ An orchestration layer for **agentic bioinformatics workflows** that combines:
4
+
5
+ - Dynamic MCP tool registration
6
+ - Dual-mode reasoning (`T1`) and execution (`V1`)
7
+ - Layered validation (`E1`) with Agent System integration
8
+ - File-based shared memory for continual improvement
9
+
10
+ ---
11
+
12
+ ## Why This Repository Exists
13
+
14
+ `BioScientist/agent_system` is designed to run practical computational biology tasks with a structured loop:
15
+
16
+ 1. Propose hypotheses and strategies
17
+ 2. Validate them with increasing rigor (L1 -> L4)
18
+ 3. Capture execution evidence and insights
19
+ 4. Reuse those insights for better next-round planning
20
+
21
+ This gives you a reproducible bridge between **LLM reasoning**, **MCP tools**, and **real data artifacts**.
22
+
23
+ ---
24
+
25
+ ## Architecture Overview
26
+
27
+ ### Core Components
28
+
29
+ - `V1 Executor` (`engines/v1_executor.py`)
30
+ - Pipeline-style task executor
31
+ - Routes tools through MCP servers
32
+ - Supports local and Docker backends
33
+ - Persists run artifacts and reports
34
+
35
+ - `T1 Consultant` (`engines/t1_consultant.py`)
36
+ - Reflection and strategy engine
37
+ - Generates hypotheses (with data-grounded operations)
38
+ - Ranks hypotheses by historical success proxies
39
+
40
+ - `E1 Validator` (`engines/e1_validator.py`)
41
+ - Multi-level validation engine:
42
+ - `L1`: rule consistency
43
+ - `L2`: Agent System/MCP readiness
44
+ - `L3`: lightweight data-backed validation
45
+ - `L4`: extended data-backed validation
46
+ - Calls Agent System runtime `A1.go(...)` when available
47
+
48
+ - `Shared Knowledge Space` (`shared_memory.py`)
49
+ - File-based memory bridge across modules
50
+ - Stores experiment reports, hypotheses, validation reports, insights, and summary statistics
51
+
52
+ - `Orchestrator` (`orchestrator.py`)
53
+ - Unified entrypoint wiring `V1 + T1 + E1`
54
+ - Exposes high-level modes like:
55
+ - `execute`
56
+ - `consult`
57
+ - `autopilot`
58
+ - `hypothesis-generate`
59
+ - `hypothesis-loop`
60
+
61
+ ### Runtime Flow (Hypothesis Loop)
62
+
63
+ ```text
64
+ User Query
65
+ |
66
+ v
67
+ T1: generate + rank hypotheses
68
+ |
69
+ v
70
+ E1: optional MCP registration -> validation (L1/L2/L3/L4)
71
+ |
72
+ v
73
+ Agent System runtime (A1 + add_mcp + go) [when enabled/available]
74
+ |
75
+ v
76
+ Artifacts + Reports + Insights -> Shared Knowledge
77
+ ```
78
+
79
+ ---
80
+
81
+ ## Project Layout (Key Paths)
82
+
83
+ ```text
84
+ BioScientist/
85
+ ├── agent_system/
86
+ │ ├── main.py
87
+ │ ├── orchestrator.py
88
+ │ ├── engines/
89
+ │ │ ├── v1_executor.py
90
+ │ │ ├── t1_consultant.py
91
+ │ │ └── e1_validator.py
92
+ │ ├── shared_memory.py
93
+ │ ├── toolbase/
94
+ │ │ ├── data/biomni_data/
95
+ │ │ └── register_mcp_servers_to_biomni.py
96
+ │ └── results/
97
+ └── README.md
98
+ ```
99
+
100
+ ---
101
+
102
+ ## Environment Setup (Required)
103
+
104
+ Our software environment is large. We provide a single setup script to bootstrap dependencies.
105
+
106
+ ### 1) Activate the E1 environment first
107
+
108
+ ```bash
109
+ conda activate biomni_e1
110
+ ```
111
+
112
+ ### 2) Install the official pip package first
113
+
114
+ ```bash
115
+ pip install biomni --upgrade
116
+ ```
117
+
118
+ ### 3) Run the unified setup script
119
+
120
+ ```bash
121
+ # from the repository root
122
+ bash setup.sh
123
+ ```
124
+
125
+ ### 4) (Optional, recommended) Install the latest Biomni from source
126
+
127
+ ```bash
128
+ pip install git+https://github.com/snap-stanford/Biomni.git@main
129
+ ```
130
+
131
+ ---
132
+
133
+ ## Quick Start: Hypothesis Loop (Single-Cell Normalization)
134
+
135
+ ### 1) Set Environment Variables
136
+
137
+ Use your current setup pattern:
138
+
139
+ ```bash
140
+ export GEMINI_API_KEY="<YOUR_GEMINI_API_KEY>"
141
+ export T1_MODEL_BACKEND="gemini"
142
+ export GEMINI_MODEL="gemini-2.5-flash-lite"
143
+ export GEMINI_TEMPERATURE="0.2"
144
+ export GEMINI_TIMEOUT_SECONDS="60"
145
+ export BIOMNI_PATH=/225040511/project/Biomni/data
146
+ export BIOMNI_SOURCE="Gemini"
147
+ ```
148
+
149
+ Optional (recommended for explicit control):
150
+
151
+ ```bash
152
+ export BIOCLAW_BIOMNI_ROOT=/225040511/project/BioScientist/agent_system/engines/v1_executor_backup
153
+ ```
154
+
155
+ ### 2) Run the End-to-End Loop
156
+
157
+ ```bash
158
+ python -m agent_system.main \
159
+ --project_root /225040511/project/BioScientist \
160
+ hypothesis-loop \
161
+ --task_scope single_cell_normalization \
162
+ --user_query "Give me new ideas for normalizing single-cell data" \
163
+ --n 2 \
164
+ --top_k 1 \
165
+ --validate_top_m 1 \
166
+ --validation_level L4 \
167
+ --register_mcp true
168
+ ```
169
+
170
+ ### 3) Where to Find Outputs
171
+
172
+ - Loop-level result:
173
+ - `agent_system/results/hypothesis-loop_<timestamp>.json`
174
+ - Validation runtime reports:
175
+ - `agent_system/results/e1_runtime/*.json`
176
+ - Data-backed L3/L4 artifacts:
177
+ - `agent_system/results/l3_reports/*.json`
178
+ - `agent_system/results/l4_reports/*.json`
179
+ - Agent System execution payloads:
180
+ - `agent_system/results/biomni_exec/*.json`
181
+
182
+ ---
183
+
184
+ ## Other CLI Modes
185
+
186
+ ### Generate hypotheses only
187
+
188
+ ```bash
189
+ python -m agent_system.main \
190
+ --project_root /225040511/project/BioScientist \
191
+ hypothesis-generate \
192
+ --task_scope single_cell_normalization \
193
+ --user_query "Give me new ideas for normalizing single-cell data" \
194
+ --n 10 \
195
+ --top_k 5
196
+ ```
197
+
198
+ ### Register MCP servers only
199
+
200
+ ```bash
201
+ python -m agent_system.main \
202
+ --project_root /225040511/project/BioScientist \
203
+ register-mcp
204
+ ```
205
+
206
+ ### Consult mode (strategy only)
207
+
208
+ ```bash
209
+ python -m agent_system.main \
210
+ --project_root /225040511/project/BioScientist \
211
+ consult \
212
+ --task_scope single_cell_normalization \
213
+ --user_goal "Design a robust normalization strategy for cross-batch scRNA-seq."
214
+ ```
215
+
216
+ ---
217
+
218
+ ## Notes and Troubleshooting
219
+
220
+ - If Agent System runtime returns API/provider errors (for example region restrictions), E1 may return `inconclusive` even when local data checks succeed.
221
+ - L3/L4 still produce useful tabular evidence (`rows_scanned`, `missing_rate`, numeric summaries, relevance scores).
222
+ - If you want fully offline execution, switch to a local model source (for example Ollama) and update relevant environment variables.
223
+ - Large MCP sets are automatically reduced in E1 probe mode via minimal config generation for faster startup.
224
+
225
+ ---
226
+
227
+ ## Status Semantics
228
+
229
+ - `success`: validation/execution reached expected criteria
230
+ - `inconclusive`: partial evidence available but one or more critical external/runtime checks failed
231
+ - `failed`: contradiction or hard runtime failure detected
232
+
233
+ ---
234
+
235
+ ## License
236
+
237
+ This repository is released under the MIT License (see `LICENSE`).
BioScientist/UNCOMMITTED_CHANGES.patch ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/agent_system/toolbase/register_mcp_servers_to_biomni.py b/agent_system/toolbase/register_mcp_servers_to_biomni.py
2
+ index 5cb314a..d4cc409 100644
3
+ --- a/agent_system/toolbase/register_mcp_servers_to_biomni.py
4
+ +++ b/agent_system/toolbase/register_mcp_servers_to_biomni.py
5
+ @@ -186,26 +186,36 @@ from mcp.server.fastmcp import FastMCP
6
+
7
+
8
+ SOURCE_SERVER = Path({source_server_path!r})
9
+ +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name)
10
+ SERVER_NAME = {server_name!r}
11
+
12
+
13
+ class _ShimMCP:
14
+ @staticmethod
15
+ - def tool():
16
+ + def tool(*args, **kwargs):
17
+ + if args and callable(args[0]) and len(args) == 1 and not kwargs:
18
+ + return args[0]
19
+ def _decorator(fn):
20
+ return fn
21
+ return _decorator
22
+
23
+
24
+ +def _resolve_source_server():
25
+ + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name:
26
+ + return LOCAL_SERVER
27
+ + return SOURCE_SERVER
28
+ +
29
+ +
30
+ def _load_functions():
31
+ - code = SOURCE_SERVER.read_text(encoding="utf-8")
32
+ - tree = ast.parse(code, filename=str(SOURCE_SERVER))
33
+ + source_server = _resolve_source_server()
34
+ + code = source_server.read_text(encoding="utf-8")
35
+ + tree = ast.parse(code, filename=str(source_server))
36
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
37
+ namespace = {{
38
+ "__name__": "__mcp_source__",
39
+ "mcp": _ShimMCP(),
40
+ }}
41
+ - exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
42
+ + exec(compile(code, str(source_server), "exec"), namespace, namespace)
43
+ loaded = []
44
+ for name in function_names:
45
+ fn = namespace.get(name)
BioScientist/UNCOMMITTED_STATUS.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ M agent_system/toolbase/register_mcp_servers_to_biomni.py
2
+ ?? agent_system/toolbase/__pycache__/
BioScientist/UNTRACKED_FILES.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ agent_system/toolbase/__pycache__/register_mcp_servers_to_biomni.cpython-313.pyc
BioScientist/agent_system/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dual-mode agent system for BioinfoMCP.
2
+
3
+ This package introduces:
4
+ - BioinfoV1Executor: deterministic execution engine
5
+ - BioinfoT1Consultant: reflection and strategy engine
6
+ - SharedKnowledgeSpace: bridge for reports, insights, and pipeline configs
7
+ """
8
+
9
+ from .orchestrator import DualModeAgentSystem
10
+
11
+ __all__ = ["DualModeAgentSystem"]
BioScientist/agent_system/bioinfomcp_converter.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import requests
4
+ import ast # this is just for check code syntax whether or not it is correct
5
+ import re
6
+ from typing import List
7
+ import pymupdf
8
+ from dotenv import load_dotenv
9
+ from pathlib import Path
10
+
11
+ load_dotenv()
12
+
13
+
14
+ '''
15
+ # 0. Check whether that particular library is already installed (otherwise cannot run the help function)
16
+ # 1. Run the --help function
17
+ # 2. Let GPT-4 analyze the result from the help manual, attain the
18
+ a) What tools are there
19
+ i) For each tools, what is the input, output
20
+ ii) the CLI command, error handling
21
+ iii) capture output
22
+ iv) check output whether it is correct
23
+ '''
24
+
25
+
26
+ class BioinfoMCP():
27
+ def __init__(self, model="openai"):
28
+ prompt_path = Path(__file__).resolve().parent / "system_prompt.txt"
29
+ with open(prompt_path, "r", encoding="utf-8") as file:
30
+ self.sys_prompt = file.read()
31
+ self.backend_model = model.lower()
32
+ self.api_model_name = os.getenv('MODEL_NAME')
33
+ self.client = None
34
+
35
+ if self.backend_model == "azure":
36
+ from openai import AzureOpenAI
37
+ # Load Environment Keys
38
+ api_subscription_key = os.getenv('AZURE_OPENAI_KEY')
39
+ api_version = os.getenv('AZURE_OPENAI_API_VERSION')
40
+ api_endpoint = os.getenv('AZURE_OPENAI_ENDPOINT')
41
+ # initialize the Azure Client
42
+ self.client = AzureOpenAI(
43
+ api_version=api_version,
44
+ azure_endpoint=api_endpoint,
45
+ api_key=api_subscription_key,
46
+ )
47
+ self.api_model_name = self.api_model_name or os.getenv("AZURE_OPENAI_MODEL")
48
+
49
+ elif self.backend_model == "openai":
50
+ from openai import OpenAI
51
+ # Load Environment Keys
52
+ openai_api_key = os.getenv('OPENAI_API_KEY')
53
+ # initialize the OpenAI Client
54
+ self.client = OpenAI(
55
+ api_key=openai_api_key
56
+ )
57
+ self.api_model_name = self.api_model_name or os.getenv("OPENAI_MODEL_NAME")
58
+
59
+ elif self.backend_model == "gemini":
60
+ # Gemini uses HTTP API directly via requests
61
+ self.gemini_api_key = os.getenv("GEMINI_API_KEY")
62
+ self.api_model_name = self.api_model_name or os.getenv("GEMINI_MODEL_NAME") or "gemini-1.5-pro"
63
+ self.gemini_api_base = os.getenv("GEMINI_API_BASE", "https://generativelanguage.googleapis.com")
64
+ fallback_raw = os.getenv("GEMINI_MODEL_FALLBACKS", "gemini-2.0-flash,gemini-1.5-pro,gemini-1.5-flash")
65
+ self.gemini_model_fallbacks: List[str] = [m.strip() for m in fallback_raw.split(",") if m.strip()]
66
+ self.max_help_chars = int(os.getenv("BIOINFOMCP_MAX_HELP_CHARS", "60000"))
67
+ else:
68
+ raise ValueError(f"Unsupported model backend: {model}. Use one of openai/azure/gemini")
69
+
70
+ print(f"Succesfully created backend={self.backend_model}, model={self.api_model_name}")
71
+
72
+
73
+
74
+ def is_tool_available(self, tool_name):
75
+ """Check whether that tool is installed or not"""
76
+ try:
77
+ _ = subprocess.run([tool_name, '--version'],
78
+ capture_output=True, timeout=20, text=True)
79
+ print(f"{tool_name} is installed")
80
+ return True
81
+ except:
82
+ print(f"{tool_name} is not installed!")
83
+ return False
84
+
85
+ def extract_help_document(self, tool_name, manual, run_help_command=False):
86
+ """Extract help text from tool"""
87
+ if not run_help_command: # document provided by user, no need to run the help command
88
+ manual_path = Path(str(manual))
89
+ if manual_path.suffix.lower() == ".pdf" and manual_path.exists():
90
+ manual_doc = pymupdf.open(f'{manual}')
91
+ manual_content = ""
92
+ for page in manual_doc:
93
+ text = page.get_text()
94
+ manual_content += text
95
+ return manual_content
96
+ if manual_path.exists():
97
+ return manual_path.read_text(encoding="utf-8", errors="ignore")
98
+ return str(manual)
99
+
100
+ if self.is_tool_available(tool_name):
101
+ try:
102
+ result = subprocess.run([tool_name, manual],
103
+ capture_output=True, timeout=30, text=True)
104
+ return result.stdout + result.stderr
105
+ except:
106
+ return None
107
+ return None
108
+
109
+ def _call_openai_like(self, prompt):
110
+ response = self.client.chat.completions.create(
111
+ messages=[
112
+ {
113
+ "role" : "system",
114
+ "content": [{"type": "text", "text": self.sys_prompt}],
115
+ },
116
+ {
117
+ "role" : "user",
118
+ "content": [{"type": "text", "text": prompt}],
119
+ }
120
+ ],
121
+ temperature=0.1,
122
+ model=self.api_model_name
123
+ )
124
+ return response.choices[0].message.content
125
+
126
+ def _call_gemini(self, prompt):
127
+ if not getattr(self, "gemini_api_key", None):
128
+ raise ValueError("GEMINI_API_KEY is required for gemini backend")
129
+ models = [self.api_model_name] + [m for m in self.gemini_model_fallbacks if m != self.api_model_name]
130
+ headers = {
131
+ "Content-Type": "application/json",
132
+ "x-goog-api-key": self.gemini_api_key,
133
+ }
134
+ errors = []
135
+ for model_name in models:
136
+ url = f"{self.gemini_api_base}/v1beta/models/{model_name}:generateContent"
137
+ payload = {
138
+ "system_instruction": {
139
+ "parts": [{"text": self.sys_prompt}]
140
+ },
141
+ "contents": [
142
+ {
143
+ "role": "user",
144
+ "parts": [{"text": prompt}],
145
+ }
146
+ ],
147
+ "generationConfig": {
148
+ "temperature": 0.1,
149
+ },
150
+ }
151
+ try:
152
+ resp = requests.post(url, headers=headers, json=payload, timeout=180)
153
+ if resp.status_code >= 400:
154
+ body = resp.text[:1200]
155
+ errors.append(f"{model_name}: HTTP {resp.status_code} - {body}")
156
+ continue
157
+ data = resp.json()
158
+ candidates = data.get("candidates", [])
159
+ if not candidates:
160
+ errors.append(f"{model_name}: empty candidates")
161
+ continue
162
+ parts = candidates[0].get("content", {}).get("parts", [])
163
+ texts = [p.get("text", "") for p in parts if isinstance(p, dict)]
164
+ joined = "\n".join(texts).strip()
165
+ if joined:
166
+ return joined
167
+ errors.append(f"{model_name}: empty text in candidate parts")
168
+ except Exception as exc:
169
+ errors.append(f"{model_name}: exception {exc}")
170
+ continue
171
+ raise RuntimeError("Gemini request failed across all models. " + " | ".join(errors[-3:]))
172
+
173
+ def _call_llm(self, prompt):
174
+ if self.backend_model in ("openai", "azure"):
175
+ return self._call_openai_like(prompt)
176
+ if self.backend_model == "gemini":
177
+ return self._call_gemini(prompt)
178
+ raise ValueError(f"Unsupported backend: {self.backend_model}")
179
+
180
+ def generate_prompt(self, tool_name, help_docs):
181
+ """Generate the Prompt that later will be send to the OpenAI client"""
182
+ prompt = f"""
183
+ Convert the following bioinformatics tool into an MCP tool definition.
184
+
185
+ Tool Name: {tool_name}
186
+ Help Document:
187
+ {help_docs}
188
+
189
+ Parse the Input parameters correctly, follow the MCP best practices, and provide the complete python code with the @mcp.tool() decorator.
190
+ """
191
+ return prompt
192
+
193
+ def parse_mcpcode(self, gpt_response):
194
+ code_block = re.findall('```python\n(.*?)\n```', gpt_response, re.DOTALL)
195
+ if not code_block:
196
+ return (0, "There is no python code found in the gpt_response", None)
197
+
198
+ code = code_block[0]
199
+ try:
200
+ ast.parse(code)
201
+ except SyntaxError as e:
202
+ return (0, f"Code is not working with the following SyntaxError: {e}", code)
203
+
204
+ # Check the @mcp.tool() decorator
205
+ if '@mcp.tool' not in code:
206
+ return (0, "Code is missing the @mcp.tool() decorator", code)
207
+
208
+ return (1, None, code)
209
+
210
+ def refine_after_feedback(self, tool_name, code, error_message):
211
+ prompt = f"""
212
+ The initial code block for {tool_name}:
213
+ ```python
214
+ {code}
215
+ ```
216
+ contains the following Error:
217
+ {error_message}
218
+
219
+ Please fix the code and ensure that
220
+ 1. Cover every internal functions of the tool
221
+ 2. Has proper error handling
222
+ 3. Validates input parameters
223
+ 4. Returns structured output
224
+ 5. Follows MCP best practices
225
+
226
+ Provide only the corrected python code.
227
+
228
+ """
229
+ response_content = self._call_llm(prompt)
230
+ # output_file = open(f'./mcp_result/raw_{tool_name}', 'w')
231
+ # output_file.write(response_content)
232
+ return self.parse_mcpcode(response_content)
233
+
234
+ def autogenerate_mcp_tool(self, tool_name, manual, run_help_command):
235
+ """Autogenerate the MCP Tool using the extracted help documents"""
236
+ help_docs = self.extract_help_document(tool_name, manual, run_help_command)
237
+ if help_docs is None:
238
+ help_docs = ""
239
+ if self.backend_model == "gemini":
240
+ max_chars = getattr(self, "max_help_chars", 60000)
241
+ if len(help_docs) > max_chars:
242
+ kept = help_docs[:max_chars]
243
+ help_docs = (
244
+ f"{kept}\n\n"
245
+ f"[Truncated help document: original_length={len(help_docs)}, kept={max_chars}]"
246
+ )
247
+ # web_docs = self.fetch_web_docs(tool_name)
248
+ prompt = self.generate_prompt(tool_name, help_docs)
249
+ response_content = self._call_llm(prompt)
250
+ #print(response_content)
251
+ # output_file = open(f'./mcp_result/raw_{tool_name}', 'w')
252
+ # output_file.write(response.choices[0].message.content)
253
+
254
+ return self.parse_mcpcode(response_content)
BioScientist/agent_system/engines/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .v1_executor import BioinfoV1Executor
2
+ from .t1_consultant import BioinfoT1Consultant
3
+ from .e1_validator import BioinfoE1Validator
4
+
5
+ __all__ = ["BioinfoV1Executor", "BioinfoT1Consultant", "BioinfoE1Validator"]
BioScientist/agent_system/engines/bioinfo_platform_pipleline.svg ADDED
BioScientist/agent_system/engines/e1_v1_sequence.svg ADDED
BioScientist/agent_system/engines/e1_validator.py ADDED
@@ -0,0 +1,1400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import json
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ import importlib.util
9
+ import statistics
10
+ import urllib.request
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from ..schemas import Hypothesis, Insight, ValidationReport
16
+ from ..shared_memory import SharedKnowledgeSpace
17
+
18
+
19
+ class BioinfoE1Validator:
20
+ """
21
+ E1 validator: layered and cost-aware hypothesis validation.
22
+ First version:
23
+ - L1: logical consistency / rule checks
24
+ - L2: light tooling readiness check using Biomni + registered MCP servers
25
+ - L3: lightweight data-backed validation on biomni_data
26
+ - L4: extended data-backed validation with fuller passes and numeric checks
27
+ """
28
+
29
+ LEVEL_CONFIDENCE = {
30
+ "L1": 0.30,
31
+ "L2": 0.60,
32
+ "L3": 0.85,
33
+ "L4": 0.95,
34
+ }
35
+
36
+ def __init__(
37
+ self,
38
+ memory: SharedKnowledgeSpace,
39
+ biomni_root: str | Path,
40
+ mcp_config_path: str | Path,
41
+ project_root: str | Path,
42
+ ):
43
+ self.memory = memory
44
+ self.biomni_root = Path(biomni_root).resolve()
45
+ self.mcp_config_path = Path(mcp_config_path).resolve()
46
+ self.project_root = Path(project_root).resolve()
47
+ self._registration_state: dict[str, Any] | None = None
48
+ self._biomni_probe_cache: dict[str, Any] | None = None
49
+ self._biomni_agent_cache: dict[str, Any] | None = None
50
+
51
+ def _resolve_register_script(self) -> Path | None:
52
+ candidates = [
53
+ # when project_root=/.../BioScientist/agent_system
54
+ self.project_root / "toolbase" / "register_mcp_servers_to_biomni.py",
55
+ # when project_root=/.../BioScientist
56
+ self.project_root / "agent_system" / "toolbase" / "register_mcp_servers_to_biomni.py",
57
+ # fallback based on current file location
58
+ Path(__file__).resolve().parents[1] / "toolbase" / "register_mcp_servers_to_biomni.py",
59
+ ]
60
+ for c in candidates:
61
+ if c.exists():
62
+ return c
63
+ return None
64
+
65
+ def ensure_mcp_registered(self, dry_run: bool = False) -> dict[str, Any]:
66
+ script = self._resolve_register_script()
67
+ if script is None:
68
+ return {
69
+ "ok": False,
70
+ "status": "missing_script",
71
+ "error": (
72
+ "register script not found under either "
73
+ f"{self.project_root}/toolbase or {self.project_root}/agent_system/toolbase"
74
+ ),
75
+ }
76
+ cmd = [
77
+ sys.executable,
78
+ str(script),
79
+ "--biomni-root",
80
+ str(self.biomni_root),
81
+ "--config-out",
82
+ str(self.mcp_config_path),
83
+ ]
84
+ if dry_run:
85
+ cmd.append("--dry-run")
86
+ try:
87
+ completed = subprocess.run(cmd, capture_output=True, text=True, check=False)
88
+ state = {
89
+ "ok": completed.returncode == 0,
90
+ "status": "registered" if completed.returncode == 0 else "failed",
91
+ "return_code": completed.returncode,
92
+ "stdout_tail": "\n".join((completed.stdout or "").splitlines()[-20:]),
93
+ "stderr_tail": "\n".join((completed.stderr or "").splitlines()[-20:]),
94
+ "config_path": str(self.mcp_config_path),
95
+ }
96
+ self._registration_state = state
97
+ return state
98
+ except Exception as exc:
99
+ state = {"ok": False, "status": "failed", "error": str(exc), "config_path": str(self.mcp_config_path)}
100
+ self._registration_state = state
101
+ return state
102
+
103
+ def _coerce_hypothesis(self, hypothesis: Hypothesis | dict[str, Any]) -> dict[str, Any]:
104
+ return hypothesis.to_dict() if isinstance(hypothesis, Hypothesis) else hypothesis
105
+
106
+ def _prepare_biomni_import(self) -> dict[str, Any]:
107
+ """
108
+ Ensure `import biomni` works without requiring pip install -e.
109
+ """
110
+ info = {
111
+ "biomni_root": str(self.biomni_root),
112
+ "path_injected": False,
113
+ "package_dir_exists": (self.biomni_root / "biomni").exists(),
114
+ }
115
+ root_str = str(self.biomni_root)
116
+ if root_str not in sys.path:
117
+ sys.path.insert(0, root_str)
118
+ info["path_injected"] = True
119
+ return info
120
+
121
+ def _resolve_biomni_data_root(self) -> Path:
122
+ env = os.getenv("BIOCLAW_BIOMNI_DATA_ROOT", "").strip()
123
+ if env:
124
+ p = Path(env).expanduser().resolve()
125
+ if p.exists():
126
+ return p
127
+ candidates = [
128
+ self.project_root / "agent_system" / "toolbase" / "data" / "biomni_data",
129
+ self.project_root / "toolbase" / "data" / "biomni_data",
130
+ Path("/225040511/project/BioScientist/agent_system/toolbase/data/biomni_data"),
131
+ ]
132
+ for c in candidates:
133
+ if c.exists():
134
+ return c
135
+ return candidates[0]
136
+
137
+ def _resolve_biomni_llm_source(self) -> tuple[str, str]:
138
+ """
139
+ Resolve runtime LLM/source for Biomni execution.
140
+ Priority:
141
+ 1) BIOCLAW_BIOMNI_LLM / BIOCLAW_BIOMNI_SOURCE
142
+ 2) GEMINI_MODEL / BIOMNI_SOURCE
143
+ 3) safe Gemini defaults
144
+ """
145
+ llm = (
146
+ os.getenv("BIOCLAW_BIOMNI_LLM", "").strip()
147
+ or os.getenv("GEMINI_MODEL", "").strip()
148
+ or "gemini-2.5-flash-lite"
149
+ )
150
+ source = (
151
+ os.getenv("BIOCLAW_BIOMNI_SOURCE", "").strip()
152
+ or os.getenv("BIOMNI_SOURCE", "").strip()
153
+ or "Gemini"
154
+ )
155
+ return llm, source
156
+
157
+ def _quick_biomni_probe(self, hypothesis_text: str = "", force: bool = False) -> dict[str, Any]:
158
+ """
159
+ Minimal-cost Biomni runtime probe.
160
+ Reuses cached probe; otherwise builds/uses a cached Biomni agent context.
161
+ """
162
+ if self._biomni_probe_cache is not None and not force:
163
+ cached = dict(self._biomni_probe_cache)
164
+ cached["cache_hit"] = True
165
+ return cached
166
+
167
+ t0 = datetime.now(timezone.utc)
168
+ ctx = self._get_biomni_agent_context(hypothesis_text, force_rebuild=force)
169
+ dt = datetime.now(timezone.utc) - t0
170
+ if not ctx.get("ok", False):
171
+ result = {
172
+ "ok": False,
173
+ "status": "biomni_probe_failed",
174
+ "error": str(ctx.get("error", "unknown")),
175
+ "mcp_registration_ok": bool(ctx.get("trace", {}).get("mcp_registration_ok", False)),
176
+ "duration_ms": int(dt.total_seconds() * 1000),
177
+ "cache_hit": False,
178
+ "mcp_config_used": str(ctx.get("trace", {}).get("mcp_config_used", self.mcp_config_path)),
179
+ **(ctx.get("trace", {}) if isinstance(ctx.get("trace", {}), dict) else {}),
180
+ }
181
+ self._biomni_probe_cache = result
182
+ return result
183
+
184
+ trace = ctx.get("trace", {}) if isinstance(ctx.get("trace", {}), dict) else {}
185
+ result = {
186
+ "ok": True,
187
+ "status": "ready",
188
+ "mcp_registration_ok": True,
189
+ "custom_tool_count": int(trace.get("custom_tool_count", 0)),
190
+ "related_tool_hits": 0,
191
+ "duration_ms": int(dt.total_seconds() * 1000),
192
+ "cache_hit": False,
193
+ "mcp_config_used": str(trace.get("mcp_config_used", self.mcp_config_path)),
194
+ "loaded_server_count": int(trace.get("loaded_server_count", -1)),
195
+ "minimal_config_selected_count": int(trace.get("minimal_config_selected_count", 0)),
196
+ "full_config_server_count": int(trace.get("full_config_server_count", 0)),
197
+ "path_injected": bool(trace.get("path_injected", False)),
198
+ "package_dir_exists": bool(trace.get("package_dir_exists", False)),
199
+ "biomni_root": str(trace.get("biomni_root", self.biomni_root)),
200
+ }
201
+ self._biomni_probe_cache = result
202
+ return result
203
+
204
+ def _get_biomni_agent_context(self, hypothesis_text: str = "", force_rebuild: bool = False) -> dict[str, Any]:
205
+ """
206
+ Build/reuse a Biomni A1 agent with MCP loaded.
207
+ Returns a context dict:
208
+ {
209
+ ok: bool,
210
+ agent: A1 | None,
211
+ trace: dict[str, Any],
212
+ error: str
213
+ }
214
+ """
215
+ if self._biomni_agent_cache is not None and not force_rebuild:
216
+ return self._biomni_agent_cache
217
+
218
+ registration = self._registration_state or self.ensure_mcp_registered(dry_run=False)
219
+ if not registration.get("ok", False):
220
+ ctx = {
221
+ "ok": False,
222
+ "agent": None,
223
+ "trace": {"mcp_registration_ok": False},
224
+ "error": "mcp_registration_failed",
225
+ }
226
+ self._biomni_agent_cache = ctx
227
+ return ctx
228
+
229
+ deps_ok, missing_modules, deps_evidence = self._check_l2_dependencies()
230
+ if not deps_ok:
231
+ ctx = {
232
+ "ok": False,
233
+ "agent": None,
234
+ "trace": {
235
+ "mcp_registration_ok": True,
236
+ "missing_modules": missing_modules,
237
+ },
238
+ "error": deps_evidence,
239
+ }
240
+ self._biomni_agent_cache = ctx
241
+ return ctx
242
+
243
+ try:
244
+ import_info = self._prepare_biomni_import()
245
+ from biomni.agent import A1
246
+ llm_name, llm_source = self._resolve_biomni_llm_source()
247
+
248
+ min_cfg = self._build_minimal_mcp_config(hypothesis_text)
249
+ used_config_path = str(self.mcp_config_path)
250
+ loaded_server_count = -1
251
+ minimal_server_count = 0
252
+ full_server_count = 0
253
+ if min_cfg is not None:
254
+ minimal_server_count = int(min_cfg.get("selected_count", 0))
255
+ full_server_count = int(min_cfg.get("full_count", 0))
256
+ if minimal_server_count > 0:
257
+ used_config_path = str(min_cfg["path"])
258
+
259
+ agent = A1(llm=llm_name, source=llm_source)
260
+ agent.add_mcp(config_path=used_config_path)
261
+ tools = agent.list_custom_tools() or []
262
+ if min_cfg is not None and minimal_server_count > 0:
263
+ loaded_server_count = minimal_server_count
264
+ elif min_cfg is not None:
265
+ loaded_server_count = full_server_count
266
+ if not tools and used_config_path != str(self.mcp_config_path):
267
+ agent = A1(llm=llm_name, source=llm_source)
268
+ agent.add_mcp(config_path=str(self.mcp_config_path))
269
+ tools = agent.list_custom_tools() or []
270
+ used_config_path = str(self.mcp_config_path)
271
+ loaded_server_count = full_server_count if full_server_count > 0 else -1
272
+
273
+ ctx = {
274
+ "ok": True,
275
+ "agent": agent,
276
+ "trace": {
277
+ "custom_tool_count": len(tools),
278
+ "mcp_config_used": used_config_path,
279
+ "loaded_server_count": loaded_server_count,
280
+ "minimal_config_selected_count": minimal_server_count,
281
+ "full_config_server_count": full_server_count,
282
+ "biomni_llm": llm_name,
283
+ "biomni_source": llm_source,
284
+ **import_info,
285
+ },
286
+ "error": "",
287
+ }
288
+ self._biomni_agent_cache = ctx
289
+ return ctx
290
+ except Exception as exc:
291
+ ctx = {
292
+ "ok": False,
293
+ "agent": None,
294
+ "trace": {"mcp_registration_ok": True},
295
+ "error": str(exc),
296
+ }
297
+ self._biomni_agent_cache = ctx
298
+ return ctx
299
+
300
+ @staticmethod
301
+ def _extract_json_like_block(text: str) -> dict[str, Any]:
302
+ s = (text or "").strip()
303
+ if not s:
304
+ return {}
305
+ try:
306
+ return json.loads(s) if s.startswith("{") else {}
307
+ except Exception:
308
+ pass
309
+ # naive fallback: find first {...}
310
+ start = s.find("{")
311
+ end = s.rfind("}")
312
+ if start >= 0 and end > start:
313
+ block = s[start : end + 1]
314
+ try:
315
+ return json.loads(block)
316
+ except Exception:
317
+ return {}
318
+ return {}
319
+
320
+ def _execute_hypothesis_with_biomni(self, h: dict[str, Any]) -> dict[str, Any]:
321
+ """
322
+ Execute hypothesis using Biomni directly (A1.go) with lightweight prompt.
323
+ Returns execution summary and artifact path.
324
+ """
325
+ text = f"{h.get('title', '')} {h.get('hypothesis', '')}".strip()
326
+ ctx = self._get_biomni_agent_context(text)
327
+ if not ctx.get("ok", False):
328
+ return {
329
+ "ok": False,
330
+ "error": f"biomni_agent_unavailable: {ctx.get('error', 'unknown')}",
331
+ "trace": ctx.get("trace", {}),
332
+ }
333
+
334
+ agent = ctx.get("agent")
335
+ data_sources = [str(x) for x in h.get("data_sources", [])][:5]
336
+ ops = [x for x in h.get("data_operations", []) if isinstance(x, dict)]
337
+ prompt = (
338
+ "You are validating a bioinformatics hypothesis in lightweight mode.\n"
339
+ "Use available MCP tools where useful and provide concise execution output.\n"
340
+ "Return JSON with keys: status, summary, key_metrics, recommendation.\n\n"
341
+ f"Domain: {h.get('domain', '')}\n"
342
+ f"Hypothesis title: {h.get('title', '')}\n"
343
+ f"Hypothesis: {h.get('hypothesis', '')}\n"
344
+ f"Expected improvement: {h.get('expected_improvement', '')}\n"
345
+ f"Theoretical basis: {h.get('theoretical_basis', '')}\n"
346
+ f"Data sources: {json.dumps(data_sources, ensure_ascii=True)}\n"
347
+ f"Requested operations: {json.dumps(ops, ensure_ascii=True)}\n"
348
+ "Please execute a minimal-cost validation and return machine-readable JSON."
349
+ )
350
+
351
+ try:
352
+ logs, final_message = agent.go(prompt)
353
+ parsed = self._extract_json_like_block(str(final_message))
354
+ status_raw = str(parsed.get("status", "")).lower()
355
+ mapped_status = "success" if status_raw in {"success", "ok", "passed"} else ("failed" if status_raw in {"failed", "error"} else "inconclusive")
356
+ summary = str(parsed.get("summary", "")).strip() or str(final_message)[:1000]
357
+ key_metrics = parsed.get("key_metrics", {}) if isinstance(parsed.get("key_metrics", {}), dict) else {}
358
+ recommendation = str(parsed.get("recommendation", "")).strip()
359
+
360
+ out_dir = self.project_root / "agent_system" / "results" / "biomni_exec"
361
+ out_dir.mkdir(parents=True, exist_ok=True)
362
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
363
+ out_path = out_dir / f"biomni_exec_{h.get('hypothesis_id', 'unknown')}_{ts}.json"
364
+ out_payload = {
365
+ "hypothesis_id": h.get("hypothesis_id", ""),
366
+ "domain": h.get("domain", ""),
367
+ "prompt": prompt,
368
+ "parsed": parsed,
369
+ "status": mapped_status,
370
+ "summary": summary,
371
+ "key_metrics": key_metrics,
372
+ "recommendation": recommendation,
373
+ "final_message": str(final_message),
374
+ "log_tail": logs[-20:] if isinstance(logs, list) else [],
375
+ "trace": ctx.get("trace", {}),
376
+ "saved_at": datetime.now(timezone.utc).isoformat(),
377
+ }
378
+ out_path.write_text(json.dumps(out_payload, indent=2, ensure_ascii=True), encoding="utf-8")
379
+ return {
380
+ "ok": True,
381
+ "status": mapped_status,
382
+ "summary": summary,
383
+ "key_metrics": key_metrics,
384
+ "recommendation": recommendation,
385
+ "artifact_file": str(out_path),
386
+ "trace": ctx.get("trace", {}),
387
+ }
388
+ except Exception as exc:
389
+ return {
390
+ "ok": False,
391
+ "error": f"biomni_execution_failed: {exc}",
392
+ "trace": ctx.get("trace", {}),
393
+ }
394
+
395
+ def _build_minimal_mcp_config(self, hypothesis_text: str) -> dict[str, Any] | None:
396
+ yaml_spec = importlib.util.find_spec("yaml")
397
+ if yaml_spec is None:
398
+ return None
399
+ import yaml # type: ignore
400
+
401
+ if not self.mcp_config_path.exists():
402
+ return None
403
+
404
+ try:
405
+ raw = self.mcp_config_path.read_text(encoding="utf-8")
406
+ doc = yaml.safe_load(raw) or {}
407
+ except Exception:
408
+ return None
409
+ servers = doc.get("mcp_servers", {})
410
+ if not isinstance(servers, dict) or not servers:
411
+ return None
412
+
413
+ full_count = len(servers)
414
+ max_servers = int(os.getenv("BIOCLAW_MIN_MCP_SERVERS", "40"))
415
+ max_servers = max(5, min(200, max_servers))
416
+
417
+ q = (hypothesis_text or "").lower()
418
+ tokens = [t for t in q.replace("-", " ").replace("_", " ").split() if len(t) >= 3][:30]
419
+
420
+ scored: list[tuple[int, str, dict[str, Any]]] = []
421
+ for name, cfg in servers.items():
422
+ if not isinstance(cfg, dict):
423
+ continue
424
+ cmd = " ".join([str(x).lower() for x in cfg.get("command", [])]) if isinstance(cfg.get("command"), list) else str(cfg.get("command", "")).lower()
425
+ desc = str(cfg.get("description", "")).lower()
426
+ hay = f"{name.lower()} {desc} {cmd}"
427
+ s = 0
428
+ for tok in tokens:
429
+ if tok in hay:
430
+ s += 2
431
+ if "single" in hay or "cell" in hay or "rna" in hay:
432
+ s += 1
433
+ scored.append((s, name, cfg))
434
+
435
+ scored.sort(key=lambda x: x[0], reverse=True)
436
+ chosen = [x for x in scored if x[0] > 0][:max_servers]
437
+ if len(chosen) < min(10, max_servers):
438
+ # Backfill with top entries to keep probe meaningful.
439
+ fallback_pool = [x for x in scored if x[1] not in {c[1] for c in chosen}]
440
+ need = min(10, max_servers) - len(chosen)
441
+ chosen.extend(fallback_pool[:need])
442
+ if not chosen:
443
+ chosen = scored[: min(10, max_servers)]
444
+ if not chosen:
445
+ return None
446
+
447
+ selected_servers = {name: cfg for _, name, cfg in chosen}
448
+ out_dir = self.project_root / "agent_system" / "results" / "e1_runtime" / "min_configs"
449
+ out_dir.mkdir(parents=True, exist_ok=True)
450
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
451
+ out_path = out_dir / f"mcp_min_{ts}.yaml"
452
+ out_path.write_text(
453
+ yaml.safe_dump({"mcp_servers": selected_servers}, sort_keys=False, allow_unicode=False),
454
+ encoding="utf-8",
455
+ )
456
+ return {
457
+ "path": out_path,
458
+ "selected_count": len(selected_servers),
459
+ "full_count": full_count,
460
+ }
461
+
462
+ def _persist_runtime_artifact(self, report_dict: dict[str, Any], hypothesis: dict[str, Any]) -> str:
463
+ runtime_dir = self.project_root / "agent_system" / "results" / "e1_runtime"
464
+ runtime_dir.mkdir(parents=True, exist_ok=True)
465
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
466
+ out_path = runtime_dir / f"{report_dict.get('level', 'Lx').lower()}_{report_dict.get('validation_id', 'unknown')}_{ts}.json"
467
+ payload = {
468
+ "validation": report_dict,
469
+ "hypothesis": {
470
+ "hypothesis_id": hypothesis.get("hypothesis_id", ""),
471
+ "domain": hypothesis.get("domain", ""),
472
+ "title": hypothesis.get("title", ""),
473
+ },
474
+ "saved_at": datetime.now(timezone.utc).isoformat(),
475
+ }
476
+ out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=True), encoding="utf-8")
477
+
478
+ summary_path = runtime_dir / "summary.json"
479
+ if summary_path.exists():
480
+ try:
481
+ summary = json.loads(summary_path.read_text(encoding="utf-8"))
482
+ except Exception:
483
+ summary = {}
484
+ else:
485
+ summary = {}
486
+ by_level = summary.setdefault("by_level", {})
487
+ lvl = report_dict.get("level", "UNKNOWN")
488
+ s = by_level.setdefault(lvl, {"count": 0, "success": 0, "inconclusive": 0, "failed": 0, "avg_score": 0.0})
489
+ old_count = int(s.get("count", 0))
490
+ old_avg = float(s.get("avg_score", 0.0))
491
+ new_score = float(report_dict.get("score", 0.0))
492
+ new_count = old_count + 1
493
+ s["count"] = new_count
494
+ s["avg_score"] = (old_avg * old_count + new_score) / max(1, new_count)
495
+ st = str(report_dict.get("status", "inconclusive"))
496
+ s[st] = int(s.get(st, 0)) + 1
497
+ summary["total_reports"] = int(summary.get("total_reports", 0)) + 1
498
+ summary["last_report_file"] = str(out_path)
499
+ summary["last_updated"] = datetime.now(timezone.utc).isoformat()
500
+ summary_path.write_text(json.dumps(summary, indent=2, ensure_ascii=True), encoding="utf-8")
501
+ return str(out_path)
502
+
503
+ def _index_data_files(self, data_root: Path, limit: int = 1000) -> list[Path]:
504
+ if not data_root.exists():
505
+ return []
506
+ files: list[Path] = []
507
+ for p in sorted(data_root.rglob("*")):
508
+ if p.is_file():
509
+ files.append(p)
510
+ if len(files) >= limit:
511
+ break
512
+ return files
513
+
514
+ def _download_online_example_data(self, domain: str, max_files: int = 2) -> list[Path]:
515
+ """
516
+ Best-effort fallback downloader when no usable local dataset is available.
517
+ Downloads small public tabular files so L3/L4 can still produce bound validation reports.
518
+ """
519
+ out_dir = self.project_root / "agent_system" / "results" / "downloaded_example_data"
520
+ out_dir.mkdir(parents=True, exist_ok=True)
521
+
522
+ domain_l = str(domain).lower()
523
+ single_cell_candidates = [
524
+ (
525
+ "pbmc3k_marker_genes.csv",
526
+ "https://raw.githubusercontent.com/scverse/scanpy-tutorials/main/pbmc3k/marker_genes.csv",
527
+ ),
528
+ (
529
+ "pbmc3k_obs_metadata.csv",
530
+ "https://raw.githubusercontent.com/scverse/scanpy-tutorials/main/pbmc3k/obs_metadata.csv",
531
+ ),
532
+ ]
533
+ generic_candidates = [
534
+ (
535
+ "iris.csv",
536
+ "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/iris.csv",
537
+ ),
538
+ (
539
+ "tips.csv",
540
+ "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/tips.csv",
541
+ ),
542
+ ]
543
+ candidates = single_cell_candidates + generic_candidates if ("single" in domain_l or "cell" in domain_l) else generic_candidates + single_cell_candidates
544
+
545
+ downloaded: list[Path] = []
546
+ for filename, url in candidates:
547
+ target = out_dir / filename
548
+ if target.exists() and target.stat().st_size > 0:
549
+ downloaded.append(target)
550
+ if len(downloaded) >= max_files:
551
+ break
552
+ continue
553
+ try:
554
+ urllib.request.urlretrieve(url, str(target))
555
+ if target.exists() and target.stat().st_size > 0:
556
+ downloaded.append(target)
557
+ if len(downloaded) >= max_files:
558
+ break
559
+ except Exception:
560
+ continue
561
+ return downloaded
562
+
563
+ def _safe_read_tabular_preview(self, file_path: Path, sample_rows: int = 500) -> dict[str, Any]:
564
+ suffix = file_path.suffix.lower()
565
+ result: dict[str, Any] = {
566
+ "file": str(file_path),
567
+ "suffix": suffix,
568
+ "status": "skipped",
569
+ "rows_scanned": 0,
570
+ "columns": [],
571
+ "missing_cells": 0,
572
+ "total_cells": 0,
573
+ "numeric_columns": [],
574
+ }
575
+
576
+ if suffix in {".csv", ".tsv"}:
577
+ delim = "," if suffix == ".csv" else "\t"
578
+ with file_path.open("r", encoding="utf-8", errors="ignore", newline="") as fh:
579
+ reader = csv.DictReader(fh, delimiter=delim)
580
+ cols = reader.fieldnames or []
581
+ result["columns"] = cols
582
+ rows = 0
583
+ missing = 0
584
+ total = 0
585
+ numeric_candidates: dict[str, int] = {c: 0 for c in cols}
586
+ for row in reader:
587
+ rows += 1
588
+ for c in cols:
589
+ v = (row.get(c) or "").strip()
590
+ total += 1
591
+ if v == "":
592
+ missing += 1
593
+ else:
594
+ try:
595
+ float(v)
596
+ numeric_candidates[c] += 1
597
+ except Exception:
598
+ pass
599
+ if rows >= sample_rows:
600
+ break
601
+ result["rows_scanned"] = rows
602
+ result["missing_cells"] = missing
603
+ result["total_cells"] = total
604
+ result["numeric_columns"] = [c for c, n in numeric_candidates.items() if n > 0]
605
+ result["status"] = "loaded"
606
+ return result
607
+
608
+ if suffix == ".parquet":
609
+ pd_spec = importlib.util.find_spec("pandas")
610
+ if pd_spec is None:
611
+ result["status"] = "skipped"
612
+ result["error"] = "pandas_not_installed_for_parquet"
613
+ return result
614
+ import pandas as pd # type: ignore
615
+
616
+ df = pd.read_parquet(file_path)
617
+ if len(df) > sample_rows:
618
+ df = df.head(sample_rows)
619
+ result["rows_scanned"] = int(len(df))
620
+ cols = [str(c) for c in df.columns.tolist()]
621
+ result["columns"] = cols
622
+ total = int(df.shape[0] * df.shape[1]) if df.shape[1] > 0 else 0
623
+ missing = int(df.isna().sum().sum()) if total > 0 else 0
624
+ numeric_cols = [str(c) for c in df.select_dtypes(include=["number"]).columns.tolist()]
625
+ result["missing_cells"] = missing
626
+ result["total_cells"] = total
627
+ result["numeric_columns"] = numeric_cols
628
+ result["status"] = "loaded"
629
+ return result
630
+
631
+ if suffix == ".json":
632
+ with file_path.open("r", encoding="utf-8", errors="ignore") as fh:
633
+ payload = json.load(fh)
634
+ if isinstance(payload, list):
635
+ rows = min(sample_rows, len(payload))
636
+ cols = sorted({k for item in payload[:rows] if isinstance(item, dict) for k in item.keys()})
637
+ result["rows_scanned"] = rows
638
+ result["columns"] = cols
639
+ result["status"] = "loaded"
640
+ elif isinstance(payload, dict):
641
+ result["rows_scanned"] = 1
642
+ result["columns"] = sorted(payload.keys())
643
+ result["status"] = "loaded"
644
+ else:
645
+ result["status"] = "loaded"
646
+ return result
647
+
648
+ result["status"] = "skipped"
649
+ result["error"] = f"unsupported_suffix:{suffix or 'none'}"
650
+ return result
651
+
652
+ def _safe_read_tabular_full(self, file_path: Path, max_rows: int = 200000) -> dict[str, Any]:
653
+ """
654
+ L4-oriented data pass.
655
+ Attempts a fuller scan (or up to max_rows for safety) and includes basic numeric summaries.
656
+ """
657
+ suffix = file_path.suffix.lower()
658
+ result: dict[str, Any] = {
659
+ "file": str(file_path),
660
+ "suffix": suffix,
661
+ "status": "skipped",
662
+ "rows_scanned": 0,
663
+ "columns": [],
664
+ "missing_cells": 0,
665
+ "total_cells": 0,
666
+ "numeric_columns": [],
667
+ "truncated": False,
668
+ "numeric_summary": {},
669
+ }
670
+
671
+ if suffix in {".csv", ".tsv"}:
672
+ delim = "," if suffix == ".csv" else "\t"
673
+ with file_path.open("r", encoding="utf-8", errors="ignore", newline="") as fh:
674
+ reader = csv.DictReader(fh, delimiter=delim)
675
+ cols = reader.fieldnames or []
676
+ result["columns"] = cols
677
+ rows = 0
678
+ missing = 0
679
+ total = 0
680
+ numeric_samples: dict[str, list[float]] = {c: [] for c in cols}
681
+ for row in reader:
682
+ rows += 1
683
+ for c in cols:
684
+ v = (row.get(c) or "").strip()
685
+ total += 1
686
+ if v == "":
687
+ missing += 1
688
+ else:
689
+ try:
690
+ fv = float(v)
691
+ if len(numeric_samples[c]) < 5000:
692
+ numeric_samples[c].append(fv)
693
+ except Exception:
694
+ pass
695
+ if rows >= max_rows:
696
+ result["truncated"] = True
697
+ break
698
+ result["rows_scanned"] = rows
699
+ result["missing_cells"] = missing
700
+ result["total_cells"] = total
701
+ numeric_cols = [c for c, arr in numeric_samples.items() if arr]
702
+ result["numeric_columns"] = numeric_cols
703
+ summary = {}
704
+ for c in numeric_cols[:20]:
705
+ arr = numeric_samples[c]
706
+ summary[c] = {
707
+ "count": len(arr),
708
+ "mean": float(statistics.fmean(arr)),
709
+ "min": float(min(arr)),
710
+ "max": float(max(arr)),
711
+ }
712
+ result["numeric_summary"] = summary
713
+ result["status"] = "loaded"
714
+ return result
715
+
716
+ if suffix == ".parquet":
717
+ pd_spec = importlib.util.find_spec("pandas")
718
+ if pd_spec is None:
719
+ result["status"] = "skipped"
720
+ result["error"] = "pandas_not_installed_for_parquet"
721
+ return result
722
+ import pandas as pd # type: ignore
723
+
724
+ df = pd.read_parquet(file_path)
725
+ if len(df) > max_rows:
726
+ df = df.head(max_rows)
727
+ result["truncated"] = True
728
+ result["rows_scanned"] = int(len(df))
729
+ cols = [str(c) for c in df.columns.tolist()]
730
+ result["columns"] = cols
731
+ total = int(df.shape[0] * df.shape[1]) if df.shape[1] > 0 else 0
732
+ missing = int(df.isna().sum().sum()) if total > 0 else 0
733
+ numeric_cols = [str(c) for c in df.select_dtypes(include=["number"]).columns.tolist()]
734
+ result["missing_cells"] = missing
735
+ result["total_cells"] = total
736
+ result["numeric_columns"] = numeric_cols
737
+ summary = {}
738
+ for c in numeric_cols[:20]:
739
+ s = df[c].dropna()
740
+ if len(s) == 0:
741
+ continue
742
+ summary[str(c)] = {
743
+ "count": int(len(s)),
744
+ "mean": float(s.mean()),
745
+ "min": float(s.min()),
746
+ "max": float(s.max()),
747
+ }
748
+ result["numeric_summary"] = summary
749
+ result["status"] = "loaded"
750
+ return result
751
+
752
+ if suffix == ".json":
753
+ with file_path.open("r", encoding="utf-8", errors="ignore") as fh:
754
+ payload = json.load(fh)
755
+ if isinstance(payload, list):
756
+ rows = len(payload)
757
+ if rows > max_rows:
758
+ rows = max_rows
759
+ result["truncated"] = True
760
+ cols = sorted({k for item in payload[:rows] if isinstance(item, dict) for k in item.keys()})
761
+ result["rows_scanned"] = rows
762
+ result["columns"] = cols
763
+ result["status"] = "loaded"
764
+ elif isinstance(payload, dict):
765
+ result["rows_scanned"] = 1
766
+ result["columns"] = sorted(payload.keys())
767
+ result["status"] = "loaded"
768
+ else:
769
+ result["status"] = "loaded"
770
+ return result
771
+
772
+ result["status"] = "skipped"
773
+ result["error"] = f"unsupported_suffix:{suffix or 'none'}"
774
+ return result
775
+
776
+ @staticmethod
777
+ def _domain_relevance_score(domain: str, selected_files: list[Path], per_file_results: list[dict[str, Any]]) -> tuple[float, list[str]]:
778
+ domain_l = str(domain).lower()
779
+ if not selected_files:
780
+ return 0.0, ["no_selected_files"]
781
+ hints = []
782
+ if "single_cell" in domain_l or "single" in domain_l:
783
+ hints = ["single", "cell", "rna", "census", "marker", "celltype", "expression"]
784
+ else:
785
+ hints = [x for x in domain_l.split("_") if x]
786
+
787
+ matched = 0
788
+ explanations: list[str] = []
789
+ for p in selected_files:
790
+ p_low = str(p).lower()
791
+ if any(h in p_low for h in hints):
792
+ matched += 1
793
+ explanations.append(f"file_match:{p.name}")
794
+ for r in per_file_results:
795
+ cols = " ".join([str(c).lower() for c in r.get("columns", [])])
796
+ if any(h in cols for h in hints):
797
+ matched += 1
798
+ explanations.append(f"column_match:{Path(str(r.get('file', 'unknown'))).name}")
799
+ denom = max(1, len(selected_files) + len(per_file_results))
800
+ return min(1.0, matched / denom), explanations[:10]
801
+
802
+ @staticmethod
803
+ def _build_interpretability_summary(
804
+ *,
805
+ level: str,
806
+ loaded_count: int,
807
+ selected_count: int,
808
+ rows_scanned: int,
809
+ missing_rate: float,
810
+ numeric_cols_total: int,
811
+ relevance_score: float,
812
+ ) -> dict[str, Any]:
813
+ quality = "high" if missing_rate < 0.01 else ("medium" if missing_rate < 0.1 else "low")
814
+ coverage = loaded_count / max(1, selected_count)
815
+ coverage_label = "high" if coverage >= 0.8 else ("medium" if coverage >= 0.5 else "low")
816
+ relevance_label = "high" if relevance_score >= 0.6 else ("medium" if relevance_score >= 0.3 else "low")
817
+ return {
818
+ "level": level,
819
+ "data_quality": quality,
820
+ "coverage": coverage_label,
821
+ "domain_relevance": relevance_label,
822
+ "rows_scanned": rows_scanned,
823
+ "numeric_signal_strength": "high" if numeric_cols_total >= 10 else ("medium" if numeric_cols_total >= 3 else "low"),
824
+ "recommendations": [
825
+ "Prefer domain-relevant files if domain_relevance is low.",
826
+ "Increase file coverage when coverage is medium/low.",
827
+ "Escalate to L4 only after L3 relevance is acceptable.",
828
+ ],
829
+ }
830
+
831
+ @staticmethod
832
+ def _check_l2_dependencies() -> tuple[bool, list[str], str]:
833
+ required_modules = ["nest_asyncio", "mcp", "yaml"]
834
+ missing = [m for m in required_modules if importlib.util.find_spec(m) is None]
835
+ if not missing:
836
+ return True, [], ""
837
+
838
+ module_to_pip = {
839
+ "nest_asyncio": "nest_asyncio",
840
+ "mcp": "mcp",
841
+ "yaml": "PyYAML",
842
+ }
843
+ pip_pkgs = [module_to_pip[m] for m in missing]
844
+ install_cmd = f"{sys.executable} -m pip install " + " ".join(pip_pkgs)
845
+ evidence = (
846
+ "L2 dependency check failed. Missing modules: "
847
+ f"{', '.join(missing)}. "
848
+ f"Install with: {install_cmd}. "
849
+ f"(module->pip: {', '.join(f'{m}->{module_to_pip[m]}' for m in missing)})"
850
+ )
851
+ return False, missing, evidence
852
+
853
+ def _validate_l1(self, h: dict[str, Any]) -> tuple[str, float, dict[str, Any], str, str]:
854
+ text = f"{h.get('title', '')} {h.get('hypothesis', '')}".lower()
855
+ violations: list[str] = []
856
+ if "敲除" in text and "增殖加快" in text:
857
+ violations.append("possible essential-gene-growth contradiction")
858
+ if "不存在的工具" in text:
859
+ violations.append("depends on non-existing tool")
860
+ if "必须" in text and "不需要数据" in text:
861
+ violations.append("self-contradictory requirement")
862
+
863
+ if violations:
864
+ return (
865
+ "failed",
866
+ 0.1,
867
+ {"rule_violations": violations, "violation_count": len(violations)},
868
+ "biological_or_tooling_inconsistency",
869
+ "L1 rules detected contradictions.",
870
+ )
871
+ return (
872
+ "success",
873
+ 0.6,
874
+ {"rule_violations": [], "violation_count": 0},
875
+ "",
876
+ "L1 rules found no obvious contradiction.",
877
+ )
878
+
879
+ def _validate_l2(self, h: dict[str, Any]) -> tuple[str, float, dict[str, Any], str, str]:
880
+ registration = self._registration_state or self.ensure_mcp_registered(dry_run=False)
881
+ if not registration.get("ok", False):
882
+ return (
883
+ "inconclusive",
884
+ 0.3,
885
+ {"mcp_registration_ok": False},
886
+ "mcp_registration_failed",
887
+ "L2 could not ensure MCP registration.",
888
+ )
889
+
890
+ deps_ok, missing_modules, deps_evidence = self._check_l2_dependencies()
891
+ if not deps_ok:
892
+ return (
893
+ "inconclusive",
894
+ 0.2,
895
+ {
896
+ "mcp_registration_ok": True,
897
+ "l2_dependency_check_ok": False,
898
+ "missing_modules": missing_modules,
899
+ },
900
+ "biomni_dependency_missing",
901
+ deps_evidence,
902
+ )
903
+
904
+ try:
905
+ import_info = self._prepare_biomni_import()
906
+ from biomni.agent import A1
907
+ llm_name, llm_source = self._resolve_biomni_llm_source()
908
+
909
+ agent = A1(llm=llm_name, source=llm_source)
910
+ agent.add_mcp(config_path=str(self.mcp_config_path))
911
+ tools = agent.list_custom_tools() or []
912
+ if not tools:
913
+ return (
914
+ "inconclusive",
915
+ 0.35,
916
+ {
917
+ "mcp_registration_ok": True,
918
+ "custom_tool_count": 0,
919
+ "biomni_llm": llm_name,
920
+ "biomni_source": llm_source,
921
+ **import_info,
922
+ },
923
+ "no_mcp_tools_discovered",
924
+ "Biomni loaded config but no tools were discovered.",
925
+ )
926
+
927
+ text = f"{h.get('title', '')} {h.get('hypothesis', '')}".lower()
928
+ related = [t for t in tools if any(tok in t.lower() for tok in text.split()[:20])]
929
+ score = 0.5 + min(0.4, len(related) * 0.05)
930
+ return (
931
+ "success",
932
+ score,
933
+ {
934
+ "mcp_registration_ok": True,
935
+ "custom_tool_count": len(tools),
936
+ "related_tool_hits": len(related),
937
+ "biomni_llm": llm_name,
938
+ "biomni_source": llm_source,
939
+ **import_info,
940
+ },
941
+ "",
942
+ "L2 passed using Biomni MCP tool readiness check.",
943
+ )
944
+ except Exception as exc:
945
+ import_info = self._prepare_biomni_import()
946
+ return (
947
+ "inconclusive",
948
+ 0.25,
949
+ {"mcp_registration_ok": True, **import_info},
950
+ "biomni_probe_failed",
951
+ f"Biomni probe failed: {exc}",
952
+ )
953
+
954
+ def _validate_l3(self, h: dict[str, Any]) -> tuple[str, float, dict[str, Any], str, str]:
955
+ probe = self._quick_biomni_probe(f"{h.get('title', '')} {h.get('hypothesis', '')}")
956
+ if not probe.get("ok", False):
957
+ return (
958
+ "inconclusive",
959
+ 0.25,
960
+ {
961
+ "mcp_registration_ok": bool(probe.get("mcp_registration_ok", False)),
962
+ "biomni_probe_status": probe.get("status", ""),
963
+ "biomni_probe_duration_ms": probe.get("duration_ms", 0),
964
+ "biomni_call_trace": {
965
+ "registration_attempted": True,
966
+ "biomni_runtime_called": False,
967
+ "cache_hit": bool(probe.get("cache_hit", False)),
968
+ },
969
+ },
970
+ str(probe.get("status", "biomni_probe_failed")),
971
+ f"L3 aborted: Biomni quick probe failed ({probe.get('error', 'unknown_error')}).",
972
+ )
973
+
974
+ data_root = self._resolve_biomni_data_root()
975
+ data_files = self._index_data_files(data_root, limit=1500)
976
+ if not data_files:
977
+ return (
978
+ "inconclusive",
979
+ 0.3,
980
+ {"data_root": str(data_root), "indexed_files": 0},
981
+ "l3_data_unavailable",
982
+ "L3 could not locate biomni_data files.",
983
+ )
984
+
985
+ requested = [Path(str(x)) for x in h.get("data_sources", []) if str(x).strip()]
986
+ if requested:
987
+ selected = [p for p in requested if p.exists()][:5]
988
+ else:
989
+ selected = data_files[:5]
990
+ downloaded_examples: list[Path] = []
991
+ if not selected:
992
+ downloaded_examples = self._download_online_example_data(h.get("domain", ""), max_files=2)
993
+ selected = downloaded_examples[:]
994
+
995
+ operations = [x for x in h.get("data_operations", []) if isinstance(x, dict)]
996
+ if not operations:
997
+ operations = [
998
+ {"action": "load_table", "target": "all_selected"},
999
+ {"action": "sample_rows", "rows": 500},
1000
+ {"action": "profile_missingness"},
1001
+ {"action": "numeric_summary"},
1002
+ ]
1003
+
1004
+ per_file_results: list[dict[str, Any]] = []
1005
+ loaded_count = 0
1006
+ for p in selected:
1007
+ try:
1008
+ r = self._safe_read_tabular_preview(p, sample_rows=500)
1009
+ per_file_results.append(r)
1010
+ if r.get("status") == "loaded":
1011
+ loaded_count += 1
1012
+ except Exception as exc:
1013
+ per_file_results.append(
1014
+ {
1015
+ "file": str(p),
1016
+ "status": "failed",
1017
+ "error": str(exc),
1018
+ }
1019
+ )
1020
+
1021
+ op_names = [str(op.get("action", "")) for op in operations]
1022
+ rows_scanned = sum(int(r.get("rows_scanned", 0) or 0) for r in per_file_results)
1023
+ total_cells = sum(int(r.get("total_cells", 0) or 0) for r in per_file_results)
1024
+ missing_cells = sum(int(r.get("missing_cells", 0) or 0) for r in per_file_results)
1025
+ missing_rate = (missing_cells / total_cells) if total_cells > 0 else 0.0
1026
+ numeric_cols_total = sum(len(r.get("numeric_columns", []) or []) for r in per_file_results)
1027
+ relevance_score, relevance_evidence = self._domain_relevance_score(h.get("domain", ""), selected, per_file_results)
1028
+
1029
+ results_dir = self.project_root / "agent_system" / "results" / "l3_reports"
1030
+ results_dir.mkdir(parents=True, exist_ok=True)
1031
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
1032
+ artifact_path = results_dir / f"l3_{h.get('hypothesis_id', 'unknown')}_{ts}.json"
1033
+ artifact_payload = {
1034
+ "hypothesis_id": h.get("hypothesis_id", ""),
1035
+ "domain": h.get("domain", ""),
1036
+ "data_root": str(data_root),
1037
+ "selected_files": [str(p) for p in selected],
1038
+ "operations": operations,
1039
+ "per_file_results": per_file_results,
1040
+ "rows_scanned": rows_scanned,
1041
+ "missing_rate": missing_rate,
1042
+ }
1043
+ artifact_path.write_text(json.dumps(artifact_payload, indent=2, ensure_ascii=True), encoding="utf-8")
1044
+
1045
+ if loaded_count == 0:
1046
+ return (
1047
+ "inconclusive",
1048
+ 0.35,
1049
+ {
1050
+ "data_root": str(data_root),
1051
+ "indexed_files": len(data_files),
1052
+ "selected_files": [str(p) for p in selected],
1053
+ "loaded_files": 0,
1054
+ "operations_requested": op_names,
1055
+ "l3_report_file": str(artifact_path),
1056
+ },
1057
+ "l3_no_loadable_data",
1058
+ "L3 selected files but none were loadable in lightweight mode.",
1059
+ )
1060
+
1061
+ score_components = {
1062
+ "base": 0.45,
1063
+ "loaded_files_component": 0.08 * loaded_count,
1064
+ "operation_component": 0.03 * min(8, len(op_names)),
1065
+ "domain_relevance_component": 0.08 * relevance_score,
1066
+ }
1067
+ score = min(0.92, sum(score_components.values()))
1068
+ status = "success" if loaded_count >= 1 else "inconclusive"
1069
+ biomni_exec = self._execute_hypothesis_with_biomni(h)
1070
+ if biomni_exec.get("ok", False):
1071
+ b_status = biomni_exec.get("status", "inconclusive")
1072
+ score = min(1.0, score + (0.08 if b_status == "success" else 0.0))
1073
+ if b_status == "failed":
1074
+ status = "failed"
1075
+ elif status != "failed" and b_status == "inconclusive":
1076
+ status = "inconclusive"
1077
+ else:
1078
+ score = max(0.0, score - 0.08)
1079
+ if status == "success":
1080
+ status = "inconclusive"
1081
+ evidence = (
1082
+ "L3 executed lightweight full-data checks with sampled previews; "
1083
+ f"loaded {loaded_count}/{len(selected)} files, scanned_rows={rows_scanned}, "
1084
+ f"missing_rate={missing_rate:.4f}, domain_relevance={relevance_score:.2f}. Report: {artifact_path}"
1085
+ )
1086
+ return (
1087
+ status,
1088
+ score,
1089
+ {
1090
+ "data_root": str(data_root),
1091
+ "indexed_files": len(data_files),
1092
+ "selected_files": [str(p) for p in selected],
1093
+ "loaded_files": loaded_count,
1094
+ "rows_scanned": rows_scanned,
1095
+ "missing_rate": missing_rate,
1096
+ "numeric_columns_total": numeric_cols_total,
1097
+ "operations_requested": op_names,
1098
+ "domain_relevance_score": relevance_score,
1099
+ "domain_relevance_evidence": relevance_evidence,
1100
+ "score_breakdown": score_components,
1101
+ "interpretability_summary": self._build_interpretability_summary(
1102
+ level="L3",
1103
+ loaded_count=loaded_count,
1104
+ selected_count=len(selected),
1105
+ rows_scanned=rows_scanned,
1106
+ missing_rate=missing_rate,
1107
+ numeric_cols_total=numeric_cols_total,
1108
+ relevance_score=relevance_score,
1109
+ ),
1110
+ "biomni_call_trace": {
1111
+ "registration_attempted": bool(self._registration_state),
1112
+ "biomni_runtime_called": True,
1113
+ "cache_hit": bool(probe.get("cache_hit", False)),
1114
+ "biomni_probe_duration_ms": probe.get("duration_ms", 0),
1115
+ "custom_tool_count": probe.get("custom_tool_count", 0),
1116
+ "related_tool_hits": probe.get("related_tool_hits", 0),
1117
+ "mcp_config_used": probe.get("mcp_config_used", str(self.mcp_config_path)),
1118
+ "loaded_server_count": probe.get("loaded_server_count", -1),
1119
+ "minimal_config_selected_count": probe.get("minimal_config_selected_count", 0),
1120
+ "full_config_server_count": probe.get("full_config_server_count", 0),
1121
+ "note": "L3 first performs a minimal Biomni runtime probe, then runs lightweight data checks.",
1122
+ },
1123
+ "downloaded_example_files": [str(p) for p in downloaded_examples],
1124
+ "l3_report_file": str(artifact_path),
1125
+ "biomni_execution": biomni_exec,
1126
+ },
1127
+ "" if biomni_exec.get("ok", False) else "biomni_execution_failed",
1128
+ evidence,
1129
+ )
1130
+
1131
+ def _validate_l4(self, h: dict[str, Any]) -> tuple[str, float, dict[str, Any], str, str]:
1132
+ probe = self._quick_biomni_probe(f"{h.get('title', '')} {h.get('hypothesis', '')}")
1133
+ if not probe.get("ok", False):
1134
+ return (
1135
+ "inconclusive",
1136
+ 0.3,
1137
+ {
1138
+ "mcp_registration_ok": bool(probe.get("mcp_registration_ok", False)),
1139
+ "biomni_probe_status": probe.get("status", ""),
1140
+ "biomni_probe_duration_ms": probe.get("duration_ms", 0),
1141
+ "biomni_call_trace": {
1142
+ "registration_attempted": True,
1143
+ "biomni_runtime_called": False,
1144
+ "cache_hit": bool(probe.get("cache_hit", False)),
1145
+ },
1146
+ },
1147
+ str(probe.get("status", "biomni_probe_failed")),
1148
+ f"L4 aborted: Biomni quick probe failed ({probe.get('error', 'unknown_error')}).",
1149
+ )
1150
+
1151
+ data_root = self._resolve_biomni_data_root()
1152
+ data_files = self._index_data_files(data_root, limit=3000)
1153
+ if not data_files:
1154
+ return (
1155
+ "inconclusive",
1156
+ 0.3,
1157
+ {"data_root": str(data_root), "indexed_files": 0},
1158
+ "l4_data_unavailable",
1159
+ "L4 could not locate biomni_data files.",
1160
+ )
1161
+
1162
+ requested = [Path(str(x)) for x in h.get("data_sources", []) if str(x).strip()]
1163
+ if requested:
1164
+ selected = [p for p in requested if p.exists()][:8]
1165
+ else:
1166
+ selected = data_files[:5]
1167
+ downloaded_examples: list[Path] = []
1168
+ if not selected:
1169
+ downloaded_examples = self._download_online_example_data(h.get("domain", ""), max_files=3)
1170
+ selected = downloaded_examples[:]
1171
+
1172
+ operations = [x for x in h.get("data_operations", []) if isinstance(x, dict)]
1173
+ if not operations:
1174
+ operations = [
1175
+ {"action": "load_table", "target": "all_selected"},
1176
+ {"action": "sample_rows", "rows": 500},
1177
+ {"action": "profile_missingness"},
1178
+ {"action": "numeric_summary"},
1179
+ ]
1180
+
1181
+ max_rows = int(os.getenv("BIOCLAW_L4_MAX_ROWS", "200000"))
1182
+ max_rows = max(1000, min(1000000, max_rows))
1183
+
1184
+ per_file_results: list[dict[str, Any]] = []
1185
+ loaded_count = 0
1186
+ truncated_count = 0
1187
+ for p in selected:
1188
+ try:
1189
+ r = self._safe_read_tabular_full(p, max_rows=max_rows)
1190
+ per_file_results.append(r)
1191
+ if r.get("status") == "loaded":
1192
+ loaded_count += 1
1193
+ if r.get("truncated"):
1194
+ truncated_count += 1
1195
+ except Exception as exc:
1196
+ per_file_results.append(
1197
+ {
1198
+ "file": str(p),
1199
+ "status": "failed",
1200
+ "error": str(exc),
1201
+ }
1202
+ )
1203
+
1204
+ rows_scanned = sum(int(r.get("rows_scanned", 0) or 0) for r in per_file_results)
1205
+ total_cells = sum(int(r.get("total_cells", 0) or 0) for r in per_file_results)
1206
+ missing_cells = sum(int(r.get("missing_cells", 0) or 0) for r in per_file_results)
1207
+ missing_rate = (missing_cells / total_cells) if total_cells > 0 else 0.0
1208
+ numeric_cols_total = sum(len(r.get("numeric_columns", []) or []) for r in per_file_results)
1209
+ relevance_score, relevance_evidence = self._domain_relevance_score(h.get("domain", ""), selected, per_file_results)
1210
+ op_names = [str(op.get("action", "")) for op in operations]
1211
+
1212
+ results_dir = self.project_root / "agent_system" / "results" / "l4_reports"
1213
+ results_dir.mkdir(parents=True, exist_ok=True)
1214
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
1215
+ artifact_path = results_dir / f"l4_{h.get('hypothesis_id', 'unknown')}_{ts}.json"
1216
+ artifact_payload = {
1217
+ "hypothesis_id": h.get("hypothesis_id", ""),
1218
+ "domain": h.get("domain", ""),
1219
+ "data_root": str(data_root),
1220
+ "selected_files": [str(p) for p in selected],
1221
+ "operations": operations,
1222
+ "max_rows_per_file": max_rows,
1223
+ "per_file_results": per_file_results,
1224
+ "rows_scanned": rows_scanned,
1225
+ "missing_rate": missing_rate,
1226
+ "numeric_columns_total": numeric_cols_total,
1227
+ "truncated_file_count": truncated_count,
1228
+ }
1229
+ artifact_path.write_text(json.dumps(artifact_payload, indent=2, ensure_ascii=True), encoding="utf-8")
1230
+
1231
+ if loaded_count == 0:
1232
+ return (
1233
+ "inconclusive",
1234
+ 0.35,
1235
+ {
1236
+ "data_root": str(data_root),
1237
+ "indexed_files": len(data_files),
1238
+ "selected_files": [str(p) for p in selected],
1239
+ "loaded_files": 0,
1240
+ "l4_report_file": str(artifact_path),
1241
+ },
1242
+ "l4_no_loadable_data",
1243
+ "L4 selected files but none were loadable.",
1244
+ )
1245
+
1246
+ completeness = 1.0 - min(1.0, missing_rate * 10.0)
1247
+ coverage = min(1.0, loaded_count / max(1, len(selected)))
1248
+ richness = min(1.0, numeric_cols_total / 20.0)
1249
+ trunc_penalty = 0.08 if truncated_count > 0 else 0.0
1250
+ score_components = {
1251
+ "base": 0.45,
1252
+ "coverage_component": 0.25 * coverage,
1253
+ "completeness_component": 0.2 * completeness,
1254
+ "richness_component": 0.15 * richness,
1255
+ "domain_relevance_component": 0.1 * relevance_score,
1256
+ "truncation_penalty": -trunc_penalty,
1257
+ }
1258
+ score = max(0.0, min(1.0, sum(score_components.values())))
1259
+ status = "success" if (loaded_count >= max(1, min(2, len(selected))) and completeness >= 0.5) else "inconclusive"
1260
+ biomni_exec = self._execute_hypothesis_with_biomni(h)
1261
+ if biomni_exec.get("ok", False):
1262
+ b_status = biomni_exec.get("status", "inconclusive")
1263
+ score = min(1.0, score + (0.1 if b_status == "success" else 0.0))
1264
+ if b_status == "failed":
1265
+ status = "failed"
1266
+ elif status != "failed" and b_status == "inconclusive":
1267
+ status = "inconclusive"
1268
+ else:
1269
+ score = max(0.0, score - 0.1)
1270
+ if status == "success":
1271
+ status = "inconclusive"
1272
+ evidence = (
1273
+ "L4 executed extended data checks; "
1274
+ f"loaded {loaded_count}/{len(selected)} files, rows_scanned={rows_scanned}, "
1275
+ f"missing_rate={missing_rate:.4f}, numeric_columns_total={numeric_cols_total}, domain_relevance={relevance_score:.2f}, "
1276
+ f"truncated_files={truncated_count}. Report: {artifact_path}"
1277
+ )
1278
+ return (
1279
+ status,
1280
+ score,
1281
+ {
1282
+ "data_root": str(data_root),
1283
+ "indexed_files": len(data_files),
1284
+ "selected_files": [str(p) for p in selected],
1285
+ "loaded_files": loaded_count,
1286
+ "rows_scanned": rows_scanned,
1287
+ "missing_rate": missing_rate,
1288
+ "numeric_columns_total": numeric_cols_total,
1289
+ "truncated_file_count": truncated_count,
1290
+ "operations_requested": op_names,
1291
+ "domain_relevance_score": relevance_score,
1292
+ "domain_relevance_evidence": relevance_evidence,
1293
+ "score_breakdown": score_components,
1294
+ "interpretability_summary": self._build_interpretability_summary(
1295
+ level="L4",
1296
+ loaded_count=loaded_count,
1297
+ selected_count=len(selected),
1298
+ rows_scanned=rows_scanned,
1299
+ missing_rate=missing_rate,
1300
+ numeric_cols_total=numeric_cols_total,
1301
+ relevance_score=relevance_score,
1302
+ ),
1303
+ "biomni_call_trace": {
1304
+ "registration_attempted": bool(self._registration_state),
1305
+ "biomni_runtime_called": True,
1306
+ "cache_hit": bool(probe.get("cache_hit", False)),
1307
+ "biomni_probe_duration_ms": probe.get("duration_ms", 0),
1308
+ "custom_tool_count": probe.get("custom_tool_count", 0),
1309
+ "related_tool_hits": probe.get("related_tool_hits", 0),
1310
+ "mcp_config_used": probe.get("mcp_config_used", str(self.mcp_config_path)),
1311
+ "loaded_server_count": probe.get("loaded_server_count", -1),
1312
+ "minimal_config_selected_count": probe.get("minimal_config_selected_count", 0),
1313
+ "full_config_server_count": probe.get("full_config_server_count", 0),
1314
+ "note": "L4 first performs a minimal Biomni runtime probe, then runs extended data checks.",
1315
+ },
1316
+ "downloaded_example_files": [str(p) for p in downloaded_examples],
1317
+ "l4_report_file": str(artifact_path),
1318
+ "biomni_execution": biomni_exec,
1319
+ },
1320
+ "" if biomni_exec.get("ok", False) else "biomni_execution_failed",
1321
+ evidence,
1322
+ )
1323
+
1324
+ def validate_hypothesis(self, hypothesis: Hypothesis | dict[str, Any], level: str = "L1") -> dict[str, Any]:
1325
+ h = self._coerce_hypothesis(hypothesis)
1326
+ level = level.upper().strip()
1327
+ if level not in self.LEVEL_CONFIDENCE:
1328
+ level = "L1"
1329
+
1330
+ if level == "L1":
1331
+ status, score, metrics, failure_reason, evidence = self._validate_l1(h)
1332
+ elif level == "L2":
1333
+ status, score, metrics, failure_reason, evidence = self._validate_l2(h)
1334
+ elif level == "L3":
1335
+ status, score, metrics, failure_reason, evidence = self._validate_l3(h)
1336
+ elif level == "L4":
1337
+ status, score, metrics, failure_reason, evidence = self._validate_l4(h)
1338
+ else:
1339
+ status, score, metrics, failure_reason, evidence = (
1340
+ "inconclusive",
1341
+ 0.4,
1342
+ {"implemented": False},
1343
+ f"{level}_not_implemented_in_v1",
1344
+ f"{level} validation is scaffolded in first version.",
1345
+ )
1346
+
1347
+ report = ValidationReport.build(
1348
+ hypothesis_id=h.get("hypothesis_id", ""),
1349
+ domain=h.get("domain", ""),
1350
+ level=level,
1351
+ status=status,
1352
+ score=score,
1353
+ confidence=self.LEVEL_CONFIDENCE[level],
1354
+ key_metrics=metrics,
1355
+ failure_reason=failure_reason,
1356
+ evidence=evidence,
1357
+ )
1358
+ self.memory.save_validation_report(report)
1359
+ # Save an insight so T1 can leverage execution outcomes as experience.
1360
+ try:
1361
+ title = f"{h.get('domain', 'general')} {level} {status}"
1362
+ recommendation = report.evidence
1363
+ biomni_exec = report.key_metrics.get("biomni_execution", {})
1364
+ if isinstance(biomni_exec, dict) and biomni_exec.get("recommendation"):
1365
+ recommendation = str(biomni_exec.get("recommendation"))
1366
+ ins = Insight.build(
1367
+ title=title,
1368
+ hypothesis=str(h.get("hypothesis", ""))[:1000],
1369
+ recommendation=recommendation[:2000],
1370
+ confidence=float(report.confidence),
1371
+ evidence_run_ids=[report.validation_id],
1372
+ tags=[str(h.get("domain", "general")), f"validation-{level.lower()}", status],
1373
+ )
1374
+ self.memory.save_insight(ins)
1375
+ except Exception:
1376
+ pass
1377
+ self.memory.update_summary_statistics()
1378
+ report_dict = report.to_dict()
1379
+ report_dict["runtime_report_file"] = self._persist_runtime_artifact(report_dict, h)
1380
+ return report_dict
1381
+
1382
+ def validate_top_hypotheses(
1383
+ self,
1384
+ ranked_hypotheses: list[dict[str, Any]],
1385
+ top_m: int = 3,
1386
+ level: str = "L1",
1387
+ ) -> list[dict[str, Any]]:
1388
+ reports: list[dict[str, Any]] = []
1389
+ selected = ranked_hypotheses[: max(0, top_m)]
1390
+ total = len(selected)
1391
+ for idx, h in enumerate(selected, start=1):
1392
+ hid = h.get("hypothesis_id", f"idx_{idx}")
1393
+ print(f"[STAGE:VALIDATION] running {idx}/{total} level={level.upper()} hypothesis_id={hid}", flush=True)
1394
+ report = self.validate_hypothesis(h, level=level)
1395
+ print(
1396
+ f"[STAGE:VALIDATION] finished {idx}/{total} hypothesis_id={hid} status={report.get('status', 'unknown')} score={report.get('score', 0)}",
1397
+ flush=True,
1398
+ )
1399
+ reports.append(report)
1400
+ return reports
BioScientist/agent_system/engines/t1_consultant.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from ..llm import (
10
+ ClaudeClientConfigError,
11
+ ClaudeCodeClient,
12
+ GeminiClientConfigError,
13
+ GeminiCodeClient,
14
+ KimiClientConfigError,
15
+ KimiCodeClient,
16
+ Qwen3ClientConfigError,
17
+ Qwen3LocalClient,
18
+ )
19
+ from ..schemas import Hypothesis, Insight, PipelineConfiguration
20
+ from ..shared_memory import SharedKnowledgeSpace
21
+
22
+
23
+ class BioinfoT1Consultant:
24
+ """Thought engine: reflect on reports and produce strategy/config guidance."""
25
+
26
+ def __init__(self, memory: SharedKnowledgeSpace):
27
+ self.memory = memory
28
+ self.backend = os.getenv("T1_MODEL_BACKEND", "claude").strip().lower()
29
+ self.last_generation_meta: dict[str, Any] = {
30
+ "requested_backend": self.backend,
31
+ "actual_backend": "none",
32
+ "used_fallback": False,
33
+ "error": "",
34
+ "history_size": 0,
35
+ "available_data_files": 0,
36
+ "candidates_returned": 0,
37
+ }
38
+ self.claude: ClaudeCodeClient | None = None
39
+ self.kimi: KimiCodeClient | None = None
40
+ self.qwen3: Qwen3LocalClient | None = None
41
+ self.gemini: GeminiCodeClient | None = None
42
+ if self.backend == "qwen3":
43
+ try:
44
+ self.qwen3 = Qwen3LocalClient()
45
+ except Qwen3ClientConfigError:
46
+ self.qwen3 = None
47
+ elif self.backend == "gemini":
48
+ try:
49
+ self.gemini = GeminiCodeClient()
50
+ except GeminiClientConfigError:
51
+ self.gemini = None
52
+ elif self.backend == "kimi":
53
+ try:
54
+ self.kimi = KimiCodeClient()
55
+ except KimiClientConfigError:
56
+ self.kimi = None
57
+ else:
58
+ try:
59
+ self.claude = ClaudeCodeClient()
60
+ except ClaudeClientConfigError:
61
+ self.claude = None
62
+
63
+ def review_reports(self) -> list[dict[str, Any]]:
64
+ reports = self.memory.list_reports()
65
+ if not reports:
66
+ return []
67
+
68
+ produced: list[dict[str, Any]] = []
69
+ for rep in reports[-20:]:
70
+ status = rep.get("status", "unknown")
71
+ task = rep.get("task", "generic")
72
+ if status == "failed":
73
+ insight = Insight.build(
74
+ title=f"{task}: failure pattern",
75
+ hypothesis="Parameter set or tool ordering may be unstable.",
76
+ recommendation="Use a conservative config and verify dependencies first.",
77
+ confidence=0.65,
78
+ evidence_run_ids=[rep.get("run_id", "unknown")],
79
+ tags=[task, "failure-mode"],
80
+ )
81
+ else:
82
+ insight = Insight.build(
83
+ title=f"{task}: successful path",
84
+ hypothesis="Current tool chain is reproducible for this task scope.",
85
+ recommendation="Promote this parameter set to default pipeline config.",
86
+ confidence=0.75,
87
+ evidence_run_ids=[rep.get("run_id", "unknown")],
88
+ tags=[task, "best-practice"],
89
+ )
90
+ self.memory.save_insight(insight)
91
+ produced.append(insight.to_dict())
92
+ return produced
93
+
94
+ def consult(self, user_goal: str, task_scope: str) -> dict[str, Any]:
95
+ insights = self.memory.list_insights()
96
+ matched = [
97
+ item
98
+ for item in insights
99
+ if task_scope.lower() in " ".join(item.get("tags", [])).lower()
100
+ or task_scope.lower() in item.get("title", "").lower()
101
+ ]
102
+ top = matched[-3:] if matched else insights[-3:]
103
+ recommendation = top[-1]["recommendation"] if top else "No prior insight found."
104
+
105
+ # 优先走可用 LLM 后端(Qwen3/Kimi/Claude);失败则回退规则推荐
106
+ llm_summary: dict[str, Any] | None = None
107
+ model_backend = "heuristic"
108
+ if self.qwen3 is not None or self.kimi is not None or self.gemini is not None or self.claude is not None:
109
+ try:
110
+ system_prompt = (
111
+ "You are a senior bioinformatics workflow consultant. "
112
+ "Return strict JSON with keys: primary_hypothesis, step_by_step_plan, recommendation, reasoning, risk_checks, next_actions. "
113
+ "step_by_step_plan, risk_checks and next_actions must be arrays of strings."
114
+ )
115
+ user_prompt = json.dumps(
116
+ {
117
+ "task_scope": task_scope,
118
+ "user_goal": user_goal,
119
+ "insights": top,
120
+ },
121
+ ensure_ascii=True,
122
+ )
123
+ if self.qwen3 is not None:
124
+ llm_summary = self.qwen3.complete_json(system_prompt=system_prompt, user_prompt=user_prompt)
125
+ model_backend = "qwen3"
126
+ elif self.kimi is not None:
127
+ text = self.kimi.complete(system_prompt=system_prompt, user_prompt=user_prompt)
128
+ llm_summary = json.loads(text)
129
+ model_backend = "kimi"
130
+ elif self.gemini is not None:
131
+ llm_summary = self.gemini.complete_json(system_prompt=system_prompt, user_prompt=user_prompt)
132
+ model_backend = "gemini"
133
+ elif self.claude is not None:
134
+ llm_summary = self.claude.complete_json(system_prompt=system_prompt, user_prompt=user_prompt)
135
+ model_backend = "claude"
136
+ recommendation = llm_summary.get("recommendation") or recommendation
137
+ except Exception:
138
+ llm_summary = None
139
+ model_backend = "heuristic"
140
+
141
+ return {
142
+ "task_scope": task_scope,
143
+ "user_goal": user_goal,
144
+ "insight_candidates": top,
145
+ "recommendation": recommendation,
146
+ "model_backend": model_backend if llm_summary is not None else "heuristic",
147
+ "llm_summary": llm_summary,
148
+ }
149
+
150
+ def emit_pipeline_config(
151
+ self,
152
+ task_scope: str,
153
+ strategy_name: str,
154
+ tools: list[str],
155
+ parameters: dict[str, Any],
156
+ rationale: str,
157
+ ) -> dict[str, Any]:
158
+ top_insights = self.memory.list_insights()[-3:]
159
+ cfg = PipelineConfiguration.build(
160
+ strategy_name=strategy_name,
161
+ task_scope=task_scope,
162
+ tools=tools,
163
+ parameters=parameters,
164
+ rationale=rationale,
165
+ source_insight_ids=[it.get("insight_id", "") for it in top_insights if it.get("insight_id")],
166
+ )
167
+ self.memory.save_pipeline_config(cfg)
168
+ return cfg.to_dict()
169
+
170
+ @staticmethod
171
+ def _tokenize(text: str) -> set[str]:
172
+ return {x for x in re.split(r"[^a-zA-Z0-9_]+", text.lower()) if len(x) > 2}
173
+
174
+ @staticmethod
175
+ def _supported_data_operations() -> set[str]:
176
+ return {"load_table", "sample_rows", "profile_missingness", "numeric_summary"}
177
+
178
+ @staticmethod
179
+ def _normalize_operations(ops: list[dict[str, Any]]) -> list[dict[str, Any]]:
180
+ supported = BioinfoT1Consultant._supported_data_operations()
181
+ normalized: list[dict[str, Any]] = []
182
+ for op in ops:
183
+ action = str(op.get("action", "")).strip()
184
+ if action not in supported:
185
+ continue
186
+ if action == "sample_rows":
187
+ rows = op.get("rows", 500)
188
+ try:
189
+ rows = int(rows)
190
+ except Exception:
191
+ rows = 500
192
+ rows = max(50, min(2000, rows))
193
+ normalized.append({"action": "sample_rows", "rows": rows})
194
+ elif action == "load_table":
195
+ normalized.append({"action": "load_table", "target": "all_selected"})
196
+ else:
197
+ normalized.append({"action": action})
198
+ if not normalized:
199
+ normalized = [
200
+ {"action": "load_table", "target": "all_selected"},
201
+ {"action": "sample_rows", "rows": 500},
202
+ {"action": "profile_missingness"},
203
+ {"action": "numeric_summary"},
204
+ ]
205
+ return normalized
206
+
207
+ def _domain_keyword_hints(self, domain: str, user_query: str) -> set[str]:
208
+ tokens = self._tokenize(f"{domain} {user_query}")
209
+ if "single_cell" in domain or "single" in tokens or "cell" in tokens:
210
+ tokens |= {
211
+ "single",
212
+ "cell",
213
+ "census",
214
+ "marker",
215
+ "celltype",
216
+ "rna",
217
+ "gene",
218
+ "normalization",
219
+ "expression",
220
+ }
221
+ return tokens
222
+
223
+ @staticmethod
224
+ def _resolve_biomni_data_root() -> Path:
225
+ env = os.getenv("BIOCLAW_BIOMNI_DATA_ROOT", "").strip()
226
+ if env:
227
+ p = Path(env).expanduser().resolve()
228
+ if p.exists():
229
+ return p
230
+ candidates = [
231
+ Path(__file__).resolve().parents[1] / "toolbase" / "data" / "biomni_data",
232
+ Path("/225040511/project/BioScientist/agent_system/toolbase/data/biomni_data"),
233
+ ]
234
+ for c in candidates:
235
+ if c.exists():
236
+ return c
237
+ return candidates[0]
238
+
239
+ def _list_available_data_files(self, limit: int = 400) -> list[str]:
240
+ root = self._resolve_biomni_data_root()
241
+ if not root.exists():
242
+ return []
243
+ files: list[str] = []
244
+ for p in sorted(root.rglob("*")):
245
+ if p.is_file():
246
+ files.append(str(p))
247
+ if len(files) >= limit:
248
+ break
249
+ return files
250
+
251
+ def _suggest_data_plan(
252
+ self,
253
+ *,
254
+ domain: str,
255
+ user_query: str,
256
+ hypothesis_text: str,
257
+ available_files: list[str],
258
+ ) -> tuple[list[str], list[dict[str, Any]]]:
259
+ text = f"{domain} {user_query} {hypothesis_text}".lower()
260
+ keywords = self._tokenize(text) | self._domain_keyword_hints(domain, user_query)
261
+
262
+ scored: list[tuple[int, str]] = []
263
+ for fp in available_files:
264
+ p = Path(fp)
265
+ name = p.name.lower()
266
+ parent = str(p.parent).lower()
267
+ score = 0
268
+ for kw in keywords:
269
+ if kw in name:
270
+ score += 1
271
+ if kw in parent:
272
+ score += 1
273
+ if any(k in name for k in ("single", "cell", "census", "marker", "gtex", "gene", "rna", "expression")):
274
+ score += 2
275
+ if "benchmark" in parent:
276
+ score -= 1
277
+ if score > 0:
278
+ scored.append((score, fp))
279
+ scored.sort(key=lambda x: x[0], reverse=True)
280
+ selected = [fp for _, fp in scored[:5]]
281
+ if not selected:
282
+ selected = available_files[:3]
283
+
284
+ ops = [
285
+ {"action": "load_table", "target": "all_selected"},
286
+ {"action": "sample_rows", "rows": 500},
287
+ {"action": "profile_missingness"},
288
+ {"action": "numeric_summary"},
289
+ ]
290
+ return selected, ops
291
+
292
+ @staticmethod
293
+ def _inject_data_grounding_text(base_hypothesis: str, selected_sources: list[str], selected_ops: list[dict[str, Any]]) -> str:
294
+ clean = base_hypothesis.strip()
295
+ source_names = [Path(x).name for x in selected_sources[:2]]
296
+ op_names = [str(x.get("action", "")) for x in selected_ops]
297
+ if not source_names:
298
+ return clean
299
+ grounding = f" Data-backed plan: use {', '.join(source_names)} with ops {', '.join(op_names)}."
300
+ if "data-backed plan" in clean.lower():
301
+ return clean
302
+ return (clean + grounding).strip()
303
+
304
+ @staticmethod
305
+ def _hypothesis_prompt_template_en(
306
+ *,
307
+ domain: str,
308
+ user_query: str,
309
+ tools_list_text: str,
310
+ success_patterns_text: str,
311
+ failure_patterns_text: str,
312
+ ) -> str:
313
+ return (
314
+ f"# Role\n"
315
+ f"You are an AI scientist specializing in the {domain} domain. "
316
+ f"Your task is to propose concrete, testable, and quantifiable analytical hypotheses.\n\n"
317
+ f"# Available Tooling Ecosystem (Injected from T0/T1)\n"
318
+ f"{tools_list_text}\n\n"
319
+ f"# Historical Success Patterns (Injected from memory)\n"
320
+ f"{success_patterns_text}\n\n"
321
+ f"# Historical Failure Patterns (Injected from memory)\n"
322
+ f"{failure_patterns_text}\n\n"
323
+ f"# Current User Request\n"
324
+ f"{user_query}\n\n"
325
+ f"# Hypothesis Generation Specification\n\n"
326
+ f"## Each hypothesis must include exactly these 5 parts:\n\n"
327
+ f"### 1. Core Hypothesis (one sentence)\n"
328
+ f"State the idea to be validated in one clear sentence.\n\n"
329
+ f"### 2. Concrete Method (2-3 sentences)\n"
330
+ f"Explain how to execute it, including:\n"
331
+ f"- Which tools/functions are used\n"
332
+ f"- Key parameters\n"
333
+ f"- How it differs from the baseline method\n\n"
334
+ f"### 3. Expected Effect (quantified)\n"
335
+ f"Must include explicit numerical targets, e.g.:\n"
336
+ f"- Clustering metrics: ARI / NMI improves by X%\n"
337
+ f"- Batch effects: kBET decreases by X%\n"
338
+ f"- Differential genes: +X significant genes\n"
339
+ f"- Runtime: reduced by X%\n\n"
340
+ f"### 4. Validation Plan\n"
341
+ f"Specify:\n"
342
+ f"- Which dataset(s) to use (must be from the available data list)\n"
343
+ f"- Which baseline to compare against\n"
344
+ f"- Success threshold (e.g., ARI > 0.6)\n\n"
345
+ f"### 5. Theoretical Rationale (biology/statistics)\n"
346
+ f"Explain why the hypothesis may hold, grounded in biological principles or statistical intuition.\n\n"
347
+ f"## Output format example\n\n"
348
+ f"[HYPOTHESIS-001]\n"
349
+ f"**Core Hypothesis**: ...\n"
350
+ f"**Concrete Method**: ...\n"
351
+ f"**Expected Effect**: ...\n"
352
+ f"**Validation Plan**: ...\n"
353
+ f"**Theoretical Rationale**: ...\n"
354
+ )
355
+
356
+ def generate_hypotheses(
357
+ self,
358
+ user_query: str,
359
+ domain: str,
360
+ n: int = 10,
361
+ top_k: int = 5,
362
+ ) -> list[dict[str, Any]]:
363
+ history = self.memory.get_hypothesis_context(domain=domain, top_k=top_k)
364
+ failed_patterns = []
365
+ success_examples = []
366
+ historical_reflection_pool: list[str] = []
367
+ error_avoidance_pool: list[str] = []
368
+ for item in history:
369
+ h = item.get("hypothesis", {})
370
+ if h.get("historical_reflection"):
371
+ historical_reflection_pool.extend([str(x) for x in h.get("historical_reflection", []) if str(x).strip()])
372
+ if h.get("error_avoidance"):
373
+ error_avoidance_pool.extend([str(x) for x in h.get("error_avoidance", []) if str(x).strip()])
374
+ for vr in item.get("validation_reports", []):
375
+ if vr.get("status") == "failed" and vr.get("failure_reason"):
376
+ failed_patterns.append(vr["failure_reason"])
377
+ error_avoidance_pool.append(f"Avoid failure mode: {vr['failure_reason']}")
378
+ if vr.get("status") == "success":
379
+ success_examples.append(
380
+ {
381
+ "title": h.get("title", ""),
382
+ "hypothesis": h.get("hypothesis", ""),
383
+ "score": vr.get("score", 0.0),
384
+ }
385
+ )
386
+ historical_reflection_pool.append(
387
+ f"Success case: {h.get('title', '')} (score={vr.get('score', 0.0)})"
388
+ )
389
+
390
+ for ins in self.memory.list_insights()[-40:]:
391
+ tags = [str(x).lower() for x in ins.get("tags", [])]
392
+ if domain.lower() not in " ".join(tags + [ins.get("title", "").lower()]):
393
+ continue
394
+ title = str(ins.get("title", "")).strip()
395
+ reco = str(ins.get("recommendation", "")).strip()
396
+ if title or reco:
397
+ historical_reflection_pool.append(f"Insight: {title} -> {reco}")
398
+ if "failed" in " ".join(tags) or "inconclusive" in " ".join(tags):
399
+ if reco:
400
+ error_avoidance_pool.append(f"Risk to avoid: {reco}")
401
+
402
+ generated: list[dict[str, Any]] = []
403
+ llm_data: dict[str, Any] | None = None
404
+ available_files = self._list_available_data_files(limit=500)
405
+ llm_backend = "none"
406
+ llm_error = ""
407
+
408
+ if self.qwen3 is not None or self.kimi is not None or self.gemini is not None or self.claude is not None:
409
+ try:
410
+ tools_list_text = "No explicit tool list injected; use available MCP/Biomni tools relevant to the domain."
411
+ success_patterns_text = json.dumps(success_examples[-10:], ensure_ascii=True)
412
+ failure_patterns_text = json.dumps(failed_patterns[-10:], ensure_ascii=True)
413
+ generation_spec = self._hypothesis_prompt_template_en(
414
+ domain=domain,
415
+ user_query=user_query,
416
+ tools_list_text=tools_list_text,
417
+ success_patterns_text=success_patterns_text,
418
+ failure_patterns_text=failure_patterns_text,
419
+ )
420
+ system_prompt = (
421
+ "You are a bioinformatics hypothesis generator.\n"
422
+ "Follow the provided Hypothesis Generation Specification strictly.\n"
423
+ "Return strict JSON only with key `hypotheses`.\n"
424
+ "Each item must include fields:\n"
425
+ "- title\n"
426
+ "- hypothesis (include core hypothesis + concise method)\n"
427
+ "- expected_improvement (must be quantified)\n"
428
+ "- validation_plan\n"
429
+ "- theoretical_basis\n"
430
+ "- historical_reflection (array of 2-5 concise points grounded in prior cases)\n"
431
+ "- error_avoidance (array of 2-5 concrete mistakes to avoid)\n"
432
+ "- reasoning_chain (array of 3-7 steps explaining how prior evidence leads to this hypothesis)\n"
433
+ "- tags\n"
434
+ "- data_sources (must come from available_data_files)\n"
435
+ "- data_operations (only from load_table/sample_rows/profile_missingness/numeric_summary)\n"
436
+ "Do not repeat failed patterns. Prefer variants inspired by high-score prior ideas.\n"
437
+ "Every hypothesis must explicitly reflect on historical cases and produce an actionable reasoning chain."
438
+ )
439
+ user_payload = {
440
+ "generation_spec_en": generation_spec,
441
+ "domain": domain,
442
+ "user_query": user_query,
443
+ "generate_n": n,
444
+ "failed_patterns_to_avoid": failed_patterns[-10:],
445
+ "success_examples_to_learn_from": success_examples[-10:],
446
+ "historical_reflection_candidates": historical_reflection_pool[-20:],
447
+ "error_avoidance_candidates": error_avoidance_pool[-20:],
448
+ "available_data_files": available_files[:200],
449
+ }
450
+ user_prompt = json.dumps(user_payload, ensure_ascii=True)
451
+ if self.qwen3 is not None:
452
+ llm_backend = "qwen3"
453
+ llm_data = self.qwen3.complete_json(system_prompt=system_prompt, user_prompt=user_prompt)
454
+ elif self.kimi is not None:
455
+ llm_backend = "kimi"
456
+ text = self.kimi.complete(system_prompt=system_prompt, user_prompt=user_prompt)
457
+ llm_data = json.loads(text)
458
+ elif self.gemini is not None:
459
+ llm_backend = "gemini"
460
+ llm_data = self.gemini.complete_json(system_prompt=system_prompt, user_prompt=user_prompt)
461
+ elif self.claude is not None:
462
+ llm_backend = "claude"
463
+ llm_data = self.claude.complete_json(system_prompt=system_prompt, user_prompt=user_prompt)
464
+ except Exception as exc:
465
+ llm_data = None
466
+ llm_error = str(exc)
467
+
468
+ candidates = (llm_data or {}).get("hypotheses", []) if isinstance(llm_data, dict) else []
469
+ used_fallback = not bool(candidates)
470
+ if not candidates:
471
+ for i in range(max(1, n)):
472
+ suggested_sources, suggested_ops = self._suggest_data_plan(
473
+ domain=domain,
474
+ user_query=user_query,
475
+ hypothesis_text=user_query,
476
+ available_files=available_files,
477
+ )
478
+ candidates.append(
479
+ {
480
+ "title": f"{domain} hypothesis {i + 1}",
481
+ "hypothesis": self._inject_data_grounding_text(
482
+ f"Apply a normalization variant for: {user_query}.",
483
+ suggested_sources,
484
+ suggested_ops,
485
+ ),
486
+ "expected_improvement": "Improve normalization stability, reduce batch effects, and keep biological signal.",
487
+ "validation_plan": "Use selected data sources, compare against standard normalization baseline, and require metric improvement over baseline.",
488
+ "theoretical_basis": "Selected available datasets are used for immediate lightweight validation before expensive full runs.",
489
+ "historical_reflection": [
490
+ f"Referenced {min(len(success_examples), top_k)} successful historical cases in the same domain.",
491
+ "Observed prior failures and kept this hypothesis conservative in scope.",
492
+ ],
493
+ "error_avoidance": (
494
+ [f"Avoid: {x}" for x in failed_patterns[-3:]]
495
+ if failed_patterns
496
+ else ["Avoid unsupported tools and unverifiable claims."]
497
+ ),
498
+ "reasoning_chain": [
499
+ "Review historical validation outcomes in the same domain.",
500
+ "Extract stable successful patterns and recurring failure reasons.",
501
+ "Select currently available data files for immediate verification.",
502
+ "Propose a minimally risky, testable variant with quantifiable expectations.",
503
+ "Bind operations so E1 can execute immediately and report metrics.",
504
+ ],
505
+ "tags": [domain, "generated-v1"],
506
+ "data_sources": suggested_sources,
507
+ "data_operations": suggested_ops,
508
+ }
509
+ )
510
+ if not llm_error and llm_backend != "none":
511
+ llm_error = "model_returned_empty_or_non_json_hypotheses"
512
+ if llm_backend == "none":
513
+ llm_error = "no_llm_backend_available"
514
+
515
+ source_example_ids = [it.get("hypothesis", {}).get("hypothesis_id", "") for it in history]
516
+ known_paths = set(available_files)
517
+ for c in candidates[: max(1, n)]:
518
+ selected_sources = [str(x) for x in c.get("data_sources", []) if str(x).strip() and str(x) in known_paths]
519
+ selected_ops = [x for x in c.get("data_operations", []) if isinstance(x, dict)]
520
+ if not selected_sources or not selected_ops:
521
+ suggested_sources, suggested_ops = self._suggest_data_plan(
522
+ domain=domain,
523
+ user_query=user_query,
524
+ hypothesis_text=str(c.get("hypothesis", "")),
525
+ available_files=available_files,
526
+ )
527
+ if not selected_sources:
528
+ selected_sources = suggested_sources
529
+ if not selected_ops:
530
+ selected_ops = suggested_ops
531
+ selected_ops = self._normalize_operations(selected_ops)
532
+ grounded_hypothesis = self._inject_data_grounding_text(
533
+ str(c.get("hypothesis", "")),
534
+ selected_sources,
535
+ selected_ops,
536
+ )
537
+ hyp = Hypothesis.build(
538
+ domain=domain,
539
+ user_query=user_query,
540
+ title=str(c.get("title", "Untitled hypothesis")).strip(),
541
+ hypothesis=grounded_hypothesis,
542
+ expected_improvement=str(c.get("expected_improvement", "")).strip(),
543
+ theoretical_basis=(
544
+ f"{str(c.get('theoretical_basis', '')).strip()} "
545
+ f"Validation plan: {str(c.get('validation_plan', '')).strip()}"
546
+ ).strip(),
547
+ tags=[str(x) for x in c.get("tags", []) if str(x).strip()],
548
+ source_examples=[x for x in source_example_ids if x],
549
+ data_sources=selected_sources,
550
+ data_operations=selected_ops,
551
+ historical_reflection=[
552
+ str(x).strip()
553
+ for x in c.get("historical_reflection", [])
554
+ if str(x).strip()
555
+ ][:6],
556
+ error_avoidance=[
557
+ str(x).strip()
558
+ for x in c.get("error_avoidance", [])
559
+ if str(x).strip()
560
+ ][:6],
561
+ reasoning_chain=[
562
+ str(x).strip()
563
+ for x in c.get("reasoning_chain", [])
564
+ if str(x).strip()
565
+ ][:8],
566
+ )
567
+ self.memory.save_hypothesis(hyp)
568
+ generated.append(hyp.to_dict())
569
+
570
+ self.last_generation_meta = {
571
+ "requested_backend": self.backend,
572
+ "actual_backend": llm_backend,
573
+ "used_fallback": used_fallback,
574
+ "error": llm_error[:1000],
575
+ "history_size": len(history),
576
+ "available_data_files": len(available_files),
577
+ "candidates_returned": len(candidates),
578
+ "generated_count": len(generated),
579
+ }
580
+ return generated
581
+
582
+ def rank_hypotheses_by_success_proxy(
583
+ self,
584
+ hypotheses: list[dict[str, Any]],
585
+ domain: str,
586
+ ) -> list[dict[str, Any]]:
587
+ stats = self.memory.get_summary_statistics()
588
+ tag_summary = stats.get("tag_summary", {})
589
+ history = self.memory.get_hypothesis_context(domain=domain, top_k=20)
590
+
591
+ successful_texts = []
592
+ for item in history:
593
+ reports = item.get("validation_reports", [])
594
+ if any(r.get("status") == "success" for r in reports):
595
+ h = item.get("hypothesis", {})
596
+ successful_texts.append(f"{h.get('title', '')} {h.get('hypothesis', '')}")
597
+
598
+ successful_tokens = [self._tokenize(x) for x in successful_texts if x.strip()]
599
+
600
+ ranked = []
601
+ for h in hypotheses:
602
+ tags = h.get("tags", []) or []
603
+ if not tags:
604
+ tags = [domain]
605
+ tag_scores = []
606
+ for t in tags:
607
+ s = tag_summary.get(t, {})
608
+ tag_scores.append(float(s.get("success_rate", 0.5)))
609
+ tag_score = sum(tag_scores) / len(tag_scores) if tag_scores else 0.5
610
+
611
+ h_tokens = self._tokenize(f"{h.get('title', '')} {h.get('hypothesis', '')}")
612
+ sim_score = 0.0
613
+ if successful_tokens and h_tokens:
614
+ overlaps = []
615
+ for st in successful_tokens:
616
+ inter = len(h_tokens & st)
617
+ union = len(h_tokens | st) or 1
618
+ overlaps.append(inter / union)
619
+ sim_score = max(overlaps) if overlaps else 0.0
620
+
621
+ predicted_success = max(0.0, min(1.0, 0.7 * tag_score + 0.3 * sim_score))
622
+ ranked.append({**h, "predicted_success": predicted_success})
623
+
624
+ ranked.sort(key=lambda x: x.get("predicted_success", 0.0), reverse=True)
625
+ return ranked
BioScientist/agent_system/engines/test_gemini.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ import os
3
+
4
+ # 替换为你的 Gemini API Key
5
+ api_key = os.environ.get("GEMINI_API_KEY")
6
+ print("api_key:"+api_key)
7
+ os.environ["GEMINI_API_KEY"] = api_key
8
+ genai.configure(api_key=os.environ["GEMINI_API_KEY"])
9
+
10
+ def list_gemini_models():
11
+ print("Listing available Gemini models:")
12
+ print("-" * 50)
13
+
14
+ # 遍历所有模型
15
+ for model in genai.list_models():
16
+ # 过滤掉仅支持旧版或特定功能的模型(可选)
17
+ if 'generateContent' in model.supported_generation_methods:
18
+ print(f"Model Name: {model.name}")
19
+ print(f"Description: {model.description}")
20
+ print(f"Input Token Limit: {model.input_token_limit}")
21
+ print(f"Output Token Limit: {model.output_token_limit}")
22
+ print("-" * 50)
23
+
24
+ if __name__ == "__main__":
25
+ list_gemini_models()
BioScientist/agent_system/engines/v1_executor.py ADDED
@@ -0,0 +1,1348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib.util
4
+ from pathlib import Path
5
+ from typing import Any
6
+ import json
7
+ import os
8
+ import re
9
+ import shlex
10
+ import shutil
11
+ import subprocess
12
+ import traceback
13
+ import requests
14
+
15
+ from ..mcp_router import MCPToolRouter
16
+ from ..schemas import ExperimentReport, FailureMode
17
+ from ..shared_memory import SharedKnowledgeSpace
18
+
19
+
20
+ class BioinfoV1Executor:
21
+ """Execution engine: plan task -> call MCP servers -> publish structured report."""
22
+
23
+ def __init__(
24
+ self,
25
+ memory: SharedKnowledgeSpace,
26
+ default_results_root: str | Path,
27
+ project_root: str | Path,
28
+ execution_backend: str = "docker",
29
+ ):
30
+ self.memory = memory
31
+ self.default_results_root = Path(default_results_root)
32
+ self.default_results_root.mkdir(parents=True, exist_ok=True)
33
+ self.project_root = Path(project_root)
34
+ self.router = MCPToolRouter(project_root=project_root)
35
+ self.execution_backend = execution_backend
36
+
37
+ @staticmethod
38
+ def _append_log(log_file: Path, message: str) -> None:
39
+ with log_file.open("a", encoding="utf-8") as lf:
40
+ lf.write(message.rstrip() + "\n")
41
+
42
+ @staticmethod
43
+ def _jsonable(value: Any) -> Any:
44
+ if isinstance(value, Path):
45
+ return str(value)
46
+ if isinstance(value, dict):
47
+ return {str(k): BioinfoV1Executor._jsonable(v) for k, v in value.items()}
48
+ if isinstance(value, list):
49
+ return [BioinfoV1Executor._jsonable(v) for v in value]
50
+ if isinstance(value, tuple):
51
+ return [BioinfoV1Executor._jsonable(v) for v in value]
52
+ return value
53
+
54
+ @staticmethod
55
+ def _read_log_tail(log_file: Path, max_lines: int = 200) -> str:
56
+ try:
57
+ lines = log_file.read_text(encoding="utf-8", errors="replace").splitlines()
58
+ return "\n".join(lines[-max_lines:])
59
+ except Exception:
60
+ return ""
61
+
62
+ @staticmethod
63
+ def _pick_trimmed_pair(trim_dir: Path) -> tuple[Path | None, Path | None]:
64
+ r1_patterns = [
65
+ "*_val_1.fq.gz",
66
+ "*_val_1.fq",
67
+ "*_R1_val_1.fq.gz",
68
+ "*_1_val_1.fq.gz",
69
+ "*_fastp_R1.fastq",
70
+ "*_fastp_R1.fastq.gz",
71
+ ]
72
+ r2_patterns = [
73
+ "*_val_2.fq.gz",
74
+ "*_val_2.fq",
75
+ "*_R2_val_2.fq.gz",
76
+ "*_2_val_2.fq.gz",
77
+ "*_fastp_R2.fastq",
78
+ "*_fastp_R2.fastq.gz",
79
+ ]
80
+ r1_candidates: list[Path] = []
81
+ r2_candidates: list[Path] = []
82
+ for pattern in r1_patterns:
83
+ r1_candidates.extend(sorted(trim_dir.glob(pattern)))
84
+ for pattern in r2_patterns:
85
+ r2_candidates.extend(sorted(trim_dir.glob(pattern)))
86
+ return (r1_candidates[-1] if r1_candidates else None, r2_candidates[-1] if r2_candidates else None)
87
+
88
+ def _plan_task(
89
+ self,
90
+ task: str,
91
+ task_scope: str,
92
+ pipeline_config: dict[str, Any] | None,
93
+ ) -> list[dict[str, Any]]:
94
+ """
95
+ Plan execution in a Biomni-like style:
96
+ 1) understand scope
97
+ 2) choose candidate tools
98
+ 3) execute step-by-step with artifacts passed forward
99
+ """
100
+ cfg_tools = (pipeline_config or {}).get("tools") or []
101
+
102
+ if task_scope == "first_pipeline":
103
+ task_lower = task.lower()
104
+ wants_alignment = any(
105
+ kw in task_lower
106
+ for kw in ("align", "alignment", "map", "mapping", "variant", "snp", "bam")
107
+ )
108
+ benchmark_repro_mode = any(
109
+ kw in task_lower
110
+ for kw in ("code repository", "original open-source code", "reproduce paper", "reproducibility")
111
+ )
112
+ base_plan = [
113
+ {
114
+ "name": "qc_raw",
115
+ "description": "Quality control on raw reads",
116
+ "candidates": cfg_tools or ["fastqc", "fastp"],
117
+ },
118
+ {
119
+ "name": "trim",
120
+ "description": "Adapter/quality trimming",
121
+ "candidates": cfg_tools or ["trim_galore", "cutadapt", "trimmomatic", "fastp"],
122
+ },
123
+ {
124
+ "name": "align",
125
+ "description": "Read alignment to reference index",
126
+ "candidates": cfg_tools or ["bowtie2", "bwa", "hisat2", "star", "minimap2"],
127
+ },
128
+ {
129
+ "name": "qc_trimmed",
130
+ "description": "Quality control after trimming",
131
+ "candidates": cfg_tools or ["fastqc", "qualimap"],
132
+ },
133
+ {
134
+ "name": "aggregate",
135
+ "description": "Aggregate reports",
136
+ "candidates": cfg_tools or ["multiqc"],
137
+ },
138
+ ]
139
+ if not wants_alignment:
140
+ base_plan = [s for s in base_plan if s["name"] != "align"]
141
+
142
+ if benchmark_repro_mode:
143
+ base_plan.extend(
144
+ [
145
+ {
146
+ "name": "source_clone",
147
+ "description": "Clone original paper source code repository",
148
+ "local_executor": "source_clone",
149
+ "candidates": [],
150
+ },
151
+ {
152
+ "name": "source_execute",
153
+ "description": "Run reproducibility-oriented source code execution attempts",
154
+ "local_executor": "source_execute",
155
+ "candidates": [],
156
+ },
157
+ {
158
+ "name": "summarize_repro",
159
+ "description": "Summarize reproducibility with deviations and evidence",
160
+ "local_executor": "summarize_repro",
161
+ "candidates": [],
162
+ },
163
+ ]
164
+ )
165
+ return base_plan
166
+
167
+ # generic mode: one tool per configured entry
168
+ if cfg_tools:
169
+ return [
170
+ {
171
+ "name": f"step_{i+1}",
172
+ "description": f"Configured execution step for {tool}",
173
+ "candidates": [tool],
174
+ }
175
+ for i, tool in enumerate(cfg_tools)
176
+ ]
177
+
178
+ # fallback
179
+ return [
180
+ {
181
+ "name": "generic_step",
182
+ "description": f"Generic execution for task: {task}",
183
+ "candidates": ["fastqc"],
184
+ }
185
+ ]
186
+
187
+ def _route_or_generate(self, tool_name: str, log_file: Path):
188
+ if self.router.has_tool(tool_name):
189
+ return self.router.resolve(tool_name)
190
+
191
+ self._append_log(log_file, f"[planner] MCP tool missing: {tool_name}, invoking converter...")
192
+ self._try_generate_mcp_server(tool_name, log_file)
193
+ self.router.refresh()
194
+ if self.router.has_tool(tool_name):
195
+ return self.router.resolve(tool_name)
196
+ return None
197
+
198
+ def _try_generate_mcp_server(self, tool_name: str, log_file: Path) -> None:
199
+ converter_path = self.project_root / "src" / "bioinfomcp_converter.py"
200
+ if not converter_path.exists():
201
+ self._append_log(log_file, f"[converter] converter not found: {converter_path}")
202
+ return
203
+
204
+ try:
205
+ spec = importlib.util.spec_from_file_location("bioinfomcp_converter", str(converter_path))
206
+ if spec is None or spec.loader is None:
207
+ raise RuntimeError("Failed to load converter module spec.")
208
+ module = importlib.util.module_from_spec(spec)
209
+ spec.loader.exec_module(module)
210
+ converter_cls = getattr(module, "BioinfoMCP", None)
211
+ if converter_cls is None:
212
+ raise RuntimeError("BioinfoMCP class not found in converter.")
213
+
214
+ converter = converter_cls(model="openai")
215
+ ok, error_msg, code = converter.autogenerate_mcp_tool(
216
+ tool_name=tool_name,
217
+ manual="--help",
218
+ run_help_command=True,
219
+ )
220
+ if not ok or not code:
221
+ raise RuntimeError(f"Converter failed: {error_msg}")
222
+
223
+ mcp_dir = self.project_root / "mcp-servers" / f"mcp_{tool_name}" / "app"
224
+ mcp_dir.mkdir(parents=True, exist_ok=True)
225
+ server_file = mcp_dir / f"{tool_name}_server.py"
226
+ server_file.write_text(self._wrap_generated_mcp_code(code), encoding="utf-8")
227
+ self._append_log(log_file, f"[converter] generated MCP server: {server_file}")
228
+ except Exception as exc: # pragma: no cover - defensive path
229
+ self._append_log(log_file, f"[converter] generation failed for {tool_name}: {exc}")
230
+
231
+ @staticmethod
232
+ def _wrap_generated_mcp_code(code: str) -> str:
233
+ if "FastMCP" in code and "mcp = FastMCP()" in code:
234
+ if "if __name__ == '__main__':" in code or "if __name__ == \"__main__\":" in code:
235
+ return code
236
+ return f"{code}\n\nif __name__ == '__main__':\n mcp.run()\n"
237
+
238
+ return (
239
+ "from fastmcp import FastMCP\n"
240
+ "mcp = FastMCP()\n\n"
241
+ f"{code}\n\n"
242
+ "if __name__ == '__main__':\n"
243
+ " mcp.run()\n"
244
+ )
245
+
246
+ @staticmethod
247
+ def _load_tool_callable(server_script: Path, function_name: str):
248
+ mod_name = f"mcp_module_{server_script.stem}_{abs(hash(str(server_script)))}"
249
+ spec = importlib.util.spec_from_file_location(mod_name, str(server_script))
250
+ if spec is None or spec.loader is None:
251
+ raise RuntimeError(f"Cannot load module for {server_script}")
252
+ module = importlib.util.module_from_spec(spec)
253
+ spec.loader.exec_module(module)
254
+ func = getattr(module, function_name, None)
255
+ if func is None:
256
+ raise RuntimeError(f"Function '{function_name}' not found in {server_script}")
257
+ return func
258
+
259
+ def _invoke_mcp_tool(
260
+ self,
261
+ route,
262
+ kwargs: dict[str, Any],
263
+ log_file: Path,
264
+ ) -> dict[str, Any]:
265
+ self._append_log(
266
+ log_file,
267
+ f"[toolcall] {route.tool_name}.{route.function_name} script={route.server_script} kwargs={json.dumps({k: str(v) for k, v in kwargs.items()}, ensure_ascii=True)}",
268
+ )
269
+ if self.execution_backend == "docker":
270
+ return self._invoke_mcp_tool_docker(route, kwargs=kwargs, log_file=log_file)
271
+
272
+ try:
273
+ tool_fn = self._load_tool_callable(route.server_script, route.function_name)
274
+ result = tool_fn(**kwargs)
275
+ if not isinstance(result, dict):
276
+ result = {"raw_result": result}
277
+ ok = "error" not in result
278
+ self._append_log(log_file, f"[toolcall] status={'ok' if ok else 'error'}")
279
+ return {"ok": ok, "result": result}
280
+ except FileNotFoundError as exc:
281
+ tb = traceback.format_exc()
282
+ self._append_log(log_file, f"[toolcall] FileNotFoundError: {exc}\n{tb}")
283
+ return {"ok": False, "result": {"error": f"FileNotFoundError: {exc}", "traceback": tb}}
284
+ except Exception as exc:
285
+ tb = traceback.format_exc()
286
+ self._append_log(log_file, f"[toolcall] exception: {exc}\n{tb}")
287
+ return {"ok": False, "result": {"error": str(exc), "traceback": tb}}
288
+
289
+ def _invoke_mcp_tool_docker(self, route, kwargs: dict[str, Any], log_file: Path) -> dict[str, Any]:
290
+ if shutil.which("docker") is None:
291
+ return {
292
+ "ok": False,
293
+ "result": {"error": "docker_not_found", "hint": "Install Docker or switch execution_backend=python"},
294
+ }
295
+
296
+ run_dir = log_file.parent
297
+ payload_file = run_dir / f"_mcp_payload_{route.function_name}.json"
298
+ runner_file = run_dir / "_mcp_docker_runner.py"
299
+ payload = {
300
+ "server_script": str(route.server_script),
301
+ "function_name": route.function_name,
302
+ "kwargs": self._jsonable(kwargs),
303
+ }
304
+ payload_file.write_text(json.dumps(payload, ensure_ascii=True), encoding="utf-8")
305
+ runner_file.write_text(self._docker_runner_script(), encoding="utf-8")
306
+
307
+ mount_root = self.project_root.parent
308
+ docker_cmd = [
309
+ "docker",
310
+ "run",
311
+ "--rm",
312
+ "-v",
313
+ f"{mount_root}:{mount_root}",
314
+ "-w",
315
+ str(mount_root),
316
+ route.image_name,
317
+ "python",
318
+ str(runner_file),
319
+ str(payload_file),
320
+ ]
321
+ self._append_log(log_file, f"[toolcall-docker] cmd={' '.join(docker_cmd)}")
322
+
323
+ completed = subprocess.run(docker_cmd, capture_output=True, text=True)
324
+ stdout = completed.stdout or ""
325
+ stderr = completed.stderr or ""
326
+ if completed.returncode != 0:
327
+ self._append_log(log_file, f"[toolcall-docker] failed rc={completed.returncode}\n{stderr}")
328
+ return {
329
+ "ok": False,
330
+ "result": {
331
+ "error": f"docker_run_failed rc={completed.returncode}",
332
+ "stdout": stdout,
333
+ "stderr": stderr,
334
+ "image": route.image_name,
335
+ "hint": (
336
+ f"Ensure image '{route.image_name}' exists/builds, "
337
+ f"or run with execution_backend=python."
338
+ ),
339
+ },
340
+ }
341
+
342
+ try:
343
+ result = json.loads(stdout.strip() or "{}")
344
+ if not isinstance(result, dict):
345
+ result = {"raw_result": result}
346
+ except Exception:
347
+ result = {"raw_stdout": stdout, "raw_stderr": stderr}
348
+
349
+ ok = "error" not in result
350
+ return {"ok": ok, "result": result}
351
+
352
+ @staticmethod
353
+ def _docker_runner_script() -> str:
354
+ return """from __future__ import annotations
355
+ import importlib.util
356
+ import inspect
357
+ import json
358
+ import sys
359
+ from pathlib import Path
360
+ from typing import Any, get_args, get_origin, Union
361
+
362
+
363
+ def to_jsonable(v: Any):
364
+ if isinstance(v, Path):
365
+ return str(v)
366
+ if isinstance(v, dict):
367
+ return {str(k): to_jsonable(val) for k, val in v.items()}
368
+ if isinstance(v, list):
369
+ return [to_jsonable(x) for x in v]
370
+ if isinstance(v, tuple):
371
+ return [to_jsonable(x) for x in v]
372
+ return v
373
+
374
+
375
+ def is_path_type(tp: Any) -> bool:
376
+ return tp is Path
377
+
378
+
379
+ def convert_value(value: Any, ann: Any) -> Any:
380
+ if ann is inspect._empty:
381
+ return value
382
+ origin = get_origin(ann)
383
+ if origin in (list, tuple):
384
+ args = get_args(ann)
385
+ inner = args[0] if args else Any
386
+ if isinstance(value, list):
387
+ return [convert_value(v, inner) for v in value]
388
+ return value
389
+ if origin is Union:
390
+ for a in get_args(ann):
391
+ if a is type(None):
392
+ continue
393
+ try:
394
+ return convert_value(value, a)
395
+ except Exception:
396
+ pass
397
+ return value
398
+ if is_path_type(ann):
399
+ return Path(value) if value is not None else value
400
+ return value
401
+
402
+
403
+ def main():
404
+ payload_path = Path(sys.argv[1])
405
+ payload = json.loads(payload_path.read_text(encoding="utf-8"))
406
+ server_script = payload["server_script"]
407
+ function_name = payload["function_name"]
408
+ kwargs = payload.get("kwargs", {})
409
+
410
+ spec = importlib.util.spec_from_file_location("mcp_runtime_mod", server_script)
411
+ if spec is None or spec.loader is None:
412
+ print(json.dumps({"error": f"cannot_load_module:{server_script}"}))
413
+ sys.exit(0)
414
+ mod = importlib.util.module_from_spec(spec)
415
+ spec.loader.exec_module(mod)
416
+ fn = getattr(mod, function_name, None)
417
+ if fn is None:
418
+ print(json.dumps({"error": f"function_not_found:{function_name}"}))
419
+ sys.exit(0)
420
+
421
+ sig = inspect.signature(fn)
422
+ call_kwargs = {}
423
+ for k, v in kwargs.items():
424
+ if k in sig.parameters:
425
+ call_kwargs[k] = convert_value(v, sig.parameters[k].annotation)
426
+ else:
427
+ call_kwargs[k] = v
428
+
429
+ try:
430
+ result = fn(**call_kwargs)
431
+ print(json.dumps(to_jsonable(result), ensure_ascii=True))
432
+ except Exception as exc:
433
+ import traceback
434
+ print(json.dumps({"error": str(exc), "traceback": traceback.format_exc()}, ensure_ascii=True))
435
+
436
+
437
+ if __name__ == "__main__":
438
+ main()
439
+ """
440
+
441
+ def _build_step_kwargs(
442
+ self,
443
+ step_name: str,
444
+ route_function: str,
445
+ context: dict[str, Any],
446
+ ) -> dict[str, Any]:
447
+ run_dir: Path = context["run_dir"]
448
+ r1: Path = context["r1"]
449
+ r2: Path = context["r2"]
450
+ threads: int = context["threads"]
451
+ quality_cutoff: int = context["quality_cutoff"]
452
+ index_base = context["index_base"]
453
+ artifacts = context["artifacts"]
454
+
455
+ if step_name == "qc_raw":
456
+ outdir = run_dir / "01_fastqc_raw"
457
+ outdir.mkdir(parents=True, exist_ok=True)
458
+ return {"input_files": [r1, r2], "outdir": outdir, "threads": threads}
459
+
460
+ if step_name == "trim":
461
+ outdir = run_dir / "02_trim"
462
+ outdir.mkdir(parents=True, exist_ok=True)
463
+ if route_function == "fastp":
464
+ out1 = outdir / f"{r1.stem}_fastp_R1.fastq"
465
+ out2 = outdir / f"{r2.stem}_fastp_R2.fastq"
466
+ json_report = str(outdir / "fastp.json")
467
+ html_report = str(outdir / "fastp.html")
468
+ return {
469
+ "in1": r1,
470
+ "in2": r2,
471
+ "out1": out1,
472
+ "out2": out2,
473
+ "qualified_quality_phred": quality_cutoff,
474
+ "cut_mean_quality": quality_cutoff,
475
+ "cut_right": True,
476
+ "thread": threads,
477
+ "json": json_report,
478
+ "html": html_report,
479
+ "report_title": "fastp report (BioClawMCP)",
480
+ }
481
+
482
+ return {
483
+ "input_files": [r1, r2],
484
+ "paired": True,
485
+ "quality": quality_cutoff,
486
+ "output_dir": outdir,
487
+ "cores": threads,
488
+ }
489
+
490
+ if step_name == "align":
491
+ align_dir = run_dir / "03_align"
492
+ align_dir.mkdir(parents=True, exist_ok=True)
493
+ sam_out = align_dir / "alignment.sam"
494
+ artifacts["sam"] = sam_out
495
+ trimmed_r1 = artifacts.get("trimmed_r1", r1)
496
+ trimmed_r2 = artifacts.get("trimmed_r2", r2)
497
+ if route_function == "bowtie2_align":
498
+ return {
499
+ "index_base": str(index_base),
500
+ "mate1_files": str(trimmed_r1),
501
+ "mate2_files": str(trimmed_r2),
502
+ "sam_output": sam_out,
503
+ "threads": threads,
504
+ }
505
+ # generic aligner fall back shape
506
+ return {
507
+ "input_files": [trimmed_r1, trimmed_r2],
508
+ "reference_index_base": str(index_base),
509
+ "output_dir": align_dir,
510
+ "threads": threads,
511
+ }
512
+
513
+ if step_name == "qc_trimmed":
514
+ outdir = run_dir / "04_fastqc_trimmed"
515
+ outdir.mkdir(parents=True, exist_ok=True)
516
+ trimmed_r1 = artifacts.get("trimmed_r1", r1)
517
+ trimmed_r2 = artifacts.get("trimmed_r2", r2)
518
+ return {"input_files": [trimmed_r1, trimmed_r2], "outdir": outdir, "threads": threads}
519
+
520
+ if step_name == "aggregate":
521
+ outdir = run_dir / "05_multiqc"
522
+ outdir.mkdir(parents=True, exist_ok=True)
523
+ return {
524
+ "analysis_directory": run_dir,
525
+ "outdir": outdir,
526
+ "filename": "multiqc_report.html",
527
+ "force": True,
528
+ }
529
+
530
+ # generic fallback for configured custom step
531
+ return {
532
+ "analysis_directory": run_dir,
533
+ "outdir": run_dir / f"{step_name}_output",
534
+ }
535
+
536
+ @staticmethod
537
+ def _extract_code_repo(task: str, input_manifest: dict[str, Any]) -> str:
538
+ manifest_repo = str(input_manifest.get("code_repo") or "").strip()
539
+ if manifest_repo:
540
+ return manifest_repo
541
+ m = re.search(r"Code repo:\s*(https?://\S+)", task, re.I)
542
+ if m:
543
+ return m.group(1).rstrip(").,;")
544
+ return ""
545
+
546
+ def _run_local_command(self, cmd: list[str], log_file: Path, cwd: Path | None = None, timeout_s: int = 900) -> dict[str, Any]:
547
+ try:
548
+ self._append_log(log_file, f"[local-cmd] {' '.join(cmd)} cwd={cwd or self.project_root}")
549
+ completed = subprocess.run(
550
+ cmd,
551
+ cwd=str(cwd) if cwd else None,
552
+ capture_output=True,
553
+ text=True,
554
+ timeout=timeout_s,
555
+ )
556
+ return {
557
+ "command_executed": " ".join(cmd),
558
+ "return_code": completed.returncode,
559
+ "stdout": completed.stdout or "",
560
+ "stderr": completed.stderr or "",
561
+ }
562
+ except Exception as exc:
563
+ tb = traceback.format_exc()
564
+ return {
565
+ "command_executed": " ".join(cmd),
566
+ "return_code": -1,
567
+ "error": str(exc),
568
+ "traceback": tb,
569
+ }
570
+
571
+ @staticmethod
572
+ def _extract_readme_run_commands(source_dir: Path, max_commands: int = 6) -> list[list[str]]:
573
+ candidates: list[list[str]] = []
574
+ readme_files = [
575
+ source_dir / "README.md",
576
+ source_dir / "readme.md",
577
+ source_dir / "README.rst",
578
+ ]
579
+ text = ""
580
+ for fp in readme_files:
581
+ if fp.exists():
582
+ try:
583
+ text = fp.read_text(encoding="utf-8", errors="replace")
584
+ break
585
+ except Exception:
586
+ continue
587
+ if not text:
588
+ return candidates
589
+
590
+ # extract fenced code blocks first
591
+ blocks = re.findall(r"```(?:bash|sh|shell)?\n([\s\S]*?)```", text, re.I)
592
+ lines: list[str] = []
593
+ for b in blocks:
594
+ lines.extend(b.splitlines())
595
+ if not lines:
596
+ lines = text.splitlines()
597
+
598
+ allowed_prefix = (
599
+ "python ",
600
+ "python3 ",
601
+ "bash ",
602
+ "sh ",
603
+ "./",
604
+ "Rscript ",
605
+ "R -e ",
606
+ "R --vanilla ",
607
+ "R ",
608
+ "snakemake",
609
+ "nextflow run",
610
+ )
611
+ forbidden = ("sudo ", "rm -rf", "docker system", "shutdown", "reboot")
612
+ for raw in lines:
613
+ line = raw.strip()
614
+ if line.startswith("$ "):
615
+ line = line[2:].strip()
616
+ if not line or line.startswith("#"):
617
+ continue
618
+ if any(bad in line for bad in forbidden):
619
+ continue
620
+ if line.startswith(allowed_prefix):
621
+ try:
622
+ cmd = shlex.split(line)
623
+ except Exception:
624
+ continue
625
+ if cmd:
626
+ candidates.append(cmd)
627
+ if len(candidates) >= max_commands:
628
+ break
629
+ return candidates
630
+
631
+ @staticmethod
632
+ def _is_safe_run_command(cmd: list[str]) -> bool:
633
+ if not cmd:
634
+ return False
635
+ joined = " ".join(cmd).lower()
636
+ forbidden = [
637
+ "rm -rf",
638
+ "sudo ",
639
+ "shutdown",
640
+ "reboot",
641
+ ":(){:|:&};:",
642
+ "mkfs",
643
+ "dd if=",
644
+ "curl ",
645
+ "wget ",
646
+ "scp ",
647
+ "ssh ",
648
+ "docker system",
649
+ ]
650
+ if any(x in joined for x in forbidden):
651
+ return False
652
+ allowed_heads = {"python", "python3", "bash", "sh", "rscript", "r", "snakemake", "nextflow", "make"}
653
+ head = cmd[0].lower()
654
+ return head in allowed_heads or head.startswith("./")
655
+
656
+ def _plan_source_commands_with_gemini(
657
+ self,
658
+ *,
659
+ task: str,
660
+ source_dir: Path,
661
+ input_manifest: dict[str, Any],
662
+ log_file: Path,
663
+ max_commands: int = 5,
664
+ ) -> list[list[str]]:
665
+ api_key = os.getenv("GEMINI_API_KEY", "").strip()
666
+ print("api_key:"+api_key)
667
+ if not api_key:
668
+ self._append_log(log_file, "[gemini] planner skipped: GEMINI_API_KEY missing")
669
+ return []
670
+
671
+ readme_text = ""
672
+ for fp in [source_dir / "README.md", source_dir / "readme.md", source_dir / "README.rst"]:
673
+ if fp.exists():
674
+ readme_text = fp.read_text(encoding="utf-8", errors="replace")
675
+ break
676
+ if len(readme_text) > 12000:
677
+ readme_text = readme_text[:12000]
678
+ print("readme_text:"+readme_text)
679
+ endpoint = (
680
+ "https://generativelanguage.googleapis.com/v1beta/models/"
681
+ f"gemini-2.5-flash-lite:generateContent?key={api_key}"
682
+ )
683
+ planner_prompt = (
684
+ "You are a bioinformatics reproducibility execution planner.\n"
685
+ "Given repository README and task context, propose up to 5 LOCAL runnable commands.\n"
686
+ "Output JSON with key `commands`, where each command is either:\n"
687
+ '1) ["python","script.py","--arg"] or 2) "python script.py --arg"\n'
688
+ "Rules:\n"
689
+ "- Only local run commands: python/python3/bash/sh/Rscript/R/snakemake/nextflow/make\n"
690
+ "- No network download commands (curl/wget/git clone), no sudo, no destructive commands.\n"
691
+ "- Prefer commands that execute original method in the repository.\n"
692
+ "- Return JSON only.\n"
693
+ )
694
+ payload = {
695
+ "contents": [
696
+ {
697
+ "role": "user",
698
+ "parts": [
699
+ {
700
+ "text": planner_prompt
701
+ + "\n"
702
+ + json.dumps(
703
+ {
704
+ "task": task,
705
+ "repo_path": str(source_dir),
706
+ "data_type": input_manifest.get("data_type", ""),
707
+ "repro_steps": input_manifest.get("repro_steps", []),
708
+ "readme_excerpt": readme_text,
709
+ },
710
+ ensure_ascii=True,
711
+ )
712
+ }
713
+ ],
714
+ }
715
+ ],
716
+ "generationConfig": {"temperature": 0.1},
717
+ }
718
+ print("payload:"+json.dumps(payload, ensure_ascii=False))
719
+ try:
720
+ resp = requests.post(endpoint, json=payload, timeout=60)
721
+ if resp.status_code >= 400:
722
+ self._append_log(
723
+ log_file,
724
+ f"[gemini] planner failed status={resp.status_code} body={(resp.text or '')[:500]}",
725
+ )
726
+ return self._extract_readme_run_commands(source_dir, max_commands=max_commands)
727
+ data = resp.json()
728
+ text = ""
729
+ for part in (data.get("candidates", [{}])[0].get("content", {}).get("parts", []) or []):
730
+ if "text" in part:
731
+ text += part["text"]
732
+ obj = {}
733
+ try:
734
+ obj = json.loads(text) if text.strip() else {}
735
+ except Exception:
736
+ m = re.search(r"```json\s*([\s\S]*?)```", text, re.I)
737
+ if m:
738
+ obj = json.loads(m.group(1))
739
+ else:
740
+ m = re.search(r"(\{[\s\S]*\})", text)
741
+ if m:
742
+ obj = json.loads(m.group(1))
743
+ commands = obj.get("commands", [])
744
+ # Tolerate model output as a plain list
745
+ print("obj:"+json.dumps(obj, ensure_ascii=False))
746
+ if not commands and isinstance(obj, list):
747
+ commands = obj
748
+ # Tolerate inline text commands
749
+ if not commands and text.strip():
750
+ candidate_lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
751
+ commands = [
752
+ ln.lstrip("- ").strip()
753
+ for ln in candidate_lines
754
+ if ln.lower().startswith(("python ", "python3 ", "bash ", "sh ", "rscript ", "r ", "snakemake", "nextflow", "make "))
755
+ ]
756
+ safe_cmds: list[list[str]] = []
757
+ for item in commands[:max_commands]:
758
+ if isinstance(item, str):
759
+ cmd = shlex.split(item)
760
+ elif isinstance(item, list):
761
+ cmd = [str(x) for x in item]
762
+ else:
763
+ continue
764
+ if self._is_safe_run_command(cmd):
765
+ safe_cmds.append(cmd)
766
+ if not safe_cmds:
767
+ self._append_log(log_file, f"[gemini] empty command plan; raw={(text or '')[:500]}")
768
+ return self._extract_readme_run_commands(source_dir, max_commands=max_commands)
769
+ self._append_log(log_file, f"[gemini] planned_commands={json.dumps(safe_cmds, ensure_ascii=True)}")
770
+ return safe_cmds
771
+ except Exception as exc:
772
+ self._append_log(log_file, f"[gemini] planner exception: {exc}")
773
+ return self._extract_readme_run_commands(source_dir, max_commands=max_commands)
774
+
775
+ def _execute_local_step(
776
+ self,
777
+ step_name: str,
778
+ *,
779
+ task: str,
780
+ input_manifest: dict[str, Any],
781
+ context: dict[str, Any],
782
+ log_file: Path,
783
+ ) -> dict[str, Any]:
784
+ run_dir: Path = context["run_dir"]
785
+ artifacts: dict[str, Any] = context["artifacts"]
786
+ code_repo = self._extract_code_repo(task=task, input_manifest=input_manifest)
787
+ source_dir = run_dir / "06_source_code"
788
+ artifacts["source_repo"] = code_repo
789
+ artifacts["source_dir"] = source_dir
790
+
791
+ if step_name == "source_clone":
792
+ if not code_repo or "unknown_repo" in code_repo:
793
+ return {"ok": False, "skipped": True, "result": {"warning": "source_repo_missing"}}
794
+ source_dir.parent.mkdir(parents=True, exist_ok=True)
795
+ if source_dir.exists():
796
+ result = self._run_local_command(["git", "-C", str(source_dir), "pull"], log_file=log_file)
797
+ else:
798
+ result = self._run_local_command(["git", "clone", "--depth", "1", code_repo, str(source_dir)], log_file=log_file)
799
+ ok = result.get("return_code", 1) == 0
800
+ return {"ok": ok, "result": result}
801
+
802
+ if step_name == "source_execute":
803
+ if not source_dir.exists():
804
+ return {"ok": False, "skipped": True, "result": {"warning": "source_dir_not_ready"}}
805
+ attempts: list[dict[str, Any]] = []
806
+ run_attempt_success = False
807
+ has_r = shutil.which("R") is not None
808
+ # Attempt 1: install dependencies if common file exists
809
+ req = source_dir / "requirements.txt"
810
+ if req.exists():
811
+ setup = self._run_local_command(["python", "-m", "pip", "install", "-r", str(req)], cwd=source_dir, log_file=log_file)
812
+ setup["attempt_type"] = "setup"
813
+ attempts.append(setup)
814
+ r_renv = source_dir / "renv.lock"
815
+ r_desc = source_dir / "DESCRIPTION"
816
+ if r_renv.exists():
817
+ if has_r:
818
+ setup = self._run_local_command(
819
+ [
820
+ "R",
821
+ "--vanilla",
822
+ "-e",
823
+ "if (!requireNamespace('renv', quietly=TRUE)) install.packages('renv', repos='https://cloud.r-project.org'); renv::restore(prompt=FALSE)",
824
+ ],
825
+ cwd=source_dir,
826
+ log_file=log_file,
827
+ timeout_s=1800,
828
+ )
829
+ setup["attempt_type"] = "setup"
830
+ attempts.append(setup)
831
+ else:
832
+ attempts.append(
833
+ {
834
+ "attempt_type": "setup",
835
+ "return_code": -1,
836
+ "warning": "R_not_found_for_renv_restore",
837
+ "command_executed": "R --vanilla -e <renv::restore>",
838
+ }
839
+ )
840
+ elif r_desc.exists() and has_r:
841
+ setup = self._run_local_command(
842
+ [
843
+ "R",
844
+ "--vanilla",
845
+ "-e",
846
+ "if (!requireNamespace('remotes', quietly=TRUE)) install.packages('remotes', repos='https://cloud.r-project.org'); remotes::install_local('.', upgrade='never')",
847
+ ],
848
+ cwd=source_dir,
849
+ log_file=log_file,
850
+ timeout_s=1800,
851
+ )
852
+ setup["attempt_type"] = "setup"
853
+ attempts.append(setup)
854
+ # Attempt 2: common reproducibility entry scripts
855
+ candidate_scripts = ["reproduce.sh", "run.sh", "scripts/reproduce.sh"]
856
+ executed = False
857
+ for rel in candidate_scripts:
858
+ fp = source_dir / rel
859
+ if fp.exists():
860
+ run = self._run_local_command(["bash", str(fp)], cwd=source_dir, log_file=log_file)
861
+ run["attempt_type"] = "run"
862
+ attempts.append(run)
863
+ run_attempt_success = run_attempt_success or (run.get("return_code", 1) == 0)
864
+ executed = True
865
+ break
866
+ # Attempt 3: Gemini agent plans and drives repo-specific runnable commands
867
+ gemini_cmds: list[list[str]] = []
868
+ if not executed:
869
+ gemini_cmds = self._plan_source_commands_with_gemini(
870
+ task=task,
871
+ source_dir=source_dir,
872
+ input_manifest=input_manifest,
873
+ log_file=log_file,
874
+ )
875
+ print(gemini_cmds)
876
+ for cmd in gemini_cmds:
877
+ run = self._run_local_command(cmd, cwd=source_dir, log_file=log_file)
878
+ run["attempt_type"] = "run_gemini"
879
+ attempts.append(run)
880
+ if run.get("return_code", 1) == 0:
881
+ run_attempt_success = True
882
+ executed = True
883
+ break
884
+
885
+ if run_attempt_success:
886
+ return {"ok": True, "result": {"attempts": attempts, "gemini_planned_commands": gemini_cmds}}
887
+ warning = "source_execution_not_reproduced"
888
+ if not gemini_cmds and not executed:
889
+ warning = "gemini_no_executable_command"
890
+ return {
891
+ "ok": False,
892
+ "skipped": True,
893
+ "result": {
894
+ "warning": warning,
895
+ "gemini_planned_commands": gemini_cmds,
896
+ "attempts": attempts,
897
+ },
898
+ }
899
+
900
+ if step_name == "summarize_repro":
901
+ summary = {
902
+ "source_repo": code_repo or "unknown_repo",
903
+ "data_sources": input_manifest.get("data_sources", []),
904
+ "repro_steps": input_manifest.get("repro_steps", []),
905
+ "notes": (
906
+ "Summary generated from benchmark prompt execution. "
907
+ "Review source execution attempts and MCP preprocessing outputs for final conclusion."
908
+ ),
909
+ }
910
+ return {"ok": True, "result": summary}
911
+
912
+ return {"ok": False, "result": {"error": f"unsupported_local_step:{step_name}"}}
913
+
914
+ @staticmethod
915
+ def _bowtie2_index_exists(index_base: str | Path) -> bool:
916
+ base = Path(index_base)
917
+ bt2_suffixes = [".1.bt2", ".2.bt2", ".3.bt2", ".4.bt2", ".rev.1.bt2", ".rev.2.bt2"]
918
+ bt2l_suffixes = [s.replace(".bt2", ".bt2l") for s in bt2_suffixes]
919
+ return any((base.parent / (base.name + s)).exists() for s in bt2_suffixes) or any(
920
+ (base.parent / (base.name + s)).exists() for s in bt2l_suffixes
921
+ )
922
+
923
+ def execute_task(
924
+ self,
925
+ task: str,
926
+ input_manifest: dict[str, Any],
927
+ task_scope: str,
928
+ pipeline_config: dict[str, Any] | None = None,
929
+ ) -> dict[str, Any]:
930
+ report = ExperimentReport.new(
931
+ task=task,
932
+ input_manifest=input_manifest,
933
+ pipeline_config_id=(pipeline_config or {}).get("config_id"),
934
+ )
935
+ run_dir = self.default_results_root / report.run_id
936
+ run_dir.mkdir(parents=True, exist_ok=True)
937
+ log_path = run_dir / "pipeline.log"
938
+ log_path.write_text("", encoding="utf-8")
939
+
940
+ plan = self._plan_task(task=task, task_scope=task_scope, pipeline_config=pipeline_config)
941
+ route_snapshot: dict[str, Any] = {}
942
+ self._append_log(log_path, f"[planner] generated_plan={json.dumps(plan, ensure_ascii=True)}")
943
+
944
+ try:
945
+ params = (pipeline_config or {}).get("parameters", {})
946
+ threads = int(params.get("threads", 4))
947
+ quality_cutoff = int(params.get("quality_cutoff", 20))
948
+ index_base = input_manifest.get("reference_index_base") or params.get("reference_index_base")
949
+ r1 = Path(input_manifest["r1"]).resolve()
950
+ r2 = Path(input_manifest["r2"]).resolve()
951
+
952
+ if task_scope != "first_pipeline":
953
+ self._append_log(
954
+ log_path,
955
+ "[planner] non-first_pipeline scope detected; running generic configured steps plan",
956
+ )
957
+ if not r1.exists() or not r2.exists():
958
+ raise FileNotFoundError("Input FASTQ files not found for r1/r2.")
959
+
960
+ index_ready = bool(index_base) and self._bowtie2_index_exists(index_base)
961
+ if not index_ready:
962
+ before = len(plan)
963
+ plan = [s for s in plan if s.get("name") != "align"]
964
+ self._append_log(
965
+ log_path,
966
+ "[planner] align_step_skipped reason=missing_or_invalid_reference_index",
967
+ )
968
+ self._append_log(log_path, f"[planner] plan_rewritten from_steps={before} to_steps={len(plan)}")
969
+
970
+ step_results: dict[str, Any] = {}
971
+ artifacts: dict[str, Any] = {}
972
+ warnings: list[str] = []
973
+ skippable_steps = {"aggregate"}
974
+ context = {
975
+ "run_dir": run_dir,
976
+ "r1": r1,
977
+ "r2": r2,
978
+ "threads": threads,
979
+ "quality_cutoff": quality_cutoff,
980
+ "index_base": index_base,
981
+ "artifacts": artifacts,
982
+ }
983
+
984
+ for step in plan:
985
+ step_name = step["name"]
986
+ if step.get("local_executor"):
987
+ local_result = self._execute_local_step(
988
+ step_name=step_name,
989
+ task=task,
990
+ input_manifest=input_manifest,
991
+ context=context,
992
+ log_file=log_path,
993
+ )
994
+ step_results[step_name] = local_result
995
+ if not local_result.get("ok"):
996
+ warn = f"skip_or_fail_local_step:{step_name}"
997
+ warnings.append(warn)
998
+ self._append_log(log_path, f"[planner] {warn}")
999
+ continue
1000
+ candidates = step["candidates"]
1001
+ chosen_route = None
1002
+ for candidate in candidates:
1003
+ chosen_route = self._route_or_generate(candidate, log_file=log_path)
1004
+ if chosen_route is not None:
1005
+ if self.router.binary_available(chosen_route.function_name):
1006
+ break
1007
+ self._append_log(
1008
+ log_path,
1009
+ f"[planner] skip_candidate={candidate} reason=binary_unavailable binary={chosen_route.binary_name}",
1010
+ )
1011
+ chosen_route = None
1012
+ if chosen_route is None:
1013
+ if step_name in skippable_steps:
1014
+ warn = f"skip_step:{step_name} reason=no_available_mcp_route"
1015
+ warnings.append(warn)
1016
+ self._append_log(log_path, f"[planner] {warn}")
1017
+ step_results[step_name] = {
1018
+ "ok": False,
1019
+ "skipped": True,
1020
+ "result": {"warning": warn},
1021
+ }
1022
+ continue
1023
+ raise RuntimeError(f"no_mcp_route_found_for_step:{step_name}")
1024
+
1025
+ route_snapshot[step_name] = {
1026
+ "requested_candidates": candidates,
1027
+ "selected_tool": chosen_route.tool_name,
1028
+ "selected_function": chosen_route.function_name,
1029
+ "binary": chosen_route.binary_name,
1030
+ "binary_available": self.router.binary_available(chosen_route.function_name),
1031
+ "server_script": str(chosen_route.server_script),
1032
+ "server_exists": chosen_route.server_script.exists(),
1033
+ }
1034
+
1035
+ kwargs = self._build_step_kwargs(
1036
+ step_name=step_name,
1037
+ route_function=chosen_route.function_name,
1038
+ context=context,
1039
+ )
1040
+ result = self._invoke_mcp_tool(chosen_route, kwargs=kwargs, log_file=log_path)
1041
+ step_results[step_name] = result
1042
+ if not result["ok"]:
1043
+ if step_name in skippable_steps:
1044
+ warn = f"skip_step:{step_name} reason=tool_execution_failed"
1045
+ warnings.append(warn)
1046
+ self._append_log(log_path, f"[planner] {warn}")
1047
+ step_results[step_name] = {
1048
+ "ok": False,
1049
+ "skipped": True,
1050
+ "result": {
1051
+ **self._jsonable(result["result"]),
1052
+ "warning": warn,
1053
+ },
1054
+ }
1055
+ continue
1056
+ raise RuntimeError(f"{step_name}_failed")
1057
+
1058
+ # capture key artifacts
1059
+ output_files = result["result"].get("output_files") or []
1060
+ if step_name == "trim":
1061
+ trim_dir = run_dir / "02_trim"
1062
+ # best-effort: prefer explicit output_files when available
1063
+ if output_files:
1064
+ r1_candidates = [Path(p) for p in output_files if ("_val_1" in p or "_fastp_R1" in p)]
1065
+ r2_candidates = [Path(p) for p in output_files if ("_val_2" in p or "_fastp_R2" in p)]
1066
+ if r1_candidates and r2_candidates:
1067
+ artifacts["trimmed_r1"] = r1_candidates[-1]
1068
+ artifacts["trimmed_r2"] = r2_candidates[-1]
1069
+
1070
+ if "trimmed_r1" not in artifacts or "trimmed_r2" not in artifacts:
1071
+ trimmed_r1, trimmed_r2 = self._pick_trimmed_pair(trim_dir)
1072
+ if trimmed_r1 and trimmed_r2:
1073
+ artifacts["trimmed_r1"] = trimmed_r1
1074
+ artifacts["trimmed_r2"] = trimmed_r2
1075
+ if "trimmed_r1" not in artifacts or "trimmed_r2" not in artifacts:
1076
+ raise RuntimeError("trimmed_files_not_found")
1077
+
1078
+ multiqc_report = run_dir / "05_multiqc" / "multiqc_report.html"
1079
+ if (step_results.get("aggregate") or {}).get("ok") and multiqc_report.exists():
1080
+ artifacts["multiqc_report"] = multiqc_report
1081
+
1082
+ self._collect_fastqc_artifacts(run_dir=run_dir, artifacts=artifacts)
1083
+
1084
+ summary = {
1085
+ "status": "completed_with_warnings" if warnings else "completed",
1086
+ "task_scope": task_scope,
1087
+ "task": task,
1088
+ "plan": self._jsonable(plan),
1089
+ "steps": self._jsonable({k: {"ok": v["ok"], "result": v["result"]} for k, v in step_results.items()}),
1090
+ "warnings": warnings,
1091
+ "artifacts": {
1092
+ "trimmed_r1": str(artifacts.get("trimmed_r1", "")),
1093
+ "trimmed_r2": str(artifacts.get("trimmed_r2", "")),
1094
+ "sam": str(artifacts.get("sam", "")),
1095
+ "multiqc_report": str(artifacts.get("multiqc_report", multiqc_report)),
1096
+ "fastqc_raw_html": self._jsonable(artifacts.get("fastqc_raw_html", [])),
1097
+ "fastqc_trimmed_html": self._jsonable(artifacts.get("fastqc_trimmed_html", [])),
1098
+ },
1099
+ "router": self._jsonable(route_snapshot),
1100
+ }
1101
+ (run_dir / "summary.json").write_text(
1102
+ json.dumps(summary, indent=2, ensure_ascii=True),
1103
+ encoding="utf-8",
1104
+ )
1105
+
1106
+ analysis_report_path = self._write_analysis_report(
1107
+ run_dir=run_dir,
1108
+ task=task,
1109
+ task_scope=task_scope,
1110
+ status=summary["status"],
1111
+ step_results=step_results,
1112
+ warnings=warnings,
1113
+ artifacts=artifacts,
1114
+ )
1115
+
1116
+ report.status = "completed_with_warnings" if warnings else "completed"
1117
+ report.execution_log = str(log_path)
1118
+ report.output_artifacts = [str(run_dir / "summary.json"), str(analysis_report_path)]
1119
+ if artifacts.get("multiqc_report"):
1120
+ report.output_artifacts.append(str(artifacts["multiqc_report"]))
1121
+ report.metrics = {
1122
+ "steps": len(plan),
1123
+ "has_pipeline_config": bool(pipeline_config),
1124
+ "task_scope": task_scope,
1125
+ "plan": self._jsonable(plan),
1126
+ "router": self._jsonable(route_snapshot),
1127
+ "step_results": self._jsonable(step_results),
1128
+ "warnings": warnings,
1129
+ "log_tail": self._read_log_tail(log_path),
1130
+ }
1131
+ if warnings:
1132
+ report.notes = (
1133
+ "Executed with warnings via MCP routing plan. "
1134
+ f"Warnings: {'; '.join(warnings)}"
1135
+ )
1136
+ else:
1137
+ report.notes = "Executed via MCP routing plan with dynamic tool selection and converter fallback."
1138
+ except Exception as exc: # pragma: no cover - defensive path
1139
+ report.status = "failed"
1140
+ report.execution_log = str(log_path)
1141
+ report.failures.append(
1142
+ FailureMode(
1143
+ step_name="executor",
1144
+ error_type=type(exc).__name__,
1145
+ error_message=str(exc),
1146
+ hint="Inspect pipeline.log and parameters.",
1147
+ )
1148
+ )
1149
+ self._append_log(log_path, f"[V1] status=failed error={exc}")
1150
+ failure_summary = {
1151
+ "status": "failed",
1152
+ "task_scope": task_scope,
1153
+ "task": task,
1154
+ "plan": self._jsonable(plan),
1155
+ "router": self._jsonable(route_snapshot),
1156
+ "partial_steps": self._jsonable(step_results),
1157
+ "artifacts": self._jsonable(artifacts),
1158
+ "error": {"type": type(exc).__name__, "message": str(exc)},
1159
+ "log_tail": self._read_log_tail(log_path),
1160
+ }
1161
+ (run_dir / "summary.json").write_text(
1162
+ json.dumps(failure_summary, indent=2, ensure_ascii=True),
1163
+ encoding="utf-8",
1164
+ )
1165
+ report.output_artifacts = [str(run_dir / "summary.json")]
1166
+ report.metrics = {
1167
+ "task_scope": task_scope,
1168
+ "router": self._jsonable(route_snapshot),
1169
+ "plan": self._jsonable(plan),
1170
+ "partial_steps": self._jsonable(step_results),
1171
+ "log_tail": self._read_log_tail(log_path),
1172
+ }
1173
+
1174
+ self.memory.save_report(report)
1175
+ return report.to_dict()
1176
+
1177
+ def execute_autopilot(
1178
+ self,
1179
+ user_goal: str,
1180
+ data_dir: str | Path,
1181
+ task_scope: str = "first_pipeline",
1182
+ pipeline_config: dict[str, Any] | None = None,
1183
+ manifest_overrides: dict[str, Any] | None = None,
1184
+ ) -> dict[str, Any]:
1185
+ r1, r2 = self._discover_paired_fastq(Path(data_dir))
1186
+ manifest: dict[str, Any] = {"r1": str(r1), "r2": str(r2)}
1187
+ if manifest_overrides:
1188
+ manifest.update(manifest_overrides)
1189
+ # reference index is optional; execute_task 会根据有效性决定是否执行 align
1190
+ if pipeline_config and pipeline_config.get("parameters", {}).get("reference_index_base"):
1191
+ manifest["reference_index_base"] = pipeline_config["parameters"]["reference_index_base"]
1192
+ return self.execute_task(
1193
+ task=user_goal,
1194
+ input_manifest=manifest,
1195
+ task_scope=task_scope,
1196
+ pipeline_config=pipeline_config,
1197
+ )
1198
+
1199
+ @staticmethod
1200
+ def _discover_paired_fastq(data_dir: Path) -> tuple[Path, Path]:
1201
+ if not data_dir.exists():
1202
+ raise FileNotFoundError(f"data_dir not found: {data_dir}")
1203
+
1204
+ files = sorted(
1205
+ [
1206
+ p for p in data_dir.iterdir()
1207
+ if p.is_file() and p.name.lower().endswith((".fastq", ".fq", ".fastq.gz", ".fq.gz"))
1208
+ ]
1209
+ )
1210
+ if len(files) < 2:
1211
+ raise ValueError("Need at least two FASTQ files in data_dir.")
1212
+
1213
+ # 优先找 R1/R2 命名对
1214
+ for f in files:
1215
+ name = f.name
1216
+ r2_name = (
1217
+ name.replace("_R1", "_R2")
1218
+ .replace(".R1.", ".R2.")
1219
+ .replace("_1.", "_2.")
1220
+ )
1221
+ for g in files:
1222
+ if g.name == r2_name:
1223
+ return f, g
1224
+
1225
+ # fallback: 前两个 FASTQ
1226
+ return files[0], files[1]
1227
+
1228
+ @staticmethod
1229
+ def _collect_fastqc_artifacts(run_dir: Path, artifacts: dict[str, Any]) -> None:
1230
+ raw_dir = run_dir / "01_fastqc_raw"
1231
+ trim_dir = run_dir / "04_fastqc_trimmed"
1232
+ if raw_dir.exists():
1233
+ artifacts["fastqc_raw_html"] = [str(p) for p in sorted(raw_dir.glob("*_fastqc.html"))]
1234
+ if trim_dir.exists():
1235
+ artifacts["fastqc_trimmed_html"] = [str(p) for p in sorted(trim_dir.glob("*_fastqc.html"))]
1236
+
1237
+ @staticmethod
1238
+ def _extract_fastp_metrics(step_results: dict[str, Any]) -> dict[str, Any]:
1239
+ trim = step_results.get("trim", {})
1240
+ result = trim.get("result", {}) if isinstance(trim, dict) else {}
1241
+ output_files = result.get("output_files") or []
1242
+ json_fp = None
1243
+ for fp in output_files:
1244
+ if str(fp).endswith(".json") and "fastp" in str(fp):
1245
+ json_fp = Path(fp)
1246
+ break
1247
+ if not json_fp or not json_fp.exists():
1248
+ return {}
1249
+ try:
1250
+ payload = json.loads(json_fp.read_text(encoding="utf-8"))
1251
+ summary = payload.get("summary", {})
1252
+ before = summary.get("before_filtering", {})
1253
+ after = summary.get("after_filtering", {})
1254
+ filtering = summary.get("filtering_result", {})
1255
+ return {
1256
+ "before_total_reads": before.get("total_reads"),
1257
+ "after_total_reads": after.get("total_reads"),
1258
+ "q30_rate_after": after.get("q30_rate"),
1259
+ "passed_filter_reads": filtering.get("passed_filter_reads"),
1260
+ "low_quality_reads": filtering.get("low_quality_reads"),
1261
+ }
1262
+ except Exception:
1263
+ return {}
1264
+
1265
+ def _write_analysis_report(
1266
+ self,
1267
+ run_dir: Path,
1268
+ task: str,
1269
+ task_scope: str,
1270
+ status: str,
1271
+ step_results: dict[str, Any],
1272
+ warnings: list[str],
1273
+ artifacts: dict[str, Any],
1274
+ ) -> Path:
1275
+ metrics = self._extract_fastp_metrics(step_results)
1276
+ lines: list[str] = []
1277
+ lines.append("# BioClawMCP Analysis Report")
1278
+ lines.append("")
1279
+ lines.append(f"- Task: {task}")
1280
+ lines.append(f"- Task Scope: {task_scope}")
1281
+ lines.append(f"- Status: {status}")
1282
+ lines.append("")
1283
+ if warnings:
1284
+ lines.append("## Warnings")
1285
+ for w in warnings:
1286
+ lines.append(f"- {w}")
1287
+ lines.append("")
1288
+
1289
+ lines.append("## Pipeline Execution Summary")
1290
+ lines.append("| Step | Status |")
1291
+ lines.append("|---|---|")
1292
+ for step_name, step_payload in step_results.items():
1293
+ ok = step_payload.get("ok", False)
1294
+ skipped = step_payload.get("skipped", False)
1295
+ status_text = "skipped" if skipped else ("ok" if ok else "failed")
1296
+ lines.append(f"| {step_name} | {status_text} |")
1297
+ lines.append("")
1298
+
1299
+ if metrics:
1300
+ lines.append("## fastp Key Metrics")
1301
+ lines.append(f"- Before total reads: {metrics.get('before_total_reads')}")
1302
+ lines.append(f"- After total reads: {metrics.get('after_total_reads')}")
1303
+ lines.append(f"- Q30 rate after: {metrics.get('q30_rate_after')}")
1304
+ lines.append(f"- Passed filter reads: {metrics.get('passed_filter_reads')}")
1305
+ lines.append(f"- Low quality reads: {metrics.get('low_quality_reads')}")
1306
+ lines.append("")
1307
+
1308
+ lines.append("## Output Artifacts")
1309
+ if artifacts.get("trimmed_r1"):
1310
+ lines.append(f"- Trimmed R1: {artifacts.get('trimmed_r1')}")
1311
+ if artifacts.get("trimmed_r2"):
1312
+ lines.append(f"- Trimmed R2: {artifacts.get('trimmed_r2')}")
1313
+ if artifacts.get("sam"):
1314
+ lines.append(f"- Alignment SAM: {artifacts.get('sam')}")
1315
+ if artifacts.get("multiqc_report"):
1316
+ lines.append(f"- MultiQC report: {artifacts.get('multiqc_report')}")
1317
+ for fp in artifacts.get("fastqc_raw_html", []):
1318
+ lines.append(f"- FastQC raw HTML: {fp}")
1319
+ for fp in artifacts.get("fastqc_trimmed_html", []):
1320
+ lines.append(f"- FastQC trimmed HTML: {fp}")
1321
+ lines.append("")
1322
+
1323
+ lines.append("## Per-step Command & Logs")
1324
+ for step_name, step_payload in step_results.items():
1325
+ lines.append(f"### {step_name}")
1326
+ result = step_payload.get("result", {}) if isinstance(step_payload, dict) else {}
1327
+ cmd = result.get("command_executed", "")
1328
+ if cmd:
1329
+ lines.append("```bash")
1330
+ lines.append(cmd)
1331
+ lines.append("```")
1332
+ stderr = result.get("stderr", "")
1333
+ stdout = result.get("stdout", "")
1334
+ if stderr:
1335
+ lines.append("stderr:")
1336
+ lines.append("```text")
1337
+ lines.append(str(stderr)[:6000])
1338
+ lines.append("```")
1339
+ if stdout:
1340
+ lines.append("stdout:")
1341
+ lines.append("```text")
1342
+ lines.append(str(stdout)[:6000])
1343
+ lines.append("```")
1344
+ lines.append("")
1345
+
1346
+ report_path = run_dir / "analysis_report.md"
1347
+ report_path.write_text("\n".join(lines), encoding="utf-8")
1348
+ return report_path
BioScientist/agent_system/engines/v1_executor_backup/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .version import __version__
2
+
3
+ __all__ = ["__version__"]
BioScientist/agent_system/engines/v1_executor_backup/agent/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from biomni.agent.a1 import A1 # noqa: F401
BioScientist/agent_system/engines/v1_executor_backup/agent/a1.py ADDED
The diff for this file is too large to render. See raw diff
 
BioScientist/agent_system/engines/v1_executor_backup/agent/env_collection.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import re
4
+ from typing import Any
5
+
6
+ from langchain_core.prompts import ChatPromptTemplate
7
+ from langchain_text_splitters import RecursiveCharacterTextSplitter
8
+
9
+ from biomni.agent.base_agent import base_agent
10
+
11
+
12
+ class PaperTaskExtractor(base_agent):
13
+ """Agent that extracts generalizable tasks/experiments from academic papers.
14
+ It processes papers in chunks and identifies common research tasks that could be shared across papers.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ llm="claude-3-7-sonnet-20250219",
20
+ cheap_llm=None,
21
+ tools=None,
22
+ chunk_size=4000,
23
+ chunk_overlap=400,
24
+ ):
25
+ """Initialize the PaperTaskExtractor agent.
26
+
27
+ Args:
28
+ llm (str): The LLM model to use
29
+ cheap_llm (str, optional): A cheaper LLM for simpler tasks
30
+ tools (list, optional): Any tools to use (not needed for this agent)
31
+ chunk_size (int): Size of text chunks for processing
32
+ chunk_overlap (int): Overlap between chunks
33
+
34
+ """
35
+ super().__init__(llm, cheap_llm, tools)
36
+ self.chunk_size = chunk_size
37
+ self.chunk_overlap = chunk_overlap
38
+ self.log = []
39
+ self.configure()
40
+
41
+ def configure(self):
42
+ """Configure the agent with appropriate prompts."""
43
+ # Prompt for analyzing paper chunks
44
+ self.chunk_analysis_prompt = """You are a research methodology expert specializing in identifying computational tasks and data analysis procedures in academic papers.
45
+
46
+ Your job is to analyze chunks of academic papers and identify ONLY the most common, generalizable computational tasks that are widely used across biomedical research and can be implemented with Python or Linux code.
47
+
48
+ STRICT GUIDELINES:
49
+ 1. ONLY extract tasks that are extremely common and standard in computational biomedical research
50
+ 2. Each task MUST have clear, well-defined inputs and outputs
51
+ 3. Tasks MUST be generalizable across many different papers and research questions
52
+ 4. Be VERY selective - only include tasks that appear in hundreds of papers
53
+ 5. If a task is specific to this paper, unclear, or not widely used, DO NOT include it
54
+ 6. Focus on computational tasks that can be implemented with Python or Linux code
55
+ 7. Each task should be something that could be implemented as a function with clear inputs/outputs
56
+ 8. Also identify commonly used databases and software packages mentioned in the text
57
+ 9. Tasks MUST be CONCRETE and SPECIFIC - include exact methodological details
58
+ 10. Avoid vague task names like "Statistical Analysis" - instead use specific protocol names like "Two-way ANOVA with Tukey's Post-hoc Test using SciPy"
59
+ 11. DO NOT include wet lab procedures that cannot be implemented computationally
60
+ 12. ONLY include tasks that could be automated with code
61
+
62
+ For the following chunk of text from an academic paper, provide:
63
+ 1. A list of ONLY the most common, generalizable COMPUTATIONAL tasks identified (be extremely selective)
64
+ 2. For each task, clearly define:
65
+ - Task name: A SPECIFIC and CONCRETE name with methodological details (e.g., "RNA-seq Differential Expression Analysis with DESeq2" instead of just "Gene Expression Analysis")
66
+ - Input: What SPECIFIC data or parameters the task requires
67
+ - Output: What SPECIFIC data or results the task produces
68
+ - Code implementation: How this task could be implemented with Python or Linux code, including key libraries/packages
69
+ - Frequency: How common this computational task is in biomedical research
70
+ - Standard methods: The established computational techniques used to perform this task
71
+ - Example: A brief description of how THIS specific paper uses this task (with specific details from the paper)
72
+ 3. A list of commonly used databases mentioned in the text (if any)
73
+ 4. A list of commonly used software packages/tools mentioned in the text (if any)
74
+
75
+ PAPER CHUNK:
76
+ {chunk_text}
77
+
78
+ Remember, it's better to return NO tasks than to include tasks that aren't extremely common, generalizable, and implementable with code. Quality over quantity is essential. Tasks MUST be CONCRETE with SPECIFIC methodological details and MUST be implementable with Python or Linux code.
79
+ """
80
+
81
+ # Prompt for consolidating tasks
82
+ self.consolidation_prompt = """You are a research methodology expert. Your task is to consolidate lists of computational research tasks extracted from different chunks of an academic paper.
83
+
84
+ BE EXTREMELY SELECTIVE. Only include tasks that are:
85
+ 1. Fundamental to computational biomedical research
86
+ 2. Used in hundreds of papers across different subfields
87
+ 3. Have clear, well-defined inputs and outputs
88
+ 4. Represent standard computational approaches
89
+ 5. Could be implemented as a function with specific inputs and outputs
90
+ 6. Are CONCRETE and SPECIFIC with exact methodological details
91
+ 7. Can be implemented with Python or Linux code
92
+ 8. Are computational in nature, not wet lab procedures
93
+
94
+ REMOVE any tasks that:
95
+ - Are specific to a particular paper or dataset
96
+ - Lack clear inputs or outputs
97
+ - Are not widely used across biomedical research
98
+ - Are vague or poorly defined
99
+ - Represent niche or specialized techniques
100
+ - Have generic names without specific methodological details
101
+ - Cannot be implemented with code
102
+ - Require physical lab equipment or manual intervention
103
+
104
+ The output should be a JSON object with three main keys:
105
+ 1. "tasks": A list of task objects, where each task has:
106
+ - "task_name": A SPECIFIC and CONCRETE name with methodological details (e.g., "Single-cell RNA-seq Clustering with Seurat" instead of just "Cell Clustering")
107
+ - "description": A clear description of what the computational task does
108
+ - "inputs": SPECIFIC data types or parameters the task requires
109
+ - "outputs": SPECIFIC data types or results the task produces
110
+ - "code_implementation": How this task could be implemented with Python or Linux code, including key libraries/packages and a brief pseudocode example
111
+ - "frequency": How common this computational task is in biomedical research
112
+ - "standard_methods": The established computational techniques used to perform this task
113
+ - "example": A specific example from THIS paper showing how the task was used (with concrete details)
114
+
115
+ 2. "databases": A list of database objects, where each database has:
116
+ - "name": The name of the database
117
+ - "description": A brief description of what the database contains
118
+ - "url": The URL of the database (if mentioned)
119
+ - "usage": How the database is commonly used in computational biomedical research
120
+ - "example": How this specific paper uses the database
121
+
122
+ 3. "software": A list of software package objects, where each package has:
123
+ - "name": The name of the software package
124
+ - "description": A brief description of what the software does
125
+ - "url": The URL or reference to the software (if mentioned)
126
+ - "usage": How the software is commonly used in computational biomedical research
127
+ - "example": How this specific paper uses the software
128
+
129
+ EXTRACTED INFORMATION FROM PAPER CHUNKS:
130
+ {task_lists}
131
+
132
+ Be ruthless in filtering - it's better to return a few truly common computational tasks than many that aren't universal or implementable with code.
133
+ Respond with only a valid JSON object containing the three lists described above.
134
+ """
135
+
136
+ def process_paper(self, paper_text: str) -> dict[str, list[dict[str, Any]]]:
137
+ """Process a paper and extract generalizable tasks/experiments, databases, and software.
138
+
139
+ Args:
140
+ paper_text (str): The full text of the paper
141
+
142
+ Returns:
143
+ Dict[str, List[Dict[str, Any]]]: A dictionary with tasks, databases, and software
144
+
145
+ """
146
+ # Split the paper into chunks
147
+ text_splitter = RecursiveCharacterTextSplitter(
148
+ chunk_size=self.chunk_size,
149
+ chunk_overlap=self.chunk_overlap,
150
+ length_function=len,
151
+ separators=["\n\n", "\n", ". ", " ", ""],
152
+ )
153
+ chunks = text_splitter.split_text(paper_text)
154
+
155
+ # Process each chunk to extract tasks
156
+ chunk_results = []
157
+ for i, chunk in enumerate(chunks):
158
+ print(f"Processing chunk {i + 1}/{len(chunks)}...")
159
+ chunk_tasks = self._process_chunk(chunk)
160
+ chunk_results.append(chunk_tasks)
161
+
162
+ # Consolidate tasks from all chunks
163
+ consolidated_results = self._consolidate_tasks(chunk_results)
164
+ return consolidated_results
165
+
166
+ def _process_chunk(self, chunk_text: str) -> str:
167
+ """Process a single chunk of the paper to extract tasks.
168
+
169
+ Args:
170
+ chunk_text (str): The chunk text to process
171
+
172
+ Returns:
173
+ str: Extracted tasks from this chunk
174
+
175
+ """
176
+ prompt = self.chunk_analysis_prompt.format(chunk_text=chunk_text)
177
+ message = self.llm.invoke(prompt)
178
+ return message.content
179
+
180
+ def _consolidate_tasks(self, chunk_results: list[str]) -> dict[str, list[dict[str, Any]]]:
181
+ """Consolidate tasks, databases, and software extracted from different chunks into a unified structure.
182
+
183
+ Args:
184
+ chunk_results (List[str]): Results from each chunk
185
+
186
+ Returns:
187
+ Dict[str, List[Dict[str, Any]]]: Consolidated information with tasks, databases, and software
188
+
189
+ """
190
+ # Combine all chunk results
191
+ all_tasks = "\n\n===== CHUNK SEPARATOR =====\n\n".join(chunk_results)
192
+
193
+ # Use the consolidation prompt to merge and organize tasks
194
+ prompt = self.consolidation_prompt.format(task_lists=all_tasks)
195
+ response = self.llm.invoke(prompt)
196
+
197
+ # Extract the JSON from the response
198
+ try:
199
+ # Try to parse the entire response as JSON
200
+ result = json.loads(response.content)
201
+ except json.JSONDecodeError:
202
+ # If that fails, try to extract JSON from the text
203
+ try:
204
+ # Look for JSON-like content between triple backticks
205
+ json_match = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", response.content)
206
+ if json_match:
207
+ result = json.loads(json_match.group(1))
208
+ else:
209
+ # Fallback: just return the text response
210
+ return {
211
+ "tasks": [
212
+ {
213
+ "error": "Could not parse JSON",
214
+ "raw_response": response.content,
215
+ }
216
+ ],
217
+ "databases": [],
218
+ "software": [],
219
+ }
220
+ except Exception:
221
+ return {
222
+ "tasks": [
223
+ {
224
+ "error": "Could not parse JSON",
225
+ "raw_response": response.content,
226
+ }
227
+ ],
228
+ "databases": [],
229
+ "software": [],
230
+ }
231
+
232
+ # Ensure the result has the expected structure
233
+ if not isinstance(result, dict):
234
+ result = {
235
+ "tasks": result if isinstance(result, list) else [],
236
+ "databases": [],
237
+ "software": [],
238
+ }
239
+
240
+ # Ensure all required keys exist
241
+ for key in ["tasks", "databases", "software"]:
242
+ if key not in result:
243
+ result[key] = []
244
+
245
+ return result
246
+
247
+ def go(self, paper_text: str):
248
+ """Process a paper and return the extracted tasks, databases, and software.
249
+
250
+ Args:
251
+ paper_text (str): The full text of the paper
252
+
253
+ Returns:
254
+ tuple: (log, results) where log is a list of processing steps and results is the final result
255
+
256
+ """
257
+ self.log = []
258
+ self.log.append(
259
+ (
260
+ "user",
261
+ "Extract only the most common and generalizable biomedical research tasks, databases, and software from this paper",
262
+ )
263
+ )
264
+
265
+ results = self.process_paper(paper_text)
266
+
267
+ result_str = json.dumps(results, indent=2)
268
+ self.log.append(("assistant", result_str))
269
+
270
+ return self.log, results
271
+
272
+ def save_results(self, results: dict[str, list[dict[str, Any]]], output_path: str):
273
+ """Save the extracted tasks, databases, and software to a JSON file.
274
+
275
+ Args:
276
+ results (Dict[str, List[Dict[str, Any]]]): The extracted tasks, databases, and software
277
+ output_path (str): Path to save the results
278
+
279
+ """
280
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
281
+ with open(output_path, "w") as f:
282
+ json.dump(results, f, indent=2)
283
+ print(f"Results saved to {output_path}")
284
+
285
+ def result_formatting(self, output_class, task_intention):
286
+ """Format the results according to a specific output class.
287
+
288
+ Args:
289
+ output_class: The class to format the output as
290
+ task_intention: Description of the task
291
+
292
+ Returns:
293
+ The formatted result
294
+
295
+ """
296
+ format_check_prompt = ChatPromptTemplate.from_messages(
297
+ [
298
+ (
299
+ "system",
300
+ (
301
+ "You are evaluateGPT, tasked with extract and parse the task output based on the history of an agent. "
302
+ "Review the entire history of messages provided. "
303
+ "Here is the task output requirement: \n"
304
+ f"'{task_intention.replace('{', '{{').replace('}', '}}')}'.\n"
305
+ ),
306
+ ),
307
+ ("placeholder", "{messages}"),
308
+ ]
309
+ )
310
+
311
+ checker_llm = format_check_prompt | self.llm.with_structured_output(output_class)
312
+ result = checker_llm.invoke({"messages": [("user", str(self.log))]}).dict()
313
+ return result
BioScientist/agent_system/engines/v1_executor_backup/agent/function_generator.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ from biomni.llm import get_llm
4
+
5
+
6
+ class base_agent:
7
+ def __init__(self, llm="claude-3-haiku-20240307", cheap_llm=None, tools=None, temperature=0.7):
8
+ self.tools = tools
9
+ self.llm = get_llm(llm, temperature)
10
+ if cheap_llm is None:
11
+ self.cheap_llm = llm
12
+ else:
13
+ self.cheap_llm = cheap_llm
14
+
15
+ def configure(self):
16
+ pass
17
+
18
+ def go(self, input):
19
+ pass
20
+
21
+
22
+ class FunctionGenerator(base_agent):
23
+ """Agent that generates executable Python code scripts given a task description."""
24
+
25
+ def __init__(self, llm="claude-3-7-sonnet-20250219", cheap_llm=None, temperature=0.7):
26
+ """Initialize the PaperTaskExtractor agent.
27
+
28
+ Args:
29
+ llm (str): The LLM model to use
30
+ cheap_llm (str, optional): A cheaper LLM for simpler tasks
31
+ """
32
+ super().__init__(llm, cheap_llm, temperature)
33
+ self.log = []
34
+ self.configure()
35
+
36
+ def configure(self):
37
+ """Configure the agent with appropriate prompts."""
38
+ # Prompt for Python code generation
39
+ self.system_prompt = """You are a senior Python engineer. Generate robust, idiomatic Python code that solves the user's task. Requirements:
40
+ 1. Output ONLY Python code, ideally inside a single triple-backtick code block.
41
+ 2. Include minimal inline comments and a small docstring.
42
+ 3. Add a `main()` and an `if __name__ == '__main__':` guard when appropriate.
43
+ 4. Avoid external dependencies unless necessary; if used, show `pip` installs in comments.
44
+ 5. Do not include prose before or after the code.
45
+ 6. When applicable, prioritize the use of codes on public repositories, such as HuggingFace or Github
46
+
47
+ Generate Python codes for the following task:
48
+ {task}
49
+ """
50
+
51
+ def _generate_code(self, task_description: str) -> str:
52
+ """Generate codes given a task description.
53
+ Args:
54
+ task_description (str): task descriptions (possibly generated from previous steps)
55
+
56
+ Returns:
57
+ str: generated code string
58
+
59
+ """
60
+ prompt = self.system_prompt.format(task=task_description)
61
+ message = self.llm.invoke(prompt)
62
+ return message.content
63
+
64
+ def _generate_script_filename(self, task_description: str, max_words: int = 6) -> str:
65
+ """
66
+ Generate a safe, meaningful Python script filename from a task description.
67
+ Poised for update: may ask the agent to suggest meaningful names.
68
+
69
+ Parameters:
70
+ -----------
71
+ task_description (str): task descriptions (possibly generated from previous steps)
72
+
73
+ max_words : int
74
+ Maximum number of words to include in the filename.
75
+
76
+ Returns:
77
+ --------
78
+ str
79
+ A lowercase, hyphen-free, safe filename ending in '.py'.
80
+ """
81
+ # Lowercase and remove non-alphanumeric (allow spaces for splitting)
82
+ cleaned = re.sub(r"[^a-zA-Z0-9\s]", "", task_description.lower())
83
+
84
+ # Tokenize and select top words
85
+ words = cleaned.split()
86
+ selected_words = words[:max_words] if words else ["script"]
87
+
88
+ # Join with underscores
89
+ base_name = "_".join(selected_words)
90
+ return f"{base_name}.py"
91
+
92
+ def go(self, task_description: str):
93
+ """Implement the inherited function to get the tasks done.
94
+
95
+ Args:
96
+ task_description (str): task descriptions (possibly generated from previous steps)
97
+
98
+ Returns:
99
+ tuple: (script_filename, results) where script_filename is a generated name for script file and results is the generated codes
100
+
101
+ """
102
+ self.log = []
103
+ self.log.append(
104
+ (
105
+ "user",
106
+ "Generate Python codes given a task description",
107
+ )
108
+ )
109
+
110
+ script_filename = self._generate_script_filename(task_description)
111
+ results = self._generate_code(task_description)
112
+ return script_filename, self._extract_code_block(results)
113
+
114
+ def _extract_code_block(self, s: str) -> str:
115
+ """
116
+ Extract the first fenced code block (``` or ```python) from s.
117
+ """
118
+ m = re.search(r"```(?:python)?\s*(.+?)\s*```", s, flags=re.DOTALL | re.IGNORECASE)
119
+ return m.group(1).strip() if m else None
BioScientist/agent_system/engines/v1_executor_backup/agent/qa_llm.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_core.prompts import ChatPromptTemplate
2
+
3
+ from biomni.llm import get_llm
4
+
5
+
6
+ class qa_llm:
7
+ def __init__(self, path="./data", llm="claude-3-haiku-20240307", lab_bench_reproduce=False):
8
+ self.path = path
9
+ self.llm = get_llm(llm)
10
+
11
+ if lab_bench_reproduce:
12
+ self.prompt_modifier = """
13
+ The following is a multiple choice question about biology.
14
+ Please answer by responding with the letter of the correct answer.
15
+
16
+ Think step by step. \n
17
+ """
18
+ else:
19
+ self.prompt_modifier = ""
20
+ self.log = []
21
+
22
+ def configure(self):
23
+ pass
24
+
25
+ def go(self, input):
26
+ self.log = []
27
+ self.log.append(("user", input))
28
+ message = self.llm.invoke(self.prompt_modifier + input)
29
+ self.log.append(("assistant", message.content))
30
+ return [message.content], message.content
31
+
32
+ def result_formatting(self, output_class, task_intention):
33
+ self.format_check_prompt = ChatPromptTemplate.from_messages(
34
+ [
35
+ (
36
+ "system",
37
+ (
38
+ "You are evaluateGPT, tasked with extract and parse the task output based on the history of an agent. "
39
+ "Review the entire history of messages provided. "
40
+ "Here is the task output requirement: \n"
41
+ f"'{task_intention.replace('{', '{{').replace('}', '}}')}'.\n"
42
+ ),
43
+ ),
44
+ ("placeholder", "{messages}"),
45
+ ]
46
+ )
47
+
48
+ checker_llm = self.format_check_prompt | self.llm.with_structured_output(output_class)
49
+ result = checker_llm.invoke({"messages": [("user", str(self.log))]}).dict()
50
+ return result
BioScientist/agent_system/engines/v1_executor_backup/agent/react.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import inspect
3
+ import json
4
+ import os
5
+ import signal
6
+ from collections.abc import Sequence
7
+ from functools import wraps
8
+ from multiprocessing import Process, Queue
9
+ from typing import Annotated, TypedDict
10
+
11
+ from langchain_core.messages import BaseMessage, SystemMessage, ToolMessage
12
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
13
+ from langchain_core.runnables import RunnableConfig
14
+ from langgraph.graph import END, StateGraph
15
+ from langgraph.graph.message import add_messages
16
+
17
+ from biomni.config import default_config
18
+ from biomni.env_desc import data_lake_dict, library_content_dict
19
+ from biomni.llm import get_llm
20
+ from biomni.model.retriever import ToolRetriever
21
+ from biomni.tool.tool_registry import ToolRegistry
22
+ from biomni.utils import (
23
+ api_schema_to_langchain_tool,
24
+ function_to_api_schema,
25
+ pretty_print,
26
+ read_module2api,
27
+ )
28
+
29
+
30
+ # Define the AgentState TypedDict for our custom implementation
31
+ class AgentState(TypedDict):
32
+ """The state of the agent."""
33
+
34
+ # add_messages is a reducer that combines message sequences
35
+ messages: Annotated[Sequence[BaseMessage], add_messages]
36
+
37
+
38
+ class react:
39
+ def __init__(
40
+ self,
41
+ path: str | None = None,
42
+ llm: str | None = None,
43
+ use_tool_retriever: bool | None = None,
44
+ timeout_seconds: int | None = None,
45
+ ):
46
+ # Use default_config values for unspecified parameters
47
+ if path is None:
48
+ path = default_config.path
49
+ if llm is None:
50
+ llm = default_config.llm
51
+ if use_tool_retriever is None:
52
+ use_tool_retriever = default_config.use_tool_retriever
53
+ if timeout_seconds is None:
54
+ timeout_seconds = default_config.timeout_seconds
55
+
56
+ self.path = path
57
+ if not os.path.exists(path):
58
+ os.makedirs(path)
59
+ print(f"Created directory: {path}")
60
+ ### TODO: Download the data
61
+ else:
62
+ print(f"Data directory already exists: {path}, loading...")
63
+
64
+ module2api = read_module2api()
65
+
66
+ self.llm = get_llm(llm, config=default_config)
67
+ tools = []
68
+ for module, api_list in module2api.items():
69
+ print("Registering tools from module:", module)
70
+ tools += [api_schema_to_langchain_tool(api, mode="custom_tool", module_name=module) for api in api_list]
71
+ self.tools = tools
72
+ self.module2api = module2api
73
+ self.use_tool_retriever = use_tool_retriever
74
+
75
+ # Store dictionaries for data lake and library content
76
+ self.data_lake_dict = data_lake_dict
77
+ self.library_content_dict = library_content_dict
78
+
79
+ if self.use_tool_retriever:
80
+ self.tool_registry = ToolRegistry(module2api)
81
+ self.retriever = ToolRetriever()
82
+
83
+ self.timeout_seconds = timeout_seconds # 10 minutes default timeout
84
+
85
+ # When wrapping tools with timeout
86
+ self.tools = self._add_timeout_to_tools(self.tools)
87
+ self.prompt = ""
88
+ self.system_prompt = ""
89
+
90
+ def _add_timeout_to_tools(self, tools):
91
+ """Apply timeout wrapper to all tool functions using multiprocessing."""
92
+
93
+ def create_timed_func(original_func, timeout):
94
+ """Factory function that creates a unique timed function for each tool."""
95
+ tool_name = getattr(original_func, "__name__", "unknown")
96
+ # print(f"Applying timeout wrapper to tool: {tool_name}")
97
+
98
+ def process_func(func, args, kwargs, result_queue):
99
+ """Function to run in a separate process."""
100
+ try:
101
+ result = func(*args, **kwargs)
102
+ result_queue.put(("success", result))
103
+ except Exception as e:
104
+ result_queue.put(("error", str(e)))
105
+
106
+ @wraps(original_func)
107
+ def timed_func(*args, **kwargs):
108
+ # print(f"Executing tool with timeout: {tool_name}")
109
+ result_queue = Queue()
110
+
111
+ # Start a separate process
112
+ proc = Process(
113
+ target=process_func,
114
+ args=(original_func, args, kwargs, result_queue),
115
+ )
116
+ proc.start()
117
+
118
+ # Wait for the specified timeout
119
+ proc.join(timeout)
120
+
121
+ # Check if the process is still running after timeout
122
+ if proc.is_alive():
123
+ print(f"TIMEOUT: Tool {tool_name} execution timed out after {timeout} seconds")
124
+ # Force terminate the process
125
+ proc.terminate()
126
+ proc.join(1) # Give it a second to terminate
127
+
128
+ # If it's still not dead, kill it with more force
129
+ if proc.is_alive():
130
+ os.kill(proc.pid, signal.SIGKILL)
131
+
132
+ return f"ERROR: Tool execution timed out after {timeout} seconds. Please try with simpler inputs or break your task into smaller steps."
133
+
134
+ # Get the result from the queue
135
+ if not result_queue.empty():
136
+ status, result = result_queue.get()
137
+ if status == "success":
138
+ return result
139
+ else:
140
+ return f"Error in tool execution: {result}"
141
+
142
+ return "Error: Tool execution completed but no result was returned"
143
+
144
+ return timed_func
145
+
146
+ wrapped_tools = []
147
+ for tool in tools:
148
+ wrapped_tool = tool
149
+ wrapped_tool.func = create_timed_func(tool.func, self.timeout_seconds)
150
+ wrapped_tools.append(wrapped_tool)
151
+
152
+ return wrapped_tools
153
+
154
+ def add_tool(self, api):
155
+ function_code = inspect.getsource(api)
156
+ schema = function_to_api_schema(function_code, self.llm)
157
+ new_tool = api_schema_to_langchain_tool(schema, mode="custom_tool", module_name=api.__module__)
158
+
159
+ # Create a single wrapped tool using the existing _add_timeout_to_tools method
160
+ wrapped_tools = self._add_timeout_to_tools([new_tool])
161
+
162
+ # Get the wrapped tool and add it to our tools list
163
+ if wrapped_tools:
164
+ self.tools.append(wrapped_tools[0])
165
+
166
+ def configure(
167
+ self,
168
+ plan=False,
169
+ reflect=False,
170
+ data_lake=False,
171
+ react_code_search=False,
172
+ library_access=False,
173
+ ):
174
+ data_lake_path = self.path + "/data_lake"
175
+ data_lake_content = glob.glob(data_lake_path + "/*")
176
+ data_lake_items = [x.split("/")[-1] for x in data_lake_content]
177
+
178
+ if react_code_search:
179
+ tools = [i for i in self.tools if i.name in ["run_python_repl", "search_google"]]
180
+
181
+ prompt_modifier = """
182
+ You are a helpful biomedical assistant assigned with the task of problem-solving.
183
+
184
+ You have access to two tools:
185
+ 1) run_python_repl: to write and run python code
186
+ 2) search_google: to search google for information
187
+
188
+ You can use them to solve the problem.
189
+ """
190
+ else:
191
+ tools = self.tools
192
+ if (not plan) and (not reflect):
193
+ prompt_modifier = """You are a helpful biologist and expert geneticist.
194
+ """
195
+ elif plan and (not reflect):
196
+ prompt_modifier = """You are a helpful biologist and expert geneticist.
197
+ Given the question from the user,
198
+ - First, come up with a high level plan based on your understanding of the problem and available tools and record it in the Research Plan and Status. You can revise the plan later.
199
+ - Research Plan and Status should well organized and succinctly keep track of 1) high level plan (can be revised), 2) what steps have been done and what steps are in progress, 3) short results and conclusions of each step after it has been performed. Do not perform action in research plan.
200
+ - Research Plan and Status must only include progress that has been made by previous steps. It should not include results not directly confirmed by the previous observation.
201
+ - Follow the plan and try to achieve the goal as straightforwardly as possible. Use tools as necessary.
202
+ """
203
+ elif (not plan) and reflect:
204
+ prompt_modifier = """You are a helpful biologist and expert geneticist.
205
+ In each round after the tool is used, conduct "reflection" step: reflect on the current state of the problem and the results of the last round. What does the observation mean? If there is an error, what caused the error and how to debug?
206
+ """
207
+ else:
208
+ prompt_modifier = """You are a helpful biologist and expert geneticist.
209
+ Given the question from the user,
210
+ - First, come up with a high level plan based on your understanding of the problem and available tools and record it in the Research Plan and Status. You can revise the plan later.
211
+ - Research Plan and Status should well organized and succinctly keep track of 1) high level plan (can be revised), 2) what steps have been done and what steps are in progress, 3) short results and conclusions of each step after it has been performed. Do not perform action in research plan.
212
+ - Research Plan and Status must only include progress that has been made by previous steps. It should not include results not directly confirmed by the previous observation.
213
+ - Follow the plan and try to achieve the goal as straightforwardly as possible. Use tools as necessary.
214
+ In each round after the tool is used, conduct "reflection" step: reflect on the current state of the problem and the results of the last round. What does the observation mean? If there is an error, what caused the error and how to debug?
215
+ You have access to write_python_code and run_python_repl tool to write and run your own code if tools fail, or if the given tools are not enough. Please always make sure to write code when dealing with substantial data, including finding the length of long sequences or elements at different positions.
216
+ """
217
+
218
+ if data_lake:
219
+ # Format data lake items with descriptions
220
+ data_lake_formatted = []
221
+ for item in data_lake_items:
222
+ description = data_lake_dict.get(item, f"Data lake item: {item}")
223
+ data_lake_formatted.append(f"{item}: {description}")
224
+
225
+ prompt_modifier += """
226
+ You can also access a biological data lake at the following path: {data_lake_path}. You can use the run_python_repl tool to write code to understand the data, process and utilize it for the task.
227
+ Here is the list of datasets with their descriptions:
228
+ ----
229
+ {data_lake_formatted}
230
+ ----
231
+ """.format(
232
+ data_lake_path=data_lake_path,
233
+ data_lake_formatted="\n".join(data_lake_formatted),
234
+ )
235
+
236
+ if library_access:
237
+ # Format library content with descriptions
238
+ library_formatted = []
239
+ for lib_name, lib_desc in library_content_dict.items():
240
+ library_formatted.append(f"{lib_name}: {lib_desc}")
241
+
242
+ prompt_modifier += """
243
+ You also have access to a list of software packages that can be used to perform various tasks.
244
+ You can use the run_python_repl tool to write code to access and utilize the library for the task.
245
+ Don't forget the import statement.
246
+ Here is the list of available libraries with their descriptions:
247
+ ----
248
+ {library_formatted}
249
+ ----
250
+ """.format(library_formatted="\n".join(library_formatted))
251
+
252
+ print("=" * 25 + "System Prompt" + "=" * 25)
253
+ print(prompt_modifier)
254
+ self.system_prompt = prompt_modifier
255
+ self.prompt = ChatPromptTemplate.from_messages(
256
+ [
257
+ ("system", prompt_modifier),
258
+ MessagesPlaceholder(variable_name="messages"),
259
+ ]
260
+ )
261
+
262
+ # Store the tools for later use
263
+ self.active_tools = tools
264
+
265
+ # Create a custom implementation of the ReAct agent using LangGraph
266
+ self.app = self._create_custom_react_agent(self.llm, tools, self.prompt)
267
+
268
+ def _create_custom_react_agent(self, llm, tools, prompt):
269
+ """Create a custom ReAct agent using LangGraph."""
270
+ # Create a dictionary mapping tool names to tool objects for easy lookup
271
+ tools_by_name = {tool.name: tool for tool in tools}
272
+
273
+ # Bind the tools to the language model
274
+ llm_with_tools = llm.bind_tools(tools)
275
+
276
+ # Define the node that calls the model
277
+ def call_model(state: AgentState, config: RunnableConfig = None):
278
+ """Node that calls the language model to get the next action."""
279
+ system_message = SystemMessage(content=self.system_prompt)
280
+ messages = [system_message] + state["messages"]
281
+ response = llm_with_tools.invoke(messages, config=config)
282
+ return {"messages": [response]}
283
+
284
+ # Define the node that executes tools
285
+ def tool_node(state: AgentState):
286
+ """Node that executes tools based on the LLM's decisions."""
287
+ outputs = []
288
+ for tool_call in state["messages"][-1].tool_calls:
289
+ try:
290
+ tool_result = tools_by_name[tool_call["name"]].invoke(tool_call["args"])
291
+ outputs.append(
292
+ ToolMessage(
293
+ content=json.dumps(tool_result),
294
+ name=tool_call["name"],
295
+ tool_call_id=tool_call["id"],
296
+ )
297
+ )
298
+ except Exception as e:
299
+ # Handle any errors that occur during tool execution
300
+ outputs.append(
301
+ ToolMessage(
302
+ content=json.dumps({"error": str(e)}),
303
+ name=tool_call["name"],
304
+ tool_call_id=tool_call["id"],
305
+ )
306
+ )
307
+ return {"messages": outputs}
308
+
309
+ # Define the conditional edge that determines whether to continue or not
310
+ def should_continue(state: AgentState):
311
+ """Determine if we should continue running the graph or finish."""
312
+ messages = state["messages"]
313
+ last_message = messages[-1]
314
+ # If there is no tool call, then we finish
315
+ if not hasattr(last_message, "tool_calls") or not last_message.tool_calls:
316
+ return "end"
317
+ # Otherwise if there is, we continue
318
+ else:
319
+ return "continue"
320
+
321
+ # Define a new graph
322
+ workflow = StateGraph(AgentState)
323
+
324
+ # Define the two nodes we will cycle between
325
+ workflow.add_node("agent", call_model)
326
+ workflow.add_node("tools", tool_node)
327
+
328
+ # Set the entrypoint as `agent`
329
+ workflow.set_entry_point("agent")
330
+
331
+ # Add conditional edges
332
+ workflow.add_conditional_edges(
333
+ "agent",
334
+ should_continue,
335
+ {
336
+ "continue": "tools",
337
+ "end": END,
338
+ },
339
+ )
340
+
341
+ # Add edge from tools back to agent
342
+ workflow.add_edge("tools", "agent")
343
+
344
+ # Compile the graph
345
+ return workflow.compile()
346
+
347
+ def go(self, prompt):
348
+ """Execute the agent with the given prompt.
349
+
350
+ Args:
351
+ prompt: The user's query
352
+
353
+ """
354
+ if self.use_tool_retriever:
355
+ # Gather all available tools from the registry
356
+ all_tools = self.tool_registry.tools if hasattr(self, "tool_registry") else []
357
+
358
+ # Get data lake items with descriptions
359
+ data_lake_path = self.path + "/data_lake"
360
+ data_lake_content = glob.glob(data_lake_path + "/*")
361
+ data_lake_items = [x.split("/")[-1] for x in data_lake_content]
362
+
363
+ # Create data lake descriptions for retrieval
364
+ data_lake_descriptions = []
365
+ for item in data_lake_items:
366
+ description = self.data_lake_dict.get(item, f"Data lake item: {item}")
367
+ data_lake_descriptions.append({"name": item, "description": description})
368
+
369
+ # Libraries with descriptions
370
+ library_descriptions = []
371
+ for lib_name, lib_desc in self.library_content_dict.items():
372
+ library_descriptions.append({"name": lib_name, "description": lib_desc})
373
+
374
+ # Prepare resources for retrieval
375
+ resources = {
376
+ "tools": all_tools,
377
+ "data_lake": data_lake_descriptions,
378
+ "libraries": library_descriptions,
379
+ }
380
+
381
+ # Use prompt-based retrieval with the agent's LLM
382
+ selected_resources = self.retriever.prompt_based_retrieval(prompt, resources, llm=self.llm)
383
+ print("Using prompt-based retrieval with the agent's LLM")
384
+
385
+ # If we're using prompt or embedding based retrieval, print the selected resources
386
+ print("\nSelected tools:")
387
+ for tool in selected_resources["tools"]:
388
+ if isinstance(tool, dict):
389
+ print(f"- {tool.get('name', 'Unknown')}: {tool.get('description', '')}")
390
+ else:
391
+ print(f"- {getattr(tool, 'name', str(tool))}: {getattr(tool, 'description', '')}")
392
+
393
+ print("\nSelected data lake items:")
394
+ for item in selected_resources["data_lake"]:
395
+ if isinstance(item, dict):
396
+ name = item.get("name", "Unknown")
397
+ description = self.data_lake_dict.get(name, f"Data lake item: {name}")
398
+ print(f"- {name}: {description}")
399
+ elif isinstance(item, str) and ": " in item:
400
+ # If the item already has a description, print it as is
401
+ print(f"- {item}")
402
+ else:
403
+ description = self.data_lake_dict.get(item, f"Data lake item: {item}")
404
+ print(f"- {item}: {description}")
405
+
406
+ print("\nSelected libraries:")
407
+ for lib in selected_resources["libraries"]:
408
+ if isinstance(lib, dict):
409
+ print(f"- {lib.get('name', 'Unknown')}: {lib.get('description', '')}")
410
+ else:
411
+ print(f"- {lib}")
412
+
413
+ # Convert selected tools to langchain tool objects
414
+ tool_names = [
415
+ tool["name"] if isinstance(tool, dict) else getattr(tool, "name", str(tool))
416
+ for tool in selected_resources["tools"]
417
+ ]
418
+ retrieved_list_of_tools = []
419
+
420
+ # Get the tool objects by name
421
+ for tool_name in tool_names:
422
+ # Find the tool in the original tools list
423
+ matching_tools = [t for t in self.tools if getattr(t, "name", None) == tool_name]
424
+ if matching_tools:
425
+ retrieved_list_of_tools.append(matching_tools[0])
426
+
427
+ # Add back coding tool if not already included
428
+ if len([i for i in retrieved_list_of_tools if i.name == "run_python_repl"]) == 0:
429
+ retrieved_list_of_tools = retrieved_list_of_tools + [
430
+ i for i in self.tools if i.name == "run_python_repl"
431
+ ]
432
+
433
+ print("Retrieved tools: \n" + "\n".join([l.name + ": " + l.description for l in retrieved_list_of_tools]))
434
+ # Recreate the custom agent with the retrieved tools
435
+ self.app = self._create_custom_react_agent(self.llm, retrieved_list_of_tools, self.prompt)
436
+
437
+ # Default behavior (no tool retriever or retrieval_method is 'none')
438
+ config = {"recursion_limit": 50}
439
+ inputs = {"messages": [("user", prompt)]}
440
+ self.log = []
441
+ for s in self.app.stream(inputs, stream_mode="values", config=config):
442
+ message = s["messages"][-1]
443
+ out = pretty_print(message)
444
+ self.log.append(out)
445
+ return self.log, s["messages"][-1].content
446
+
447
+ def result_formatting(self, output_class, task_intention):
448
+ self.format_check_prompt = ChatPromptTemplate.from_messages(
449
+ [
450
+ (
451
+ "system",
452
+ (
453
+ "You are evaluateGPT, tasked with extract and parse the task output based on the history of an agent. "
454
+ "Review the entire history of messages provided. "
455
+ "Here is the task output requirement: \n"
456
+ f"'{task_intention.replace('{', '{{').replace('}', '}}')}'.\n"
457
+ ),
458
+ ),
459
+ ("placeholder", "{messages}"),
460
+ ]
461
+ )
462
+
463
+ checker_llm = self.format_check_prompt | self.llm.with_structured_output(output_class)
464
+ result = checker_llm.invoke({"messages": [("user", str(self.log))]}).dict()
465
+ return result
BioScientist/agent_system/engines/v1_executor_backup/biorxiv_scripts/extract_biorxiv_tasks.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Script to extract common tasks, databases, and software from bioRxiv papers
3
+ using the PaperTaskExtractor and existing metadata CSV.
4
+ """
5
+
6
+ import argparse
7
+ import io
8
+ import json
9
+ import os
10
+ import random
11
+ import sys
12
+ import time
13
+ from typing import Any
14
+
15
+ import pandas as pd
16
+ import PyPDF2
17
+ import requests
18
+ from tqdm import tqdm
19
+
20
+ # Add the parent directory to the path so we can import the bioagentos package
21
+ sys.path.append("../../")
22
+ from biomni.agent.env_collection import PaperTaskExtractor
23
+
24
+
25
+ def parse_arguments():
26
+ """Parse command line arguments."""
27
+ parser = argparse.ArgumentParser(description="Extract tasks from bioRxiv papers in a specific subject area.")
28
+ parser.add_argument(
29
+ "--subject",
30
+ type=str,
31
+ required=True,
32
+ help='Subject area to search for papers (e.g., "neuroscience", "bioinformatics")',
33
+ )
34
+ parser.add_argument(
35
+ "--limit",
36
+ type=int,
37
+ default=10,
38
+ help="Maximum number of papers to process (default: 10)",
39
+ )
40
+ parser.add_argument(
41
+ "--metadata-path",
42
+ type=str,
43
+ default="/dfs/user/kexinh/BioAgentOS/data/biorxiv_metadata.csv",
44
+ help="Path to bioRxiv metadata CSV file (default: data/biorxiv_metadata.csv)",
45
+ )
46
+ parser.add_argument(
47
+ "--output-dir",
48
+ type=str,
49
+ default=None,
50
+ help="Directory to save results (default: ./biorxiv_results_{subject}_{limit})",
51
+ )
52
+ parser.add_argument(
53
+ "--model",
54
+ type=str,
55
+ default="claude-3-haiku-20240307",
56
+ help="LLM model to use for extraction (default: claude-3-haiku-20240307)",
57
+ )
58
+ parser.add_argument(
59
+ "--chunk-size",
60
+ type=int,
61
+ default=4000,
62
+ help="Chunk size for text processing (default: 4000)",
63
+ )
64
+ parser.add_argument(
65
+ "--chunk-overlap",
66
+ type=int,
67
+ default=400,
68
+ help="Chunk overlap for text processing (default: 400)",
69
+ )
70
+ parser.add_argument(
71
+ "--max-paper-length",
72
+ type=int,
73
+ default=200000,
74
+ help="Maximum paper length in characters (default: 200000)",
75
+ )
76
+ parser.add_argument("--save-pdfs", action="store_true", help="Save downloaded PDFs (default: False)")
77
+ parser.add_argument(
78
+ "--random-sample",
79
+ action="store_true",
80
+ help="Randomly sample papers instead of taking the first N (default: False)",
81
+ )
82
+ return parser.parse_args()
83
+
84
+
85
+ def load_papers_from_csv(metadata_path: str, subject: str, limit: int, random_sample: bool) -> pd.DataFrame:
86
+ """Load papers from bioRxiv metadata CSV file.
87
+
88
+ Args:
89
+ metadata_path: Path to the metadata CSV file
90
+ subject: Subject area to filter by
91
+ limit: Maximum number of papers to return
92
+ random_sample: Whether to randomly sample papers
93
+
94
+ Returns:
95
+ DataFrame of filtered papers
96
+
97
+ """
98
+ try:
99
+ # Load the metadata CSV
100
+ df_biorxiv = pd.read_csv(metadata_path)
101
+
102
+ # Filter published papers in the specified subject
103
+ if subject.lower() == "all":
104
+ filtered_df = df_biorxiv[df_biorxiv.published != "NA"]
105
+ else:
106
+ filtered_df = df_biorxiv[
107
+ (df_biorxiv.published != "NA") & (df_biorxiv.category.str.lower() == subject.lower())
108
+ ]
109
+
110
+ # Sample papers
111
+ if len(filtered_df) > limit:
112
+ filtered_df = filtered_df.sample(limit, random_state=42) if random_sample else filtered_df.head(limit)
113
+
114
+ print(f"Loaded {len(filtered_df)} papers in subject: {subject}")
115
+ return filtered_df
116
+
117
+ except Exception as e:
118
+ print(f"Error loading papers from CSV: {e}")
119
+ return pd.DataFrame()
120
+
121
+
122
+ def download_pdf(paper_doi: str, save_path: str | None = None) -> str | None:
123
+ """Download PDF for a given paper DOI.
124
+
125
+ Args:
126
+ paper_doi: DOI of the paper
127
+ save_path: Path to save the PDF (if None, won't save to disk)
128
+
129
+ Returns:
130
+ PDF text content or None if download failed
131
+
132
+ """
133
+ # Construct PDF URL from DOI
134
+ pdf_url = f"https://www.biorxiv.org/content/{paper_doi}v1.full.pdf"
135
+
136
+ try:
137
+ # Add random delay to avoid rate limiting
138
+ time.sleep(random.uniform(1, 3))
139
+
140
+ response = requests.get(pdf_url, stream=True)
141
+ response.raise_for_status()
142
+
143
+ # Save PDF if requested
144
+ if save_path:
145
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
146
+ with open(save_path, "wb") as f:
147
+ for chunk in response.iter_content(chunk_size=8192):
148
+ f.write(chunk)
149
+
150
+ # Extract text from PDF
151
+ pdf_text = extract_text_from_pdf(io.BytesIO(response.content))
152
+ return pdf_text
153
+
154
+ except requests.exceptions.RequestException as e:
155
+ print(f"Error downloading PDF for {paper_doi}: {e}")
156
+ return None
157
+
158
+
159
+ def extract_text_from_pdf(pdf_file) -> str:
160
+ """Extract text content from a PDF file.
161
+
162
+ Args:
163
+ pdf_file: File-like object containing PDF data
164
+
165
+ Returns:
166
+ Extracted text content
167
+
168
+ """
169
+ try:
170
+ pdf_reader = PyPDF2.PdfReader(pdf_file)
171
+ text = ""
172
+ for page_num in range(len(pdf_reader.pages)):
173
+ page = pdf_reader.pages[page_num]
174
+ text += page.extract_text() + "\n\n"
175
+ return text
176
+ except Exception as e:
177
+ print(f"Error extracting text from PDF: {e}")
178
+ return ""
179
+
180
+
181
+ def truncate_text(text: str, max_length: int) -> str:
182
+ """Truncate text to a maximum length while preserving complete sentences.
183
+
184
+ Args:
185
+ text: The text to truncate
186
+ max_length: Maximum length in characters
187
+
188
+ Returns:
189
+ Truncated text
190
+
191
+ """
192
+ if len(text) <= max_length:
193
+ return text
194
+
195
+ # Find the last sentence boundary before max_length
196
+ truncated = text[:max_length]
197
+ last_period = truncated.rfind(".")
198
+ last_question = truncated.rfind("?")
199
+ last_exclamation = truncated.rfind("!")
200
+
201
+ # Find the last sentence boundary
202
+ last_boundary = max(last_period, last_question, last_exclamation)
203
+
204
+ if last_boundary > 0:
205
+ return text[: last_boundary + 1]
206
+ else:
207
+ # If no sentence boundary found, just truncate at max_length
208
+ return truncated
209
+
210
+
211
+ def process_papers(papers_df: pd.DataFrame, args) -> list[dict[str, Any]]:
212
+ """Process papers using PaperTaskExtractor.
213
+
214
+ Args:
215
+ papers_df: DataFrame of paper metadata
216
+ args: Command line arguments
217
+
218
+ Returns:
219
+ List of papers with extracted tasks, databases, and software
220
+
221
+ """
222
+ # Initialize the task extractor
223
+ extractor = PaperTaskExtractor(llm=args.model, chunk_size=args.chunk_size, chunk_overlap=args.chunk_overlap)
224
+
225
+ results = []
226
+
227
+ for _, paper in tqdm(papers_df.iterrows(), total=len(papers_df), desc="Processing papers"):
228
+ paper_doi = paper.get("doi")
229
+ if not paper_doi:
230
+ continue
231
+
232
+ print(f"\nProcessing paper: {paper.get('title')} (DOI: {paper_doi})")
233
+
234
+ # Create paths
235
+ pdf_path = None
236
+ if args.save_pdfs:
237
+ pdf_path = os.path.join(args.output_dir, "pdfs", f"{paper_doi.replace('/', '_')}.pdf")
238
+
239
+ result_path = os.path.join(args.output_dir, "results", f"{paper_doi.replace('/', '_')}.json")
240
+
241
+ # Skip if already processed
242
+ if os.path.exists(result_path):
243
+ print(f"Paper already processed, loading from {result_path}")
244
+ with open(result_path) as f:
245
+ paper_result = json.load(f)
246
+ results.append(paper_result)
247
+ continue
248
+
249
+ # Download and process PDF
250
+ pdf_text = download_pdf(paper_doi, pdf_path)
251
+ if not pdf_text:
252
+ print(f"Failed to download or extract text from {paper_doi}")
253
+ continue
254
+
255
+ # Truncate text if it exceeds max length
256
+ if len(pdf_text) > args.max_paper_length:
257
+ original_length = len(pdf_text)
258
+ pdf_text = truncate_text(pdf_text, args.max_paper_length)
259
+ print(f"Truncated paper from {original_length} to {len(pdf_text)} characters")
260
+
261
+ # Extract tasks, databases, and software
262
+ try:
263
+ _, extraction_results = extractor.go(pdf_text)
264
+
265
+ # Add paper metadata to results
266
+ paper_result = {
267
+ "metadata": {
268
+ "doi": paper.get("doi"),
269
+ "title": paper.get("title"),
270
+ "authors": paper.get("authors", ""),
271
+ "abstract": paper.get("abstract", ""),
272
+ "date": paper.get("date", ""),
273
+ "category": paper.get("category", ""),
274
+ "text_length": len(pdf_text),
275
+ },
276
+ "extraction": extraction_results,
277
+ }
278
+
279
+ # Save results
280
+ os.makedirs(os.path.dirname(result_path), exist_ok=True)
281
+ with open(result_path, "w") as f:
282
+ json.dump(paper_result, f, indent=2)
283
+
284
+ results.append(paper_result)
285
+
286
+ except Exception as e:
287
+ print(f"Error processing paper {paper_doi}: {e}")
288
+
289
+ return results
290
+
291
+
292
+ def generate_summary(results: list[dict[str, Any]], output_dir: str):
293
+ """Generate summary of extracted tasks, databases, and software.
294
+
295
+ Args:
296
+ results: List of papers with extraction results
297
+ output_dir: Directory to save summary
298
+
299
+ """
300
+ # Collect all tasks, databases, and software
301
+ all_tasks = []
302
+ all_databases = []
303
+ all_software = []
304
+
305
+ for paper in results:
306
+ extraction = paper.get("extraction", {})
307
+
308
+ # Add paper metadata to each item
309
+ paper_meta = paper.get("metadata", {})
310
+ paper_id = f"{paper_meta.get('title')} ({paper_meta.get('doi')})"
311
+
312
+ # Process tasks
313
+ for task in extraction.get("tasks", []):
314
+ task["paper"] = paper_id
315
+ all_tasks.append(task)
316
+
317
+ # Process databases
318
+ for db in extraction.get("databases", []):
319
+ db["paper"] = paper_id
320
+ all_databases.append(db)
321
+
322
+ # Process software
323
+ for sw in extraction.get("software", []):
324
+ sw["paper"] = paper_id
325
+ all_software.append(sw)
326
+
327
+ # Create summary dataframes
328
+ if all_tasks:
329
+ tasks_df = pd.DataFrame(all_tasks)
330
+ tasks_df.to_csv(os.path.join(output_dir, "tasks_summary.csv"), index=False)
331
+
332
+ if all_databases:
333
+ db_df = pd.DataFrame(all_databases)
334
+ db_df.to_csv(os.path.join(output_dir, "databases_summary.csv"), index=False)
335
+
336
+ if all_software:
337
+ sw_df = pd.DataFrame(all_software)
338
+ sw_df.to_csv(os.path.join(output_dir, "software_summary.csv"), index=False)
339
+
340
+ # Generate frequency counts
341
+ task_counts = {}
342
+ for task in all_tasks:
343
+ task_name = task.get("task_name")
344
+ if task_name:
345
+ task_counts[task_name] = task_counts.get(task_name, 0) + 1
346
+
347
+ db_counts = {}
348
+ for db in all_databases:
349
+ db_name = db.get("name")
350
+ if db_name:
351
+ db_counts[db_name] = db_counts.get(db_name, 0) + 1
352
+
353
+ sw_counts = {}
354
+ for sw in all_software:
355
+ sw_name = sw.get("name")
356
+ if sw_name:
357
+ sw_counts[sw_name] = sw_counts.get(sw_name, 0) + 1
358
+
359
+ # Save frequency counts
360
+ with open(os.path.join(output_dir, "frequency_summary.json"), "w") as f:
361
+ json.dump(
362
+ {"tasks": task_counts, "databases": db_counts, "software": sw_counts},
363
+ f,
364
+ indent=2,
365
+ )
366
+
367
+ print(f"Summary files saved to {output_dir}")
368
+
369
+
370
+ def main():
371
+ """Main function to run the script."""
372
+ args = parse_arguments()
373
+
374
+ # Set default output directory if not specified
375
+ if args.output_dir is None:
376
+ # Clean subject name for directory name (replace spaces with underscores, lowercase)
377
+ clean_subject = args.subject.lower().replace(" ", "_").replace("/", "_")
378
+ args.output_dir = f"./biorxiv_results_{clean_subject}_{args.limit}"
379
+
380
+ # Create output directories
381
+ os.makedirs(args.output_dir, exist_ok=True)
382
+ os.makedirs(os.path.join(args.output_dir, "results"), exist_ok=True)
383
+ if args.save_pdfs:
384
+ os.makedirs(os.path.join(args.output_dir, "pdfs"), exist_ok=True)
385
+
386
+ # Load papers from CSV
387
+ print(f"Loading papers from {args.metadata_path} in subject area: {args.subject}")
388
+ papers_df = load_papers_from_csv(args.metadata_path, args.subject, args.limit, args.random_sample)
389
+
390
+ if len(papers_df) == 0:
391
+ print(f"No papers found for subject: {args.subject}")
392
+ return
393
+
394
+ # Process papers
395
+ results = process_papers(papers_df, args)
396
+
397
+ # Generate summary
398
+ generate_summary(results, args.output_dir)
399
+
400
+ print("Done!")
401
+
402
+
403
+ if __name__ == "__main__":
404
+ main()
BioScientist/agent_system/engines/v1_executor_backup/biorxiv_scripts/generate_function.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Command-line tool to generate Python functions from task descriptions using the function_generator agent."""
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+
8
+ from biomni.agent.function_generator import FunctionGenerator
9
+ from tqdm import tqdm
10
+
11
+
12
+ def main():
13
+ """Main function for the command-line tool."""
14
+ parser = argparse.ArgumentParser(description="Generate Python functions given task descriptions")
15
+ parser.add_argument(
16
+ "--task",
17
+ "-t",
18
+ type=str,
19
+ help="JSON file containing a list of task descriptions",
20
+ )
21
+ parser.add_argument(
22
+ "--output-dir",
23
+ "-o",
24
+ type=str,
25
+ default="generated_functions",
26
+ help="Directory to save the generated functions (default: generated_functions)",
27
+ )
28
+ parser.add_argument(
29
+ "--model",
30
+ "-m",
31
+ type=str,
32
+ default="claude-3-7-sonnet-latest",
33
+ help="LLM model to use (default: claude-3-7-sonnet-latest)",
34
+ )
35
+ parser.add_argument(
36
+ "--temperature",
37
+ type=float,
38
+ default=0.7,
39
+ help="Temperature setting for the LLM (default: 0.7)",
40
+ )
41
+
42
+ args = parser.parse_args()
43
+
44
+ with open(args.task) as f_tasks:
45
+ task_list = json.load(f_tasks)
46
+ task_descriptions = list(task_list["tasks"])
47
+
48
+ # Create the output directory if it doesn't exist
49
+ os.makedirs(args.output_dir, exist_ok=True)
50
+
51
+ # Initialize the function generator agent
52
+ function_generator = FunctionGenerator(llm=args.model, temperature=args.temperature)
53
+
54
+ if not task_list:
55
+ print("No tasks found.")
56
+ else:
57
+ # tqdm shows a progress bar, file names as description
58
+ for _i, desc in enumerate(tqdm(task_descriptions, desc="Generating Python scripts given task descriptions"), 1):
59
+ generated_script_name, generated_codes = function_generator.go(desc)
60
+
61
+ # Save results
62
+ result_path = os.path.join(args.output_dir, generated_script_name)
63
+
64
+ os.makedirs(os.path.dirname(result_path), exist_ok=True)
65
+ with open(result_path, "w") as f:
66
+ f.write(generated_codes)
67
+
68
+ print("DONE")
69
+
70
+
71
+ if __name__ == "__main__":
72
+ main()
BioScientist/agent_system/engines/v1_executor_backup/biorxiv_scripts/process_all_subjects.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Script to process all bioRxiv subjects and extract computational tasks from the top 100 papers in each."""
3
+
4
+ import argparse
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ import time
9
+
10
+ import pandas as pd
11
+ from tqdm import tqdm
12
+
13
+ # Add the parent directory to the path so we can import the bioagentos package
14
+ sys.path.append("/dfs/user/kexinh/BioAgentOS/")
15
+
16
+ # List of all bioRxiv subjects
17
+ BIORXIV_SUBJECTS = [
18
+ "evolutionary biology",
19
+ "ecology",
20
+ "neuroscience",
21
+ "developmental biology",
22
+ "plant biology",
23
+ "microbiology",
24
+ "cancer biology",
25
+ "immunology",
26
+ "cell biology",
27
+ "biochemistry",
28
+ "genetics",
29
+ "bioinformatics",
30
+ "animal behavior and cognition",
31
+ "biophysics",
32
+ "genomics",
33
+ "systems biology",
34
+ "bioengineering",
35
+ "molecular biology",
36
+ "physiology",
37
+ "zoology",
38
+ "scientific communication and education",
39
+ "pathology",
40
+ "synthetic biology",
41
+ "paleontology",
42
+ "pharmacology and toxicology",
43
+ ]
44
+
45
+
46
+ def parse_arguments():
47
+ """Parse command line arguments."""
48
+ parser = argparse.ArgumentParser(description="Process all bioRxiv subjects and extract tasks from papers.")
49
+ parser.add_argument(
50
+ "--papers-per-subject",
51
+ type=int,
52
+ default=100,
53
+ help="Number of papers to process per subject (default: 100)",
54
+ )
55
+ parser.add_argument(
56
+ "--metadata-path",
57
+ type=str,
58
+ default="/dfs/user/kexinh/BioAgentOS/data/biorxiv_metadata.csv",
59
+ help="Path to bioRxiv metadata CSV file (default: data/biorxiv_metadata.csv)",
60
+ )
61
+ parser.add_argument(
62
+ "--output-dir",
63
+ type=str,
64
+ default="./biorxiv_all_subjects",
65
+ help="Base directory to save results (default: ./biorxiv_all_subjects)",
66
+ )
67
+ parser.add_argument(
68
+ "--model",
69
+ type=str,
70
+ default="claude-3-haiku-20240307",
71
+ help="LLM model to use for extraction (default: claude-3-haiku-20240307)",
72
+ )
73
+ parser.add_argument(
74
+ "--max-paper-length",
75
+ type=int,
76
+ default=200000,
77
+ help="Maximum paper length in characters (default: 200000)",
78
+ )
79
+ parser.add_argument(
80
+ "--chunk-size",
81
+ type=int,
82
+ default=10000,
83
+ help="Chunk size for text processing (default: 10000)",
84
+ )
85
+ parser.add_argument(
86
+ "--chunk-overlap",
87
+ type=int,
88
+ default=400,
89
+ help="Chunk overlap for text processing (default: 400)",
90
+ )
91
+ parser.add_argument("--save-pdfs", action="store_true", help="Save downloaded PDFs (default: False)")
92
+ parser.add_argument(
93
+ "--random-sample",
94
+ action="store_true",
95
+ help="Randomly sample papers instead of taking the first N (default: False)",
96
+ )
97
+ parser.add_argument(
98
+ "--subjects",
99
+ type=str,
100
+ nargs="+",
101
+ help="Specific subjects to process (default: all subjects)",
102
+ )
103
+ parser.add_argument(
104
+ "--delay",
105
+ type=int,
106
+ default=60,
107
+ help="Delay in seconds between processing subjects (default: 60)",
108
+ )
109
+ parser.add_argument(
110
+ "--summary-only",
111
+ action="store_true",
112
+ help="Only generate the combined summary (default: False)",
113
+ )
114
+ return parser.parse_args()
115
+
116
+
117
+ def check_subject_availability(metadata_path, subjects):
118
+ """Check which subjects have papers available in the metadata.
119
+
120
+ Args:
121
+ metadata_path: Path to the metadata CSV file
122
+ subjects: List of subjects to check
123
+
124
+ Returns:
125
+ List of subjects with available papers
126
+
127
+ """
128
+ try:
129
+ df_biorxiv = pd.read_csv(metadata_path)
130
+ available_subjects = []
131
+
132
+ for subject in subjects:
133
+ count = len(
134
+ df_biorxiv[(df_biorxiv.published != "NA") & (df_biorxiv.category.str.lower() == subject.lower())]
135
+ )
136
+ if count > 0:
137
+ available_subjects.append((subject, count))
138
+ print(f"Subject '{subject}' has {count} papers available")
139
+ else:
140
+ print(f"Subject '{subject}' has no papers available")
141
+
142
+ return available_subjects
143
+ except Exception as e:
144
+ print(f"Error checking subject availability: {e}")
145
+ return []
146
+
147
+
148
+ def process_subject(subject, args):
149
+ """Process a single subject by calling the extract_biorxiv_tasks.py script.
150
+
151
+ Args:
152
+ subject: Subject to process
153
+ args: Command line arguments
154
+
155
+ """
156
+ # Clean subject name for command line
157
+ subject.replace(" ", "\\ ")
158
+
159
+ # Build command
160
+ cmd = [
161
+ "python",
162
+ "BioAgentOS/bioagentos/scripts/extract_biorxiv_tasks.py",
163
+ "--subject",
164
+ f'"{subject}"',
165
+ "--limit",
166
+ str(args.papers_per_subject),
167
+ "--metadata-path",
168
+ args.metadata_path,
169
+ "--model",
170
+ args.model,
171
+ "--max-paper-length",
172
+ str(args.max_paper_length),
173
+ "--chunk-size",
174
+ str(args.chunk_size),
175
+ "--chunk-overlap",
176
+ str(args.chunk_overlap),
177
+ ]
178
+
179
+ # Add optional arguments
180
+ if args.save_pdfs:
181
+ cmd.append("--save-pdfs")
182
+ if args.random_sample:
183
+ cmd.append("--random-sample")
184
+
185
+ # Convert command list to string
186
+ cmd_str = " ".join(cmd)
187
+
188
+ print(f"\n{'=' * 80}\nProcessing subject: {subject}\n{'=' * 80}")
189
+ print(f"Running command: {cmd_str}")
190
+
191
+ # Execute command
192
+ try:
193
+ subprocess.run(cmd_str, shell=True, check=True)
194
+ print(f"Successfully processed subject: {subject}")
195
+ except subprocess.CalledProcessError as e:
196
+ print(f"Error processing subject '{subject}': {e}")
197
+
198
+
199
+ def combine_summaries(base_dir, subjects, papers_per_subject):
200
+ """Combine frequency summaries from all subjects into a single summary.
201
+
202
+ Args:
203
+ base_dir: Base directory containing subject results
204
+ subjects: List of subjects that were processed
205
+ papers_per_subject: Number of papers processed per subject
206
+
207
+ """
208
+ all_tasks = {}
209
+ all_databases = {}
210
+ all_software = {}
211
+
212
+ for subject, _ in subjects:
213
+ # Clean subject name for directory name
214
+ clean_subject = subject.lower().replace(" ", "_").replace("/", "_")
215
+ subject_dir = f"biorxiv_results_{clean_subject}_{papers_per_subject}"
216
+ summary_path = os.path.join(subject_dir, "frequency_summary.json")
217
+
218
+ try:
219
+ if os.path.exists(summary_path):
220
+ with open(summary_path) as f:
221
+ summary = json.load(f)
222
+
223
+ # Merge tasks
224
+ for task, count in summary.get("tasks", {}).items():
225
+ if task in all_tasks:
226
+ all_tasks[task] += count
227
+ else:
228
+ all_tasks[task] = count
229
+
230
+ # Merge databases
231
+ for db, count in summary.get("databases", {}).items():
232
+ if db in all_databases:
233
+ all_databases[db] += count
234
+ else:
235
+ all_databases[db] = count
236
+
237
+ # Merge software
238
+ for sw, count in summary.get("software", {}).items():
239
+ if sw in all_software:
240
+ all_software[sw] += count
241
+ else:
242
+ all_software[sw] = count
243
+ else:
244
+ print(f"Warning: Summary file not found for subject '{subject}'")
245
+ except Exception as e:
246
+ print(f"Error processing summary for subject '{subject}': {e}")
247
+
248
+ # Sort by frequency (descending)
249
+ all_tasks = dict(sorted(all_tasks.items(), key=lambda item: item[1], reverse=True))
250
+ all_databases = dict(sorted(all_databases.items(), key=lambda item: item[1], reverse=True))
251
+ all_software = dict(sorted(all_software.items(), key=lambda item: item[1], reverse=True))
252
+
253
+ # Create combined summary
254
+ combined_summary = {
255
+ "tasks": all_tasks,
256
+ "databases": all_databases,
257
+ "software": all_software,
258
+ }
259
+
260
+ # Save combined summary
261
+ combined_path = os.path.join(base_dir, "combined_summary.json")
262
+ os.makedirs(base_dir, exist_ok=True)
263
+
264
+ with open(combined_path, "w") as f:
265
+ json.dump(combined_summary, f, indent=2)
266
+
267
+ print(f"Combined summary saved to {combined_path}")
268
+
269
+ # Create CSV files for each category
270
+ tasks_df = pd.DataFrame(list(all_tasks.items()), columns=["Task", "Frequency"])
271
+ tasks_df.to_csv(os.path.join(base_dir, "tasks_frequency.csv"), index=False)
272
+
273
+ db_df = pd.DataFrame(list(all_databases.items()), columns=["Database", "Frequency"])
274
+ db_df.to_csv(os.path.join(base_dir, "databases_frequency.csv"), index=False)
275
+
276
+ sw_df = pd.DataFrame(list(all_software.items()), columns=["Software", "Frequency"])
277
+ sw_df.to_csv(os.path.join(base_dir, "software_frequency.csv"), index=False)
278
+
279
+ print(f"CSV summaries saved to {base_dir}")
280
+
281
+
282
+ def main():
283
+ """Main function to run the script."""
284
+ args = parse_arguments()
285
+
286
+ # Determine which subjects to process
287
+ subjects_to_process = args.subjects if args.subjects else BIORXIV_SUBJECTS
288
+
289
+ # Check which subjects have papers available
290
+ available_subjects = check_subject_availability(args.metadata_path, subjects_to_process)
291
+
292
+ if not available_subjects:
293
+ print("No subjects with available papers found. Exiting.")
294
+ return
295
+
296
+ if not args.summary_only:
297
+ # Process each subject
298
+ for subject, _count in tqdm(available_subjects, desc="Processing subjects"):
299
+ process_subject(subject, args)
300
+
301
+ # Add delay between subjects to avoid rate limiting
302
+ if args.delay > 0:
303
+ print(f"Waiting {args.delay} seconds before processing the next subject...")
304
+ time.sleep(args.delay)
305
+
306
+ # Combine summaries from all subjects
307
+ combine_summaries(args.output_dir, available_subjects, args.papers_per_subject)
308
+
309
+ print("All subjects processed successfully!")
310
+
311
+
312
+ if __name__ == "__main__":
313
+ import json # Import here to avoid circular import with the main script
314
+
315
+ main()
BioScientist/agent_system/engines/v1_executor_backup/config.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Biomni Configuration Management
3
+
4
+ Simple configuration class for centralizing common settings.
5
+ Maintains full backward compatibility with existing code.
6
+ """
7
+
8
+ import os
9
+ from dataclasses import dataclass
10
+
11
+
12
+ @dataclass
13
+ class BiomniConfig:
14
+ """Central configuration for Biomni agent.
15
+
16
+ All settings are optional and have sensible defaults.
17
+ API keys are still read from environment variables to maintain
18
+ compatibility with existing .env file structure.
19
+
20
+ Usage:
21
+ # Create config with defaults
22
+ config = BiomniConfig()
23
+
24
+ # Override specific settings
25
+ config = BiomniConfig(llm="gpt-4", timeout_seconds=1200)
26
+
27
+ # Modify after creation
28
+ config.path = "./custom_data"
29
+ """
30
+
31
+ # Data and execution settings
32
+ path: str = "./data"
33
+ timeout_seconds: int = 600
34
+
35
+ # LLM settings (API keys still from environment)
36
+ llm: str = "claude-sonnet-4-6"
37
+ temperature: float = 0.7
38
+
39
+ # Tool settings
40
+ use_tool_retriever: bool = True
41
+
42
+ # Data licensing settings
43
+ commercial_mode: bool = False # If True, excludes non-commercial datasets
44
+
45
+ # Custom model settings (for custom LLM serving)
46
+ base_url: str | None = None
47
+ api_key: str | None = None # Only for custom models, not provider API keys
48
+
49
+ # LLM source (auto-detected if None)
50
+ source: str | None = None
51
+
52
+ # Third-party integrations
53
+ protocols_io_access_token: str | None = None
54
+
55
+ def __post_init__(self):
56
+ """Load any environment variable overrides if they exist."""
57
+ # Check for environment variable overrides (optional)
58
+ # Support both old and new names for backwards compatibility
59
+ if os.getenv("BIOMNI_PATH") or os.getenv("BIOMNI_DATA_PATH"):
60
+ self.path = os.getenv("BIOMNI_PATH") or os.getenv("BIOMNI_DATA_PATH")
61
+ if os.getenv("BIOMNI_TIMEOUT_SECONDS"):
62
+ self.timeout_seconds = int(os.getenv("BIOMNI_TIMEOUT_SECONDS"))
63
+ if os.getenv("BIOMNI_LLM") or os.getenv("BIOMNI_LLM_MODEL"):
64
+ self.llm = os.getenv("BIOMNI_LLM") or os.getenv("BIOMNI_LLM_MODEL")
65
+ if os.getenv("BIOMNI_USE_TOOL_RETRIEVER"):
66
+ self.use_tool_retriever = os.getenv("BIOMNI_USE_TOOL_RETRIEVER").lower() == "true"
67
+ if os.getenv("BIOMNI_COMMERCIAL_MODE"):
68
+ self.commercial_mode = os.getenv("BIOMNI_COMMERCIAL_MODE").lower() == "true"
69
+ if os.getenv("BIOMNI_TEMPERATURE"):
70
+ self.temperature = float(os.getenv("BIOMNI_TEMPERATURE"))
71
+ if os.getenv("BIOMNI_CUSTOM_BASE_URL"):
72
+ self.base_url = os.getenv("BIOMNI_CUSTOM_BASE_URL")
73
+ if os.getenv("BIOMNI_CUSTOM_API_KEY"):
74
+ self.api_key = os.getenv("BIOMNI_CUSTOM_API_KEY")
75
+ if os.getenv("BIOMNI_SOURCE"):
76
+ self.source = os.getenv("BIOMNI_SOURCE")
77
+
78
+ # Protocols.io access token (prefer specific env vars)
79
+ env_token = os.getenv("PROTOCOLS_IO_ACCESS_TOKEN") or os.getenv("BIOMNI_PROTOCOLS_IO_ACCESS_TOKEN")
80
+ if env_token:
81
+ self.protocols_io_access_token = env_token
82
+
83
+ def to_dict(self) -> dict:
84
+ """Convert config to dictionary for easy access."""
85
+ return {
86
+ "path": self.path,
87
+ "timeout_seconds": self.timeout_seconds,
88
+ "llm": self.llm,
89
+ "temperature": self.temperature,
90
+ "use_tool_retriever": self.use_tool_retriever,
91
+ "commercial_mode": self.commercial_mode,
92
+ "base_url": self.base_url,
93
+ "api_key": self.api_key,
94
+ "source": self.source,
95
+ }
96
+
97
+
98
+ # Global default config instance (optional, for convenience)
99
+ default_config = BiomniConfig()
BioScientist/agent_system/engines/v1_executor_backup/env_desc.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data lake dictionary with detailed descriptions
2
+ data_lake_dict = {
3
+ "affinity_capture-ms.parquet": "Protein-protein interactions detected via affinity capture and mass spectrometry.",
4
+ "affinity_capture-rna.parquet": "Protein-RNA interactions detected by affinity capture.",
5
+ "BindingDB_All_202409.tsv": "Measured binding affinities between proteins and small molecules for drug discovery.",
6
+ "broad_repurposing_hub_molecule_with_smiles.parquet": "Molecules from Broad Institute's Drug Repurposing Hub with SMILES annotations.",
7
+ "broad_repurposing_hub_phase_moa_target_info.parquet": "Drug phases, mechanisms of action, and target information from Broad Institute.",
8
+ "co-fractionation.parquet": "Protein-protein interactions from co-fractionation experiments.",
9
+ "czi_census_datasets_v4.parquet": "Datasets from the Chan Zuckerberg Initiative's Cell Census.",
10
+ "DepMap_CRISPRGeneDependency.csv": "Gene dependency probability estimates for cancer cell lines, including all DepMap models.",
11
+ "DepMap_CRISPRGeneEffect.csv": "Genome-wide CRISPR gene effect estimates for cancer cell lines, including all DepMap models.",
12
+ "DepMap_Model.csv": "Metadata describing all cancer models/cell lines which are referenced by a dataset contained within the DepMap portal.",
13
+ "DepMap_OmicsExpressionProteinCodingGenesTPMLogp1.csv": "Gene expression in TPMs for cancer cell lines, including all DepMap models.",
14
+ "ddinter_alimentary_tract_metabolism.csv": "Drug-drug interactions for alimentary tract and metabolism drugs from DDInter 2.0 database.",
15
+ "ddinter_antineoplastic.csv": "Drug-drug interactions for antineoplastic and immunomodulating agents from DDInter 2.0 database.",
16
+ "ddinter_antiparasitic.csv": "Drug-drug interactions for antiparasitic products from DDInter 2.0 database.",
17
+ "ddinter_blood_organs.csv": "Drug-drug interactions for blood and blood forming organs drugs from DDInter 2.0 database.",
18
+ "ddinter_dermatological.csv": "Drug-drug interactions for dermatological drugs from DDInter 2.0 database.",
19
+ "ddinter_hormonal.csv": "Drug-drug interactions for systemic hormonal preparations from DDInter 2.0 database.",
20
+ "ddinter_respiratory.csv": "Drug-drug interactions for respiratory system drugs from DDInter 2.0 database.",
21
+ "ddinter_various.csv": "Drug-drug interactions for various drugs from DDInter 2.0 database.",
22
+ "DisGeNET.parquet": "Gene-disease associations from multiple sources.",
23
+ "dosage_growth_defect.parquet": "Gene dosage changes affecting growth.",
24
+ "enamine_cloud_library_smiles.pkl": "Compounds from Enamine REAL library with SMILES annotations.",
25
+ "evebio_assay_table.csv": "Assay metadata with one row per assay from EveBio pharmome mapping.",
26
+ "evebio_bundle_table.csv": "Target subfamily bundles used for screening-to-profiling progression.",
27
+ "evebio_compound_table.csv": "Compound metadata with common identifiers from EveBio screening.",
28
+ "evebio_control_table.csv": "Control datapoints for all screening and profiling plates.",
29
+ "evebio_detailed_result_table.csv": "Expanded results on evebio_summary_result_table with curve fit parameters and phase categories.",
30
+ "evebio_observed_points_table.csv": "Raw observed datapoints from all screening and profiling experiments.",
31
+ "evebio_summary_result_table.csv": "Succinct summary of results for each assay-compound combination.",
32
+ "evebio_target_table.csv": "Target metadata with common identifiers from EveBio screening.",
33
+ "genebass_missense_LC_filtered.pkl": "Filtered missense variants from GeneBass.",
34
+ "genebass_pLoF_filtered.pkl": "Predicted loss-of-function variants from GeneBass.",
35
+ "genebass_synonymous_filtered.pkl": "Filtered synonymous variants from GeneBass.",
36
+ "gene_info.parquet": "Comprehensive gene information.",
37
+ "genetic_interaction.parquet": "Genetic interactions between genes.",
38
+ "go-plus.json": "Gene ontology data for functional gene annotations.",
39
+ "gtex_tissue_gene_tpm.parquet": "Gene expression (TPM) across human tissues from GTEx.",
40
+ "gwas_catalog.pkl": "Genome-wide association studies (GWAS) results.",
41
+ "hp.obo": "Official HPO release in obographs format",
42
+ "kg.csv": "Precision medicine knowledge graph with 17,080 diseases and 4+ million relationships across biological scales.",
43
+ "marker_celltype.parquet": "Cell type marker genes for identification.",
44
+ "McPAS-TCR.parquet": "T-cell receptor sequences and specificity data from McPAS database.",
45
+ "miRDB_v6.0_results.parquet": "Predicted microRNA targets from miRDB.",
46
+ "miRTarBase_microRNA_target_interaction.parquet": "Experimentally validated microRNA-target interactions from miRTarBase.",
47
+ "miRTarBase_microRNA_target_interaction_pubmed_abtract.txt": "PubMed abstracts for microRNA-target interactions in miRTarBase.",
48
+ "miRTarBase_MicroRNA_Target_Sites.parquet": "Binding sites of microRNAs on target genes from miRTarBase.",
49
+ "mousemine_m1_positional_geneset.parquet": "Positional gene sets from MouseMine.",
50
+ "mousemine_m2_curated_geneset.parquet": "Curated gene sets from MouseMine.",
51
+ "mousemine_m3_regulatory_target_geneset.parquet": "Regulatory target gene sets from MouseMine.",
52
+ "mousemine_m5_ontology_geneset.parquet": "Ontology-based gene sets from MouseMine.",
53
+ "mousemine_m8_celltype_signature_geneset.parquet": "Cell type signature gene sets from MouseMine.",
54
+ "mousemine_mh_hallmark_geneset.parquet": "Hallmark gene sets from MouseMine.",
55
+ "msigdb_human_c1_positional_geneset.parquet": "Human positional gene sets from MSigDB.",
56
+ "msigdb_human_c2_curated_geneset.parquet": "Curated human gene sets from MSigDB.",
57
+ "msigdb_human_c3_regulatory_target_geneset.parquet": "Regulatory target gene sets from MSigDB.",
58
+ "msigdb_human_c3_subset_transcription_factor_targets_from_GTRD.parquet": "Transcription factor targets from GTRD/MSigDB.",
59
+ "msigdb_human_c4_computational_geneset.parquet": "Computationally derived gene sets from MSigDB.",
60
+ "msigdb_human_c5_ontology_geneset.parquet": "Ontology-based gene sets from MSigDB.",
61
+ "msigdb_human_c6_oncogenic_signature_geneset.parquet": "Oncogenic signatures from MSigDB.",
62
+ "msigdb_human_c7_immunologic_signature_geneset.parquet": "Immunologic signatures from MSigDB.",
63
+ "msigdb_human_c8_celltype_signature_geneset.parquet": "Cell type signatures from MSigDB.",
64
+ "msigdb_human_h_hallmark_geneset.parquet": "Hallmark gene sets from MSigDB.",
65
+ "omim.parquet": "Genetic disorders and associated genes from OMIM.",
66
+ "proteinatlas.tsv": "Protein expression data from Human Protein Atlas.",
67
+ "proximity_label-ms.parquet": "Protein interactions via proximity labeling and mass spectrometry.",
68
+ "reconstituted_complex.parquet": "Protein complexes reconstituted in vitro.",
69
+ "sgRNA_KO_SP_mouse.txt": "sgRNA knockout data for mouse.",
70
+ "sgRNA_KO_SP_human.txt": "sgRNA knockout data for human.",
71
+ "synthetic_growth_defect.parquet": "Synthetic growth defects from genetic interactions.",
72
+ "synthetic_lethality.parquet": "Synthetic lethal interactions.",
73
+ "synthetic_rescue.parquet": "Genetic interactions rescuing phenotypes.",
74
+ "two-hybrid.parquet": "Protein-protein interactions detected by yeast two-hybrid assays.",
75
+ "variant_table.parquet": "Annotated genetic variants table.",
76
+ "Virus-Host_PPI_P-HIPSTER_2020.parquet": "Virus-host protein-protein interactions from P-HIPSTER.",
77
+ "txgnn_name_mapping.pkl": "Name mapping for TXGNN.",
78
+ "txgnn_prediction.pkl": "Prediction data for TXGNN.",
79
+ }
80
+
81
+ # Updated library_content as a dictionary with detailed descriptions
82
+ library_content_dict = {
83
+ # === PYTHON PACKAGES ===
84
+ # Core Bioinformatics Libraries (Python)
85
+ "biopython": "[Python Package] A set of tools for biological computation including parsers for bioinformatics files, access to online services, and interfaces to common bioinformatics programs.",
86
+ "biom-format": "[Python Package] The Biological Observation Matrix (BIOM) format is designed for representing biological sample by observation contingency tables with associated metadata.",
87
+ "scanpy": "[Python Package] A scalable toolkit for analyzing single-cell gene expression data, specifically designed for large datasets using AnnData.",
88
+ "scikit-bio": "[Python Package] Data structures, algorithms, and educational resources for bioinformatics, including sequence analysis, phylogenetics, and ordination methods.",
89
+ "anndata": "[Python Package] A Python package for handling annotated data matrices in memory and on disk, primarily used for single-cell genomics data.",
90
+ "mudata": "[Python Package] A Python package for multimodal data storage and manipulation, extending AnnData to handle multiple modalities.",
91
+ "pyliftover": "[Python Package] A Python implementation of UCSC liftOver tool for converting genomic coordinates between genome assemblies.",
92
+ "biopandas": "[Python Package] A package that provides pandas DataFrames for working with molecular structures and biological data.",
93
+ "biotite": "[Python Package] A comprehensive library for computational molecular biology, providing tools for sequence analysis, structure analysis, and more.",
94
+ "lazyslide": "[Python Package] A Python framework that brings interoperable, reproducible whole slide image analysis, enabling seamless histopathology workflows from preprocessing to deep learning.",
95
+ # Genomics & Variant Analysis (Python)
96
+ "gget": "[Python Package] A toolkit for accessing genomic databases and retrieving sequences, annotations, and other genomic data.",
97
+ "lifelines": "[Python Package] A complete survival analysis library for fitting models, plotting, and statistical tests.",
98
+ # "scvi-tools": "[Python Package] A package for probabilistic modeling of single-cell omics data, including deep generative models.",
99
+ "gseapy": "[Python Package] A Python wrapper for Gene Set Enrichment Analysis (GSEA) and visualization.",
100
+ "scrublet": "[Python Package] A tool for detecting doublets in single-cell RNA-seq data.",
101
+ "cellxgene-census": "[Python Package] A tool for accessing and analyzing the CellxGene Census, a collection of single-cell datasets. To download a dataset, use the download_source_h5ad function with the dataset id as the argument (856c1b98-5727-49da-bf0f-151bdb8cb056, no .h5ad extension).",
102
+ "hyperopt": "[Python Package] A Python library for optimizing hyperparameters of machine learning algorithms.",
103
+ "scvelo": "[Python Package] A tool for RNA velocity analysis in single cells using dynamical models.",
104
+ "pysam": "[Python Package] A Python module for reading, manipulating and writing genomic data sets in SAM/BAM/VCF/BCF formats.",
105
+ "pyfaidx": "[Python Package] A Python package for efficient random access to FASTA files.",
106
+ "pyranges": "[Python Package] A Python package for interval manipulation with a pandas-like interface.",
107
+ "pybedtools": "[Python Package] A Python wrapper for Aaron Quinlan's BEDTools programs.",
108
+ # "panhumanpy": "A Python package for hierarchical, cross-tissue cell type annotation of human single-cell RNA-seq data",
109
+ # Structural Biology & Drug Discovery (Python)
110
+ "rdkit": "[Python Package] A collection of cheminformatics and machine learning tools for working with chemical structures and drug discovery.",
111
+ "deeppurpose": "[Python Package] A deep learning library for drug-target interaction prediction and virtual screening.",
112
+ "pyscreener": "[Python Package] A Python package for virtual screening of chemical compounds.",
113
+ "openbabel": "[Python Package] A chemical toolbox designed to speak the many languages of chemical data, supporting file format conversion and molecular modeling.",
114
+ "descriptastorus": "[Python Package] A library for computing molecular descriptors for machine learning applications in drug discovery.",
115
+ # "pymol": "[Python Package] A molecular visualization system for rendering and animating 3D molecular structures.",
116
+ "openmm": "[Python Package] A toolkit for molecular simulation using high-performance GPU computing.",
117
+ "pytdc": "[Python Package] A Python package for Therapeutics Data Commons, providing access to machine learning datasets for drug discovery.",
118
+ # Data Science & Statistical Analysis (Python)
119
+ "pandas": "[Python Package] A fast, powerful, and flexible data analysis and manipulation library for Python.",
120
+ "numpy": "[Python Package] The fundamental package for scientific computing with Python, providing support for arrays, matrices, and mathematical functions.",
121
+ "scipy": "[Python Package] A Python library for scientific and technical computing, including modules for optimization, linear algebra, integration, and statistics.",
122
+ "scikit-learn": "[Python Package] A machine learning library featuring various classification, regression, and clustering algorithms.",
123
+ "matplotlib": "[Python Package] A comprehensive library for creating static, animated, and interactive visualizations in Python.",
124
+ "seaborn": "[Python Package] A statistical data visualization library based on matplotlib with a high-level interface for drawing attractive statistical graphics.",
125
+ "statsmodels": "[Python Package] A Python module for statistical modeling and econometrics, including descriptive statistics and estimation of statistical models.",
126
+ "pymc3": "[Python Package] A Python package for Bayesian statistical modeling and probabilistic machine learning.",
127
+ # "pystan": "[Python Package] A Python interface to Stan, a platform for statistical modeling and high-performance statistical computation.",
128
+ "umap-learn": "[Python Package] Uniform Manifold Approximation and Projection, a dimension reduction technique.",
129
+ "faiss-cpu": "[Python Package] A library for efficient similarity search and clustering of dense vectors.",
130
+ "harmony-pytorch": "[Python Package] A PyTorch implementation of the Harmony algorithm for integrating single-cell data.",
131
+ # General Bioinformatics & Computational Utilities (Python)
132
+ "tiledb": "[Python Package] A powerful engine for storing and analyzing large-scale genomic data.",
133
+ "tiledbsoma": "[Python Package] A library for working with the SOMA (Stack of Matrices) format using TileDB.",
134
+ "h5py": "[Python Package] A Python interface to the HDF5 binary data format, allowing storage of large amounts of numerical data.",
135
+ "tqdm": "[Python Package] A fast, extensible progress bar for loops and CLI applications.",
136
+ "joblib": "[Python Package] A set of tools to provide lightweight pipelining in Python, including transparent disk-caching and parallel computing.",
137
+ "opencv-python": "[Python Package] OpenCV library for computer vision tasks, useful for image analysis in biological contexts.",
138
+ "PyPDF2": "[Python Package] A library for working with PDF files, useful for extracting text from scientific papers.",
139
+ "googlesearch-python": "[Python Package] A library for performing Google searches programmatically.",
140
+ "scikit-image": "[Python Package] A collection of algorithms for image processing in Python.",
141
+ "pymed": "[Python Package] A Python library for accessing PubMed articles.",
142
+ "arxiv": "[Python Package] A Python wrapper for the arXiv API, allowing access to scientific papers.",
143
+ "scholarly": "[Python Package] A module to retrieve author and publication information from Google Scholar.",
144
+ "cryosparc-tools": "[Python Package] Tools for working with cryoSPARC, a platform for cryo-EM data processing.",
145
+ "mageck": "[Python Package] Analysis of CRISPR screen data.",
146
+ "igraph": "[Python Package] Network analysis and visualization.",
147
+ "pyscenic": "[Python Package] Analysis of single-cell RNA-seq data and gene regulatory networks.",
148
+ "cooler": "[Python Package] Storage and analysis of Hi-C data.",
149
+ "trackpy": "[Python Package] Particle tracking in images and video.",
150
+ "nnunet": "[Python Package] A deep learning framework for biomedical image segmentation, providing a standardized approach to training and inference.",
151
+ # "flowcytometrytools": "[Python Package] Analysis and visualization of flow cytometry data.",
152
+ "cellpose": "[Python Package] Cell segmentation in microscopy images.",
153
+ "viennarna": "[Python Package] RNA secondary structure prediction.",
154
+ "PyMassSpec": "[Python Package] Mass spectrometry data analysis.",
155
+ "python-libsbml": "[Python Package] Working with SBML files for computational biology.",
156
+ "cobra": "[Python Package] Constraint-based modeling of metabolic networks.",
157
+ "reportlab": "[Python Package] Creation of PDF documents.",
158
+ "flowkit": "[Python Package] Toolkit for processing flow cytometry data.",
159
+ "hmmlearn": "[Python Package] Hidden Markov model analysis.",
160
+ "msprime": "[Python Package] Simulation of genetic variation.",
161
+ "tskit": "[Python Package] Handling tree sequences and population genetics data.",
162
+ "cyvcf2": "[Python Package] Fast parsing of VCF files.",
163
+ "pykalman": "[Python Package] Kalman filter and smoother implementation.",
164
+ "fanc": "[Python Package] Analysis of chromatin conformation data.",
165
+ "loompy": "A Python implementation of the Loom file format for efficiently storing and working with large omics datasets.",
166
+ "pyBigWig": "A Python library for accessing bigWig and bigBed files for genome browser track data.",
167
+ "pymzml": "A Python module for high-throughput bioinformatics analysis of mass spectrometry data.",
168
+ "optlang": "A Python package for modeling optimization problems symbolically.",
169
+ "FlowIO": "A Python package for reading and writing flow cytometry data files.",
170
+ "FlowUtils": "Utilities for processing and analyzing flow cytometry data.",
171
+ "arboreto": "A Python package for inferring gene regulatory networks from single-cell RNA-seq data.",
172
+ "pdbfixer": "A Python package for fixing problems in PDB files in preparation for molecular simulations.",
173
+ # === R PACKAGES ===
174
+ # Core R Packages for Data Analysis
175
+ "ggplot2": "[R Package] A system for declaratively creating graphics, based on The Grammar of Graphics. Use with subprocess.run(['Rscript', '-e', 'library(ggplot2); ...']).",
176
+ "dplyr": "[R Package] A grammar of data manipulation, providing a consistent set of verbs that help you solve the most common data manipulation challenges. Use with subprocess.",
177
+ "tidyr": "[R Package] A package that helps you create tidy data, where each column is a variable, each row is an observation, and each cell is a single value. Use with subprocess.",
178
+ "readr": "[R Package] A fast and friendly way to read rectangular data like CSV, TSV, and FWF. Use with subprocess.run(['Rscript', '-e', 'library(readr); ...']).",
179
+ "stringr": "[R Package] A cohesive set of functions designed to make working with strings as easy as possible. Use with subprocess calls.",
180
+ "Matrix": "[R Package] A package that provides classes and methods for dense and sparse matrices. Required for Seurat. Use with subprocess calls.",
181
+ # "Rcpp": "[R Package] Seamless R and C++ Integration, allowing R functions to call compiled C++ code. Use with subprocess calls.",
182
+ # "devtools": "[R Package] Tools to make developing R packages easier, including functions to install packages from GitHub. Use with subprocess calls.",
183
+ # "remotes": "[R Package] Install R packages from GitHub, GitLab, Bitbucket, or other remote repositories. Use with subprocess calls.",
184
+ # Bioinformatics R Packages
185
+ "DESeq2": "[R Package] Differential gene expression analysis based on the negative binomial distribution. Use with subprocess.run(['Rscript', '-e', 'library(DESeq2); ...']).",
186
+ "clusterProfiler": "[R Package] A package for statistical analysis and visualization of functional profiles for genes and gene clusters. Use with subprocess calls.",
187
+ # "DADA2": "[R Package] A package for modeling and correcting Illumina-sequenced amplicon errors. Use with subprocess calls.",
188
+ # "xcms": "[R Package] A package for processing and visualization of LC-MS and GC-MS data. Use with subprocess calls.",
189
+ # "FlowCore": "[R Package] Basic infrastructure for flow cytometry data. Use with subprocess calls.",
190
+ "edgeR": "[R Package] Empirical Analysis of Digital Gene Expression Data in R, for differential expression analysis. Use with subprocess calls.",
191
+ "limma": "[R Package] Linear Models for Microarray Data, for differential expression analysis. Use with subprocess calls.",
192
+ "harmony": "[R Package] A method for integrating and analyzing single-cell data across datasets. Use with subprocess calls.",
193
+ "WGCNA": "[R Package] Weighted Correlation Network Analysis for studying biological networks. Use with subprocess calls.",
194
+ # === CLI TOOLS ===
195
+ # Sequence Analysis Tools
196
+ "samtools": "[CLI Tool] A suite of programs for interacting with high-throughput sequencing data. Use with subprocess.run(['samtools', ...]).",
197
+ "bowtie2": "[CLI Tool] An ultrafast and memory-efficient tool for aligning sequencing reads to long reference sequences. Use with subprocess.run(['bowtie2', ...]).",
198
+ "bwa": "[CLI Tool] Burrows-Wheeler Aligner for mapping low-divergent sequences against a large reference genome. Use with subprocess.run(['bwa', ...]).",
199
+ "bedtools": "[CLI Tool] A powerful toolset for genome arithmetic, allowing operations like intersect, merge, count, and complement on genomic features. Use with subprocess.run(['bedtools', ...]).",
200
+ "macs2": "[CLI Tool] Model-based Analysis of ChIP-Seq data, a tool for identifying transcript factor binding sites.",
201
+ # Quality Control and Processing Tools
202
+ "fastqc": "[CLI Tool] A quality control tool for high throughput sequence data. Use with subprocess.run(['fastqc', ...]).",
203
+ "trimmomatic": "[CLI Tool] A flexible read trimming tool for Illumina NGS data. Use with subprocess.run(['trimmomatic', ...]).",
204
+ # Multiple Sequence Alignment and Phylogenetics
205
+ "mafft": "[CLI Tool] A multiple sequence alignment program for unix-like operating systems. Use with subprocess.run(['mafft', ...]).",
206
+ "Homer": "[CLI Tool] Motif discovery and next-gen sequencing analysis.",
207
+ "FastTree": "[CLI Tool] Phylogenetic trees from sequence alignments.",
208
+ "muscle": "[CLI Tool] Multiple sequence alignment tool.",
209
+ # Genetic Analysis Tools
210
+ "plink": "[CLI Tool] A comprehensive toolkit for genome association studies that can perform a range of large-scale analyses in a computationally efficient manner. Use with subprocess.run(['plink', ...]).",
211
+ "plink2": "[CLI Tool] A comprehensive toolkit for genome association studies that can perform a range of large-scale analyses in a computationally efficient manner. Use with subprocess.run(['plink2', ...]).",
212
+ "gcta64": "[CLI Tool] Genome-wide Complex Trait Analysis (GCTA) tool for estimating the proportion of phenotypic variance explained by genome-wide SNPs and analyzing genetic relationships. Use with subprocess.run(['gcta64', ...]).",
213
+ "iqtree2": "[CLI Tool] An efficient phylogenetic software for maximum likelihood analysis with built-in model selection and ultrafast bootstrap. Use with subprocess.run(['iqtree2', ...]).",
214
+ "ADFR": "AutoDock for Receptors suite for molecular docking and virtual screening. ",
215
+ "diamond": "A sequence aligner for protein and translated DNA searches, designed for high performance analysis of big sequence data. ",
216
+ "fcsparser": "A command-line tool for parsing and analyzing flow cytometry standard (FCS) files. ",
217
+ "plannotate": "[CLI Tool] A tool for annotating plasmid sequences with common features. ",
218
+ "vina": "[CLI Tool] An open-source program for molecular docking and virtual screening, known for its speed and accuracy improvements over AutoDock 4.",
219
+ "autosite": "[CLI Tool] A binding site detection tool used to identify potential ligand binding pockets on protein structures for molecular docking.",
220
+ "PyLabRobot": "[Python Package] A Python package for controlling liquid-handling robots and other lab automation equipment.",
221
+ }
BioScientist/agent_system/engines/v1_executor_backup/env_desc_cm.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Data lake dictionary with detailed descriptions (Commercial Mode - Non-commercial datasets commented out)
2
+ data_lake_dict = {
3
+ "affinity_capture-ms.parquet": "Protein-protein interactions detected via affinity capture and mass spectrometry.",
4
+ "affinity_capture-rna.parquet": "Protein-RNA interactions detected by affinity capture.",
5
+ # "BindingDB_All_202409.tsv": "Measured binding affinities between proteins and small molecules for drug discovery.", # Requires commercial license
6
+ "broad_repurposing_hub_molecule_with_smiles.parquet": "Molecules from Broad Institute's Drug Repurposing Hub with SMILES annotations.",
7
+ "broad_repurposing_hub_phase_moa_target_info.parquet": "Drug phases, mechanisms of action, and target information from Broad Institute.",
8
+ "co-fractionation.parquet": "Protein-protein interactions from co-fractionation experiments.",
9
+ "czi_census_datasets_v4.parquet": "Datasets from the Chan Zuckerberg Initiative's Cell Census.",
10
+ "DepMap_CRISPRGeneDependency.csv": "Gene dependency probability estimates for cancer cell lines, including all DepMap models.",
11
+ "DepMap_CRISPRGeneEffect.csv": "Genome-wide CRISPR gene effect estimates for cancer cell lines, including all DepMap models.",
12
+ "DepMap_Model.csv": "Metadata describing all cancer models/cell lines which are referenced by a dataset contained within the DepMap portal.",
13
+ "DepMap_OmicsExpressionProteinCodingGenesTPMLogp1.csv": "Gene expression in TPMs for cancer cell lines, including all DepMap models.",
14
+ # "ddinter_alimentary_tract_metabolism.csv": "Drug-drug interactions for alimentary tract and metabolism drugs from DDInter 2.0 database.", # CC BY-NC-SA 4.0 - Non-commercial only
15
+ # "ddinter_antineoplastic.csv": "Drug-drug interactions for antineoplastic and immunomodulating agents from DDInter 2.0 database.", # CC BY-NC-SA 4.0 - Non-commercial only
16
+ # "ddinter_antiparasitic.csv": "Drug-drug interactions for antiparasitic products from DDInter 2.0 database.", # CC BY-NC-SA 4.0 - Non-commercial only
17
+ # "ddinter_blood_organs.csv": "Drug-drug interactions for blood and blood forming organs drugs from DDInter 2.0 database.", # CC BY-NC-SA 4.0 - Non-commercial only
18
+ # "ddinter_dermatological.csv": "Drug-drug interactions for dermatological drugs from DDInter 2.0 database.", # CC BY-NC-SA 4.0 - Non-commercial only
19
+ # "ddinter_hormonal.csv": "Drug-drug interactions for systemic hormonal preparations from DDInter 2.0 database.", # CC BY-NC-SA 4.0 - Non-commercial only
20
+ # "ddinter_respiratory.csv": "Drug-drug interactions for respiratory system drugs from DDInter 2.0 database.", # CC BY-NC-SA 4.0 - Non-commercial only
21
+ # "ddinter_various.csv": "Drug-drug interactions for various drugs from DDInter 2.0 database.", # CC BY-NC-SA 4.0 - Non-commercial only
22
+ # "DisGeNET.parquet": "Gene-disease associations from multiple sources.", # CC BY-NC-SA 4.0 - Non-commercial only
23
+ "dosage_growth_defect.parquet": "Gene dosage changes affecting growth.",
24
+ # "enamine_cloud_library_smiles.pkl": "Compounds from Enamine REAL library with SMILES annotations.", # Proprietary - Requires license
25
+ # "evebio_assay_table.csv": "Assay metadata with one row per assay from EveBio pharmome mapping.", # Proprietary - Requires permission
26
+ # "evebio_bundle_table.csv": "Target subfamily bundles used for screening-to-profiling progression.", # Proprietary - Requires permission
27
+ # "evebio_compound_table.csv": "Compound metadata with common identifiers from EveBio screening.", # Proprietary - Requires permission
28
+ # "evebio_control_table.csv": "Control datapoints for all screening and profiling plates.", # Proprietary - Requires permission
29
+ # "evebio_detailed_result_table.csv": "Expanded results on evebio_summary_result_table with curve fit parameters and phase categories.", # Proprietary - Requires permission
30
+ # "evebio_observed_points_table.csv": "Raw observed datapoints from all screening and profiling experiments.", # Proprietary - Requires permission
31
+ # "evebio_summary_result_table.csv": "Succinct summary of results for each assay-compound combination.", # Proprietary - Requires permission
32
+ # "evebio_target_table.csv": "Target metadata with common identifiers from EveBio screening.", # Proprietary - Requires permission
33
+ "genebass_missense_LC_filtered.pkl": "Filtered missense variants from GeneBass.",
34
+ "genebass_pLoF_filtered.pkl": "Predicted loss-of-function variants from GeneBass.",
35
+ "genebass_synonymous_filtered.pkl": "Filtered synonymous variants from GeneBass.",
36
+ "gene_info.parquet": "Comprehensive gene information.",
37
+ "genetic_interaction.parquet": "Genetic interactions between genes.",
38
+ "go-plus.json": "Gene ontology data for functional gene annotations.",
39
+ "gtex_tissue_gene_tpm.parquet": "Gene expression (TPM) across human tissues from GTEx.",
40
+ "gwas_catalog.pkl": "Genome-wide association studies (GWAS) results.",
41
+ "hp.obo": "Official HPO release in obographs format",
42
+ "kg.csv": "Precision medicine knowledge graph with 17,080 diseases and 4+ million relationships across biological scales.",
43
+ "marker_celltype.parquet": "Cell type marker genes for identification.",
44
+ # "McPAS-TCR.parquet": "T-cell receptor sequences and specificity data from McPAS database.", # CC BY-NC-SA 4.0 - Non-commercial only
45
+ # "miRDB_v6.0_results.parquet": "Predicted microRNA targets from miRDB.", # Non-commercial use only
46
+ # "miRTarBase_microRNA_target_interaction.parquet": "Experimentally validated microRNA-target interactions from miRTarBase.", # CC BY-NC 4.0 - Non-commercial only
47
+ # "miRTarBase_microRNA_target_interaction_pubmed_abtract.txt": "PubMed abstracts for microRNA-target interactions in miRTarBase.", # CC BY-NC 4.0 - Non-commercial only
48
+ # "miRTarBase_MicroRNA_Target_Sites.parquet": "Binding sites of microRNAs on target genes from miRTarBase.", # CC BY-NC 4.0 - Non-commercial only
49
+ "mousemine_m1_positional_geneset.parquet": "Positional gene sets from MouseMine.",
50
+ "mousemine_m2_curated_geneset.parquet": "Curated gene sets from MouseMine.",
51
+ "mousemine_m3_regulatory_target_geneset.parquet": "Regulatory target gene sets from MouseMine.",
52
+ "mousemine_m5_ontology_geneset.parquet": "Ontology-based gene sets from MouseMine.",
53
+ "mousemine_m8_celltype_signature_geneset.parquet": "Cell type signature gene sets from MouseMine.",
54
+ "mousemine_mh_hallmark_geneset.parquet": "Hallmark gene sets from MouseMine.",
55
+ # "msigdb_human_c1_positional_geneset.parquet": "Human positional gene sets from MSigDB.", # Requires commercial license
56
+ # "msigdb_human_c2_curated_geneset.parquet": "Curated human gene sets from MSigDB.", # Requires commercial license
57
+ # "msigdb_human_c3_regulatory_target_geneset.parquet": "Regulatory target gene sets from MSigDB.", # Requires commercial license
58
+ # "msigdb_human_c3_subset_transcription_factor_targets_from_GTRD.parquet": "Transcription factor targets from GTRD/MSigDB.", # Requires commercial license
59
+ # "msigdb_human_c4_computational_geneset.parquet": "Computationally derived gene sets from MSigDB.", # Requires commercial license
60
+ # "msigdb_human_c5_ontology_geneset.parquet": "Ontology-based gene sets from MSigDB.", # Requires commercial license
61
+ # "msigdb_human_c6_oncogenic_signature_geneset.parquet": "Oncogenic signatures from MSigDB.", # Requires commercial license
62
+ # "msigdb_human_c7_immunologic_signature_geneset.parquet": "Immunologic signatures from MSigDB.", # Requires commercial license
63
+ # "msigdb_human_c8_celltype_signature_geneset.parquet": "Cell type signatures from MSigDB.", # Requires commercial license
64
+ # "msigdb_human_h_hallmark_geneset.parquet": "Hallmark gene sets from MSigDB.", # Requires commercial license
65
+ # "omim.parquet": "Genetic disorders and associated genes from OMIM.", # Requires commercial license
66
+ "proteinatlas.tsv": "Protein expression data from Human Protein Atlas.",
67
+ "proximity_label-ms.parquet": "Protein interactions via proximity labeling and mass spectrometry.",
68
+ "reconstituted_complex.parquet": "Protein complexes reconstituted in vitro.",
69
+ "sgRNA_KO_SP_mouse.txt": "sgRNA knockout data for mouse.",
70
+ "sgRNA_KO_SP_human.txt": "sgRNA knockout data for human.",
71
+ "synthetic_growth_defect.parquet": "Synthetic growth defects from genetic interactions.",
72
+ "synthetic_lethality.parquet": "Synthetic lethal interactions.",
73
+ "synthetic_rescue.parquet": "Genetic interactions rescuing phenotypes.",
74
+ "two-hybrid.parquet": "Protein-protein interactions detected by yeast two-hybrid assays.",
75
+ "variant_table.parquet": "Annotated genetic variants table.",
76
+ "Virus-Host_PPI_P-HIPSTER_2020.parquet": "Virus-host protein-protein interactions from P-HIPSTER.",
77
+ "txgnn_name_mapping.pkl": "Name mapping for TXGNN.",
78
+ "txgnn_prediction.pkl": "Prediction data for TXGNN.",
79
+ }
80
+
81
+ # Updated library_content as a dictionary with detailed descriptions
82
+ library_content_dict = {
83
+ # === PYTHON PACKAGES ===
84
+ # Core Bioinformatics Libraries (Python)
85
+ "biopython": "[Python Package] A set of tools for biological computation including parsers for bioinformatics files, access to online services, and interfaces to common bioinformatics programs.",
86
+ "biom-format": "[Python Package] The Biological Observation Matrix (BIOM) format is designed for representing biological sample by observation contingency tables with associated metadata.",
87
+ "scanpy": "[Python Package] A scalable toolkit for analyzing single-cell gene expression data, specifically designed for large datasets using AnnData.",
88
+ "scikit-bio": "[Python Package] Data structures, algorithms, and educational resources for bioinformatics, including sequence analysis, phylogenetics, and ordination methods.",
89
+ "anndata": "[Python Package] A Python package for handling annotated data matrices in memory and on disk, primarily used for single-cell genomics data.",
90
+ "mudata": "[Python Package] A Python package for multimodal data storage and manipulation, extending AnnData to handle multiple modalities.",
91
+ "pyliftover": "[Python Package] A Python implementation of UCSC liftOver tool for converting genomic coordinates between genome assemblies.",
92
+ "biopandas": "[Python Package] A package that provides pandas DataFrames for working with molecular structures and biological data.",
93
+ "biotite": "[Python Package] A comprehensive library for computational molecular biology, providing tools for sequence analysis, structure analysis, and more.",
94
+ "lazyslide": "[Python Package] A Python framework that brings interoperable, reproducible whole slide image analysis, enabling seamless histopathology workflows from preprocessing to deep learning.",
95
+ # Genomics & Variant Analysis (Python)
96
+ "gget": "[Python Package] A toolkit for accessing genomic databases and retrieving sequences, annotations, and other genomic data.",
97
+ "lifelines": "[Python Package] A complete survival analysis library for fitting models, plotting, and statistical tests.",
98
+ # "scvi-tools": "[Python Package] A package for probabilistic modeling of single-cell omics data, including deep generative models.",
99
+ "gseapy": "[Python Package] A Python wrapper for Gene Set Enrichment Analysis (GSEA) and visualization.",
100
+ "scrublet": "[Python Package] A tool for detecting doublets in single-cell RNA-seq data.",
101
+ "cellxgene-census": "[Python Package] A tool for accessing and analyzing the CellxGene Census, a collection of single-cell datasets. To download a dataset, use the download_source_h5ad function with the dataset id as the argument (856c1b98-5727-49da-bf0f-151bdb8cb056, no .h5ad extension).",
102
+ "hyperopt": "[Python Package] A Python library for optimizing hyperparameters of machine learning algorithms.",
103
+ "scvelo": "[Python Package] A tool for RNA velocity analysis in single cells using dynamical models.",
104
+ "pysam": "[Python Package] A Python module for reading, manipulating and writing genomic data sets in SAM/BAM/VCF/BCF formats.",
105
+ "pyfaidx": "[Python Package] A Python package for efficient random access to FASTA files.",
106
+ "pyranges": "[Python Package] A Python package for interval manipulation with a pandas-like interface.",
107
+ "pybedtools": "[Python Package] A Python wrapper for Aaron Quinlan's BEDTools programs.",
108
+ # "panhumanpy": "A Python package for hierarchical, cross-tissue cell type annotation of human single-cell RNA-seq data",
109
+ # Structural Biology & Drug Discovery (Python)
110
+ "rdkit": "[Python Package] A collection of cheminformatics and machine learning tools for working with chemical structures and drug discovery.",
111
+ "deeppurpose": "[Python Package] A deep learning library for drug-target interaction prediction and virtual screening.",
112
+ "pyscreener": "[Python Package] A Python package for virtual screening of chemical compounds.",
113
+ "openbabel": "[Python Package] A chemical toolbox designed to speak the many languages of chemical data, supporting file format conversion and molecular modeling.",
114
+ "descriptastorus": "[Python Package] A library for computing molecular descriptors for machine learning applications in drug discovery.",
115
+ # "pymol": "[Python Package] A molecular visualization system for rendering and animating 3D molecular structures.",
116
+ "openmm": "[Python Package] A toolkit for molecular simulation using high-performance GPU computing.",
117
+ "pytdc": "[Python Package] A Python package for Therapeutics Data Commons, providing access to machine learning datasets for drug discovery.",
118
+ # Data Science & Statistical Analysis (Python)
119
+ "pandas": "[Python Package] A fast, powerful, and flexible data analysis and manipulation library for Python.",
120
+ "numpy": "[Python Package] The fundamental package for scientific computing with Python, providing support for arrays, matrices, and mathematical functions.",
121
+ "scipy": "[Python Package] A Python library for scientific and technical computing, including modules for optimization, linear algebra, integration, and statistics.",
122
+ "scikit-learn": "[Python Package] A machine learning library featuring various classification, regression, and clustering algorithms.",
123
+ "matplotlib": "[Python Package] A comprehensive library for creating static, animated, and interactive visualizations in Python.",
124
+ "seaborn": "[Python Package] A statistical data visualization library based on matplotlib with a high-level interface for drawing attractive statistical graphics.",
125
+ "statsmodels": "[Python Package] A Python module for statistical modeling and econometrics, including descriptive statistics and estimation of statistical models.",
126
+ "pymc3": "[Python Package] A Python package for Bayesian statistical modeling and probabilistic machine learning.",
127
+ # "pystan": "[Python Package] A Python interface to Stan, a platform for statistical modeling and high-performance statistical computation.",
128
+ "umap-learn": "[Python Package] Uniform Manifold Approximation and Projection, a dimension reduction technique.",
129
+ "faiss-cpu": "[Python Package] A library for efficient similarity search and clustering of dense vectors.",
130
+ "harmony-pytorch": "[Python Package] A PyTorch implementation of the Harmony algorithm for integrating single-cell data.",
131
+ # General Bioinformatics & Computational Utilities (Python)
132
+ "tiledb": "[Python Package] A powerful engine for storing and analyzing large-scale genomic data.",
133
+ "tiledbsoma": "[Python Package] A library for working with the SOMA (Stack of Matrices) format using TileDB.",
134
+ "h5py": "[Python Package] A Python interface to the HDF5 binary data format, allowing storage of large amounts of numerical data.",
135
+ "tqdm": "[Python Package] A fast, extensible progress bar for loops and CLI applications.",
136
+ "joblib": "[Python Package] A set of tools to provide lightweight pipelining in Python, including transparent disk-caching and parallel computing.",
137
+ "opencv-python": "[Python Package] OpenCV library for computer vision tasks, useful for image analysis in biological contexts.",
138
+ "PyPDF2": "[Python Package] A library for working with PDF files, useful for extracting text from scientific papers.",
139
+ "googlesearch-python": "[Python Package] A library for performing Google searches programmatically.",
140
+ "scikit-image": "[Python Package] A collection of algorithms for image processing in Python.",
141
+ "pymed": "[Python Package] A Python library for accessing PubMed articles.",
142
+ "arxiv": "[Python Package] A Python wrapper for the arXiv API, allowing access to scientific papers.",
143
+ "scholarly": "[Python Package] A module to retrieve author and publication information from Google Scholar.",
144
+ "cryosparc-tools": "[Python Package] Tools for working with cryoSPARC, a platform for cryo-EM data processing.",
145
+ "mageck": "[Python Package] Analysis of CRISPR screen data.",
146
+ "igraph": "[Python Package] Network analysis and visualization.",
147
+ "pyscenic": "[Python Package] Analysis of single-cell RNA-seq data and gene regulatory networks.",
148
+ "cooler": "[Python Package] Storage and analysis of Hi-C data.",
149
+ "trackpy": "[Python Package] Particle tracking in images and video.",
150
+ # "flowcytometrytools": "[Python Package] Analysis and visualization of flow cytometry data.",
151
+ "cellpose": "[Python Package] Cell segmentation in microscopy images.",
152
+ "viennarna": "[Python Package] RNA secondary structure prediction.",
153
+ "PyMassSpec": "[Python Package] Mass spectrometry data analysis.",
154
+ "python-libsbml": "[Python Package] Working with SBML files for computational biology.",
155
+ "cobra": "[Python Package] Constraint-based modeling of metabolic networks.",
156
+ "reportlab": "[Python Package] Creation of PDF documents.",
157
+ "flowkit": "[Python Package] Toolkit for processing flow cytometry data.",
158
+ "hmmlearn": "[Python Package] Hidden Markov model analysis.",
159
+ "msprime": "[Python Package] Simulation of genetic variation.",
160
+ "tskit": "[Python Package] Handling tree sequences and population genetics data.",
161
+ "cyvcf2": "[Python Package] Fast parsing of VCF files.",
162
+ "pykalman": "[Python Package] Kalman filter and smoother implementation.",
163
+ "fanc": "[Python Package] Analysis of chromatin conformation data.",
164
+ "loompy": "A Python implementation of the Loom file format for efficiently storing and working with large omics datasets.",
165
+ "pyBigWig": "A Python library for accessing bigWig and bigBed files for genome browser track data.",
166
+ "pymzml": "A Python module for high-throughput bioinformatics analysis of mass spectrometry data.",
167
+ "optlang": "A Python package for modeling optimization problems symbolically.",
168
+ "FlowIO": "A Python package for reading and writing flow cytometry data files.",
169
+ "FlowUtils": "Utilities for processing and analyzing flow cytometry data.",
170
+ "arboreto": "A Python package for inferring gene regulatory networks from single-cell RNA-seq data.",
171
+ "pdbfixer": "A Python package for fixing problems in PDB files in preparation for molecular simulations.",
172
+ # === R PACKAGES ===
173
+ # Core R Packages for Data Analysis
174
+ "ggplot2": "[R Package] A system for declaratively creating graphics, based on The Grammar of Graphics. Use with subprocess.run(['Rscript', '-e', 'library(ggplot2); ...']).",
175
+ "dplyr": "[R Package] A grammar of data manipulation, providing a consistent set of verbs that help you solve the most common data manipulation challenges. Use with subprocess.",
176
+ "tidyr": "[R Package] A package that helps you create tidy data, where each column is a variable, each row is an observation, and each cell is a single value. Use with subprocess.",
177
+ "readr": "[R Package] A fast and friendly way to read rectangular data like CSV, TSV, and FWF. Use with subprocess.run(['Rscript', '-e', 'library(readr); ...']).",
178
+ "stringr": "[R Package] A cohesive set of functions designed to make working with strings as easy as possible. Use with subprocess calls.",
179
+ "Matrix": "[R Package] A package that provides classes and methods for dense and sparse matrices. Required for Seurat. Use with subprocess calls.",
180
+ # "Rcpp": "[R Package] Seamless R and C++ Integration, allowing R functions to call compiled C++ code. Use with subprocess calls.",
181
+ # "devtools": "[R Package] Tools to make developing R packages easier, including functions to install packages from GitHub. Use with subprocess calls.",
182
+ # "remotes": "[R Package] Install R packages from GitHub, GitLab, Bitbucket, or other remote repositories. Use with subprocess calls.",
183
+ # Bioinformatics R Packages
184
+ "DESeq2": "[R Package] Differential gene expression analysis based on the negative binomial distribution. Use with subprocess.run(['Rscript', '-e', 'library(DESeq2); ...']).",
185
+ "clusterProfiler": "[R Package] A package for statistical analysis and visualization of functional profiles for genes and gene clusters. Use with subprocess calls.",
186
+ # "DADA2": "[R Package] A package for modeling and correcting Illumina-sequenced amplicon errors. Use with subprocess calls.",
187
+ # "xcms": "[R Package] A package for processing and visualization of LC-MS and GC-MS data. Use with subprocess calls.",
188
+ # "FlowCore": "[R Package] Basic infrastructure for flow cytometry data. Use with subprocess calls.",
189
+ "edgeR": "[R Package] Empirical Analysis of Digital Gene Expression Data in R, for differential expression analysis. Use with subprocess calls.",
190
+ "limma": "[R Package] Linear Models for Microarray Data, for differential expression analysis. Use with subprocess calls.",
191
+ "harmony": "[R Package] A method for integrating and analyzing single-cell data across datasets. Use with subprocess calls.",
192
+ "WGCNA": "[R Package] Weighted Correlation Network Analysis for studying biological networks. Use with subprocess calls.",
193
+ # === CLI TOOLS ===
194
+ # Sequence Analysis Tools
195
+ "samtools": "[CLI Tool] A suite of programs for interacting with high-throughput sequencing data. Use with subprocess.run(['samtools', ...]).",
196
+ "bowtie2": "[CLI Tool] An ultrafast and memory-efficient tool for aligning sequencing reads to long reference sequences. Use with subprocess.run(['bowtie2', ...]).",
197
+ "bwa": "[CLI Tool] Burrows-Wheeler Aligner for mapping low-divergent sequences against a large reference genome. Use with subprocess.run(['bwa', ...]).",
198
+ "bedtools": "[CLI Tool] A powerful toolset for genome arithmetic, allowing operations like intersect, merge, count, and complement on genomic features. Use with subprocess.run(['bedtools', ...]).",
199
+ "macs2": "[CLI Tool] Model-based Analysis of ChIP-Seq data, a tool for identifying transcript factor binding sites.",
200
+ # Quality Control and Processing Tools
201
+ "fastqc": "[CLI Tool] A quality control tool for high throughput sequence data. Use with subprocess.run(['fastqc', ...]).",
202
+ "trimmomatic": "[CLI Tool] A flexible read trimming tool for Illumina NGS data. Use with subprocess.run(['trimmomatic', ...]).",
203
+ # Multiple Sequence Alignment and Phylogenetics
204
+ "mafft": "[CLI Tool] A multiple sequence alignment program for unix-like operating systems. Use with subprocess.run(['mafft', ...]).",
205
+ "Homer": "[CLI Tool] Motif discovery and next-gen sequencing analysis.",
206
+ "FastTree": "[CLI Tool] Phylogenetic trees from sequence alignments.",
207
+ "muscle": "[CLI Tool] Multiple sequence alignment tool.",
208
+ # Genetic Analysis Tools
209
+ "plink": "[CLI Tool] A comprehensive toolkit for genome association studies that can perform a range of large-scale analyses in a computationally efficient manner. Use with subprocess.run(['plink', ...]).",
210
+ "plink2": "[CLI Tool] A comprehensive toolkit for genome association studies that can perform a range of large-scale analyses in a computationally efficient manner. Use with subprocess.run(['plink2', ...]).",
211
+ "gcta64": "[CLI Tool] Genome-wide Complex Trait Analysis (GCTA) tool for estimating the proportion of phenotypic variance explained by genome-wide SNPs and analyzing genetic relationships. Use with subprocess.run(['gcta64', ...]).",
212
+ "iqtree2": "[CLI Tool] An efficient phylogenetic software for maximum likelihood analysis with built-in model selection and ultrafast bootstrap. Use with subprocess.run(['iqtree2', ...]).",
213
+ "ADFR": "AutoDock for Receptors suite for molecular docking and virtual screening. ",
214
+ "diamond": "A sequence aligner for protein and translated DNA searches, designed for high performance analysis of big sequence data. ",
215
+ "fcsparser": "A command-line tool for parsing and analyzing flow cytometry standard (FCS) files. ",
216
+ "plannotate": "[CLI Tool] A tool for annotating plasmid sequences with common features. ",
217
+ "vina": "[CLI Tool] An open-source program for molecular docking and virtual screening, known for its speed and accuracy improvements over AutoDock 4.",
218
+ "autosite": "[CLI Tool] A binding site detection tool used to identify potential ligand binding pockets on protein structures for molecular docking.",
219
+ }
BioScientist/agent_system/engines/v1_executor_backup/eval/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .biomni_eval1 import BiomniEval1
2
+
3
+ __all__ = ["BiomniEval1"]
BioScientist/agent_system/engines/v1_executor_backup/eval/biomni_eval1.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ BiomniEval1: Evaluation loader for Biomni tasks
3
+
4
+ This class provides a unified interface to evaluate user answers against ground truth
5
+ for all tasks in the BiomniEval1 benchmark.
6
+ """
7
+
8
+ import json
9
+ from typing import Any
10
+
11
+ import pandas as pd
12
+
13
+
14
+ class BiomniEval1:
15
+ """
16
+ Evaluation loader for BiomniEval1 benchmark
17
+
18
+ Usage:
19
+ evaluator = BiomniEval1('biomni_eval1_dataset.parquet')
20
+ score = evaluator.evaluate('gwas_causal_gene_opentargets', 0, 'BRCA1')
21
+ """
22
+
23
+ def __init__(self):
24
+ """
25
+ Initialize the BiomniEval1 evaluator
26
+
27
+ Args:
28
+ dataset_path: Path to the merged dataset parquet file
29
+ """
30
+
31
+ self.df = pd.read_parquet("hf://datasets/biomni/Eval1/biomni_eval1_dataset.parquet")
32
+
33
+ # Create index mapping for fast lookup using task_instance_id
34
+ self.instance_map = {}
35
+ for idx, row in self.df.iterrows():
36
+ key = (row["task_name"], row["task_instance_id"])
37
+ self.instance_map[key] = idx
38
+
39
+ print(f"Loaded BiomniEval1 dataset: {len(self.df)} instances across {self.df['task_name'].nunique()} tasks")
40
+
41
+ def evaluate(self, task_name: str, task_instance_id: int, user_answer: str) -> float:
42
+ """
43
+ Evaluate a user's answer for a given task and instance
44
+
45
+ Args:
46
+ task_name: Name of the task (e.g., 'gwas_causal_gene_opentargets')
47
+ task_instance_id: Task-specific instance ID (not the global instance_id)
48
+ user_answer: User's answer (format depends on task)
49
+
50
+ Returns:
51
+ float: Reward score (0.0 to 1.0)
52
+ """
53
+ # Look up the instance in the dataset using task_instance_id
54
+ key = (task_name, task_instance_id)
55
+ if key not in self.instance_map:
56
+ raise ValueError(f"Instance not found: task={task_name}, task_instance_id={task_instance_id}")
57
+
58
+ df_idx = self.instance_map[key]
59
+ row = self.df.iloc[df_idx]
60
+ ground_truth = row["answer"]
61
+
62
+ # Call task-specific evaluation function
63
+ try:
64
+ reward = self._compute_reward(task_name, user_answer, ground_truth)
65
+ return float(reward)
66
+
67
+ except Exception as e:
68
+ # Preserve original traceback context for easier debugging
69
+ raise RuntimeError(f"Error computing reward for {task_name} instance {task_instance_id}: {e}") from e
70
+
71
+ def _compute_reward(self, task_name: str, user_answer: str, ground_truth: str) -> float:
72
+ """Compute reward using task-specific logic"""
73
+
74
+ if task_name == "crispr_delivery":
75
+ # CRISPR expects answer as a letter (a-f), exact match
76
+ return 1.0 if user_answer.strip().lower() == ground_truth.strip().lower() else 0.0
77
+
78
+ elif task_name.startswith("gwas_causal_gene"):
79
+ # GWAS causal gene expects exact gene match (case-insensitive)
80
+ return 1.0 if user_answer.strip().upper() == ground_truth.strip().upper() else 0.0
81
+
82
+ elif task_name == "gwas_variant_prioritization":
83
+ # GWAS variant expects exact variant match
84
+ return 1.0 if user_answer.strip() == ground_truth.strip() else 0.0
85
+
86
+ elif task_name == "hle":
87
+ # HLE expects letter answer (A-Z), case-insensitive
88
+ return 1.0 if user_answer.strip().upper() == ground_truth.strip().upper() else 0.0
89
+
90
+ elif task_name.startswith("lab_bench"):
91
+ # Lab bench expects letter answer (A-Z), case-insensitive
92
+ return 1.0 if user_answer.strip().upper() == ground_truth.strip().upper() else 0.0
93
+
94
+ elif task_name == "rare_disease_diagnosis":
95
+ # Rare disease expects JSON with OMIM_ID match
96
+ # Parse both user answer and ground truth
97
+ try:
98
+ if isinstance(user_answer, str):
99
+ try:
100
+ user_dict = json.loads(user_answer)
101
+ except json.JSONDecodeError:
102
+ import ast
103
+
104
+ user_dict = ast.literal_eval(user_answer)
105
+ else:
106
+ user_dict = user_answer
107
+
108
+ if isinstance(ground_truth, str):
109
+ gt_dict = json.loads(ground_truth)
110
+ else:
111
+ gt_dict = ground_truth
112
+
113
+ # Compare OMIM_ID
114
+ return 1.0 if user_dict.get("OMIM_ID") == gt_dict.get("OMIM_ID") else 0.0
115
+
116
+ except Exception:
117
+ return 0.0
118
+
119
+ elif task_name == "screen_gene_retrieval":
120
+ # Screen gene retrieval expects gene symbol (case-insensitive)
121
+ return 1.0 if user_answer.strip().upper() == ground_truth.strip().upper() else 0.0
122
+
123
+ elif task_name == "patient_gene_detection":
124
+ # Patient gene detection expects JSON with causal_gene list
125
+ # Ground truth is a comma-separated string or single gene ID
126
+ try:
127
+ if isinstance(user_answer, str):
128
+ try:
129
+ user_dict = json.loads(user_answer)
130
+ except json.JSONDecodeError:
131
+ import ast
132
+
133
+ user_dict = ast.literal_eval(user_answer)
134
+ else:
135
+ user_dict = user_answer
136
+
137
+ # Get predicted genes
138
+ predicted_genes = user_dict.get("causal_gene", [])
139
+ if not isinstance(predicted_genes, list):
140
+ predicted_genes = [predicted_genes]
141
+
142
+ # Get ground truth genes (stored as comma-separated or single)
143
+ if "," in ground_truth:
144
+ true_genes = [g.strip() for g in ground_truth.split(",")]
145
+ else:
146
+ true_genes = [ground_truth]
147
+
148
+ # Check for intersection
149
+ if predicted_genes and set(true_genes) & set(predicted_genes):
150
+ return 1.0
151
+ else:
152
+ return 0.0
153
+
154
+ except Exception:
155
+ return 0.0
156
+
157
+ else:
158
+ raise ValueError(f"Unknown task: {task_name}")
159
+
160
+ def get_instance(self, task_name: str, task_instance_id: int) -> dict[str, Any]:
161
+ """
162
+ Get information about a specific instance
163
+
164
+ Args:
165
+ task_name: Name of the task
166
+ task_instance_id: Task-specific instance ID
167
+
168
+ Returns:
169
+ dict: Instance information including prompt, answer, etc.
170
+ """
171
+ key = (task_name, task_instance_id)
172
+ if key not in self.instance_map:
173
+ raise ValueError(f"Instance not found: task={task_name}, task_instance_id={task_instance_id}")
174
+
175
+ df_idx = self.instance_map[key]
176
+ row = self.df.iloc[df_idx]
177
+
178
+ return {
179
+ "global_instance_id": row["instance_id"],
180
+ "task_instance_id": row["task_instance_id"],
181
+ "task_name": row["task_name"],
182
+ "split": row["split"],
183
+ "prompt": row["prompt"],
184
+ "answer": row["answer"],
185
+ }
186
+
187
+ def list_tasks(self) -> list:
188
+ """Get list of all available tasks"""
189
+ return sorted(self.df["task_name"].unique().tolist())
190
+
191
+ def get_task_stats(self, task_name: str = None) -> dict[str, Any]:
192
+ """
193
+ Get statistics for a task or all tasks
194
+
195
+ Args:
196
+ task_name: Optional task name to filter by
197
+
198
+ Returns:
199
+ dict: Statistics including counts by split
200
+ """
201
+ if task_name:
202
+ task_df = self.df[self.df["task_name"] == task_name]
203
+ if len(task_df) == 0:
204
+ raise ValueError(f"Task not found: {task_name}")
205
+ else:
206
+ task_df = self.df
207
+
208
+ stats = {
209
+ "total_instances": len(task_df),
210
+ "train_instances": len(task_df[task_df["split"] == "train"]),
211
+ "val_instances": len(task_df[task_df["split"] == "val"]),
212
+ }
213
+
214
+ if not task_name:
215
+ stats["tasks"] = {}
216
+ for tn in self.list_tasks():
217
+ stats["tasks"][tn] = self.get_task_stats(tn)
218
+
219
+ return stats
220
+
221
+ def batch_evaluate(self, evaluations: list) -> list:
222
+ """
223
+ Evaluate multiple instances at once
224
+
225
+ Args:
226
+ evaluations: List of tuples (task_name, task_instance_id, user_answer)
227
+
228
+ Returns:
229
+ list: List of reward scores
230
+ """
231
+ results = []
232
+ for task_name, task_instance_id, user_answer in evaluations:
233
+ try:
234
+ score = self.evaluate(task_name, task_instance_id, user_answer)
235
+ results.append(score)
236
+ except Exception as e:
237
+ print(f"Error evaluating {task_name} instance {task_instance_id}: {e}")
238
+ results.append(0.0)
239
+
240
+ return results
241
+
242
+ def get_instances_by_task(self, task_name: str, split: str = None) -> pd.DataFrame:
243
+ """
244
+ Get all instances for a specific task
245
+
246
+ Args:
247
+ task_name: Name of the task
248
+ split: Optional split filter ('train' or 'val')
249
+
250
+ Returns:
251
+ DataFrame with instances
252
+ """
253
+ task_df = self.df[self.df["task_name"] == task_name]
254
+
255
+ if split:
256
+ task_df = task_df[task_df["split"] == split]
257
+
258
+ return task_df.copy()
259
+
260
+ def __repr__(self):
261
+ return f"BiomniEval1(instances={len(self.df)}, tasks={self.df['task_name'].nunique()})"
262
+
263
+ def __len__(self):
264
+ return len(self.df)
265
+
266
+
267
+ def main():
268
+ """Demo usage of BiomniEval1"""
269
+ evaluator = BiomniEval1()
270
+
271
+ print("\nAvailable tasks:")
272
+ for task in evaluator.list_tasks():
273
+ print(f" - {task}")
274
+
275
+ print("\nOverall statistics:")
276
+ stats = evaluator.get_task_stats()
277
+ print(f" Total instances: {stats['total_instances']}")
278
+ print(f" Train: {stats['train_instances']}, Val: {stats['val_instances']}")
279
+
280
+ print("\nPer-task statistics:")
281
+ for task_name in evaluator.list_tasks():
282
+ task_stats = evaluator.get_task_stats(task_name)
283
+ print(
284
+ f" {task_name}: {task_stats['total_instances']} total ({task_stats['train_instances']} train, {task_stats['val_instances']} val)"
285
+ )
286
+
287
+ # Example evaluation
288
+ print("\n" + "=" * 60)
289
+ print("Example evaluation:")
290
+ print("=" * 60)
291
+
292
+ # Get first instance from gwas_variant_prioritization
293
+ first_instance = evaluator.df[evaluator.df["task_name"] == "gwas_variant_prioritization"].iloc[0]
294
+ task_name = first_instance["task_name"]
295
+ task_instance_id = first_instance["task_instance_id"]
296
+ ground_truth = first_instance["answer"]
297
+
298
+ print(f"\nTask: {task_name}")
299
+ print(f"Task Instance ID: {task_instance_id}")
300
+ print(f"Ground truth: {ground_truth}")
301
+ print(f"Prompt preview: {first_instance['prompt'][:200]}...")
302
+
303
+ # Test with correct answer
304
+ score = evaluator.evaluate(task_name, task_instance_id, ground_truth)
305
+ print(f"\nScore (correct answer '{ground_truth}'): {score}")
306
+
307
+ # Test with wrong answer
308
+ score = evaluator.evaluate(task_name, task_instance_id, "wrong_answer")
309
+ print(f"Score (wrong answer 'wrong_answer'): {score}")
310
+
311
+ # Batch evaluation example
312
+ print("\n" + "=" * 60)
313
+ print("Batch evaluation example:")
314
+ print("=" * 60)
315
+ batch_evals = [
316
+ (task_name, task_instance_id, ground_truth), # Correct
317
+ (task_name, task_instance_id, "wrong"), # Wrong
318
+ ]
319
+ scores = evaluator.batch_evaluate(batch_evals)
320
+ print(f"Batch scores: {scores}")
321
+
322
+
323
+ if __name__ == "__main__":
324
+ main()
BioScientist/agent_system/engines/v1_executor_backup/know_how/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ """Know-How library for Biomni agent.
2
+
3
+ This module provides functionality to load and manage know-how documents
4
+ that contain best practices, protocols, and troubleshooting guides.
5
+ """
6
+
7
+ from .loader import KnowHowLoader
8
+
9
+ __all__ = ["KnowHowLoader"]
BioScientist/agent_system/engines/v1_executor_backup/know_how/loader.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Loader for know-how documents."""
2
+
3
+ import glob
4
+ import os
5
+ from pathlib import Path
6
+
7
+
8
+ class KnowHowLoader:
9
+ """Load and manage know-how documents for the agent."""
10
+
11
+ def __init__(self, know_how_dir: str | None = None):
12
+ """Initialize the know-how loader.
13
+
14
+ Args:
15
+ know_how_dir: Directory containing know-how documents.
16
+ If None, uses the default know_how directory.
17
+
18
+ """
19
+ if know_how_dir is None:
20
+ # Default to the know_how directory in the package
21
+ current_dir = Path(__file__).parent
22
+ know_how_dir = str(current_dir)
23
+
24
+ self.know_how_dir = know_how_dir
25
+ self.documents = {}
26
+ self._load_documents()
27
+
28
+ def _load_documents(self):
29
+ """Load all markdown documents from the know-how directory."""
30
+ pattern = os.path.join(self.know_how_dir, "*.md")
31
+ md_files = glob.glob(pattern)
32
+
33
+ for filepath in md_files:
34
+ filename = os.path.basename(filepath)
35
+ filename_without_ext = os.path.splitext(filename)[0]
36
+
37
+ # Skip README, QUICK_START, and other meta documentation (all caps filenames)
38
+ if filename.upper() in ["README.MD", "QUICK_START.MD"] or filename_without_ext.isupper():
39
+ continue
40
+
41
+ # Read the document
42
+ with open(filepath) as f:
43
+ content = f.read()
44
+
45
+ # Extract title, description, and metadata from the document
46
+ title, description, metadata = self._extract_metadata(content, filename)
47
+
48
+ # Use short_description from metadata if available, otherwise fall back to extracted description
49
+ if "short_description" in metadata and metadata["short_description"]:
50
+ description = metadata["short_description"]
51
+
52
+ # Store document info
53
+ doc_id = os.path.splitext(filename)[0]
54
+ self.documents[doc_id] = {
55
+ "id": doc_id,
56
+ "name": title,
57
+ "description": description,
58
+ "content": content,
59
+ "content_without_metadata": self._strip_metadata(content),
60
+ "filepath": filepath,
61
+ "metadata": metadata,
62
+ }
63
+
64
+ def _extract_metadata(self, content: str, filename: str) -> tuple[str, str, dict]:
65
+ """Extract title, description, and metadata from markdown content.
66
+
67
+ Args:
68
+ content: Markdown content
69
+ filename: Filename (used as fallback for title)
70
+
71
+ Returns:
72
+ Tuple of (title, description, metadata_dict)
73
+
74
+ """
75
+ lines = content.split("\n")
76
+
77
+ # Extract title (first h1)
78
+ title = None
79
+ for line in lines:
80
+ if line.startswith("# "):
81
+ title = line[2:].strip()
82
+ break
83
+
84
+ if title is None:
85
+ # Fallback to filename
86
+ title = filename.replace("_", " ").replace(".md", "").title()
87
+
88
+ # Extract metadata section
89
+ metadata = {}
90
+ in_metadata = False
91
+ current_field = None
92
+
93
+ for _i, line in enumerate(lines):
94
+ if line.startswith("## Metadata"):
95
+ in_metadata = True
96
+ continue
97
+ elif in_metadata:
98
+ if line.startswith("##") and "Metadata" not in line:
99
+ # End of metadata section
100
+ break
101
+ elif line.startswith("**") and "**:" in line:
102
+ # New metadata field (e.g., **Authors**:)
103
+ field_match = line.split("**")[1]
104
+ current_field = field_match.lower().replace(" ", "_")
105
+ # Get the value after the colon if it exists on the same line
106
+ colon_idx = line.find("**:")
107
+ if colon_idx != -1:
108
+ value_part = line[colon_idx + 3 :].strip()
109
+ if value_part:
110
+ metadata[current_field] = value_part
111
+ else:
112
+ metadata[current_field] = ""
113
+ elif current_field and line.strip() and not line.startswith("---"):
114
+ # Continuation of current field
115
+ if current_field not in metadata:
116
+ metadata[current_field] = ""
117
+ if line.startswith("- "):
118
+ # List item
119
+ if metadata[current_field]:
120
+ metadata[current_field] += ", " + line[2:].strip()
121
+ else:
122
+ metadata[current_field] = line[2:].strip()
123
+ elif not line.startswith("```"):
124
+ # Regular text
125
+ if metadata[current_field]:
126
+ metadata[current_field] += " " + line.strip()
127
+ else:
128
+ metadata[current_field] = line.strip()
129
+
130
+ # Extract description (content under ## Overview or first paragraph)
131
+ description = ""
132
+ in_overview = False
133
+ overview_lines = []
134
+
135
+ for _i, line in enumerate(lines):
136
+ if line.startswith("## Overview"):
137
+ in_overview = True
138
+ continue
139
+ elif in_overview:
140
+ if line.startswith("##"):
141
+ # End of overview section
142
+ break
143
+ elif line.strip():
144
+ overview_lines.append(line.strip())
145
+
146
+ if overview_lines:
147
+ description = " ".join(overview_lines)
148
+ else:
149
+ # Fallback: get first non-empty paragraph after title
150
+ found_title = False
151
+ for line in lines:
152
+ if line.startswith("# "):
153
+ found_title = True
154
+ continue
155
+ if found_title and line.strip() and not line.startswith("#"):
156
+ description = line.strip()
157
+ break
158
+
159
+ # Limit description length
160
+ if len(description) > 200:
161
+ description = description[:197] + "..."
162
+
163
+ return title, description, metadata
164
+
165
+ def _strip_metadata(self, content: str) -> str:
166
+ """Strip the metadata section from document content.
167
+
168
+ Args:
169
+ content: Full document content with metadata
170
+
171
+ Returns:
172
+ Content without metadata section
173
+
174
+ """
175
+ lines = content.split("\n")
176
+ result_lines = []
177
+ in_metadata = False
178
+ skip_until_separator = False
179
+ found_first_h1 = False
180
+
181
+ for line in lines:
182
+ # Track first H1 (title)
183
+ if line.startswith("# ") and not found_first_h1:
184
+ result_lines.append(line)
185
+ found_first_h1 = True
186
+ continue
187
+
188
+ # Detect metadata section start
189
+ if line.startswith("## Metadata"):
190
+ in_metadata = True
191
+ continue
192
+
193
+ # Skip separator lines before and after metadata
194
+ if line.strip() == "---":
195
+ if not in_metadata:
196
+ # This might be the separator before metadata
197
+ skip_until_separator = True
198
+ continue
199
+ else:
200
+ # This is the separator after metadata
201
+ in_metadata = False
202
+ skip_until_separator = False
203
+ continue
204
+
205
+ # Skip lines in metadata section
206
+ if in_metadata or skip_until_separator:
207
+ # Check if we hit another H2 (end of metadata)
208
+ if line.startswith("##") and "Metadata" not in line:
209
+ in_metadata = False
210
+ skip_until_separator = False
211
+ result_lines.append(line)
212
+ continue
213
+
214
+ # Keep all other lines
215
+ result_lines.append(line)
216
+
217
+ # Join and clean up extra blank lines
218
+ result = "\n".join(result_lines)
219
+
220
+ # Remove excessive blank lines (more than 2 consecutive)
221
+ while "\n\n\n\n" in result:
222
+ result = result.replace("\n\n\n\n", "\n\n\n")
223
+
224
+ return result.strip()
225
+
226
+ def get_all_documents(self) -> list[dict]:
227
+ """Get all know-how documents as a list.
228
+
229
+ Returns:
230
+ List of document dictionaries with keys: id, name, description, content
231
+
232
+ """
233
+ return list(self.documents.values())
234
+
235
+ def get_document_by_id(self, doc_id: str) -> dict | None:
236
+ """Get a specific know-how document by ID.
237
+
238
+ Args:
239
+ doc_id: Document identifier
240
+
241
+ Returns:
242
+ Document dictionary or None if not found
243
+
244
+ """
245
+ return self.documents.get(doc_id)
246
+
247
+ def get_document_summaries(self) -> list[dict]:
248
+ """Get summaries of all documents (without full content).
249
+
250
+ Returns:
251
+ List of document summaries with keys: id, name, description
252
+
253
+ """
254
+ return [
255
+ {"id": doc["id"], "name": doc["name"], "description": doc["description"]} for doc in self.documents.values()
256
+ ]
257
+
258
+ def add_custom_document(self, doc_id: str, name: str, description: str, content: str, metadata: dict | None = None):
259
+ """Add a custom know-how document programmatically.
260
+
261
+ Args:
262
+ doc_id: Unique identifier for the document
263
+ name: Document title
264
+ description: Brief description
265
+ content: Full document content
266
+ metadata: Optional metadata dictionary (authors, license, etc.)
267
+
268
+ """
269
+ if metadata is None:
270
+ metadata = {}
271
+
272
+ self.documents[doc_id] = {
273
+ "id": doc_id,
274
+ "name": name,
275
+ "description": description,
276
+ "content": content,
277
+ "filepath": None,
278
+ "metadata": metadata,
279
+ }
280
+
281
+ def get_document_metadata(self, doc_id: str) -> dict | None:
282
+ """Get metadata for a specific document.
283
+
284
+ Args:
285
+ doc_id: Document identifier
286
+
287
+ Returns:
288
+ Metadata dictionary or None if not found
289
+
290
+ """
291
+ doc = self.documents.get(doc_id)
292
+ return doc.get("metadata", {}) if doc else None
293
+
294
+ def print_document_info(self, doc_id: str):
295
+ """Print formatted information about a document including metadata.
296
+
297
+ Args:
298
+ doc_id: Document identifier
299
+
300
+ """
301
+ doc = self.documents.get(doc_id)
302
+ if not doc:
303
+ print(f"Document '{doc_id}' not found")
304
+ return
305
+
306
+ print("=" * 70)
307
+ print(f"📚 {doc['name']}")
308
+ print("=" * 70)
309
+ print(f"\nDescription: {doc['description']}")
310
+
311
+ metadata = doc.get("metadata", {})
312
+ if metadata:
313
+ print("\n" + "-" * 70)
314
+ print("METADATA")
315
+ print("-" * 70)
316
+
317
+ # Display key metadata fields
318
+ if "authors" in metadata:
319
+ print(f"Authors: {metadata['authors']}")
320
+ if "affiliations" in metadata:
321
+ print(f"Affiliations: {metadata['affiliations']}")
322
+ if "version" in metadata:
323
+ print(f"Version: {metadata['version']}")
324
+ if "last_updated" in metadata:
325
+ print(f"Last Updated: {metadata['last_updated']}")
326
+ if "license" in metadata:
327
+ print(f"License: {metadata['license']}")
328
+ if "commercial_use" in metadata:
329
+ print(f"Commercial Use: {metadata['commercial_use']}")
330
+ if "status" in metadata:
331
+ print(f"Status: {metadata['status']}")
332
+
333
+ print("=" * 70)
334
+
335
+ def remove_document(self, doc_id: str):
336
+ """Remove a know-how document.
337
+
338
+ Args:
339
+ doc_id: Document identifier
340
+
341
+ """
342
+ if doc_id in self.documents:
343
+ del self.documents[doc_id]
344
+
345
+ def reload(self):
346
+ """Reload all documents from disk."""
347
+ self.documents = {}
348
+ self._load_documents()
BioScientist/agent_system/engines/v1_executor_backup/know_how/resource/CRISPick_download_links.txt ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_8030_ICSASG_v2_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20230421.txt.gz
2
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_8030_ICSASG_v2_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20230421.summary.txt
3
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_8030_ICSASG_v2_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20230421.txt.gz
4
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_8030_ICSASG_v2_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20230421.summary.txt
5
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10029_CHOK1GS_HDv1_SaurCas9_CRISPRa_Azimuth_2.0_Ensembl_20241114.txt.gz
6
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10029_CHOK1GS_HDv1_SaurCas9_CRISPRa_Azimuth_2.0_Ensembl_20241114.summary.txt
7
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10029_CHOK1GS_HDv1_SaurCas9_CRISPRi_Azimuth_2.0_Ensembl_20241114.txt.gz
8
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10029_CHOK1GS_HDv1_SaurCas9_CRISPRi_Azimuth_2.0_Ensembl_20241114.summary.txt
9
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10029_CHOK1GS_HDv1_SaurCas9_CRISPRko_Azimuth_2.0_Ensembl_20241114.txt.gz
10
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10029_CHOK1GS_HDv1_SaurCas9_CRISPRko_Azimuth_2.0_Ensembl_20241114.summary.txt
11
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10029_CHOK1GS_HDv1_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20241114.txt.gz
12
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10029_CHOK1GS_HDv1_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20241114.summary.txt
13
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10029_CHOK1GS_HDv1_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20241114.txt.gz
14
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10029_CHOK1GS_HDv1_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20241114.summary.txt
15
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_74940_Otsh_v1.0_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20230424.txt.gz
16
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_74940_Otsh_v1.0_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20230424.summary.txt
17
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_74940_Otsh_v1.0_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20230424.txt.gz
18
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_74940_Otsh_v1.0_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20230424.summary.txt
19
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9913_ARS-UCD1.2_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20230418.txt.gz
20
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9913_ARS-UCD1.2_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20230418.summary.txt
21
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9913_ARS-UCD1.2_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20230418.txt.gz
22
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9913_ARS-UCD1.2_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20230418.summary.txt
23
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_CanFam3.1_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20220923.txt.gz
24
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_CanFam3.1_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20220923.summary.txt
25
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_CanFam3.1_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20220923.txt.gz
26
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_CanFam3.1_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20220923.summary.txt
27
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRa_Seq-DeepCpf1_Ensembl_20251031.txt.gz
28
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRa_Seq-DeepCpf1_Ensembl_20251031.summary.txt
29
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRa_Seq-DeepCpf1_NCBI_20240611.txt.gz
30
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRa_Seq-DeepCpf1_NCBI_20240611.summary.txt
31
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRi_Seq-DeepCpf1_Ensembl_20251031.txt.gz
32
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRi_Seq-DeepCpf1_Ensembl_20251031.summary.txt
33
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRi_Seq-DeepCpf1_NCBI_20240611.txt.gz
34
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRi_Seq-DeepCpf1_NCBI_20240611.summary.txt
35
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRko_Seq-DeepCpf1_Ensembl_20251031.txt.gz
36
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRko_Seq-DeepCpf1_Ensembl_20251031.summary.txt
37
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRko_Seq-DeepCpf1_NCBI_20240611.txt.gz
38
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_AsCas12a_CRISPRko_Seq-DeepCpf1_NCBI_20240611.summary.txt
39
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRa_enPAM+GB_Ensembl_20241031.txt.gz
40
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRa_enPAM+GB_Ensembl_20241031.summary.txt
41
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRa_enPAM+GB_NCBI_20240611.txt.gz
42
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRa_enPAM+GB_NCBI_20240611.summary.txt
43
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRi_enPAM+GB_Ensembl_20241031.txt.gz
44
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRi_enPAM+GB_Ensembl_20241031.summary.txt
45
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRi_enPAM+GB_NCBI_20240611.txt.gz
46
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRi_enPAM+GB_NCBI_20240611.summary.txt
47
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRko_enPAM+GB_Ensembl_20251031.txt.gz
48
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRko_enPAM+GB_Ensembl_20251031.summary.txt
49
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRko_enPAM+GB_NCBI_20240611.txt.gz
50
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_enAsCas12a_CRISPRko_enPAM+GB_NCBI_20240611.summary.txt
51
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20251031.txt.gz
52
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20251031.summary.txt
53
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20240611.txt.gz
54
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20240611.summary.txt
55
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_SpyoCas9_CRISPRi_RS3i-Chen2013_Ensembl_20251031.txt.gz
56
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_SpyoCas9_CRISPRi_RS3i-Chen2013_Ensembl_20251031.summary.txt
57
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20241031.txt.gz
58
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20241031.summary.txt
59
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20240611.txt.gz
60
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9615_ROS_Cfam_1.0_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20240611.summary.txt
61
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_7227_BDGP6.32_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20230407.txt.gz
62
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_7227_BDGP6.32_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20230407.summary.txt
63
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_7227_BDGP6.32_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20230407.txt.gz
64
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_7227_BDGP6.32_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20230407.summary.txt
65
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_59479_mRhiFer1_v1.p_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20230427.txt.gz
66
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_59479_mRhiFer1_v1.p_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20230427.summary.txt
67
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_59479_mRhiFer1_v1.p_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20230427.txt.gz
68
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_59479_mRhiFer1_v1.p_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20230427.summary.txt
69
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_AsCas12a_CRISPRa_Seq-DeepCpf1_NCBI_20220914.txt.gz
70
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_AsCas12a_CRISPRa_Seq-DeepCpf1_NCBI_20220914.summary.txt
71
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_AsCas12a_CRISPRi_Seq-DeepCpf1_NCBI_20220914.txt.gz
72
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_AsCas12a_CRISPRi_Seq-DeepCpf1_NCBI_20220914.summary.txt
73
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_AsCas12a_CRISPRko_Seq-DeepCpf1_NCBI_20220914.txt.gz
74
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_AsCas12a_CRISPRko_Seq-DeepCpf1_NCBI_20220914.summary.txt
75
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_enAsCas12a_CRISPRa_enPAM+GB_NCBI_20220914.txt.gz
76
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_enAsCas12a_CRISPRa_enPAM+GB_NCBI_20220914.summary.txt
77
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_enAsCas12a_CRISPRi_enPAM+GB_NCBI_20220914.txt.gz
78
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_enAsCas12a_CRISPRi_enPAM+GB_NCBI_20220914.summary.txt
79
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_enAsCas12a_CRISPRko_enPAM+GB_NCBI_20220914.txt.gz
80
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_enAsCas12a_CRISPRko_enPAM+GB_NCBI_20220914.summary.txt
81
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20220914.txt.gz
82
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20220914.summary.txt
83
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20220914.txt.gz
84
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_60711_Chlorocebus_sabeus_1.1_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20220914.summary.txt
85
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh37_SaurCas9_CRISPRa_Azimuth_2.0_NCBI_20241107.txt.gz
86
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh37_SaurCas9_CRISPRa_Azimuth_2.0_NCBI_20241107.summary.txt
87
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh37_SaurCas9_CRISPRi_Azimuth_2.0_NCBI_20241107.txt.gz
88
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh37_SaurCas9_CRISPRi_Azimuth_2.0_NCBI_20241107.summary.txt
89
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh37_SaurCas9_CRISPRko_Azimuth_2.0_NCBI_20241107.txt.gz
90
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh37_SaurCas9_CRISPRko_Azimuth_2.0_NCBI_20241107.summary.txt
91
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh37_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20241107.txt.gz
92
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh37_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20241107.summary.txt
93
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh37_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20241107.txt.gz
94
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh37_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20241107.summary.txt
95
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRa_Seq-DeepCpf1_Ensembl_20250806.txt.gz
96
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRa_Seq-DeepCpf1_Ensembl_20250806.summary.txt
97
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRa_Seq-DeepCpf1_NCBI_20250718.txt.gz
98
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRa_Seq-DeepCpf1_NCBI_20250718.summary.txt
99
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRi_Seq-DeepCpf1_Ensembl_20250806.txt.gz
100
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRi_Seq-DeepCpf1_Ensembl_20250806.summary.txt
101
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRi_Seq-DeepCpf1_NCBI_20250718.txt.gz
102
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRi_Seq-DeepCpf1_NCBI_20250718.summary.txt
103
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRko_Seq-DeepCpf1_Ensembl_20250806.txt.gz
104
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRko_Seq-DeepCpf1_Ensembl_20250806.summary.txt
105
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRko_Seq-DeepCpf1_NCBI_20250718.txt.gz
106
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_AsCas12a_CRISPRko_Seq-DeepCpf1_NCBI_20250718.summary.txt
107
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRa_enPAM+GB_Ensembl_20250806.txt.gz
108
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRa_enPAM+GB_Ensembl_20250806.summary.txt
109
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRa_enPAM+GB_NCBI_20250718.txt.gz
110
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRa_enPAM+GB_NCBI_20250718.summary.txt
111
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRi_enPAM+GB_Ensembl_20250806.txt.gz
112
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRi_enPAM+GB_Ensembl_20250806.summary.txt
113
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRi_enPAM+GB_NCBI_20250718.txt.gz
114
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRi_enPAM+GB_NCBI_20250718.summary.txt
115
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRko_enPAM+GB_Ensembl_20250806.txt.gz
116
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRko_enPAM+GB_Ensembl_20250806.summary.txt
117
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRko_enPAM+GB_NCBI_20250718.txt.gz
118
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_enAsCas12a_CRISPRko_enPAM+GB_NCBI_20250718.summary.txt
119
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRa_Azimuth_2.0_Ensembl_20250806.txt.gz
120
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRa_Azimuth_2.0_Ensembl_20250806.summary.txt
121
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRa_Azimuth_2.0_NCBI_20250718.txt.gz
122
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRa_Azimuth_2.0_NCBI_20250718.summary.txt
123
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRi_Azimuth_2.0_Ensembl_20250806.txt.gz
124
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRi_Azimuth_2.0_Ensembl_20250806.summary.txt
125
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRi_Azimuth_2.0_NCBI_20250718.txt.gz
126
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRi_Azimuth_2.0_NCBI_20250718.summary.txt
127
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRko_Azimuth_2.0_Ensembl_20250806.txt.gz
128
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRko_Azimuth_2.0_Ensembl_20250806.summary.txt
129
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRko_Azimuth_2.0_NCBI_20250718.txt.gz
130
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SaurCas9_CRISPRko_Azimuth_2.0_NCBI_20250718.summary.txt
131
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20250806.txt.gz
132
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20250806.summary.txt
133
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20250718.txt.gz
134
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20250718.summary.txt
135
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRi_RS3i-Chen2013_Ensembl_20250806.txt.gz
136
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRi_RS3i-Chen2013_Ensembl_20250806.summary.txt
137
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRi_RS3i-Chen2013_NCBI_20250718.txt.gz
138
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRi_RS3i-Chen2013_NCBI_20250718.summary.txt
139
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20241104.txt.gz
140
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20241104.summary.txt
141
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20241028.txt.gz
142
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20241028.summary.txt
143
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRa_Seq-DeepCpf1_NCBI_20250807.txt.gz
144
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRa_Seq-DeepCpf1_NCBI_20250807.summary.txt
145
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRa_Seq-DeepCpf1_Ensembl_20250724.txt.gz
146
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRa_Seq-DeepCpf1_Ensembl_20250724.summary.txt
147
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRi_Seq-DeepCpf1_NCBI_20250807.txt.gz
148
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRi_Seq-DeepCpf1_NCBI_20250807.summary.txt
149
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRi_Seq-DeepCpf1_Ensembl_20250724.txt.gz
150
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRi_Seq-DeepCpf1_Ensembl_20250724.summary.txt
151
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRko_Seq-DeepCpf1_NCBI_20250807.txt.gz
152
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRko_Seq-DeepCpf1_NCBI_20250807.summary.txt
153
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRko_Seq-DeepCpf1_Ensembl_20250724.txt.gz
154
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_AsCas12a_CRISPRko_Seq-DeepCpf1_Ensembl_20250724.summary.txt
155
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRa_enPAM+GB_NCBI_20250807.txt.gz
156
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRa_enPAM+GB_NCBI_20250807.summary.txt
157
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRa_enPAM+GB_Ensembl_20250724.txt.gz
158
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRa_enPAM+GB_Ensembl_20250724.summary.txt
159
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRi_enPAM+GB_NCBI_20250807.txt.gz
160
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRi_enPAM+GB_NCBI_20250807.summary.txt
161
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRi_enPAM+GB_Ensembl_20250724.txt.gz
162
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRi_enPAM+GB_Ensembl_20250724.summary.txt
163
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRko_enPAM+GB_NCBI_20250807.txt.gz
164
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRko_enPAM+GB_NCBI_20250807.summary.txt
165
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRko_enPAM+GB_Ensembl_20250724.txt.gz
166
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_enAsCas12a_CRISPRko_enPAM+GB_Ensembl_20250724.summary.txt
167
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRa_Azimuth_2.0_NCBI_20250807.txt.gz
168
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRa_Azimuth_2.0_NCBI_20250807.summary.txt
169
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRa_Azimuth_2.0_Ensembl_20250724.txt.gz
170
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRa_Azimuth_2.0_Ensembl_20250724.summary.txt
171
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRi_Azimuth_2.0_NCBI_20250807.txt.gz
172
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRi_Azimuth_2.0_NCBI_20250807.summary.txt
173
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRi_Azimuth_2.0_Ensembl_20250724.txt.gz
174
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRi_Azimuth_2.0_Ensembl_20250724.summary.txt
175
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRko_Azimuth_2.0_NCBI_20250807.txt.gz
176
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRko_Azimuth_2.0_NCBI_20250807.summary.txt
177
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRko_Azimuth_2.0_Ensembl_20250724.txt.gz
178
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SaurCas9_CRISPRko_Azimuth_2.0_Ensembl_20250724.summary.txt
179
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20250807.txt.gz
180
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20250807.summary.txt
181
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20250724.txt.gz
182
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20250724.summary.txt
183
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRi_RS3i-Chen2013_NCBI_20250807.txt.gz
184
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRi_RS3i-Chen2013_NCBI_20250807.summary.txt
185
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRi_RS3i-Chen2013_Ensembl_20250724.txt.gz
186
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRi_RS3i-Chen2013_Ensembl_20250724.summary.txt
187
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20240614.txt.gz
188
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20240614.summary.txt
189
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20230403.txt.gz
190
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10090_GRCm38_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20230403.summary.txt
191
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_8022_USDA_OmykA_1.1_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20230419.txt.gz
192
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_8022_USDA_OmykA_1.1_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20230419.summary.txt
193
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_8022_USDA_OmykA_1.1_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20230419.txt.gz
194
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_8022_USDA_OmykA_1.1_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20230419.summary.txt
195
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRa_Seq-DeepCpf1_Ensembl_20241112.txt.gz
196
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRa_Seq-DeepCpf1_Ensembl_20241112.summary.txt
197
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRa_Seq-DeepCpf1_NCBI_20240131.txt.gz
198
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRa_Seq-DeepCpf1_NCBI_20240131.summary.txt
199
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRi_Seq-DeepCpf1_Ensembl_20241112.txt.gz
200
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRi_Seq-DeepCpf1_Ensembl_20241112.summary.txt
201
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRi_Seq-DeepCpf1_NCBI_20240131.txt.gz
202
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRi_Seq-DeepCpf1_NCBI_20240131.summary.txt
203
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRko_Seq-DeepCpf1_Ensembl_20241112.txt.gz
204
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRko_Seq-DeepCpf1_Ensembl_20241112.summary.txt
205
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRko_Seq-DeepCpf1_NCBI_20240131.txt.gz
206
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_AsCas12a_CRISPRko_Seq-DeepCpf1_NCBI_20240131.summary.txt
207
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRa_enPAM+GB_Ensembl_20241112.txt.gz
208
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRa_enPAM+GB_Ensembl_20241112.summary.txt
209
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRa_enPAM+GB_NCBI_20240131.txt.gz
210
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRa_enPAM+GB_NCBI_20240131.summary.txt
211
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRi_enPAM+GB_Ensembl_20241112.txt.gz
212
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRi_enPAM+GB_Ensembl_20241112.summary.txt
213
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRi_enPAM+GB_NCBI_20240131.txt.gz
214
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRi_enPAM+GB_NCBI_20240131.summary.txt
215
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRko_enPAM+GB_Ensembl_20241112.txt.gz
216
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRko_enPAM+GB_Ensembl_20241112.summary.txt
217
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRko_enPAM+GB_NCBI_20240131.txt.gz
218
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_enAsCas12a_CRISPRko_enPAM+GB_NCBI_20240131.summary.txt
219
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20241112.txt.gz
220
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_SpyoCas9_CRISPRa_RS3seq-Chen2013_Ensembl_20241112.summary.txt
221
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20240131.txt.gz
222
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20240131.summary.txt
223
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20241112.txt.gz
224
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_Ensembl_20241112.summary.txt
225
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20240131.txt.gz
226
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_mRatBN7.2_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20240131.summary.txt
227
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_Rnor_6.0_SaurCas9_CRISPRi_Azimuth_2.0_NCBI_20220907.txt.gz
228
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_Rnor_6.0_SaurCas9_CRISPRi_Azimuth_2.0_NCBI_20220907.summary.txt
229
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_Rnor_6.0_SaurCas9_CRISPRko_Azimuth_2.0_NCBI_20220907.txt.gz
230
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_Rnor_6.0_SaurCas9_CRISPRko_Azimuth_2.0_NCBI_20220907.summary.txt
231
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_Rnor_6.0_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20220907.txt.gz
232
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_Rnor_6.0_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20220907.summary.txt
233
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_Rnor_6.0_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20220907.txt.gz
234
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_10116_Rnor_6.0_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20220907.summary.txt
235
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9544_Mmul_10_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20241025.txt.gz
236
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9544_Mmul_10_SpyoCas9_CRISPRa_RS3seq-Chen2013_NCBI_20241025.summary.txt
237
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9544_Mmul_10_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20241025.txt.gz
238
+ https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/sgRNA_design_9544_Mmul_10_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20241025.summary.txt
BioScientist/agent_system/engines/v1_executor_backup/know_how/resource/addgene_grna_sequences.csv ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Application,Cas9 Species,Depositor,Plasmid ID,PubMed ID,Target Gene,Target Sequence,Target Species
2
+ cut,S. pyogenes,Goncalves,"<a href=""/58252/"">58252</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24870050/"">24870050</a>",AAVS1,GGGGCCACTAGGGACAGGAT,H. sapiens
3
+ cut,S. pyogenes,Church,"<a href=""/41818/"">41818</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23287722/"">23287722</a>",AAVS1,GGGGCCACTAGGGACAGGAT,H. sapiens
4
+ cut,S. pyogenes,Sabatini,"<a href=""/50662/"">50662</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24336569/"">24336569</a>",AAVS1,GGGGCCACTAGGGACAGGAT,H. sapiens
5
+ cut,S. pyogenes,Sabatini,"<a href=""/70661/"">70661</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",AAVS1,GGGGCCACTAGGGACAGGAT,H. sapiens
6
+ cut,S. pyogenes,Church,"<a href=""/41817/"">41817</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23287722/"">23287722</a>",AAVS1,GTCCCCTCCACCCCACAGTG,H. sapiens
7
+ cut,S. pyogenes,Kanemaki,"<a href=""/72833/"">72833</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/27052166/"">27052166</a>",AAVS1,GGGGCCACTAGGGACAGGAT,H. sapiens
8
+ cut,S. pyogenes,Corn,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26789497/"">26789497</a>",AAVS1,TGTCCCTAGTGGCCCCACTG,H. sapiens
9
+ cut,S. pyogenes,Corn,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26789497/"">26789497</a>",AAVS1,ACAGTGGGGCCACTAGGGAC,H. sapiens
10
+ RNA targeting,S. pyogenes,Yeo,"<a href=""/74705/"">74705</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26997482/"">26997482</a>",ACTB,UGGAGCGAGCAUCCCCCAAA,H. sapiens
11
+ cut,S. pyogenes,Jiang,"<a href=""/62552/"">62552</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25739462/"">25739462</a>",actII-orf4,ATTACCAGGGACCGGAGTTC,S. coelicolor
12
+ cut,S. pyogenes,Zaratiegui,"<a href=""/52225/"">52225</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25352017/"">25352017</a>",ade6+,TCTATTGTTCAGATGCCTCG,S. pombe
13
+ cut,S. pyogenes,Zaratiegui,"<a href=""/52227/"">52227</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25352017/"">25352017</a>",ade6-L469,TCTATTGTTCAGATGCCTTG,S. pombe
14
+ cut,S. pyogenes,Zaratiegui,"<a href=""/52226/"">52226</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25352017/"">25352017</a>",ade6-M210,TCTATTGTTCAGATGCTTCG,S. pombe
15
+ cut,S. pyogenes,Ventura,"<a href=""/64071/"">64071</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25337876/"">25337876</a>",Alk and Eml,,M. musculus
16
+ nick,S. pyogenes,Shaw,"<a href=""/74374/"">74374</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26816379/"">26816379</a>",AMPK alpha 1,GGCTGTCGCCATCTTTCTCC,H. sapiens
17
+ nick,S. pyogenes,Shaw,"<a href=""/74375/"">74375</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26816379/"">26816379</a>",AMPK alpha 1,GAAGATCGGCCACTACATTC,H. sapiens
18
+ nick,S. pyogenes,Shaw,"<a href=""/74376/"">74376</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26816379/"">26816379</a>",AMPK alpha 2,GTCAGCCATCTTCGGCGCGCG,H. sapiens
19
+ nick,S. pyogenes,Shaw,"<a href=""/74377/"">74377</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26816379/"">26816379</a>",AMPK alpha 2,GAAGATCGGACACTACGTGC,H. sapiens
20
+ cut,S. pyogenes,Sabatini,"<a href=""/70660/"">70660</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>","Amplicon, JAK2",GAGGCATATTCTTCTCCTGG,H. sapiens
21
+ cut,S. pyogenes,Voytas,"<a href=""/70019/"">70019</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26541286/"">26541286</a>",ANT1,TGTCGTTTATAATTTGTAGA,S. lycopersicum
22
+ cut,S. pyogenes,Voytas,"<a href=""/70018/"">70018</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26541286/"">26541286</a>",ANT1,ACAATTTAATACACCTTTT,S. lycopersicum
23
+ cut,S. pyogenes,Kim,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26479191/"">26479191</a>",AOC,CAAAAGACTGTCAATTCCCT,N. attenuata
24
+ cut/nick,S. pyogenes,Yamamoto,"<a href=""/58780/"">58780</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24954249/"">24954249</a>",APC,GAAGCGGGCAAAGGGGCGAC,H. sapiens
25
+ cut,S. pyogenes,Joung,"<a href=""/42241/"">42241</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23360964/"">23360964</a>",apoea,GGATGAGCCAAGAAGCCGCT,D. rerio
26
+ activate,S. pyogenes,Sato,"<a href=""/64131/"">64131</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",ASCL1,TGGATGGAGAGTTTGCAAGGAGC,H. sapiens
27
+ activate,S. pyogenes,Sato,"<a href=""/64130/"">64130</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",ASCL1,TGGGCAGCCGCTCGCTGCAGCAG,H. sapiens
28
+ activate,S. pyogenes,Sato,"<a href=""/64129/"">64129</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",ASCL1,TGGGGCTGGGTGTCCCATTGAAA,H. sapiens
29
+ activate,S. pyogenes,Sato,"<a href=""/64132/"">64132</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",ASCL1,TGGTGTTTATTCAGCCGGGAGTC,H. sapiens
30
+ cut,S. pyogenes,Mashimo,"<a href=""/60968/"">60968</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24967838/"">24967838</a>",Asip,ATGACAGGAGTCTAACTCAC,R. norvegicus
31
+ tag,S. pyogenes,Mendenhall,"<a href=""/64690/"">64690</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26355004/"">26355004</a>",ATF1,TAGGAATCAAACACTTTTATTGG,H. sapiens
32
+ cut,S. pyogenes,Yamamoto,"<a href=""/58779/"">58779</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24954249/"">24954249</a>",ATM,TGAATTGGGATGCTGTTTTT,H. sapiens
33
+ cut,S. pyogenes,Mello,"<a href=""/58981/"">58981</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24879462/"">24879462</a>",avr-14,GATTGGAGAGTTAGACCACG,C. elegans
34
+ cut,S. pyogenes,Mello,"<a href=""/58982/"">58982</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24879462/"">24879462</a>",avr-15,GTTTGCAATATAAGTCACCC,C. elegans
35
+ cut,S. pyogenes,Yamamoto,"<a href=""/58782/"">58782</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24954249/"">24954249</a>",AXIN2,TATGTTGGTGACTTGCCTCC,H. sapiens
36
+ methylation,S. pyogenes,Zoldoš,"<a href=""/71828/"">71828</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26969735/"">26969735</a>",BACH2,AATGTAGCGATTGAGAGTGTGGG,H. sapiens
37
+ cut,S. pyogenes,Sabatini,"<a href=""/70658/"">70658</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",BCR/ABL amplicon,GGCTCCCTTCAAGTGGGATG,H. sapiens
38
+ cut,S. pyogenes,Corn,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26789497/"">26789497</a>",BFP,ATGGCGTGCAGTGCTTCAGC,
39
+ cut,S. pyogenes,Kim,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26479191/"">26479191</a>",BIN2,ATCACAGTGATGCTCGTCAA,L. sativa
40
+ cut,S. pyogenes,Hanna,"<a href=""/59724/"">59724</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25543152/"">25543152</a>",BLIMP1,CGGATGGGGTAAACGACCCG,H. sapiens
41
+ cut,S. pyogenes,Kim,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26479191/"">26479191</a>",BRI1,TTTGAAAGATGGAAGCGCGG,A. thaliana
42
+ cut,S. pyogenes,Kim,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26479191/"">26479191</a>",BRI1,TGAAACTAAACTGGTCCACA,A. thaliana
43
+ interfere,S. pyogenes,Lu,"<a href=""/68892/"">68892</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26918244/"">26918244</a>",BT1754,GAAAATGGGGTGTATCCTGC,B. thetaiotaomicron
44
+ interfere,S. pyogenes,Lu,"<a href=""/68891/"">68891</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26918244/"">26918244</a>",BT1854,ATTGAAGAACAAAAGCAGTT,B. thetaiotaomicron
45
+ cut,S. pyogenes,Sabatini,"<a href=""/70650/"">70650</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",C16orf80,CGATGCTGTAGAGGATGGAG,H. sapiens
46
+ cut,S. pyogenes,Sabatini,"<a href=""/70651/"">70651</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",C16orf80,TGTCTGAGAAGTAAACCCGT,H. sapiens
47
+ cut,S. pyogenes,Sabatini,"<a href=""/70653/"">70653</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",C3orf17,GGGCCAAATGGGGTTTGTGG,H. sapiens
48
+ cut,S. pyogenes,Sabatini,"<a href=""/70652/"">70652</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",C3orf17,GTGTGAGAATCCCTAAGGCG,H. sapiens
49
+ cut,S. pyogenes,Sabatini,"<a href=""/70654/"">70654</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",C9orf114,CAGGCGGGCTCACCTCCGTG,H. sapiens
50
+ cut,S. pyogenes,Sabatini,"<a href=""/70655/"">70655</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",C9orf114,GCGGCAGAGAAGGAGGACCG,H. sapiens
51
+ cut,S. pyogenes,Church,"<a href=""/43803/"">43803</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23460208/"">23460208</a>",CAN1,GATACGTTCTCTATGGAGGA,S. cerevisiae
52
+ cut,S. pyogenes,Bornhauser,"<a href=""/75164/"">75164</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/27194728/"">27194728</a>",Caspase-8,GCCTGGACTACATTCCGCAA,H. sapiens
53
+ cut,S. pyogenes,Corn,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26789497/"">26789497</a>",CCR5,TGACATCAATTATTATACAT,H. sapiens
54
+ interfere,S. pyogenes,Qi,"<a href=""/46918/"">46918</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23849981/"">23849981</a>",CD71,GGACGCGCTAGTGTGAGTGC,H. sapiens
55
+ cut,S. pyogenes,Yamamoto,"<a href=""/58781/"">58781</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24954249/"">24954249</a>",CDH1,TGACTTGCGAGGGACGCATT,H. sapiens
56
+ activate,S. pyogenes,Vale,"<a href=""/60905/"">60905</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25307933/"">25307933</a>",CDKN1B,GAAGCCGGGACCTGGACCAG,H. sapiens
57
+ tag,S. pyogenes,Mendenhall,"<a href=""/64036/"">64036</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26355004/"">26355004</a>",CEBPB,CTCCGGCCACTGCTAGCGCGG,H. sapiens
58
+ tag,S. pyogenes,Mendenhall,"<a href=""/64047/"">64047</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26355004/"">26355004</a>",CEBPB,GCCGGCAGGGGGACGCGCGCGG,H. sapiens
59
+ cut,S. pyogenes,Ikawa,"<a href=""/50718/"">50718</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24284873/"">24284873</a>",Cent1,GGCAACGTTTGACTTCCTGA,M. musculus
60
+ cut,S. pyogenes,Yamamoto,"<a href=""/58783/"">58783</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24954249/"">24954249</a>",CFTR,TCTGTATCTATATTCATCAT,H. sapiens
61
+ tag,S. pyogenes,Mendenhall,"<a href=""/64940/"">64940</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26355004/"">26355004</a>",CREB1,GCCACAAATCAGATTAATTTGG,H. sapiens
62
+ tag,S. pyogenes,Mendenhall,"<a href=""/64939/"">64939</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26355004/"">26355004</a>",CREB1,GCCACAAATCAGATTAATTTGGG,H. sapiens
63
+ cut,S. pyogenes,Hong,"<a href=""/68060/"">68060</a>","<a href=""http://fungalbiolbiotech.biomedcentral.com/articles/10.1186/s40694-015-0015-1"">Fungal Biology and Biotechnology 2015, 2:4</a>",csr-1,GAGTGGGAGGGTCCCGTCCT,N. crassa
64
+ cut,S. pyogenes,Jacks,"<a href=""/59912/"">59912</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25119044/"">25119044</a>",Ctnnb1,AGCTCCTTCCCTGAGTGGCA,M. musculus
65
+ cut,S. pyogenes,Jacks,"<a href=""/59911/"">59911</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25119044/"">25119044</a>",Ctnnb1,CTGTGGTGGTGGCACCAGAA,M. musculus
66
+ interfere,S. pyogenes,Qi,"<a href=""/46917/"">46917</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23849981/"">23849981</a>",CXCR4,GCAGGTAGCAAAGTGACGCCGA,H. sapiens
67
+ cut,S. pyogenes,Corn,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26789497/"">26789497</a>",CXCR4,CCTCTTTGTCATCACGCTTC,H. sapiens
68
+ activate,S. pyogenes,Lu,"<a href=""/64385/"">64385</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,ACAGAGCACATGCATGCCAT,S. cerevisiae
69
+ activate,S. pyogenes,Lu,"<a href=""/64387/"">64387</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,ACTAATACTTTCAACATTTT,S. cerevisiae
70
+ activate,S. pyogenes,Lu,"<a href=""/64382/"">64382</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,ATATCGAATTCCTGCAGCCC,S. cerevisiae
71
+ activate,S. pyogenes,Lu,"<a href=""/64380/"">64380</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,ATATTCTTTCCTTATACATT,S. cerevisiae
72
+ activate,S. pyogenes,Lu,"<a href=""/64379/"">64379</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,CTAGATATTAAAATGTCTAA,S. cerevisiae
73
+ activate,S. pyogenes,Lu,"<a href=""/64388/"">64388</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,GTTGAAAGTATTAGTTAAAG,S. cerevisiae
74
+ activate,S. pyogenes,Lu,"<a href=""/64381/"">64381</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,TACATACAGTAGGATCCTA,S. cerevisiae
75
+ activate,S. pyogenes,Lu,"<a href=""/64383/"">64383</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,TATAGTAATTTATGCTGCAA,S. cerevisiae
76
+ activate,S. pyogenes,Lu,"<a href=""/64384/"">64384</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,TGCAAAGGTCCTAATGTATA,S. cerevisiae
77
+ activate,S. pyogenes,Lu,"<a href=""/64386/"">64386</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,TGTATGTACATACAGTACCC,S. cerevisiae
78
+ activate,S. pyogenes,Lu,"<a href=""/64378/"">64378</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23977949/"">23977949</a>",CYC1m promoter,TTACTGTATGTACATACAGT,S. cerevisiae
79
+ cut,S. pyogenes,Wente,"<a href=""/47932/"">47932</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23918387/"">23918387</a>",ddx19,GGCAACAGATTCGTGGGCCC,D. rerio
80
+ cut,S. pyogenes,Sabatini,"<a href=""/70656/"">70656</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",DDX3Y,GCAGTTTAGCGATATTGACA,H. sapiens
81
+ cut,S. pyogenes,Sabatini,"<a href=""/70657/"">70657</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",DDX3Y,TCTTGTTGGGGCTAAAACCA,H. sapiens
82
+ cut,S. pyogenes,Church,"<a href=""/41822/"">41822</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23287722/"">23287722</a>",DNMT3A,GAGATGATCGCCCCTTCTTC,H. sapiens
83
+ cut,S. pyogenes,Church,"<a href=""/41821/"">41821</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23287722/"">23287722</a>",DNMT3A,GCATGATGCGCGGCCCAAGG,H. sapiens
84
+ cut,S. pyogenes,Church,"<a href=""/41823/"">41823</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23287722/"">23287722</a>",DNMT3B,GAATTACTCACGCCCCAAGG,H. sapiens
85
+ cut,VRER Cas9 mutant,Fire,"<a href=""/71516/"">71516</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26680661/"">26680661</a>",dpy-10,CGCTACCATAGGCACCACG,C. elegans
86
+ cut,S. pyogenes,Katic,"<a href=""/65630/"">65630</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26044730/"">26044730</a>",dpy-10,GCTACCATAGGCACCACGAG,C.elegans
87
+ cut,S. pyogenes,Fire,"<a href=""/59933/"">59933</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25161212/"">25161212</a>",dpy-10,GCTACCATAGGCACCACGAG,C. elegans
88
+ cut,VQR Cas9 variant,Fire,"<a href=""/71479/"">71479</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26680661/"">26680661</a>",dpy-10,TCCGCTACCATAGGCACCA,C. elegans
89
+ cut,S. pyogenes,Seydoux,"<a href=""/70047/"">70047</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26187122/"">26187122</a>",dpy‐10,GCTACCATAGGCACCACGAG,C. elegans
90
+ cut,S. pyogenes,Joung,"<a href=""/42242/"">42242</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23360964/"">23360964</a>",drd3,GGAAACTACAGCCCAGCGTC,D. rerio
91
+ cut,S. pyogenes,Kim,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26479191/"">26479191</a>",DWD1,TGCATCGTCCAAGCGCACAG,O. sativa
92
+ cut,S. pyogenes,Kim,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26479191/"">26479191</a>",DWD1,CTACGACGTCAGGTTCTACC,O. sativa
93
+ cut,S. pyogenes,Christiaen,"<a href=""/59990/"">59990</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25336740/"">25336740</a>",Ebf,GCTGAGGGTTGGACAACAGG,C. intestinalis
94
+ dCas9-FokI,S. pyogenes,Joung,"<a href=""/60071/"">60071</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24770325/"">24770325</a>",EGFP,"multiple, see article",A. victoria
95
+ cut,S. pyogenes,Zhang,"<a href=""/51764/"">51764</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24336571/"">24336571</a>",EGFP,GAAGTTCGAGGGCGACACCC,A. victoria
96
+ cut,S. pyogenes,Zhang,"<a href=""/51761/"">51761</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24336571/"">24336571</a>",EGFP,GAGCTGGACGGCGACGTAAA,A. victoria
97
+ cut,S. pyogenes,Joung,"<a href=""/47512/"">47512</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23792628/"">23792628</a>",EGFP,GATGCCGTTCTTCTGCTTGT,A. victoria
98
+ cut,S. pyogenes,Zhang,"<a href=""/51763/"">51763</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24336571/"">24336571</a>",EGFP,GGAGCGCACCATCTTCTTCA,A. victoria
99
+ cut,S. pyogenes,Zhang,"<a href=""/51762/"">51762</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24336571/"">24336571</a>",EGFP,GGCCACAAGTTCAGCGTGTC,A. victoria
100
+ cut,S. pyogenes,Del Bene,"<a href=""/61051/"">61051</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24179142/"">24179142</a>",EGFP,GGCGAGGGCGATGCCACCTA,A. victoria
101
+ cut,S. pyogenes,Chen,"<a href=""/46760/"">46760</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23918387/"">23918387</a>",EGFP,GGGCACGGGCAGCTTGCCGG,A. victoria
102
+ cut,S. pyogenes,Joung,"<a href=""/47511/"">47511</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23792628/"">23792628</a>",EGFP,GGGCACGGGCAGCTTGCCGG,A. victoria
103
+ cut,S. pyogenes,Zhang,"<a href=""/51760/"">51760</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24336571/"">24336571</a>",EGFP,GGGCGAGGAGCTGTTCACCG,A. victoria
104
+ cut,S. pyogenes,Zhang,"<a href=""/51765/"">51765</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24336571/"">24336571</a>",EGFP,GGTGAACCGCATCGAGCTGA,A. victoria
105
+ cut,S. pyogenes,Joung,"<a href=""/47513/"">47513</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23792628/"">23792628</a>",EGFP,GGTGGTGCAGATGAACTTCA,A. victoria
106
+ cut,S. pyogenes,Goncalves,"<a href=""/58255/"">58255</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24870050/"">24870050</a>",EGFP,TGAAGAAGATGGTGCGCTC,A. victoria
107
+ cut,S. pyogenes,Moffat,"<a href=""/74187/"">74187</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26627737/"">26627737</a>",EIF3D,TGTAGGTTGCCTCCATGGCC,H. sapiens
108
+ cut,S. pyogenes,Moffat,"<a href=""/74188/"">74188</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26627737/"">26627737</a>",EIF3D,AGACGACCCTGTCATCCGCA,H. sapiens
109
+ cut,S. pyogenes,Zhang,"<a href=""/42337/"">42337</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23287718/"">23287718</a>",Emx1,,H. sapiens
110
+ cut,S. pyogenes,Joung,"<a href=""/47508/"">47508</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23792628/"">23792628</a>",EMX1,GAGTCCGAGCAGAAGAAGAA,H. sapiens
111
+ cut,S. pyogenes,Corn,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26789497/"">26789497</a>",EMX1,CGATGTCACCTCCAATGACT,H. sapiens
112
+ cut,S. pyogenes,Chen,"<a href=""/71288/"">71288</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26193878/"">26193878</a>","ETC2, TRY, and CPC",,A. thaliana
113
+ cut,S. pyogenes,Bornhauser,"<a href=""/75166/"">75166</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/27194728/"">27194728</a>",FADD,ACTCCCGCACACGCTCTGTC,H. sapiens
114
+ cut,S. pyogenes,Joung,"<a href=""/47510/"">47510</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23792628/"">23792628</a>",FANCF,GGAATCCCTTCTGCAGCACC,H. sapiens
115
+ cut,S. pyogenes,Seydoux,"<a href=""/65597/"">65597</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25249454/"">25249454</a>",fbf-2,GTAGTCACGGCGATGATTA,C. elegans
116
+ cut,S. pyogenes,Seydoux,"<a href=""/65591/"">65591</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25249454/"">25249454</a>",fbf-2,TAATCATCGCCGTGACTAC,C. elegans
117
+ cut,S. pyogenes,Joung,"<a href=""/42244/"">42244</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23360964/"">23360964</a>",fh,GGAGCGAGCGGAGCGGTACA,D. rerio
118
+ cut,S. pyogenes,Joung,"<a href=""/42243/"">42243</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23360964/"">23360964</a>",fh,GGAGCGGTACATGGCGACCG,D. rerio
119
+ tag,S. pyogenes,Mendenhall,"<a href=""/64254/"">64254</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26355004/"">26355004</a>",GABPA,GAAAAGGATAATTGAGCCCCAGG,H. sapiens
120
+ tag,S. pyogenes,Mendenhall,"<a href=""/64255/"">64255</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26355004/"">26355004</a>",GABPA,TTTGGAGTCTCAGAATGTCCTGG,H. sapiens
121
+ activate,S. pyogenes,Qi,"<a href=""/46916/"">46916</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23849981/"">23849981</a>",GAL4 UAS,GAACGACTAGTTAGGCGTGTA,
122
+ activate,S. pyogenes,Qi,"<a href=""/46915/"">46915</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23849981/"">23849981</a>",GAL4 UAS,GTTGGAGCACTGTCCTCCGAACGT,
123
+ activate,S. pyogenes,Sato,"<a href=""/64158/"">64158</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",GAL4UAS,TGGGGACAGTACTCCGCTCGAGT,
124
+ activate,S. pyogenes,Sato,"<a href=""/64157/"">64157</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",GAL4UAS,TGGGTCTTCGGAGGACAGTACTC,
125
+ activate,S. pyogenes,Sato,"<a href=""/64159/"">64159</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",GAL4UAS,TGGTCCGTCTAGAAACTCGGTAC,
126
+ cut,S. pyogenes,Du,"<a href=""/65566/"">65566</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25849248/"">25849248</a>",gfap,GTGCGCAACACATAGCACCA,D. rerio
127
+ interfere,S. pyogenes,Qi,"<a href=""/46914/"">46914</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23849981/"">23849981</a>",GFP,GAATAGCTCAGAGGCCGAGG,A. victoria
128
+ cut,S. pyogenes,Church,"<a href=""/41820/"">41820</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23287722/"">23287722</a>",GFP,GGAGCGCACCATCTTCTTCA,A. victoria
129
+ cut,S. pyogenes,Church,"<a href=""/41819/"">41819</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23287722/"">23287722</a>",GFP,GTGAACCGCATCGAGCTGAA,A. victoria
130
+ cut,S. pyogenes,"Guigo, Johnson","<a href=""/72619/"">72619</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26493208/"">26493208</a>",GFP,gRNA1: GAGCTGGACGGCGACGTAAA; gRNA2: CAGAACACCCCCATCGGCGA,Synthetic
131
+ interfere,S. pyogenes,Hudson,"<a href=""/73221/"">73221</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26689101/"">26689101</a>",GFPmut3b,ACCATCTAATTCAACAAGAATT,A. victoria
132
+ interfere,S. pyogenes,Hudson,"<a href=""/73224/"">73224</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26689101/"">26689101</a>",GFPmut3b,ACCATCTAATTCAACAAGAATT,synthetic
133
+ CRISPR-display,S. pyogenes,Rinn,"<a href=""/68422/"">68422</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26030444/"">26030444</a>",GLuc,GATCTAGATACGACTCACTAT,synthetic
134
+ cut,S. pyogenes,Ye,"<a href=""/61833/"">61833</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24424410/"">24424410</a>",gp78,GCCCAGCCTCCGCACCTACA,H. sapiens
135
+ cut,S. pyogenes,Joung,"<a href=""/42245/"">42245</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23360964/"">23360964</a>",gsk3b,GGGACCTGACCGGCCGCAGG,D. rerio
136
+ cut,S. pyogenes,Jin,"<a href=""/64333/"">64333</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25281382/"">25281382</a>",his3,ATTGCGATCTCTTTAAAGGG,S. cerevisiae
137
+ cut,S. pyogenes,Yan,"<a href=""/69539/"">69539</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26130722/"">26130722</a>",HPRT,GACTGTAAGTGAATTACTT,H. sapiens
138
+ cut,S. pyogenes,Yamamoto,"<a href=""/58778/"">58778</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24954249/"">24954249</a>",HPRT1,CTGATAAAATCTACAGTCAT,H. sapiens
139
+ cut,S. pyogenes,Yamamoto,"<a href=""/58771/"">58771</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24954249/"">24954249</a>",HPRT1,TTATGCTGAGGATTTGGAAA,H. sapiens
140
+ activate,S. pyogenes,Sato,"<a href=""/64142/"">64142</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",IL1RN,TGGACGCAGATAAGAACCAGTT,H. sapiens
141
+ activate,S. pyogenes,Sato,"<a href=""/64151/"">64151</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",IL1RN,TGGCATCAAGTCAGCCATCAGC,H. sapiens
142
+ activate,S. pyogenes,Sato,"<a href=""/64152/"">64152</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",IL1RN,TGGGAGTCACCCTCCTGGAAAC,H. sapiens
143
+ activate,S. pyogenes,Sato,"<a href=""/64140/"">64140</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",IL1RN,TGGTGTACTCTCTGAGGTGCTC,H. sapiens
144
+ cut,S. pyogenes,Xue,"<a href=""/66582/"">66582</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26018130/"">26018130</a>",inverted GFP,GAGCGGCCGCTCGAGTCTAG,A. victoria
145
+ cut,S. pyogenes,Xue,"<a href=""/66583/"">66583</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26018130/"">26018130</a>",inverted GFP,GATATCGAATTCCTGCAGCC,A. victoria
146
+ cut,S. pyogenes,Xue,"<a href=""/66581/"">66581</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26018130/"">26018130</a>",inverted GFP,GTATCGATACCGTCGACCTCG,A. victoria
147
+ cut,S. pyogenes,Xue,"<a href=""/66584/"">66584</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26018130/"">26018130</a>",inverted GFP,GTTGATCCATAACTTCGTAT,A. victoria
148
+ purify,S. pyogenes,Fujii,"<a href=""/61079/"">61079</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23942116/"">23942116</a>",IRF1,CCGGGGGCGCTGGGCTGTCCCGG,H. sapiens
149
+ purify,S. pyogenes,Fujii,"<a href=""/61080/"">61080</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25051498/"">25051498</a>",IRF1,GCGCTTACACTTTAGGAGACACTC,H. sapiens
150
+ cut,S. pyogenes,Sabatini,"<a href=""/70679/"">70679</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26472758/"">26472758</a>",JAK2 amplicon&nbsp;,GGTTTAATGGAAGAGAAGGG,H. sapiens
151
+ cut,S. pyogenes,Seydoux,"<a href=""/66085/"">66085</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25249454/"">25249454</a>",K08F4.2,AATCACTCCCTGTTTGTGT,C. elegans
152
+ cut,S. pyogenes,Seydoux,"<a href=""/66095/"">66095</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25249454/"">25249454</a>",K08F4.2,CACGAGGTGGTATGCGCAG,C. elegans
153
+ cut,S. pyogenes,Seydoux,"<a href=""/66092/"">66092</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25249454/"">25249454</a>",K08F4.2,CGCAGCGGTTTCCAAAATG,C. elegans
154
+ cut,S. pyogenes,Seydoux,"<a href=""/66087/"">66087</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25249454/"">25249454</a>",K08F4.2,GCCTTAACCCAGAATAAGA,C. elegans
155
+ cut,S. pyogenes,Seydoux,"<a href=""/66089/"">66089</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25249454/"">25249454</a>",K08F4.2,TATTAAATGCAGATAACCT,C. elegans
156
+ cut,S. pyogenes,Wolfe,"<a href=""/69238/"">69238</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26480473/"">26480473</a>",KANK3,GCATGGGTGATGTCAATGCC,H. sapiens
157
+ cut,S. pyogenes,Mashimo,"<a href=""/60969/"">60969</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24967838/"">24967838</a>",Kit-1,CATCTGTGCGGCCGTTGGCT,R. norvegicus
158
+ cut,S. pyogenes,Mashimo,"<a href=""/60970/"">60970</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24967838/"">24967838</a>",Kit-2,CTAACGTTCCAGCGCTCGTT,R. norvegicus
159
+ cut,S. pyogenes,Mashimo,"<a href=""/60971/"">60971</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24967838/"">24967838</a>",Kit-2,GTCAAGATGTCATCTTACGG,R. norvegicus
160
+ cut,S. pyogenes,Calarco,"<a href=""/46170/"">46170</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23817069/"">23817069</a>",klp-12,GATCCACAAGTTACAATTGG,C. elegans
161
+ cut,S. pyogenes,Zhang,"<a href=""/60224/"">60224</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25263330/"">25263330</a>","Kras, p53, and Lkb1","multiple, see article",M. musculus
162
+ cut,S. pyogenes,Zhang,"<a href=""/60225/"">60225</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25263330/"">25263330</a>",LacZ,TGCGAATACGCCCACGCGAT,E. coli
163
+ cut,S. pyogenes,Moffat,"<a href=""/74179/"">74179</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26627737/"">26627737</a>",LacZ,CCCGAATCTCTATCGTGCGG,E.coli
164
+ cut,S. pyogenes,Patron,"<a href=""/68256/"">68256</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26616834/"">26616834</a>",lC.GA4a,GTTGAGAGGGGAGCCGGTGA,B. oleracea
165
+ cut,S. pyogenes,Patron,"<a href=""/68255/"">68255</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26616834/"">26616834</a>",lC.GA4a,GTTTTCACTTGCGGCCGGAG,B. oleracea
166
+ cut,S. pyogenes,Jin,"<a href=""/64332/"">64332</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25281382/"">25281382</a>",leu2,AATCACAGCCGAAGCCATTA,S. cerevisiae
167
+ cut,S. pyogenes,Winslow,"<a href=""/66894/"">66894</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26178787/"">26178787</a>",Lkb1,GTGGTGGGCCGCAGTCACAA,M. musculus
168
+ cut,S. pyogenes,Xue,"<a href=""/66586/"">66586</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26018130/"">26018130</a>",Lox-STOP-Lox,GCGTATAGCATACATTATACG,synthetic
169
+ cut,S. pyogenes,Xue,"<a href=""/66585/"">66585</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26018130/"">26018130</a>",Lox-STOP-Lox,GCGTATAGTACACATTATACG,synthetic
170
+ cut,S. pyogenes,Wolfe,"<a href=""/69237/"">69237</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26480473/"">26480473</a>",LRTM2,GCTGGCGGAAGACAGAGTGC,H. sapiens
171
+ cut,S. pyogenes,Moffat,"<a href=""/74190/"">74190</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26627737/"">26627737</a>",Luciferase,ACAACTTTACCGACCGCGCC,
172
+ cut,S. pyogenes,Cate,"<a href=""/60847/"">60847</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25139909/"">25139909</a>",LYP1,CATAATAACGTCCAATAAAT,S. cerevisiae
173
+ cut,S. pyogenes,"Guigo, Johnson","<a href=""/72620/"">72620</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26493208/"">26493208</a>",Malat1,gRNA1: GAACCGGTGGGGCTGCGTCA; gRNA2: GGCAGGAGAGGCCAGTTGCG,H. sapiens
174
+ cut,S. pyogenes,"Guigo, Johnson","<a href=""/72621/"">72621</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26493208/"">26493208</a>",Malat1,gRNA1: GCAACTTCCATTTTCAGTCT; gRNA2: GGAAGCCTCAGCTCGCCTGA,H. sapiens
175
+ cut,S. pyogenes,"Guigo, Johnson","<a href=""/72622/"">72622</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26493208/"">26493208</a>",Malat1,gRNA1:GCTGGGGCTCAGTTGCGTAA; gRNA2:AGGTTTCTAAAACATGACGG,H. sapiens
176
+ cut,S. pyogenes,"Guigo, Johnson","<a href=""/72623/"">72623</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26493208/"">26493208</a>",Malat1,gRNA1:GTTGAGATGAAGCTTCTTCA; gRNA2:TCAACCGTCCCTGCAAGGCT,H. sapiens
177
+ cut,S. pyogenes,"Guigo, Johnson","<a href=""/72624/"">72624</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26493208/"">26493208</a>",Malat1,gRNA1: GAAACCTCGTGTAGCTATCA; gRNA2: AATGTGAAGGACTTTCGTAA,H. sapiens
178
+ nick,S. pyogenes,Hanna,"<a href=""/61514/"">61514</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25569111/"">25569111</a>",Mettl14,GCCGCTCCCGGATCTCCTGC,M. musculus
179
+ nick,S. pyogenes,Hanna,"<a href=""/61515/"">61515</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25569111/"">25569111</a>",Mettl14,GCGGCAGCTCCTAGCTCAGC,M. musculus
180
+ cut,S. pyogenes,Zhao,"<a href=""/69801/"">69801</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26293209/"">26293209</a>",mitf,CTTTCGGATATAATCCACGG,S. scrofa&nbsp;
181
+ cut,S. pyogenes,Chen,"<a href=""/47931/"">47931</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23918387/"">23918387</a>",mitfa,GGTCTCTCGCAGGATGTTGC,D. rerio
182
+ cut,S. pyogenes,Bleris,"<a href=""/62715/"">62715</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25527740/"">25527740</a>",mKate,ATGAGAATCAAGGCGGTCGA,synthetic
183
+ cut,S. pyogenes,Bornhauser,"<a href=""/75167/"">75167</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/27194728/"">27194728</a>",MLKL,ATCCCCGTGGATTCTGCTAA,H. sapiens
184
+ cut,S. pyogenes,Katsanis,"<a href=""/72890/"">72890</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26429889/"">26429889</a>",mmp21,CGGAGCTGATCACTGACA,D. rerio
185
+ visualize,S. pyogenes,Qi,"<a href=""/51025/"">51025</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24360272/"">24360272</a>",MUC4,GTGGCGTGACCTGTGGATGCTG,H. sapiens
186
+ activate,S. pyogenes,Sato,"<a href=""/64138/"">64138</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",MYOD1,TGGCCTCCCTCCCTGCCCGGTAG,H. sapiens
187
+ activate,S. pyogenes,Sato,"<a href=""/64139/"">64139</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",MYOD1,TGGGAGGTTTGGAAAGGGCGTGC,H. sapiens
188
+ activate,S. pyogenes,Sato,"<a href=""/64136/"">64136</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",MYOD1,TGGGCCTGGGCTCCGGGGCGTTT,H. sapiens
189
+ activate,S. pyogenes,Sato,"<a href=""/64137/"">64137</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",MYOD1,TGGGGGCCCCTGCGGCCACCCCG,H. sapiens
190
+ activate,S. pyogenes,Sato,"<a href=""/64156/"">64156</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",NANOG,TGGCATATTCCTGATTTAAAAGT,H. sapiens
191
+ activate,S. pyogenes,Sato,"<a href=""/64153/"">64153</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",NANOG,TGGCGCCAGGAGGGGTGGGTCTA,H. sapiens
192
+ activate,S. pyogenes,Sato,"<a href=""/64154/"">64154</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",NANOG,TGGGCCTTGGTGAGACTGGTAGA,H. sapiens
193
+ activate,S. pyogenes,Sato,"<a href=""/64155/"">64155</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",NANOG,TGGTGTCTTCAGGTTCTGTTGCT,H. sapiens
194
+ interfere,S. pyogenes,Lu,"<a href=""/68897/"">68897</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26918244/"">26918244</a>",NanoLuc,AGCTTACGCCACCCTGTTCC,synthetic
195
+ interfere,S. pyogenes,Lu,"<a href=""/68898/"">68898</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26918244/"">26918244</a>",NanoLuc,GACAGAACGATGCGCTGAAT,synthetic
196
+ interfere,S. pyogenes,Lu,"<a href=""/68895/"">68895</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26918244/"">26918244</a>",NanoLuc,TCACGCTCACACCCAGGTTC,synthetic
197
+ interfere,S. pyogenes,Lu,"<a href=""/68896/"">68896</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26918244/"">26918244</a>",NanoLuc,TTGATCCAAATTATAACCCG,synthetic
198
+ cut,S. pyogenes,Lu,"<a href=""/61270/"">61270</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25240928/"">25240928</a>",NDM-1,GGGCAGTCGCTTCCAACGGTTTGATCGTCA,
199
+ cut,S. pyogenes,Cepko,"<a href=""/69992/"">69992</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25155555/"">25155555</a>",near LoxP sites,CGAAGTTATATTAAGGGTTC,synthetic
200
+ interfere,S. pyogenes,Lu,"<a href=""/68893/"">68893</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26918244/"">26918244</a>",negative control,CTGGAATGAATTGGCCTATG,
201
+ cut,S. pyogenes,Winslow,"<a href=""/66895/"">66895</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26178787/"">26178787</a>",negative control,GCGAGGTATTCGGCTCCGCG,M. musculus
202
+ cut,S. pyogenes,Christiaen,"<a href=""/60006/"">60006</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25336740/"">25336740</a>",negative control,GCTTTGCTACGATCTACATT,C. intestinalis
203
+ cut,S. pyogenes,Bleris,"<a href=""/64955/"">64955</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25527740/"">25527740</a>",negative control,GTCAAGGCACTCTTGCCTA,synthetic
204
+ ,S. pyogenes,Wolfe,"<a href=""/50927/"">50927</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24346702/"">24346702</a>",negative control,GTTCCGCGTTACATAACTTA,H. sapiens
205
+ cut,S. pyogenes,Winslow,"<a href=""/67594/"">67594</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26178787/"">26178787</a>",Neomycin,TCATGGCTGATGCAATGCGG,
206
+ cut,S. pyogenes,Zhang,"<a href=""/60227/"">60227</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25263330/"">25263330</a>",NeuN,TCCGGTTCAGGGACCCCGAC,M. musculus
207
+ activate,S. pyogenes,Sato,"<a href=""/64161/"">64161</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",Neurog2,GTCTCTATCACTGATAGGGA,H. sapiens
208
+ activate,S. pyogenes,Sato,"<a href=""/64160/"">64160</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25619936/"">25619936</a>",Neurog2,GTGAATGATGATAATACGAT,H. sapiens
209
+ methylation,S. pyogenes,Zoldoš,"<a href=""/71830/"">71830</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26969735/"">26969735</a>",Non-targeting,GTAGGCGCGCCGCTCTCTAC,H. sapiens
210
+ cut,S. pyogenes,Huangfu,"<a href=""/66989/"">66989</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26028531/"">26028531</a>",OCT4,CTCCCATGCATTCAAACTG,H. sapiens
211
+ activate,S. pyogenes,Otonkoski,"<a href=""/69537/"">69537</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26352799/"">26352799</a>",OCT4,"multiple, see article",H. sapiens
212
+ cut,N. meningitidis,Thomson,"<a href=""/47870/"">47870</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23940360/"">23940360</a>",OCT4,GTTGTAGCTCCCTTTCTCATTTCG,H. sapiens
213
+ interfere,S. pyogenes,Wolfe,"<a href=""/50922/"">50922</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24346702/"">24346702</a>",Oct4A (POU5F1),GGGGCGCCAGTTGTGTCTCC,H. sapiens
214
+ interfere,S. pyogenes,Wolfe,"<a href=""/50921/"">50921</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24346702/"">24346702</a>",Oct4A (POU5F1),GTGGGACTGGGGAGGGAGAG,H. sapiens
215
+ cut,S. pyogenes,Kim,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26479191/"">26479191</a>",P450,CATATAGTTGGGTCATGGCA,O. sativa
216
+ cut,S. pyogenes,Sherwood,"<a href=""/71483/"">71483</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26527385/"">26527385</a>",Pal1,GCTCTGTGACTAGTCACAGAG,synthetic
217
+ cut,S. pyogenes,Sherwood,"<a href=""/71484/"">71484</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26527385/"">26527385</a>",Pal7,GGCTTAGTACTAGTACTAAGC,synthetic
218
+ cut,S. pyogenes,Zhang,"<a href=""/68466/"">68466</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26145478/"">26145478</a>",PAX6,GATACTGGAGAAGCAGGGGC,H. sapiens
219
+ cut,S. pyogenes,Zhang,"<a href=""/68465/"">68465</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26145478/"">26145478</a>",PAX6,GTAGATTTTGTATGCACTGC,H. sapiens
220
+ interfere,S. pyogenes,Lu,"<a href=""/68900/"">68900</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26918244/"">26918244</a>",PcfiA,AAACAAAACCTCATCAGGCA,
221
+ interfere,S. pyogenes,Lu,"<a href=""/68899/"">68899</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26918244/"">26918244</a>",PcfiA,GAAGCTCACTCCTTAGCACG,
222
+ interfere,S. pyogenes,Lu,"<a href=""/74068/"">74068</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26829286/"">26829286</a>",pck,AGGGCGAGGCGCCGACCAAGAATA,C. glutamicum
223
+ interfere,S. pyogenes,Lu,"<a href=""/74069/"">74069</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26829286/"">26829286</a>",pck,TCCAGTTCAGCAGTTCCTTATTCT,C. glutamicum
224
+ cut,S. pyogenes,Kamoun,"<a href=""/46966/"">46966</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23929340/"">23929340</a>",PDS,GCCGTTAATTTGAGAGTCCA,N. benthamiana
225
+ cut,S. pyogenes,Kamoun,"<a href=""/49772/"">49772</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24112467/"">24112467</a>",PDS1,"multiple, see article",N. benthamiana
226
+ cut,S. pyogenes,Sheen,"<a href=""/52255/"">52255</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23929339/"">23929339</a>",PDS3,GGACTTTTGCCAGCCATGGT,A. thaliana
227
+ interfere,S. pyogenes,Lu,"<a href=""/74066/"">74066</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26829286/"">26829286</a>",pgi,TGACCGATCATTACTCAAACTTCC,C. glutamicum
228
+ interfere,S. pyogenes,Lu,"<a href=""/74067/"">74067</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26829286/"">26829286</a>",pgi,TTGCCTGGAAGTTTGAGTAATGAT,C. glutamicum
229
+ activate,S. pyogenes,Gersbach,"<a href=""/60719/"">60719</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25664691/"">25664691</a>",pGL3-Basic-8x-gRNA-eGFP reporter,AAAGGTCGAGAAACTGCAAA,synthetic
230
+ cut,S. pyogenes,Ward,"<a href=""/61252/"">61252</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25491644/"">25491644</a>",pha-1,ATGAATAACTTGATGAACAT,C. elegans
231
+ cut,S. pyogenes,Kim,"<a href=""//""></a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26479191/"">26479191</a>",PHYB,CACTAGGAGCAACACCCAA,A. thaliana
232
+ cut,S. pyogenes,Wolfe,"<a href=""/69240/"">69240</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26480473/"">26480473</a>",PLXNB2,GGGCCCAACCTAGGGCATGG,H. sapiens
233
+ cut,S. pyogenes,Patron,"<a href=""/68253/"">68253</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26616834/"">26616834</a>",PM19,GCTCTCCACTCTGGGCTCTT,H. vulgare
234
+ cut,S. pyogenes,Patron,"<a href=""/68254/"">68254</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26616834/"">26616834</a>",PM19,GGCTGGCGTTGGTCGTAACA,H. vulgare
235
+ cut,S. pyogenes,Shaw,"<a href=""/79004/"">79004</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26944679/"">26944679</a>",Prkaa1,TTATTGTCACAGGCATATGG,M. musculus
236
+ cut,S. pyogenes,Shaw,"<a href=""/79005/"">79005</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26944679/"">26944679</a>",Prkaa2,ACAGGCATATGGTTGTCCAT,M. musculus
237
+ cut,S. pyogenes,Schmitt-Ulms,"<a href=""/61857/"">61857</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25490046/"">25490046</a>",Prnp,GGTGGAACACCGGTGGAAGC,M. musculus
238
+ cut,S. pyogenes,Schmitt-Ulms,"<a href=""/61856/"">61856</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25490046/"">25490046</a>",Prnp,TTGGCCCCATCCACCGCCAT,M. musculus
239
+ cut,N. meningitidis,Church,"<a href=""/48651/"">48651</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24076762/"">24076762</a>",Protospacer A,TACCATCTCAAGCTTGTTGA,Synthetic
240
+ cut,S. thermophilus,Church,"<a href=""/48653/"">48653</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24076762/"">24076762</a>",Protospacer A,TACCATCTCAAGCTTGTTGA,Synthetic
241
+ cut,T. denticola,Church,"<a href=""/48655/"">48655</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24076762/"">24076762</a>",Protospacer A,TACCATCTCAAGCTTGTTGA,Synthetic
242
+ cut,N. meningitidis,Church,"<a href=""/48652/"">48652</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24076762/"">24076762</a>",Protospacer B,ACTTTAAAAGTATTCGCCAT,Synthetic
243
+ cut,S. thermophilus,Church,"<a href=""/48654/"">48654</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24076762/"">24076762</a>",Protospacer B,ACTTTAAAAGTATTCGCCAT,Synthetic
244
+ cut,T. denticola,Church,"<a href=""/48656/"">48656</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24076762/"">24076762</a>",Protospacer B,ACTTTAAAAGTATTCGCCAT,Synthetic
245
+ cut,S. pyogenes,Moffat,"<a href=""/74184/"">74184</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26627737/"">26627737</a>",PSMB2,ATGTTCTTGTCGCCTCCGAC,H. sapiens
246
+ cut,S. pyogenes,Moffat,"<a href=""/74185/"">74185</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26627737/"">26627737</a>",PSMB2,AATATTGTCCAGATGAAGGA,H. sapiens
247
+ cut,S. pyogenes,Moffat,"<a href=""/74180/"">74180</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26627737/"">26627737</a>",PSMD1,TGTGCGCTACGGAGCTGCAA,H. sapiens
248
+ cut,S. pyogenes,Moffat,"<a href=""/74181/"">74181</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26627737/"">26627737</a>",PSMD1,ACCAGAGCCACAATAAGCCA,H. sapiens
249
+ cut,S. pyogenes,Jacks,"<a href=""/59909/"">59909</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25119044/"">25119044</a>",Pten,AGATCGTTAGCAGAAACAAA,M. musculus
250
+ cut,S. pyogenes,Xue,"<a href=""/66588/"">66588</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26018130/"">26018130</a>",Pten,GCTGTAGTAATATCTGCTAT,M. musculus
251
+ cut,S. pyogenes,Xue,"<a href=""/66587/"">66587</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26018130/"">26018130</a>",Pten,GTTTCATAGCGGCCACGAAGT,M. musculus
252
+ interfere,S. pyogenes,Lu,"<a href=""/74070/"">74070</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26829286/"">26829286</a>",pyk,AGATTGTATGTACCCTAGGCCCAG,C. glutamicum
253
+ interfere,S. pyogenes,Lu,"<a href=""/74072/"">74072</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26829286/"">26829286</a>",pyk,ATTCCATCTGCACTAGCCACCGCT,C. glutamicum
254
+ tag,S. pyogenes,Mendenhall,"<a href=""/64057/"">64057</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26355004/"">26355004</a>",RAD21,CCAAGGTTCCATATTATATAAGG,H. sapiens
255
+ cut,S. pyogenes,Fire,"<a href=""/59927/"">59927</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25161212/"">25161212</a>",rde-1(D718),TGCCATTAACTATGTATGT,C. elegans
256
+ cut,S. pyogenes,Fire,"<a href=""/59928/"">59928</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25161212/"">25161212</a>",rde-1(D801),GATATTGTAGTCTATCGAGA,C. elegans
257
+ cut,S. pyogenes,Fire,"<a href=""/59929/"">59929</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25161212/"">25161212</a>",rde-1(H974),GATAAATGAGCATAATGAAC,C. elegans
258
+ interfere,S. pyogenes,Lu,"<a href=""/74075/"">74075</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26829286/"">26829286</a>",rfp,AAGTTCGTATGGAAGGTTCCGTTAA,
259
+ cut,S. pyogenes,Joung,"<a href=""/42246/"">42246</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23360964/"">23360964</a>",rgs4,GGAGAAGGTGAAGGACACTG,D. rerio
260
+ cut,S. pyogenes,Bornhauser,"<a href=""/75165/"">75165</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/27194728/"">27194728</a>",RIP3,TACACGAGTGATGGTTCGGT,H. sapiens
261
+ cut,S. pyogenes,Bornhauser,"<a href=""/75163/"">75163</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/27194728/"">27194728</a>",RIPK1,GCTCTGCTGGGAAGCGAATC,H. sapiens
262
+ cut,S. pyogenes,Joung,"<a href=""/47509/"">47509</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23792628/"">23792628</a>",RNF2,GTCATCTTAGTCATTACCTG,H. sapiens
263
+ cut,S. pyogenes,Fire,"<a href=""/59930/"">59930</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25161212/"">25161212</a>",rol-6(su1006),GTGAGACGTCAACAATATGG,C. elegans
264
+ cut,S. pyogenes,Kuhn,"<a href=""/64216/"">64216</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25803306/"">25803306</a>",Rosa26,ACTCCAGTCTTTCTAGAAGA,M.musculus
265
+ cut,S. pyogenes,Marraffini,"<a href=""/44505/"">44505</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23360965/"">23360965</a>",rpsL,AAAAAACCGAACTCCGCGCTGCGTAAAGTA,E. coli
266
+ interfere,S. pyogenes,Voigt,"<a href=""/62285/"">62285</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25422271/"">25422271</a>",scramble,AACCCCTGATTGTATCCGCA,synthetic
267
+ cut,S. pyogenes,Chen,"<a href=""/47930/"">47930</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23918387/"">23918387</a>",slc24a5 (golden),GGTCTCTCGCAGGATGTTGC,D. rerio
268
+ cut,S. pyogenes,Hanna,"<a href=""/59725/"">59725</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25543152/"">25543152</a>",SOX17,GCCCAGCCCGGCCATCACCG,H. sapiens
269
+ activate,S. pyogenes,Wolfe,"<a href=""/50925/"">50925</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24346702/"">24346702</a>",Sox17,GCTCCGGCTAGTTTTCCCGG,H. sapiens
270
+ activate,S. pyogenes,Wolfe,"<a href=""/50924/"">50924</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24346702/"">24346702</a>",Sox17,GGAGGGGCAAGGGGCGGGCG,H. sapiens
271
+ activate,S. pyogenes,Wolfe,"<a href=""/50926/"">50926</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24346702/"">24346702</a>",Sox17,GGGCAAGTACGTCGATTCCA,H. sapiens
272
+ activate,S. pyogenes,Wolfe,"<a href=""/50923/"">50923</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24346702/"">24346702</a>",Sox17,GGGCGTGGGCCTAACGACGC,H. sapiens
273
+ cut,S. pyogenes,Fire,"<a href=""/59935/"">59935</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25161212/"">25161212</a>",sqt-1,GGAAGGACATAGTTGTCAT,C. elegans
274
+ cut,S. pyogenes,Fire,"<a href=""/60212/"">60212</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25161212/"">25161212</a>",sqt-1,TGTGGAGTTGGGGTAGCGT,C. elegans
275
+ activate/interfere,S. pyogenes,Qi,"<a href=""/62338/"">62338</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25533786/"">25533786</a>",sv40 promoter,CATACTTCTGCCTGCTGGGGAGCCTG,synthetic
276
+ scaffold,S. pyogenes,Qi &amp; Lim,"<a href=""/62340/"">62340</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25533786/"">25533786</a>",SV40.NT1,GAATAGCTCAGAGGCCGAGG,H. sapiens
277
+ cut,S. pyogenes,Seydoux,"<a href=""/66100/"">66100</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25249454/"">25249454</a>",swan-2,ACAAATTGATATCCAATCA,C. elegans
278
+ cut,S. pyogenes,Seydoux,"<a href=""/66099/"">66099</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25249454/"">25249454</a>",swan-2,TGAAGAAAGTTATACTCGA,C. elegans
279
+ cut,S. pyogenes,Hanna,"<a href=""/59726/"">59726</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25543152/"">25543152</a>",T (BRACHYURY),CACGCGCAGTTCGCGCTCTG,H. sapiens
280
+ cut,S. pyogenes,"Guigo, Johnson","<a href=""/72627/"">72627</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26493208/"">26493208</a>",TCRC,gRNA1:GGGGAGCGGGAAAGCGGTCG; gRNA2:AACTGACCTTCAGGCCCGTA,H. sapiens
281
+ cut,N. meningitidis,Thomson,"<a href=""/47869/"">47869</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23940360/"">23940360</a>",tdtomato,CGAAATGAGAAAGGGAGCTACAAC,Synthetic
282
+ scaffold,S. pyogenes,Qi &amp; Lim,"<a href=""/62320/"">62320</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25533786/"">25533786</a>",TEF,TTGATATTTAAGTTAATAAA,S. cerevisiae
283
+ interfere,S. pyogenes,Weissman,"<a href=""/46922/"">46922</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23849981/"">23849981</a>",TEF1,TTGATATTTAAGTTAATAAA,S. cerevisiae
284
+ visualize,S. pyogenes,Qi,"<a href=""/51024/"">51024</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24360272/"">24360272</a>",telomeres,GTTAGGGTTAGGGTTAGGGTTA,H. sapiens
285
+ scaffold,S. pyogenes,Qi &amp; Lim,"<a href=""/62313/"">62313</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25533786/"">25533786</a>",TET,ACTTTTCTCTATCACTGATA,S. cerevisiae
286
+ interfere,S. pyogenes,Weissman,"<a href=""/46923/"">46923</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23849981/"">23849981</a>",TET promoter,TATCAGTGATAGAGAAAAGT,
287
+ activate/interfere,S. pyogenes,Qi,"<a href=""/62327/"">62327</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25533786/"">25533786</a>",Tet3G,GTACGTTCTCTATCACTGATA,synthetic
288
+ cut,S. pyogenes,Shaw,"<a href=""/79006/"">79006</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26944679/"">26944679</a>",Tfeb,AGCACTGTTGCCGGCCGAGG,M. musculus
289
+ RNA targeting,S. pyogenes,Yeo,"<a href=""/74709/"">74709</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26997482/"">26997482</a>",TFRC,GCACUGACCAGAUAAGAAUG,H. sapiens
290
+ cut,S. pyogenes,"Guigo, Johnson","<a href=""/72626/"">72626</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26493208/"">26493208</a>",TFRC,"gRNA1:GCAGCCTCAGAAATACAAAA, gRNA2CGGGATATCGGGTGGCGGCT",H. sapiens
291
+ cut,S. pyogenes,Wolfe,"<a href=""/69239/"">69239</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26480473/"">26480473</a>",TGM2,CCTGGACCCAACGCCCCAGG,H. sapiens
292
+ cut,S. pyogenes,Sibley,"<a href=""/59855/"">59855</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25480939/"">25480939</a>",TGME49_290860,ATTGGTCTGACAGCGATGTG,T. gondii
293
+ cut,S. pyogenes,Joung,"<a href=""/42247/"">42247</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23360964/"">23360964</a>",th,GGATGCGCGTAAGGAGCGCG,D. rerio
294
+ cut,S. pyogenes,Du,"<a href=""/65565/"">65565</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25849248/"">25849248</a>",th,GGGTTGTTACACTCATAAAG,D. rerio
295
+ cut,S. pyogenes,Joung,"<a href=""/42248/"">42248</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23360964/"">23360964</a>",tia1l,GGTATGTCGGGAACCTCTCC,D. rerio
296
+ cut,S. pyogenes,Joung,"<a href=""/42249/"">42249</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23360964/"">23360964</a>",tph1a,GGGAAAACACAACCGCAGCC,D. rerio
297
+ scaffold,S. pyogenes,Qi &amp; Lim,"<a href=""/62325/"">62325</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25533786/"">25533786</a>",TRE3G,GTACGTTCTCTATCACTGATA,H. sapiens
298
+ cut,S. pyogenes,Jin,"<a href=""/64331/"">64331</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25281382/"">25281382</a>",trp1,GTCAATTGTTCTCTTTCTAT,S. cerevisiae
299
+ cut,S. pyogenes,Jacks,"<a href=""/59910/"">59910</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25119044/"">25119044</a>",Trp53,CCTCGAGCTCCCTCTGAGCC,M. musculus
300
+ cut,S. pyogenes,Wolfe,"<a href=""/69234/"">69234</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26480473/"">26480473</a>",TS2,GACCCCCTCCACCCCGCCTC,H. sapiens
301
+ cut,S. pyogenes,Wolfe,"<a href=""/69235/"">69235</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26480473/"">26480473</a>",TS3,GGTGAGTGAGTGTGTGCGTG,H. sapiens
302
+ cut,S. pyogenes,Wolfe,"<a href=""/69236/"">69236</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26480473/"">26480473</a>",TS4,GAGTCCGAGCAGAAGAAGAA,H. sapiens
303
+ cut,S. pyogenes,Goldstein,"<a href=""/47550/"">47550</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23995389/"">23995389</a>",ttTi5605 Mos1 insertion site,ATATCAGTCTGTTTCGTAA,C. elegans
304
+ cut,S. pyogenes,Chen,"<a href=""/46761/"">46761</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23918387/"">23918387</a>",tyr,CCCCAGAAGTCCTCCAGTCC,D. rerio
305
+ cut,S. pyogenes,Chen,"<a href=""/64250/"">64250</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25855067/"">25855067</a>",tyr,GGACTGGAGGACTTCTGGGG,D. rerio
306
+ cut,S. pyogenes,Mashimo,"<a href=""/60966/"">60966</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24967838/"">24967838</a>",Tyr (albino),TTTCCAGGATTATGTAATAG,R. norvegicus
307
+ cut,S. pyogenes,Mashimo,"<a href=""/60967/"">60967</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24967838/"">24967838</a>",Tyr (wild type),TTTCCAGGATTACGTAATAG,R. norvegicus
308
+ cut,S. pyogenes,"Guigo, Johnson","<a href=""/72628/"">72628</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/26493208/"">26493208</a>",UCA1,gRNA1:GGTTTCCTTTTAGATGACGG; gRNA2:TCTGAAAAGAGAGTCAGCGA,H. sapiens
309
+ cut,S. pyogenes,Fire,"<a href=""/59932/"">59932</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25161212/"">25161212</a>",unc-109(n499),GGAACTCGTGTCAAAACAAC,C. elegans
310
+ cut,S. pyogenes,Calarco,"<a href=""/46169/"">46169</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23817069/"">23817069</a>",unc-119,GAATTTTCTGAAATTAAAGA,C. elegans
311
+ cut,S. pyogenes,Mello,"<a href=""/58202/"">58202</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24879462/"">24879462</a>",unc-22,GAACCCGTTGCCGAATACAC,C. elegans
312
+ cut,S. pyogenes,Fire,"<a href=""/59931/"">59931</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25161212/"">25161212</a>",unc-58(e665),TCCACGCACATGGTCACTA,C. elegans
313
+ cut,S. pyogenes,Sibley,"<a href=""/54467/"">54467</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24825012/"">24825012</a>",UPRT,GGCGTCTCGATTGTGAGAGC,Toxoplasma gondii
314
+ cut,S. pyogenes,Jin,"<a href=""/64330/"">64330</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25281382/"">25281382</a>",ura3,GAGTAAAAAATTGTACTTGG,S. cerevisiae
315
+ cut,S. pyogenes,Ye,"<a href=""/61812/"">61812</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24424410/"">24424410</a>",USP13,GCCGCCCGGCATGCCGAACA,H. sapiens
316
+ cut,S. pyogenes,Joung,"<a href=""/47506/"">47506</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23792628/"">23792628</a>",VEGF,GACCCCCTCCACCCCGCCTC,H. sapiens
317
+ cut,S. pyogenes,Joung,"<a href=""/47505/"">47505</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23792628/"">23792628</a>",VEGF,GGGTGGGGGGAGTTTGCTCC,H. sapiens
318
+ cut,S. pyogenes,Joung,"<a href=""/47507/"">47507</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/23792628/"">23792628</a>",VEGF,GGTGAGTGAGTGTGTGCGTG,H. sapiens
319
+ interfere,S. pyogenes,Voigt,"<a href=""/62286/"">62286</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25422271/"">25422271</a>",VR,TGCGCTCGGTCGTTCGGCTG,synthetic
320
+ nick,S. pyogenes,Yang,"<a href=""/73228/"">73228</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/27213844/"">27213844</a>",xylR,CGAGTTAGACATAATAGTGA,C. beijerinckii
321
+ cut,S. pyogenes,Ward,"<a href=""/61250/"">61250</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/25491644/"">25491644</a>",Y61A9LA.1,GGATGGATGTGTAGTCAATT,C. elegans
322
+ cut,S. pyogenes,Liu,"<a href=""/49331/"">49331</a>","<a href=""https://www.ncbi.nlm.nih.gov/pubmed/24326186/"">24326186</a>",yellow,GGTTTTGGACACTGGAACCG,D. melanogaster
BioScientist/agent_system/engines/v1_executor_backup/know_how/sgRNA_design_guide.md ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # sgRNA Design Guide: Three-Tiered Approach
2
+
3
+ ---
4
+
5
+ ## Metadata
6
+
7
+ **Short Description**: Comprehensive guide for finding or designing sgRNAs using validated sequences, CRISPick datasets, or de novo design tools.
8
+
9
+ **Authors**: Biomni Team
10
+
11
+ **Version**: 1.0
12
+
13
+ **Last Updated**: November 2025
14
+
15
+ **License**: CC BY 4.0
16
+
17
+ **Commercial Use**: ✅ Allowed
18
+
19
+ ## Citations and Acknowledgments
20
+
21
+ ### If you use validated sgRNAs from our database (Option 1):
22
+ - **Database Source**: Addgene (https://www.addgene.org)
23
+ - **Citation**: Always cite the original publication associated with each sgRNA using the PubMed ID provided in the database
24
+ - **Acknowledgment**: "Validated sgRNA sequences obtained from Addgene (https://www.addgene.org/crispr/reference/grna-sequence/)"
25
+
26
+ ### If you use CRISPick designs (Option 2):
27
+ - **Acknowledgment Statement**: "Guide designs provided by the CRISPick web tool of the GPP at the Broad Institute"
28
+ - **Citation for Cas9 designs (SpCas9, SaCas9)**: Sanson KR, et al. Optimized libraries for CRISPR-Cas9 genetic screens with multiple modalities. Nat Commun. 2018;9(1):5416. PMID: 30575746
29
+ - **Citation for Cas12a designs (AsCas12a, enAsCas12a)**: DeWeirdt PC, et al. Optimization of AsCas12a for combinatorial genetic screens in human cells. Nat Biotechnol. 2021;39(1):94-104. PMID: 32661438
30
+ - Note: This paper describes enAsCas12a optimization; specify which variant you used in your methods
31
+
32
+ ---
33
+
34
+ ## Overview
35
+
36
+ This guide provides a three-tiered approach to sgRNA design, prioritizing validated sequences before moving to computational predictions. Always start with Option 1 and proceed to subsequent options only if needed.
37
+
38
+
39
+
40
+ ## Option 1: Search Validated sgRNA Sequences (Recommended First)
41
+
42
+ ### 1.1 Search for Validated sgRNAs
43
+
44
+ **IMPORTANT**: You MUST complete BOTH Method 1 AND Method 2 before proceeding to Option 2. Do not skip Method 2 even if Method 1 finds no results.
45
+
46
+ #### Method 1: Search Our Database (Fastest)
47
+
48
+ We maintain a curated database of 300+ validated sgRNA sequences from Addgene with experimental evidence.
49
+
50
+ **Location**: `biomni/know_how/resource/addgene_grna_sequences.csv`
51
+
52
+ **Search the database**:
53
+ ```python
54
+ import pandas as pd
55
+
56
+ # Load the database
57
+ df = pd.read_csv('addgene_grna_sequences.csv')
58
+
59
+ # Search for your gene
60
+ gene_name = "TP53"
61
+ results = df[df['Target_Gene'].str.upper() == gene_name.upper()]
62
+
63
+ # Filter by species and application
64
+ results_filtered = results[
65
+ (results['Target_Species'] == 'H. sapiens') &
66
+ (results['Application'] == 'cut') # or 'activate', 'RNA targeting'
67
+ ]
68
+
69
+ # Display results with references
70
+ print(results_filtered[['Target_Gene', 'Target_Sequence',
71
+ 'Plasmid_ID', 'PubMed_ID', 'Depositor']])
72
+ ```
73
+
74
+ **Database columns**:
75
+ - `Target_Gene`: Gene symbol
76
+ - `Target_Species`: Organism (H. sapiens, M. musculus, etc.)
77
+ - `Target_Sequence`: 20bp sgRNA sequence (5' to 3')
78
+ - `Application`: cut (knockout), activate (CRISPRa), RNA targeting (CRISPRi)
79
+ - `Cas9_Species`: S. pyogenes, S. aureus, etc.
80
+ - `Plasmid_ID`: Addgene plasmid number
81
+ - `Plasmid_URL`: Direct link to plasmid page
82
+ - `PubMed_ID`: **Publication reference** (cite this in your work)
83
+ - `PubMed_URL`: Direct link to paper
84
+ - `Depositor`: Research lab that contributed the sequence
85
+
86
+ #### Method 2: Advanced Web Search (REQUIRED - Do Not Skip)
87
+
88
+ **CRITICAL**: Even if Method 1 found no results, you MUST perform this literature search before moving to Option 2. Many validated sgRNAs are published in literature but not in the Addgene database.
89
+
90
+ Use `advanced_web_search_claude` from `biomni.tool.literature` to find validated sgRNAs from literature and databases:
91
+
92
+ ```python
93
+ from biomni.tool.literature import advanced_web_search_claude
94
+
95
+ # Example usage
96
+ results = advanced_web_search_claude("sgRNA TP53 validated H. sapiens experimental")
97
+ ```
98
+
99
+ **Search queries to try (use multiple):**
100
+ ```
101
+ "sgRNA" OR "guide RNA" "[GENE_NAME]" validated experimental
102
+ "CRISPR knockout" "[GENE_NAME]" sgRNA sequence validated
103
+ "[GENE_NAME]" sgRNA "cutting efficiency" OR "on-target"
104
+ "[GENE_NAME]" "guide sequence" CRISPR validated
105
+ ```
106
+
107
+ **Example for TP53:**
108
+ ```
109
+ "sgRNA" "TP53" validated "H. sapiens" experimental
110
+ "CRISPR knockout" "TP53" guide sequence validated
111
+ ```
112
+
113
+ **What to search for in results:**
114
+ - Published papers with validated sgRNA sequences
115
+ - Supplementary materials containing sgRNA sequences
116
+ - Other CRISPR databases (e.g., GenScript, Horizon Discovery)
117
+ - Laboratory protocols with specific sgRNA sequences
118
+
119
+ **IMPORTANT**: Spend adequate time searching literature. Look through at least the first 10-15 search results and check supplementary materials of relevant papers.
120
+
121
+ #### What to Do with Results:
122
+
123
+ ✅ **If you find matching sgRNAs (from either method):**
124
+ 1. **Record the sgRNA sequence** (20bp target sequence)
125
+ 2. **Note the reference**:
126
+ - From database: Use `PubMed_ID` to cite the original paper
127
+ - From web search: Record the publication DOI/PubMed ID
128
+ 3. **Record validation details**: Cell line, cutting efficiency, any reported off-targets
129
+
130
+
131
+ **Example result format:**
132
+ ```
133
+ Gene: TP53
134
+ sgRNA sequence: GAGGTTGTGAGGCGCTGCCC
135
+ Species: H. sapiens (human)
136
+ Application: Knockout (cut)
137
+ Reference: PubMed ID 24336569 (Ran et al., 2013)
138
+ Validation: Tested in HEK293T cells, 85% cutting efficiency
139
+ ```
140
+
141
+ ❌ **If no matches found in BOTH Method 1 AND Method 2:**
142
+ Only then proceed to **Option 2: Download CRISPick Dataset**
143
+
144
+
145
+
146
+ ## Option 2: Download Pre-Computed sgRNAs from CRISPick
147
+
148
+ ### When to Use This Option?
149
+ - No validated sgRNAs found in Addgene
150
+ - Need comprehensive coverage of a gene
151
+ - Want multiple sgRNA options with predicted scores
152
+ - Working with genome-scale screening
153
+
154
+ ### 2.1 Overview of CRISPick
155
+
156
+ **CRISPick** (from Broad Institute GPP) provides pre-computed sgRNA designs for entire genomes with 238 available datasets covering:
157
+ - Human (GRCh38, GRCh37)
158
+ - Mouse (GRCm38, GRCm39)
159
+ - Dog, Cow, Monkey, and other model organisms
160
+ - Multiple Cas enzymes (SpCas9, SaCas9, AsCas12a, enAsCas12a)
161
+ - **IMPORTANT**: AsCas12a and enAsCas12a are DIFFERENT enzymes
162
+ - **AsCas12a**: Wild-type Acidaminococcus sp. Cas12a
163
+ - **enAsCas12a**: Enhanced variant with improved activity
164
+ - **Critical**: sgRNAs designed for enAsCas12a may NOT work with wild-type AsCas12a
165
+ - Always match the dataset to your specific Cas12a variant
166
+ - Different applications (knockout, activation, inhibition)
167
+
168
+ ### 2.2 Find the Download Link
169
+
170
+ **All 238 download links are available in**: `biomni/know_how/resource/CRISPick_download_links.txt`
171
+
172
+ #### Step 1: Understand File Naming Convention
173
+
174
+ Files are named: `sgRNA_design_{TAXID}_{GENOME}_{CAS}_{APPLICATION}_{ALGORITHM}_{SOURCE}_{DATE}.txt.gz`
175
+
176
+ **Common datasets:**
177
+
178
+ | Organism | Genome | Cas9 | Application | Search Pattern |
179
+ |-|--||-|-|
180
+ | Human | GRCh38 | SpCas9 | Knockout | `9606_GRCh38_SpyoCas9_CRISPRko` |
181
+ | Human | GRCh38 | SpCas9 | Activation | `9606_GRCh38_SpyoCas9_CRISPRa` |
182
+ | Human | GRCh38 | SaCas9 | Knockout | `9606_GRCh38_SaurCas9_CRISPRko` |
183
+ | Mouse | GRCm38 | SpCas9 | Knockout | `10090_GRCm38_SpyoCas9_CRISPRko` |
184
+ | Mouse | GRCm38 | SpCas9 | Activation | `10090_GRCm38_SpyoCas9_CRISPRa` |
185
+
186
+ **Key components:**
187
+ - **TAXID**: `9606` (Human), `10090` (Mouse), `9615` (Dog), `9913` (Cow)
188
+ - **CAS**:
189
+ - `SpyoCas9` (SpCas9, NGG PAM)
190
+ - `SaurCas9` (SaCas9, NNGRRT PAM)
191
+ - `AsCas12a` (Wild-type Cas12a, TTTV PAM)
192
+ - `enAsCas12a` (Enhanced Cas12a, TTTV PAM)
193
+ - **WARNING**: Do NOT use AsCas12a datasets if you have enAsCas12a, and vice versa
194
+ - **APPLICATION**: `CRISPRko` (knockout), `CRISPRa` (activation), `CRISPRi` (inhibition)
195
+
196
+ #### Step 2: Find Your Download URL
197
+
198
+ ```bash
199
+ # Search the download links file
200
+ grep "9606_GRCh38_SpyoCas9_CRISPRko" biomni/know_how/resource/CRISPick_download_links.txt
201
+
202
+ # Or for mouse
203
+ grep "10090_GRCm38_SpyoCas9_CRISPRko" biomni/know_how/resource/CRISPick_download_links.txt
204
+ ```
205
+
206
+ #### Step 3: Download and Extract
207
+
208
+ ```bash
209
+ # Copy the URL from download_links.txt, then:
210
+ wget [PASTE_URL_HERE]
211
+
212
+ # Extract the file
213
+ gunzip sgRNA_design_*.txt.gz
214
+ ```
215
+
216
+ **File sizes**: Knockout (300-700 MB), Activation (50-100 MB), Summary files (1-3 MB)
217
+
218
+ ### 2.4 Understanding the File Format
219
+
220
+ The `.txt` file is tab-delimited. Column names differ between knockout and activation/inhibition datasets.
221
+
222
+ **Essential Columns (All files):**
223
+ - **sgRNA Sequence**: The 20bp guide RNA sequence (5' to 3')
224
+ - **Target Gene Symbol**: Gene name (e.g., "TP53", "BRCA1")
225
+ - **Combined Rank**: Overall ranking (lower = better) - **Use this by default**
226
+ - **On-Target Rank**: Ranking by efficiency only (lower = better)
227
+ - **Off-Target Rank**: Ranking by specificity only (lower = better)
228
+ - **PAM Sequence**: The PAM sequence (e.g., "AGG", "TGG")
229
+
230
+ **Knockout-specific columns:**
231
+ - **sgRNA Cut Position (1-based)**: Genomic coordinate of cut site
232
+ - **Exon Number**: Which exon is targeted
233
+ - **Target Cut %**: Percentage of protein affected
234
+
235
+ **Activation/Inhibition-specific columns:**
236
+ - **sgRNA 'Cut' Position**: Position relative to gene
237
+ - **sgRNA 'Cut' Site TSS Offset**: Distance from transcription start site (bp)
238
+ - **DHS Score**: DNase hypersensitivity score (for CRISPRa)
239
+
240
+ ### 2.5 Extract and Select sgRNAs
241
+
242
+ #### Step 1: Load Data and Filter for Your Gene
243
+
244
+ ```python
245
+ import pandas as pd
246
+
247
+ # Load the dataset
248
+ df = pd.read_csv('sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRko_*.txt',
249
+ sep='\t', low_memory=False)
250
+
251
+ # Filter for your gene
252
+ gene_name = "TP53"
253
+ gene_sgrnas = df[df['Target Gene Symbol'] == gene_name].copy()
254
+
255
+ print(f"Found {len(gene_sgrnas)} sgRNAs for {gene_name}")
256
+ ```
257
+
258
+ #### Step 2: Select Top sgRNAs
259
+
260
+ **Default: Use Combined Rank (balances efficiency and specificity)**
261
+ ```python
262
+ # Sort by Combined Rank (lower is better)
263
+ top_sgrnas = gene_sgrnas.nsmallest(10, 'Combined Rank')
264
+
265
+ print(top_sgrnas[['sgRNA Sequence', 'Combined Rank',
266
+ 'Exon Number', 'sgRNA Cut Position (1-based)']])
267
+ ```
268
+
269
+ **Option A: Prioritize On-Target Efficiency**
270
+ ```python
271
+ # Sort by On-Target Rank (for maximum cutting efficiency)
272
+ efficient_sgrnas = gene_sgrnas.nsmallest(10, 'On-Target Rank')
273
+ ```
274
+
275
+ **Option B: Prioritize Off-Target Specificity**
276
+ ```python
277
+ # Sort by Off-Target Rank (for maximum specificity)
278
+ specific_sgrnas = gene_sgrnas.nsmallest(10, 'Off-Target Rank')
279
+ ```
280
+
281
+ #### Step 3: Filter by Custom Criteria (Optional)
282
+
283
+ **Filter by Exon Number:**
284
+ ```python
285
+ # Target specific exon (e.g., exon 5)
286
+ exon5_sgrnas = gene_sgrnas[gene_sgrnas['Exon Number'] == 5]
287
+ top_exon5 = exon5_sgrnas.nsmallest(5, 'Combined Rank')
288
+ ```
289
+
290
+ **Filter by Genomic Position:**
291
+ ```python
292
+ # Target specific genomic range
293
+ position_filtered = gene_sgrnas[
294
+ (gene_sgrnas['sgRNA Cut Position (1-based)'] >= 7572000) &
295
+ (gene_sgrnas['sgRNA Cut Position (1-based)'] <= 7575000)
296
+ ]
297
+ ```
298
+
299
+ **Target Early Exons for Knockout:**
300
+ ```python
301
+ # Get sgRNAs from first 3 exons
302
+ early_exons = gene_sgrnas[gene_sgrnas['Exon Number'] <= 3]
303
+ top_early = early_exons.nsmallest(10, 'Combined Rank')
304
+ ```
305
+
306
+ **Filter by Target Cut Percentage:**
307
+ ```python
308
+ # Target sgRNAs that affect significant portion of protein
309
+ high_impact = gene_sgrnas[gene_sgrnas['Target Cut %'] <= 50] # Cut in first 50%
310
+ top_high_impact = high_impact.nsmallest(10, 'Combined Rank')
311
+ ```
312
+
313
+ #### Step 4: Select Multiple sgRNAs for Validation
314
+
315
+ ```python
316
+ # Get top 4 sgRNAs from different exons for redundancy
317
+ final_selection = gene_sgrnas.sort_values('Combined Rank').groupby('Exon Number').head(1).head(4)
318
+
319
+ # Save results
320
+ final_selection.to_csv(f'{gene_name}_selected_sgRNAs.csv', index=False)
321
+
322
+ print("\nSelected sgRNAs:")
323
+ print(final_selection[['sgRNA Sequence', 'Exon Number', 'Combined Rank']])
324
+ ```
325
+
326
+ ### 2.6 What to Do with Results
327
+
328
+ ✅ **Once you have selected sgRNAs:**
329
+ 1. Choose **3-4 sgRNAs** (use Combined_Rank by default)
330
+
331
+ ❌ **If dataset doesn't cover your gene or organism:**
332
+ Proceed to **Option 3: De Novo sgRNA Design**
333
+
334
+
335
+
336
+ ## Option 3: General sgRNA Design Guidelines (Last Resort)
337
+
338
+ ### When to Use This Option?
339
+ - Gene not covered in CRISPick datasets
340
+ - Non-model organism
341
+ - Custom design requirements
342
+
343
+ ### General Design Rules
344
+
345
+ #### Essential Requirements:
346
+ 1. **Length**:
347
+ - 20 bp for SpCas9 and SaCas9
348
+ - 23-25 bp for Cas12a variants (AsCas12a, enAsCas12a)
349
+ 2. **PAM sequence**:
350
+ - **SpCas9**: Requires **NGG** immediately after target (3' end)
351
+ - **SaCas9**: Requires **NNGRRT** immediately after target (3' end)
352
+ - **AsCas12a** (wild-type): Requires **TTTV** before target (5' end)
353
+ - **enAsCas12a** (enhanced): Requires **TTTV** before target (5' end)
354
+ - **CRITICAL**: Guides designed for enAsCas12a may not work with wild-type AsCas12a due to different activity profiles
355
+ 3. **GC content**: 40-60% is optimal
356
+ 4. **Avoid**:
357
+ - TTTT sequences (terminates transcription)
358
+ - Long runs of same nucleotide (>4 repeats)
359
+
360
+ #### Target Location:
361
+ - **For knockout**: Target early exons (first 50% of gene)
362
+ - **For activation**: Target -200 to +1 bp from transcription start site (TSS)
363
+ - **For inhibition**: Target -50 to +300 bp from TSS
364
+
365
+ #### Best Practices:
366
+ - **Test 3-4 different sgRNAs** per target gene
367
+ - Select sgRNAs with high efficiency scores (>0.5) and minimal off-targets
368
+ - Validate experimentally with Sanger sequencing
369
+
370
+
371
+
372
+ ## Quick Start Examples
373
+
374
+ ### Example 1: Knockout TP53 in Human Cells
375
+
376
+ **Step 1**: Check Addgene
377
+ ```python
378
+ df = pd.read_csv('addgene_grna_sequences.csv')
379
+ tp53_results = df[(df['Target_Gene'] == 'TP53') &
380
+ (df['Target_Species'] == 'H. sapiens') &
381
+ (df['Application'] == 'cut')]
382
+ # Result: Found 0 entries → Proceed to Option 2
383
+ ```
384
+
385
+ **Step 2**: Download CRISPick dataset
386
+ ```bash
387
+ # Download human GRCh38 SpCas9 knockout dataset
388
+ wget https://portals.broadinstitute.org/gppx/public/sgrna_design/api/downloads/\
389
+ sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRko_RS3seq-Chen2013+RS3target_NCBI_20241104.txt.gz
390
+
391
+ gunzip sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRko_*.txt.gz
392
+ ```
393
+
394
+ **Step 3**: Extract TP53 sgRNAs
395
+ ```python
396
+ df = pd.read_csv('sgRNA_design_9606_GRCh38_SpyoCas9_CRISPRko_*.txt', sep='\t')
397
+ tp53 = df[df['Gene_Symbol'] == 'TP53']
398
+ top_sgrnas = tp53[
399
+ (tp53['sgRNA_score'] > 0.6) &
400
+ (tp53['Off_target_stringency'] > 0.5)
401
+ ].sort_values('sgRNA_score', ascending=False).head(4)
402
+
403
+ print(top_sgrnas[['sgRNA_sequence', 'sgRNA_score', 'Exon_ID']])
404
+ ```
405
+
406
+ ### Example 2: Activate OCT4 in Human iPSCs
407
+
408
+ **Step 1**: Check Addgene
409
+ ```python
410
+ oct4_results = df[(df['Target_Gene'] == 'OCT4') &
411
+ (df['Application'] == 'activate')]
412
+ # Found 1 validated sgRNA!
413
+ print(oct4_results['Target_Sequence'].values[0])
414
+ # Use this sequence ✅
415
+ ```
416
+
417
+
418
+
419
+ **Remember**: Always start with validated sequences (Option 1), then move to pre-computed designs (Option 2), and only use de novo design (Option 3) when necessary. Testing 3-4 sgRNAs per gene is standard practice regardless of prediction scores.
BioScientist/agent_system/engines/v1_executor_backup/know_how/single_cell_annotation.md ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Single Cell RNA-seq Cell Type Annotation
2
+
3
+ ---
4
+
5
+ ## Metadata
6
+
7
+ **Short Description**: Best practices for annotating cell types in single-cell RNA-seq data using marker-based, automated, and reference-based approaches.
8
+
9
+ **Authors**: Distilled from "Single-cell best practices" by Luecken, M.D. et al.
10
+
11
+ **Affiliations**: Helmholtz Munich, Wellcome Sanger Institute, Harvard Medical School, and contributors
12
+
13
+ **Version**: 1.0
14
+
15
+ **Last Updated**: January 2025
16
+
17
+ **License**: CC BY 4.0
18
+
19
+ **Commercial Use**: ✅ Allowed
20
+
21
+ **Source**: https://www.sc-best-practices.org/cellular_structure/annotation.html
22
+
23
+ **Citation**: Luecken, M.D., Theis, F.J. et al. (2023). Current best practices in single-cell RNA-seq analysis: a tutorial. Molecular Systems Biology.
24
+
25
+ ---
26
+
27
+ ## Overview
28
+
29
+ Cell type annotation is the process of assigning cell type labels to clusters or individual cells in single-cell RNA-seq data. This guide covers three main approaches and their practical implementation.
30
+
31
+ ## Three Annotation Approaches
32
+
33
+ ### 1. Manual Marker-Based Annotation
34
+ Identify cell types by examining expression of known marker genes in each cluster.
35
+
36
+ **Tools**: Scanpy, Seurat
37
+ **Best for**: Small datasets, novel cell types, high confidence needs
38
+
39
+ ### 2. Automated Annotation
40
+ Use pre-trained classifiers to automatically assign cell type labels.
41
+
42
+ **Tools**: CellTypist, scAnnotate
43
+ **Best for**: Standard tissues, quick preliminary annotation, large datasets
44
+
45
+ ### 3. Reference-Based Label Transfer
46
+ Transfer labels from annotated reference datasets to your query data.
47
+
48
+ **Tools**: scArches, scANVI, Azimuth, SingleR
49
+ **Best for**: Well-characterized tissues, integration with public data
50
+
51
+ ## Recommended Workflow
52
+
53
+ ### Step 1: Quality Control First
54
+ - **Remove low-quality cells before annotation**
55
+ - Filter doublets (expected doublet rate: 0.8% per 1000 cells)
56
+ - Check for ambient RNA contamination
57
+ - Verify cluster quality and resolution
58
+
59
+ ### Step 2: Initial Marker-Based Assessment
60
+
61
+ ```python
62
+ # Scanpy example
63
+ import scanpy as sc
64
+
65
+ # Calculate marker genes for clusters
66
+ sc.tl.rank_genes_groups(adata, 'leiden', method='wilcoxon')
67
+
68
+ # Visualize top markers
69
+ sc.pl.rank_genes_groups(adata, n_genes=25, sharey=False)
70
+
71
+ # Plot known markers
72
+ markers = {
73
+ 'T cells': ['CD3D', 'CD3E', 'CD4', 'CD8A'],
74
+ 'B cells': ['CD19', 'MS4A1', 'CD79A'],
75
+ 'Monocytes': ['CD14', 'FCGR3A', 'LYZ'],
76
+ 'NK cells': ['NCAM1', 'NKG7', 'GNLY']
77
+ }
78
+
79
+ sc.pl.dotplot(adata, markers, groupby='leiden')
80
+ ```
81
+
82
+ ### Step 3: Use Automated Tools for Validation
83
+
84
+ ```python
85
+ # CellTypist example (fast, accurate for immune cells)
86
+ import celltypist
87
+ from celltypist import models
88
+
89
+ # Download immune cell model
90
+ model = models.Model.load(model='Immune_All_Low.pkl')
91
+
92
+ # Predict cell types
93
+ predictions = celltypist.annotate(adata, model=model, majority_voting=True)
94
+ adata = predictions.to_adata()
95
+ ```
96
+
97
+ ### Step 4: Reference-Based Refinement
98
+
99
+ ```python
100
+ # scArches example for label transfer
101
+ import scarches as sca
102
+
103
+ # Load pre-trained reference model
104
+ model = sca.models.SCANVI.load_query_data(
105
+ adata=adata, # Your query data
106
+ reference_model="path/to/reference_model"
107
+ )
108
+
109
+ # Transfer labels
110
+ model.train(max_epochs=100)
111
+ adata.obs['transferred_labels'] = model.predict()
112
+ ```
113
+
114
+ ## Best Practices
115
+
116
+ ### Do's:
117
+ 1. **Always combine multiple approaches** - Use marker-based validation even with automated tools
118
+ 2. **Check cluster purity** - Ensure clusters represent single cell types
119
+ 3. **Validate with multiple marker sets** - Don't rely on single markers
120
+ 4. **Consider biological context** - Tissue type, disease state, developmental stage
121
+ 5. **Document confidence levels** - Note uncertain annotations
122
+ 6. **Use hierarchical annotation** - Broad categories first, then subtypes
123
+
124
+ ### Don'ts:
125
+ 1. **Don't over-cluster** - Too fine resolution creates artificial distinctions
126
+ 2. **Don't ignore batch effects** - Correct before annotation
127
+ 3. **Don't trust automation blindly** - Always validate predictions
128
+ 4. **Don't mix cell states with cell types** - Activated vs. resting cells are states, not types
129
+ 5. **Don't annotate low-quality cells** - Remove them first
130
+
131
+ ## Common Pitfalls
132
+
133
+ ### 1. Doublet Clusters
134
+ **Problem**: Clusters with markers from multiple cell types
135
+ **Solution**: Use doublet detection tools (Scrublet, DoubletFinder) before annotation
136
+
137
+ ### 2. Ambient RNA
138
+ **Problem**: Background markers in all cells
139
+ **Solution**: Use SoupX or CellBender for decontamination
140
+
141
+ ### 3. Over-interpretation of Small Clusters
142
+ **Problem**: Rare clusters may be technical artifacts
143
+ **Solution**: Require minimum cell count (e.g., >25 cells), validate with independent data
144
+
145
+ ### 4. Reference Mismatch
146
+ **Problem**: Reference from different tissue/species/condition
147
+ **Solution**: Use tissue-matched references, check marker overlap before transfer
148
+
149
+ ## Tool Selection Guide
150
+
151
+ | Scenario | Recommended Tool | Why |
152
+ |----------|------------------|-----|
153
+ | Immune cells (human) | CellTypist | Pre-trained on large immune atlases |
154
+ | Mouse tissues | scArches + Mouse Cell Atlas | Comprehensive mouse reference |
155
+ | Novel cell types | Manual + Scanpy/Seurat | Need domain expertise |
156
+ | Large datasets (>100k cells) | CellTypist | Fast, scalable |
157
+ | Cross-species | Manual markers | Limited reference transfer |
158
+ | Developmental data | scArches | Handles continuous states |
159
+
160
+ ## Key Marker Genes by Cell Type
161
+
162
+ ### Blood/Immune:
163
+ - **T cells**: CD3D, CD3E (all T cells); CD4, CD8A (subtypes)
164
+ - **B cells**: CD19, MS4A1 (CD20), CD79A
165
+ - **Monocytes/Macrophages**: CD14, CD68, LYZ
166
+ - **NK cells**: NCAM1 (CD56), NKG7, KLRD1
167
+ - **Dendritic cells**: FCER1A, CD1C
168
+
169
+ ### Epithelial:
170
+ - **General epithelial**: EPCAM, KRT18, KRT19
171
+ - **Lung AT1**: AGER, PDPN
172
+ - **Lung AT2**: SFTPC, SFTPA1
173
+ - **Intestinal**: VIL1, MUC2
174
+
175
+ ### Stromal:
176
+ - **Fibroblasts**: COL1A1, DCN, LUM
177
+ - **Endothelial**: PECAM1 (CD31), VWF, CDH5
178
+ - **Smooth muscle**: ACTA2, MYH11, TAGLN
179
+
180
+ ## Validation Checklist
181
+
182
+ - [ ] Cluster purity: >80% cells with same label per cluster
183
+ - [ ] Marker consistency: Top DE genes match expected markers
184
+ - [ ] Biological plausibility: Expected proportions for tissue type
185
+ - [ ] Cross-method agreement: Manual and automated annotations align
186
+ - [ ] Reference quality: >70% cells successfully transferred
187
+ - [ ] Doublet check: No clusters with multi-lineage markers
188
+ - [ ] Documentation: Record confidence levels and uncertain calls
189
+
190
+ ## Resources
191
+
192
+ ### Tools:
193
+ - **Scanpy**: https://scanpy.readthedocs.io/
194
+ - **CellTypist**: https://www.celltypist.org/
195
+ - **scArches**: https://scarches.readthedocs.io/
196
+ - **Seurat**: https://satijalab.org/seurat/
197
+
198
+ ### References:
199
+ - **PanglaoDB**: Database of marker genes
200
+ - **CellMarker**: Curated cell marker database
201
+ - **Human Cell Atlas**: Reference datasets
202
+
203
+ ### Pre-trained Models:
204
+ - **CellTypist models**: 30+ tissue-specific models
205
+ - **Azimuth references**: PBMC, lung, kidney, etc.
206
+ - **scArches models**: Multiple tissue references
207
+
208
+ ## Troubleshooting
209
+
210
+ **Issue**: All clusters look similar
211
+ → Increase clustering resolution, check if data is normalized
212
+
213
+ **Issue**: Too many small clusters
214
+ → Decrease resolution, merge similar clusters based on markers
215
+
216
+ **Issue**: Automated tool gives inconsistent results
217
+ → Check input normalization, try multiple tools, fall back to manual
218
+
219
+ **Issue**: Can't find clear markers for cluster
220
+ → May be transitional state, doublet, or low-quality cells
221
+
222
+ **Issue**: Reference transfer fails
223
+ → Check batch correction, ensure overlapping gene sets, verify tissue match
BioScientist/agent_system/engines/v1_executor_backup/llm.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import TYPE_CHECKING, Literal, Optional
3
+
4
+ from langchain_core.language_models.chat_models import BaseChatModel
5
+
6
+ if TYPE_CHECKING:
7
+ from biomni.config import BiomniConfig
8
+
9
+ SourceType = Literal["OpenAI", "AzureOpenAI", "Anthropic", "Ollama", "Gemini", "Bedrock", "Groq", "Custom"]
10
+ ALLOWED_SOURCES: set[str] = set(SourceType.__args__)
11
+
12
+
13
+ def get_llm(
14
+ model: str | None = None,
15
+ temperature: float | None = None,
16
+ stop_sequences: list[str] | None = None,
17
+ source: SourceType | None = None,
18
+ base_url: str | None = None,
19
+ api_key: str | None = None,
20
+ config: Optional["BiomniConfig"] = None,
21
+ ) -> BaseChatModel:
22
+ """
23
+ Get a language model instance based on the specified model name and source.
24
+ This function supports models from OpenAI, Azure OpenAI, Anthropic, Ollama, Gemini, Bedrock, and custom model serving.
25
+ Args:
26
+ model (str): The model name to use
27
+ temperature (float): Temperature setting for generation
28
+ stop_sequences (list): Sequences that will stop generation
29
+ source (str): Source provider: "OpenAI", "AzureOpenAI", "Anthropic", "Ollama", "Gemini", "Bedrock", or "Custom"
30
+ If None, will attempt to auto-detect from model name
31
+ base_url (str): The base URL for custom model serving (e.g., "http://localhost:8000/v1"), default is None
32
+ api_key (str): The API key for the custom llm
33
+ config (BiomniConfig): Optional configuration object. If provided, unspecified parameters will use config values
34
+ """
35
+ # Use config values for any unspecified parameters
36
+ if config is not None:
37
+ if model is None:
38
+ model = config.llm_model
39
+ if temperature is None:
40
+ temperature = config.temperature
41
+ if source is None:
42
+ source = config.source
43
+ if base_url is None:
44
+ base_url = config.base_url
45
+ if api_key is None:
46
+ api_key = config.api_key or "EMPTY"
47
+
48
+ # Use defaults if still not specified
49
+ if model is None:
50
+ model = "claude-3-5-sonnet-20241022"
51
+ if temperature is None:
52
+ temperature = 0.7
53
+ if api_key is None:
54
+ api_key = "EMPTY"
55
+ # Auto-detect source from model name if not specified
56
+ if source is None:
57
+ env_source = os.getenv("LLM_SOURCE")
58
+ if env_source in ALLOWED_SOURCES:
59
+ source = env_source
60
+ else:
61
+ if model[:7] == "claude-":
62
+ source = "Anthropic"
63
+ elif model[:7] == "gpt-oss":
64
+ source = "Ollama"
65
+ elif model[:4] == "gpt-":
66
+ source = "OpenAI"
67
+ elif model.startswith("azure-"):
68
+ source = "AzureOpenAI"
69
+ elif model[:7] == "gemini-":
70
+ source = "Gemini"
71
+ elif "groq" in model.lower():
72
+ source = "Groq"
73
+ elif base_url is not None:
74
+ source = "Custom"
75
+ elif "/" in model or any(
76
+ name in model.lower()
77
+ for name in [
78
+ "llama",
79
+ "mistral",
80
+ "qwen",
81
+ "gemma",
82
+ "phi",
83
+ "dolphin",
84
+ "orca",
85
+ "vicuna",
86
+ "deepseek",
87
+ ]
88
+ ):
89
+ source = "Ollama"
90
+ elif model.startswith(
91
+ ("anthropic.claude-", "amazon.titan-", "meta.llama-", "mistral.", "cohere.", "ai21.", "us.")
92
+ ):
93
+ source = "Bedrock"
94
+ else:
95
+ raise ValueError("Unable to determine model source. Please specify 'source' parameter.")
96
+
97
+ # Create appropriate model based on source
98
+ if source == "OpenAI":
99
+ try:
100
+ from langchain_openai import ChatOpenAI
101
+ except ImportError:
102
+ raise ImportError( # noqa: B904
103
+ "langchain-openai package is required for OpenAI models. Install with: pip install langchain-openai"
104
+ )
105
+ # Newer OpenAI models (e.g., gpt-5-*) require the Responses API and may reject
106
+ # legacy Chat Completions parameters like `stop`. Force Responses API when
107
+ # using gpt-5 models to avoid 400 errors such as: "Unsupported parameter: 'stop'".
108
+ use_responses = model.startswith("gpt-5")
109
+
110
+ if use_responses:
111
+ # Define a minimal subclass that drops the `stop` field when using the
112
+ # Responses API, since certain models (gpt-5-*) reject it entirely.
113
+ class _ChatOpenAIResponsesNoStop(ChatOpenAI):
114
+ def _get_request_payload(self, input_, *, stop=None, **kwargs): # type: ignore[override]
115
+ payload = super()._get_request_payload(input_, stop=stop, **kwargs)
116
+ try:
117
+ # If this call will use the Responses API, drop `stop` to avoid 400s.
118
+ if hasattr(self, "_use_responses_api") and self._use_responses_api(payload): # type: ignore[attr-defined]
119
+ payload.pop("stop", None)
120
+ # Also drop temperature for gpt-5 models as they only support default value
121
+ payload.pop("temperature", None)
122
+ except Exception:
123
+ # Be conservative: if anything goes wrong, still remove `stop` and `temperature`.
124
+ payload.pop("stop", None)
125
+ payload.pop("temperature", None)
126
+ return payload
127
+
128
+ return _ChatOpenAIResponsesNoStop(
129
+ model=model,
130
+ temperature=1, # Set to default value for gpt-5, will be removed in payload
131
+ stop_sequences=stop_sequences,
132
+ use_responses_api=True,
133
+ output_version="v0",
134
+ )
135
+ else:
136
+ return ChatOpenAI(
137
+ model=model,
138
+ temperature=temperature,
139
+ stop_sequences=stop_sequences,
140
+ )
141
+
142
+ elif source == "AzureOpenAI":
143
+ try:
144
+ from langchain_openai import AzureChatOpenAI
145
+ except ImportError:
146
+ raise ImportError( # noqa: B904
147
+ "langchain-openai package is required for Azure OpenAI models. Install with: pip install langchain-openai"
148
+ )
149
+ API_VERSION = "2024-12-01-preview"
150
+ model = model.replace("azure-", "")
151
+ return AzureChatOpenAI(
152
+ openai_api_key=os.getenv("OPENAI_API_KEY"),
153
+ azure_endpoint=os.getenv("OPENAI_ENDPOINT"),
154
+ azure_deployment=model,
155
+ openai_api_version=API_VERSION,
156
+ temperature=temperature,
157
+ )
158
+
159
+ elif source == "Anthropic":
160
+ try:
161
+ from langchain_anthropic import ChatAnthropic
162
+ except ImportError:
163
+ raise ImportError( # noqa: B904
164
+ "langchain-anthropic package is required for Anthropic models. Install with: pip install langchain-anthropic"
165
+ )
166
+
167
+ # Ensure ANTHROPIC_API_KEY is loaded from bash_profile if not in environment
168
+ if not os.environ.get("ANTHROPIC_API_KEY"):
169
+ try:
170
+ import subprocess
171
+
172
+ result = subprocess.run(
173
+ ["bash", "-c", "source ~/.bash_profile 2>/dev/null && echo $ANTHROPIC_API_KEY"],
174
+ capture_output=True,
175
+ text=True,
176
+ timeout=5,
177
+ )
178
+ if result.stdout.strip():
179
+ os.environ["ANTHROPIC_API_KEY"] = result.stdout.strip()
180
+ print("✓ Loaded ANTHROPIC_API_KEY from ~/.bash_profile")
181
+ except Exception as e:
182
+ print(f"Note: Could not load ANTHROPIC_API_KEY from bash_profile: {e}")
183
+
184
+ # Newer Claude models can reject an explicit temperature parameter.
185
+ # Omit it and use provider defaults to keep compatibility.
186
+ return ChatAnthropic(
187
+ model=model,
188
+ max_tokens=8192,
189
+ stop_sequences=stop_sequences,
190
+ )
191
+
192
+ elif source == "Gemini":
193
+ # If you want to use ChatGoogleGenerativeAI, you need to pass the stop sequences upon invoking the model.
194
+ # return ChatGoogleGenerativeAI(
195
+ # model=model,
196
+ # temperature=temperature,
197
+ # google_api_key=api_key,
198
+ # )
199
+ try:
200
+ from langchain_openai import ChatOpenAI
201
+ except ImportError:
202
+ raise ImportError( # noqa: B904
203
+ "langchain-openai package is required for Gemini models. Install with: pip install langchain-openai"
204
+ )
205
+ return ChatOpenAI(
206
+ model=model,
207
+ temperature=temperature,
208
+ api_key=os.getenv("GEMINI_API_KEY"),
209
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
210
+ stop_sequences=stop_sequences,
211
+ )
212
+
213
+ elif source == "Groq":
214
+ try:
215
+ from langchain_openai import ChatOpenAI
216
+ except ImportError:
217
+ raise ImportError( # noqa: B904
218
+ "langchain-openai package is required for Groq models. Install with: pip install langchain-openai"
219
+ )
220
+ return ChatOpenAI(
221
+ model=model,
222
+ temperature=temperature,
223
+ api_key=os.getenv("GROQ_API_KEY"),
224
+ base_url="https://api.groq.com/openai/v1",
225
+ stop_sequences=stop_sequences,
226
+ )
227
+
228
+ elif source == "Ollama":
229
+ try:
230
+ from langchain_ollama import ChatOllama
231
+ except ImportError:
232
+ raise ImportError( # noqa: B904
233
+ "langchain-ollama package is required for Ollama models. Install with: pip install langchain-ollama"
234
+ )
235
+ return ChatOllama(
236
+ model=model,
237
+ temperature=temperature,
238
+ )
239
+
240
+ elif source == "Bedrock":
241
+ try:
242
+ from langchain_aws import ChatBedrock
243
+ except ImportError:
244
+ raise ImportError( # noqa: B904
245
+ "langchain-aws package is required for Bedrock models. Install with: pip install langchain-aws"
246
+ )
247
+ return ChatBedrock(
248
+ model=model,
249
+ temperature=temperature,
250
+ stop_sequences=stop_sequences,
251
+ region_name=os.getenv("AWS_REGION", "us-east-1"),
252
+ )
253
+
254
+ elif source == "Custom":
255
+ try:
256
+ from langchain_openai import ChatOpenAI
257
+ except ImportError:
258
+ raise ImportError( # noqa: B904
259
+ "langchain-openai package is required for custom models. Install with: pip install langchain-openai"
260
+ )
261
+ # Custom LLM serving such as SGLang. Must expose an openai compatible API.
262
+ assert base_url is not None, "base_url must be provided for customly served LLMs"
263
+ llm = ChatOpenAI(
264
+ model=model,
265
+ temperature=temperature,
266
+ max_tokens=8192,
267
+ stop_sequences=stop_sequences,
268
+ base_url=base_url,
269
+ api_key=api_key,
270
+ )
271
+ return llm
272
+
273
+ else:
274
+ raise ValueError(
275
+ f"Invalid source: {source}. Valid options are 'OpenAI', 'AzureOpenAI', 'Anthropic', 'Gemini', 'Groq', 'Bedrock', or 'Ollama'"
276
+ )
BioScientist/agent_system/engines/v1_executor_backup/mcp_config_bioscientist_generated.yaml ADDED
The diff for this file is too large to render. See raw diff
 
BioScientist/agent_system/engines/v1_executor_backup/model/__init__.py ADDED
File without changes
BioScientist/agent_system/engines/v1_executor_backup/model/retriever.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import re
3
+
4
+ from langchain_core.messages import HumanMessage
5
+ from langchain_openai import ChatOpenAI
6
+
7
+
8
+ class ToolRetriever:
9
+ """Retrieve tools from the tool registry."""
10
+
11
+ def __init__(self):
12
+ pass
13
+
14
+ def prompt_based_retrieval(self, query: str, resources: dict, llm=None) -> dict:
15
+ """Use a prompt-based approach to retrieve the most relevant resources for a query.
16
+
17
+ Args:
18
+ query: The user's query
19
+ resources: A dictionary with keys 'tools', 'data_lake', 'libraries', and 'know_how',
20
+ each containing a list of available resources
21
+ llm: Optional LLM instance to use for retrieval (if None, will create a new one)
22
+
23
+ Returns:
24
+ A dictionary with the same keys, but containing only the most relevant resources
25
+
26
+ """
27
+ # Build prompt sections for available resources
28
+ prompt_sections = []
29
+ prompt_sections.append(f"""
30
+ You are an expert biomedical research assistant. Your task is to select the relevant resources to help answer a user's query.
31
+
32
+ USER QUERY: {query}
33
+
34
+ Below are the available resources. For each category, select items that are directly or indirectly relevant to answering the query.
35
+ Be generous in your selection - include resources that might be useful for the task, even if they're not explicitly mentioned in the query.
36
+ It's better to include slightly more resources than to miss potentially useful ones.
37
+
38
+ AVAILABLE TOOLS:
39
+ {self._format_resources_for_prompt(resources.get("tools", []))}
40
+
41
+ AVAILABLE DATA LAKE ITEMS:
42
+ {self._format_resources_for_prompt(resources.get("data_lake", []))}
43
+
44
+ AVAILABLE SOFTWARE LIBRARIES:
45
+ {self._format_resources_for_prompt(resources.get("libraries", []))}""")
46
+
47
+ # Add know-how section if available
48
+ if "know_how" in resources and resources["know_how"]:
49
+ prompt_sections.append(f"""
50
+ AVAILABLE KNOW-HOW DOCUMENTS (Best Practices & Protocols):
51
+ {self._format_resources_for_prompt(resources.get("know_how", []))}""")
52
+
53
+ # Build response format based on available categories
54
+ response_format = """
55
+ For each category, respond with ONLY the indices of the relevant items in the following format:
56
+ TOOLS: [list of indices]
57
+ DATA_LAKE: [list of indices]
58
+ LIBRARIES: [list of indices]"""
59
+
60
+ if "know_how" in resources and resources["know_how"]:
61
+ response_format += "\nKNOW_HOW: [list of indices]"
62
+
63
+ response_format += """
64
+
65
+ For example:
66
+ TOOLS: [0, 3, 5, 7, 9]
67
+ DATA_LAKE: [1, 2, 4]
68
+ LIBRARIES: [0, 2, 4, 5, 8]"""
69
+
70
+ if "know_how" in resources and resources["know_how"]:
71
+ response_format += "\nKNOW_HOW: [0, 1]"
72
+
73
+ response_format += """
74
+
75
+ If a category has no relevant items, use an empty list, e.g., DATA_LAKE: []
76
+
77
+ IMPORTANT GUIDELINES:
78
+ 1. Be generous but not excessive - aim to include all potentially relevant resources
79
+ 2. ALWAYS prioritize database tools for general queries - include as many database tools as possible
80
+ 3. Include all literature search tools
81
+ 4. For wet lab sequence type of queries, ALWAYS include molecular biology tools
82
+ 5. For data lake items, include datasets that could provide useful information
83
+ 6. For libraries, include those that provide functions needed for analysis
84
+ 7. For know-how documents, include those that provide relevant protocols, best practices, or troubleshooting guidance
85
+ 8. Don't exclude resources just because they're not explicitly mentioned in the query
86
+ 9. When in doubt about a database tool or molecular biology tool, include it rather than exclude it
87
+ """
88
+
89
+ prompt = "\n".join(prompt_sections) + response_format
90
+
91
+ # Use the provided LLM or create a new one
92
+ if llm is None:
93
+ llm = ChatOpenAI(model="gpt-4o")
94
+
95
+ # Invoke the LLM
96
+ if hasattr(llm, "invoke"):
97
+ # For LangChain-style LLMs
98
+ response = llm.invoke([HumanMessage(content=prompt)])
99
+ response_content = response.content
100
+ else:
101
+ # For other LLM interfaces
102
+ response_content = str(llm(prompt))
103
+
104
+ # Parse the response to extract the selected indices
105
+ selected_indices = self._parse_llm_response(response_content)
106
+
107
+ # Get the selected resources
108
+ selected_resources = {
109
+ "tools": [
110
+ resources["tools"][i] for i in selected_indices.get("tools", []) if i < len(resources.get("tools", []))
111
+ ],
112
+ "data_lake": [
113
+ resources["data_lake"][i]
114
+ for i in selected_indices.get("data_lake", [])
115
+ if i < len(resources.get("data_lake", []))
116
+ ],
117
+ "libraries": [
118
+ resources["libraries"][i]
119
+ for i in selected_indices.get("libraries", [])
120
+ if i < len(resources.get("libraries", []))
121
+ ],
122
+ }
123
+
124
+ # Add know-how if present
125
+ if "know_how" in resources and resources["know_how"]:
126
+ selected_resources["know_how"] = [
127
+ resources["know_how"][i]
128
+ for i in selected_indices.get("know_how", [])
129
+ if i < len(resources.get("know_how", []))
130
+ ]
131
+
132
+ return selected_resources
133
+
134
+ def _format_resources_for_prompt(self, resources: list) -> str:
135
+ """Format resources for inclusion in the prompt."""
136
+ formatted = []
137
+ for i, resource in enumerate(resources):
138
+ if isinstance(resource, dict):
139
+ # Handle dictionary format (from tool registry or data lake/libraries with descriptions)
140
+ name = resource.get("name", f"Resource {i}")
141
+ description = resource.get("description", "")
142
+ formatted.append(f"{i}. {name}: {description}")
143
+ elif isinstance(resource, str):
144
+ # Handle string format (simple strings)
145
+ formatted.append(f"{i}. {resource}")
146
+ else:
147
+ # Try to extract name and description from tool objects
148
+ name = getattr(resource, "name", str(resource))
149
+ desc = getattr(resource, "description", "")
150
+ formatted.append(f"{i}. {name}: {desc}")
151
+
152
+ return "\n".join(formatted) if formatted else "None available"
153
+
154
+ def _parse_llm_response(self, response) -> dict:
155
+ """Parse the LLM response to extract the selected indices.
156
+
157
+ Accepts either a plain string or a Responses API-style list of content blocks.
158
+ """
159
+ # Normalize response to string if it's a list of content blocks (Responses API)
160
+ if isinstance(response, list):
161
+ parts = []
162
+ for item in response:
163
+ # LangChain Responses API returns list of dicts like {"type": "text", "text": "..."}
164
+ if isinstance(item, dict):
165
+ if item.get("type") == "text" and "text" in item:
166
+ parts.append(str(item.get("text", "")))
167
+ # If it's a tool_call or other block, ignore for this simple parsing
168
+ elif isinstance(item, str):
169
+ parts.append(item)
170
+ response = "\n".join([p for p in parts if p])
171
+ elif not isinstance(response, str):
172
+ response = str(response)
173
+ selected_indices = {"tools": [], "data_lake": [], "libraries": [], "know_how": []}
174
+
175
+ # Extract indices for each category
176
+ tools_match = re.search(r"TOOLS:\s*\[(.*?)\]", response, re.IGNORECASE)
177
+ if tools_match and tools_match.group(1).strip():
178
+ with contextlib.suppress(ValueError):
179
+ selected_indices["tools"] = [int(idx.strip()) for idx in tools_match.group(1).split(",") if idx.strip()]
180
+
181
+ data_lake_match = re.search(r"DATA_LAKE:\s*\[(.*?)\]", response, re.IGNORECASE)
182
+ if data_lake_match and data_lake_match.group(1).strip():
183
+ with contextlib.suppress(ValueError):
184
+ selected_indices["data_lake"] = [
185
+ int(idx.strip()) for idx in data_lake_match.group(1).split(",") if idx.strip()
186
+ ]
187
+
188
+ libraries_match = re.search(r"LIBRARIES:\s*\[(.*?)\]", response, re.IGNORECASE)
189
+ if libraries_match and libraries_match.group(1).strip():
190
+ with contextlib.suppress(ValueError):
191
+ selected_indices["libraries"] = [
192
+ int(idx.strip()) for idx in libraries_match.group(1).split(",") if idx.strip()
193
+ ]
194
+
195
+ # Extract know-how indices
196
+ know_how_match = re.search(r"KNOW[-_]HOW:\s*\[(.*?)\]", response, re.IGNORECASE)
197
+ if know_how_match and know_how_match.group(1).strip():
198
+ with contextlib.suppress(ValueError):
199
+ selected_indices["know_how"] = [
200
+ int(idx.strip()) for idx in know_how_match.group(1).split(",") if idx.strip()
201
+ ]
202
+
203
+ return selected_indices
BioScientist/agent_system/engines/v1_executor_backup/task/__init__.py ADDED
File without changes
BioScientist/agent_system/engines/v1_executor_backup/task/base_task.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class base_task:
2
+ def __init__(self):
3
+ pass
4
+
5
+ def get_example(self):
6
+ pass
7
+
8
+ def get_iterator(self):
9
+ pass
10
+
11
+ def evaluate(self):
12
+ pass
13
+
14
+ def output_class(self):
15
+ pass
16
+
17
+ def get_prompt_from_input(self, input):
18
+ return self.get_example(input)["prompt"]
BioScientist/agent_system/engines/v1_executor_backup/task/hle.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ from biomni.task.base_task import base_task
5
+
6
+ np.random.seed(42)
7
+
8
+
9
+ def shuffle(x):
10
+ np.random.shuffle(x)
11
+ return x
12
+
13
+
14
+ class humanity_last_exam(base_task):
15
+ def __init__(self, path="./data", category="Biology/Medicine", answer_type="multipleChoice"):
16
+ if category not in [
17
+ "Other",
18
+ "Humanities/Social Science",
19
+ "Math",
20
+ "Physics",
21
+ "Computer Science/AI",
22
+ "Biology/Medicine",
23
+ "Chemistry",
24
+ "Engineering",
25
+ ]:
26
+ raise ValueError(
27
+ "category must be one of ['Other', 'Humanities/Social Science', 'Math', 'Physics', 'Computer Science/AI', 'Biology/Medicine', 'Chemistry', 'Engineering']"
28
+ )
29
+ if answer_type not in ["exactMatch", "multipleChoice"]:
30
+ raise ValueError("answer_type must be one of ['exactMatch' or 'multipleChoice']")
31
+
32
+ self.dataset = category # Store dataset type
33
+ self.answer_type = answer_type
34
+ df = pd.read_parquet(path + "/hle/test_sampled_biology_medicine.parquet")
35
+
36
+ # Extract answer choices from question text
37
+ def extract_options(question):
38
+ # Find the "Answer Choices:" section
39
+ if "Answer Choices:" not in question:
40
+ return []
41
+ choices = question.split("Answer Choices:")[1].strip()
42
+
43
+ # Split on A., B., C. etc and clean up
44
+ options = []
45
+ letters = [
46
+ "A.",
47
+ "B.",
48
+ "C.",
49
+ "D.",
50
+ "E.",
51
+ "F.",
52
+ "G.",
53
+ "H.",
54
+ "I.",
55
+ "J.",
56
+ "K.",
57
+ "L.",
58
+ "M.",
59
+ "N.",
60
+ "O.",
61
+ "P.",
62
+ "Q.",
63
+ "R.",
64
+ "S.",
65
+ "T.",
66
+ "U.",
67
+ "V.",
68
+ "W.",
69
+ "X.",
70
+ "Y.",
71
+ "Z.",
72
+ ]
73
+ for i, letter in enumerate(letters):
74
+ if letter in choices:
75
+ # Define the next letter if available
76
+ next_letter = letters[i + 1] if i + 1 < len(letters) else None
77
+
78
+ # Split between current letter and next letter
79
+ parts = choices.split(letter)[1]
80
+ if next_letter and next_letter in parts:
81
+ option = parts.split(next_letter)[0].strip()
82
+ else:
83
+ option = parts.strip()
84
+
85
+ options.append(option)
86
+ return options
87
+
88
+ def extract_question(question):
89
+ return question.split("Answer Choices:")[0].strip()
90
+
91
+ # Extract options and answers only for multiple choice questions and category is the same as the dataset
92
+ df = df[df["category"] == self.dataset]
93
+ df = df[df["answer_type"] == "multipleChoice"]
94
+ df["question_text"] = df.question
95
+ df["letter_answer"] = df["answer"].apply(lambda x: x[0])
96
+
97
+ self.query = df.question_text.values
98
+ # self.options = df.options_letters.values
99
+ self.answer = df.letter_answer.values
100
+
101
+ self.prompt = """Question: {question}"""
102
+
103
+ def get_example(self, index=None):
104
+ if index is None:
105
+ index = np.random.randint(len(self.query))
106
+
107
+ return {
108
+ "prompt": self.prompt.format(
109
+ question=self.query[index],
110
+ # options = self.options[index]
111
+ ),
112
+ "answer": self.answer[index],
113
+ }
114
+
115
+ def get_iterator(self):
116
+ for i in range(len(self.query)):
117
+ yield self.get_example(i)
118
+
119
+ def evaluate(self, response):
120
+ ## expected a list/array of symbols
121
+ from sklearn.metrics import accuracy_score
122
+
123
+ ground_truth = self.answer
124
+ response = np.array(response)
125
+
126
+ return {
127
+ "accuracy": accuracy_score(ground_truth, response),
128
+ "coverage": np.mean(response != self.refrain_label),
129
+ "refrain_ratio": np.mean(response == self.refrain_label),
130
+ "precision": accuracy_score(
131
+ ground_truth[np.where(response != self.refrain_label)],
132
+ response[np.where(response != self.refrain_label)],
133
+ ),
134
+ }
135
+
136
+ def output_class(self):
137
+ from pydantic import BaseModel, Field
138
+
139
+ class MultipleChoiceOutput(BaseModel):
140
+ """Multiple choice output."""
141
+
142
+ choice: str | None = Field(
143
+ description="Multiple choice answer. For example, if there is <answer>A</answer> in the prompt, the output should be 'A'."
144
+ )
145
+
146
+ return MultipleChoiceOutput
BioScientist/agent_system/engines/v1_executor_backup/task/lab_bench.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ from biomni.task.base_task import base_task
5
+
6
+ np.random.seed(42)
7
+
8
+
9
+ def shuffle(x):
10
+ np.random.shuffle(x)
11
+ return x
12
+
13
+
14
+ class lab_bench(base_task):
15
+ def __init__(self, path="./data", dataset="DbQA"):
16
+ if dataset not in ["DbQA", "SeqQA"]:
17
+ raise ValueError("dataset must be one of 'DbQA', 'SeqQA'")
18
+
19
+ self.dataset = dataset # Store dataset type
20
+ df = pd.read_parquet(path + "/" + dataset + "/train-00000-of-00001_test.parquet")
21
+
22
+ self.prompt = """The following is a multiple choice question about biology.
23
+ Please answer by responding with the letter of the correct answer.
24
+
25
+ Question: {question}
26
+ Options:
27
+ {options}
28
+
29
+ You MUST include the letter of the correct answer within the following tags:
30
+ [ANSWER] and [/ANSWER]. For example, '[ANSWER]<answer>[/ANSWER]',
31
+ where <answer> is the correct letter. Always answer in exactly this format
32
+ of a single letter between the two tags, even if you are unsure.
33
+ We require this because we use automatic parsing.
34
+ """
35
+
36
+ np.random.seed(42)
37
+ df["options"] = df.apply(
38
+ lambda x: shuffle(
39
+ x.distractors.tolist() + [x.ideal] + ["Insufficient information to answer the question."]
40
+ ),
41
+ axis=1,
42
+ )
43
+ df["options_letters"] = df.options.apply(
44
+ lambda x: "\n".join([chr(ord("A") + i) + "." + item for i, item in enumerate(x)])
45
+ )
46
+ df["letter_answer"] = df.apply(
47
+ lambda x: chr(ord("A") + np.where(np.array(x.options) == x.ideal)[0][0]),
48
+ axis=1,
49
+ )
50
+ df["letter_refrain"] = df.apply(
51
+ lambda x: chr(
52
+ ord("A") + np.where(np.array(x.options) == "Insufficient information to answer the question.")[0][0]
53
+ ),
54
+ axis=1,
55
+ )
56
+
57
+ self.query = df.question.values
58
+ self.options = df.options_letters.values
59
+ self.answer = df.letter_answer.values
60
+ self.refrain_label = df.letter_refrain.values
61
+
62
+ # Store protocol information if available
63
+ self.protocol = df.protocol.values if "protocol" in df.columns else None
64
+
65
+ def get_example(self, index=None):
66
+ if index is None:
67
+ index = np.random.randint(len(self.query))
68
+
69
+ if self.dataset == "ProtocolQA" and self.protocol is not None:
70
+ return {
71
+ "prompt": self.prompt.format(
72
+ protocol=self.protocol[index],
73
+ question=self.query[index],
74
+ options=self.options[index],
75
+ ),
76
+ "answer": self.answer[index],
77
+ }
78
+ else:
79
+ return {
80
+ "prompt": self.prompt.format(question=self.query[index], options=self.options[index]),
81
+ "answer": self.answer[index],
82
+ }
83
+
84
+ def get_iterator(self):
85
+ for i in range(len(self.query)):
86
+ yield self.get_example(i)
87
+
88
+ def evaluate(self, response):
89
+ ## expected a list/array of symbols
90
+ from sklearn.metrics import accuracy_score
91
+
92
+ ground_truth = self.answer
93
+ response = np.array(response)
94
+
95
+ return {
96
+ "accuracy": accuracy_score(ground_truth, response),
97
+ "coverage": np.mean(response != self.refrain_label),
98
+ "refrain_ratio": np.mean(response == self.refrain_label),
99
+ "precision": accuracy_score(
100
+ ground_truth[np.where(response != self.refrain_label)],
101
+ response[np.where(response != self.refrain_label)],
102
+ ),
103
+ }
104
+
105
+ def output_class(self):
106
+ from pydantic import BaseModel, Field
107
+
108
+ class MultipleChoiceOutput(BaseModel):
109
+ """Multiple choice output."""
110
+
111
+ choice: str | None = Field(
112
+ description="Multiple choice answer. For example, if there is <answer>A</answer> in the prompt, the output should be 'A'."
113
+ )
114
+
115
+ return MultipleChoiceOutput
BioScientist/agent_system/engines/v1_executor_backup/tool/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from biomni.utils import get_tool_decorated_functions # noqa: F401
BioScientist/agent_system/engines/v1_executor_backup/tool/biochemistry.py ADDED
@@ -0,0 +1,1026 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def analyze_circular_dichroism_spectra(
2
+ sample_name,
3
+ sample_type,
4
+ wavelength_data,
5
+ cd_signal_data,
6
+ temperature_data=None,
7
+ thermal_cd_data=None,
8
+ output_dir="./",
9
+ ):
10
+ """Analyzes circular dichroism (CD) spectroscopy data to determine secondary structure and thermal stability.
11
+
12
+ Parameters
13
+ ----------
14
+ sample_name : str
15
+ Name of the biomolecule sample (e.g., "Znf706", "G-quadruplex")
16
+ sample_type : str
17
+ Type of biomolecule ("protein" or "nucleic_acid")
18
+ wavelength_data : list or numpy.ndarray
19
+ Wavelength values in nm for CD spectrum
20
+ cd_signal_data : list or numpy.ndarray
21
+ CD signal intensity values (typically in mdeg or Δε)
22
+ temperature_data : list or numpy.ndarray, optional
23
+ Temperature values (°C) for thermal denaturation experiment
24
+ thermal_cd_data : list or numpy.ndarray, optional
25
+ CD signal values at specific wavelength across different temperatures
26
+ output_dir : str, optional
27
+ Directory to save result files, defaults to current directory
28
+
29
+ Returns
30
+ -------
31
+ str
32
+ Research log summarizing the CD analysis steps and results
33
+
34
+ """
35
+ import os
36
+ from datetime import datetime
37
+
38
+ import numpy as np
39
+
40
+ # Initialize research log
41
+ log = f"# Circular Dichroism Analysis Report for {sample_name}\n"
42
+ log += f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
43
+ log += "## Sample Information\n"
44
+ log += f"- Sample Name: {sample_name}\n"
45
+ log += f"- Sample Type: {sample_type}\n\n"
46
+
47
+ # Convert inputs to numpy arrays if they aren't already
48
+ wavelength_data = np.array(wavelength_data)
49
+ cd_signal_data = np.array(cd_signal_data)
50
+
51
+ # Ensure output directory exists
52
+ if not os.path.exists(output_dir):
53
+ os.makedirs(output_dir)
54
+
55
+ # 1. Analyze CD spectrum for secondary structure
56
+ log += "## Secondary Structure Analysis\n"
57
+
58
+ # Different analysis approaches based on sample type
59
+ if sample_type.lower() == "protein":
60
+ # Analyze protein secondary structure based on characteristic spectral features
61
+ alpha_helix_signal = np.sum((wavelength_data >= 190) & (wavelength_data <= 195) & (cd_signal_data > 0))
62
+ beta_sheet_signal = np.sum((wavelength_data >= 215) & (wavelength_data <= 220) & (cd_signal_data < 0))
63
+ random_coil_signal = np.sum((wavelength_data >= 195) & (wavelength_data <= 200) & (cd_signal_data < 0))
64
+
65
+ # Simple classification based on signal patterns
66
+ if alpha_helix_signal > beta_sheet_signal and alpha_helix_signal > random_coil_signal:
67
+ structure = "predominantly alpha-helical"
68
+ elif beta_sheet_signal > alpha_helix_signal and beta_sheet_signal > random_coil_signal:
69
+ structure = "predominantly beta-sheet"
70
+ else:
71
+ structure = "mixed or predominantly random coil"
72
+
73
+ log += f"- The CD spectrum indicates {structure} structure for {sample_name}.\n"
74
+ log += "- Key spectral features:\n"
75
+ log += " - 190-195 nm region: associated with alpha-helical content\n"
76
+ log += " - 215-220 nm region: associated with beta-sheet content\n\n"
77
+
78
+ elif sample_type.lower() == "nucleic_acid":
79
+ # Analyze nucleic acid structure (e.g., G-quadruplex has characteristic positive peak ~295 nm)
80
+ g_quadruplex_signal = np.sum((wavelength_data >= 290) & (wavelength_data <= 300) & (cd_signal_data > 0))
81
+ b_form_signal = np.sum((wavelength_data >= 270) & (wavelength_data <= 280) & (cd_signal_data > 0))
82
+
83
+ if g_quadruplex_signal > 0:
84
+ structure = "G-quadruplex characteristics"
85
+ elif b_form_signal > 0:
86
+ structure = "B-form characteristics"
87
+ else:
88
+ structure = "non-standard structure"
89
+
90
+ log += f"- The CD spectrum indicates {structure} for {sample_name}.\n"
91
+ log += "- Key spectral features:\n"
92
+ log += " - 290-300 nm positive peak: characteristic of G-quadruplex structures\n"
93
+ log += " - 270-280 nm positive peak: characteristic of B-form DNA\n\n"
94
+
95
+ # Save spectral data results
96
+ spectral_file = os.path.join(output_dir, f"{sample_name}_cd_spectrum_analysis.txt")
97
+ with open(spectral_file, "w") as f:
98
+ f.write("Wavelength (nm)\tCD Signal\n")
99
+ for wl, signal in zip(wavelength_data, cd_signal_data, strict=False):
100
+ f.write(f"{wl:.1f}\t{signal:.4f}\n")
101
+
102
+ log += f"- Detailed spectral data saved to: {spectral_file}\n\n"
103
+
104
+ # 2. Thermal stability analysis (if temperature data provided)
105
+ if temperature_data is not None and thermal_cd_data is not None:
106
+ temperature_data = np.array(temperature_data)
107
+ thermal_cd_data = np.array(thermal_cd_data)
108
+
109
+ log += "## Thermal Stability Analysis\n"
110
+
111
+ # Simple Tm estimation (melting temperature) - find temperature at 50% unfolding
112
+ # Normalize thermal data to 0-1 range for unfolding fraction
113
+ min_signal = np.min(thermal_cd_data)
114
+ max_signal = np.max(thermal_cd_data)
115
+ unfolded_fraction = (thermal_cd_data - min_signal) / (max_signal - min_signal)
116
+
117
+ # Find the temperature closest to 50% unfolding
118
+ tm_idx = np.argmin(np.abs(unfolded_fraction - 0.5))
119
+ tm = temperature_data[tm_idx]
120
+
121
+ log += f"- Estimated melting temperature (Tm): {tm:.1f}°C\n"
122
+
123
+ # Cooperativity assessment (crude estimate based on transition steepness)
124
+ t_range = temperature_data[-1] - temperature_data[0]
125
+ transition_width = (
126
+ t_range / len(temperature_data) * np.sum((unfolded_fraction > 0.2) & (unfolded_fraction < 0.8))
127
+ )
128
+
129
+ if transition_width < 0.2 * t_range:
130
+ cooperativity = "highly cooperative (sharp transition)"
131
+ elif transition_width < 0.4 * t_range:
132
+ cooperativity = "moderately cooperative"
133
+ else:
134
+ cooperativity = "non-cooperative (broad transition)"
135
+
136
+ log += f"- Thermal transition: {cooperativity}\n"
137
+
138
+ # Save thermal denaturation data
139
+ thermal_file = os.path.join(output_dir, f"{sample_name}_thermal_denaturation.txt")
140
+ with open(thermal_file, "w") as f:
141
+ f.write("Temperature (°C)\tCD Signal\tUnfolded Fraction\n")
142
+ for temp, signal, unfold in zip(temperature_data, thermal_cd_data, unfolded_fraction, strict=False):
143
+ f.write(f"{temp:.1f}\t{signal:.4f}\t{unfold:.4f}\n")
144
+
145
+ log += f"- Thermal denaturation data saved to: {thermal_file}\n\n"
146
+
147
+ # 3. Summary and conclusions
148
+ log += "## Conclusions\n"
149
+ if sample_type.lower() == "protein":
150
+ log += f"- {sample_name} shows {structure} according to CD spectroscopy.\n"
151
+ else:
152
+ log += f"- {sample_name} exhibits {structure} according to CD spectroscopy.\n"
153
+
154
+ if temperature_data is not None:
155
+ log += f"- The molecule has a melting temperature of {tm:.1f}°C with {cooperativity}.\n"
156
+
157
+ return log
158
+
159
+
160
+ def analyze_rna_secondary_structure_features(dot_bracket_structure, sequence=None):
161
+ """Calculate numeric values for various structural features of an RNA secondary structure.
162
+
163
+ Parameters
164
+ ----------
165
+ dot_bracket_structure : str
166
+ RNA secondary structure in dot-bracket notation (e.g., "(((...)))").
167
+ Parentheses represent base pairs, dots represent unpaired bases.
168
+ sequence : str, optional
169
+ The RNA sequence corresponding to the structure. If provided,
170
+ sequence-dependent energy calculations will be performed.
171
+
172
+ Returns
173
+ -------
174
+ str
175
+ A research log summarizing the calculated structural features and analysis steps.
176
+
177
+ """
178
+ # Initialize research log
179
+ log = "# RNA Secondary Structure Feature Analysis\n\n"
180
+
181
+ # Validate input
182
+ if not all(c in "().[]{}" for c in dot_bracket_structure):
183
+ return "Error: Invalid dot-bracket notation. Use only '()', '[]', '{}', and '.'"
184
+
185
+ log += f"Input structure (length: {len(dot_bracket_structure)}): {dot_bracket_structure}\n"
186
+ if sequence:
187
+ log += f"Input sequence (length: {len(sequence)}): {sequence}\n"
188
+ if len(sequence) != len(dot_bracket_structure):
189
+ return "Error: Sequence and structure lengths do not match."
190
+
191
+ # Extract base pairs
192
+ pairs = []
193
+ stack = []
194
+
195
+ for i, char in enumerate(dot_bracket_structure):
196
+ if char in "([{":
197
+ stack.append((i, char))
198
+ elif char in ")]}":
199
+ if not stack:
200
+ return "Error: Unbalanced structure. More closing than opening brackets."
201
+
202
+ j, opening_char = stack.pop()
203
+ # Check for matching bracket types
204
+ if (
205
+ (opening_char == "(" and char != ")")
206
+ or (opening_char == "[" and char != "]")
207
+ or (opening_char == "{" and char != "}")
208
+ ):
209
+ return "Error: Mismatched bracket types. Opening and closing brackets must match."
210
+
211
+ pairs.append((j, i))
212
+
213
+ if stack:
214
+ return "Error: Unbalanced structure. More opening than closing brackets."
215
+
216
+ # Sort pairs by position
217
+ pairs.sort()
218
+
219
+ # Identify stems (consecutive base pairs)
220
+ stems = []
221
+ current_stem = []
222
+
223
+ for i, (start, end) in enumerate(pairs):
224
+ if (i == 0 or start != pairs[i - 1][0] + 1 or end != pairs[i - 1][1] - 1) and current_stem:
225
+ stems.append(current_stem)
226
+ current_stem = []
227
+ current_stem.append((start, end))
228
+
229
+ if current_stem:
230
+ stems.append(current_stem)
231
+
232
+ # Calculate stem lengths
233
+ stem_lengths = [len(stem) for stem in stems]
234
+
235
+ # Calculate loop sizes
236
+ loops = []
237
+ for i in range(len(stems)):
238
+ stem = stems[i]
239
+ last_pair = stem[-1]
240
+ next_stem_start = stems[i + 1][0][0] if i < len(stems) - 1 else len(dot_bracket_structure)
241
+ loop_size = next_stem_start - last_pair[1] - 1
242
+ if loop_size > 0:
243
+ loops.append(loop_size)
244
+
245
+ # Calculate base pair statistics
246
+ total_paired_bases = len(pairs) * 2
247
+ total_unpaired_bases = len(dot_bracket_structure) - total_paired_bases
248
+
249
+ # Calculate simplified free energy if sequence is provided
250
+ stem_energies = []
251
+ if sequence and len(stems) > 0:
252
+ # Simplified energy parameters for nearest-neighbor model
253
+ # Values are approximate and simplified for illustration
254
+ energy_params = {
255
+ "AU": -0.9,
256
+ "UA": -0.9,
257
+ "GC": -2.1,
258
+ "CG": -2.1,
259
+ "GU": -0.5,
260
+ "UG": -0.5,
261
+ }
262
+
263
+ for stem in stems:
264
+ stem_energy = 0
265
+ for start, end in stem:
266
+ if start < len(sequence) and end < len(sequence):
267
+ pair = sequence[start] + sequence[end]
268
+ stem_energy += energy_params.get(pair, 0)
269
+ stem_energies.append(stem_energy)
270
+
271
+ # Prepare results
272
+ log += "\n## Structural Features\n\n"
273
+ log += f"Total base pairs: {len(pairs)}\n"
274
+ log += f"Number of stems: {len(stems)}\n"
275
+ log += f"Longest stem length: {max(stem_lengths) if stem_lengths else 0}\n"
276
+ log += f"Average stem length: {sum(stem_lengths) / len(stem_lengths) if stem_lengths else 0:.2f}\n"
277
+ log += f"Paired bases: {total_paired_bases} ({total_paired_bases / len(dot_bracket_structure) * 100:.1f}%)\n"
278
+ log += f"Unpaired bases: {total_unpaired_bases} ({total_unpaired_bases / len(dot_bracket_structure) * 100:.1f}%)\n"
279
+
280
+ if loops:
281
+ log += f"Number of loops: {len(loops)}\n"
282
+ log += f"Average loop size: {sum(loops) / len(loops):.2f}\n"
283
+ log += f"Largest loop size: {max(loops)}\n"
284
+
285
+ if sequence and stem_energies:
286
+ log += "\n## Energy Calculations\n\n"
287
+ log += f"Total estimated free energy: {sum(stem_energies):.2f} kcal/mol\n"
288
+
289
+ if len(stems) >= 2:
290
+ log += f"Upstream stem free energy: {stem_energies[0]:.2f} kcal/mol\n"
291
+ log += f"Downstream stem free energy: {stem_energies[-1]:.2f} kcal/mol\n"
292
+
293
+ # If the first stem is the "zipper" stem
294
+ if stem_lengths and stem_lengths[0] >= 3:
295
+ log += f"Zipper stem free energy: {stem_energies[0]:.2f} kcal/mol\n"
296
+
297
+ log += "\n## Stem Details\n\n"
298
+ for i, stem in enumerate(stems):
299
+ log += f"Stem {i + 1}: {len(stem)} base pairs\n"
300
+ log += f" Positions: {stem[0][0]}-{stem[0][1]} to {stem[-1][0]}-{stem[-1][1]}\n"
301
+ if sequence and i < len(stem_energies):
302
+ log += f" Estimated stability: {stem_energies[i]:.2f} kcal/mol\n"
303
+
304
+ return log
305
+
306
+
307
+ def analyze_protease_kinetics(
308
+ time_points,
309
+ fluorescence_data,
310
+ substrate_concentrations,
311
+ enzyme_concentration,
312
+ output_prefix="protease_kinetics",
313
+ output_dir="./",
314
+ ):
315
+ """Analyze protease kinetics data from fluorogenic peptide cleavage assays.
316
+
317
+ This function processes time-course fluorescence data from protease-mediated peptide
318
+ cleavage assays, fits the data to Michaelis-Menten kinetics, and determines key
319
+ kinetic parameters (kcat, KM, and catalytic efficiency).
320
+
321
+ Parameters
322
+ ----------
323
+ time_points : numpy.ndarray
324
+ Array of time points (in seconds) at which measurements were taken
325
+
326
+ fluorescence_data : numpy.ndarray
327
+ 2D array of fluorescence measurements where each row corresponds to a different
328
+ substrate concentration and each column corresponds to a time point
329
+
330
+ substrate_concentrations : numpy.ndarray
331
+ Array of substrate concentrations (in μM) corresponding to each row in fluorescence_data
332
+
333
+ enzyme_concentration : float
334
+ Concentration of the protease enzyme (in μM)
335
+
336
+ output_prefix : str, optional
337
+ Prefix for output files (default: "protease_kinetics")
338
+
339
+ output_dir : str, optional
340
+ Directory to save output files (default: "./")
341
+
342
+ Returns
343
+ -------
344
+ str
345
+ A research log summarizing the analysis steps and results
346
+
347
+ """
348
+ import os
349
+
350
+ import matplotlib.pyplot as plt
351
+ import numpy as np
352
+ from scipy.optimize import curve_fit
353
+
354
+ # Ensure output directory exists
355
+ if not os.path.exists(output_dir):
356
+ os.makedirs(output_dir)
357
+
358
+ # Create full output paths
359
+ plot_filename = os.path.join(output_dir, f"{output_prefix}_mm_plot.png")
360
+ results_filename = os.path.join(output_dir, f"{output_prefix}_results.txt")
361
+
362
+ # Step 1: Calculate initial velocities for each substrate concentration
363
+ initial_velocities = np.zeros(len(substrate_concentrations))
364
+
365
+ for i, fluorescence_curve in enumerate(fluorescence_data):
366
+ # Linear fit to the initial portion of the curve (first 20% of time points or at least 5 points)
367
+ num_points = max(5, int(len(time_points) * 0.2))
368
+ slope, _ = np.polyfit(time_points[:num_points], fluorescence_curve[:num_points], 1)
369
+ initial_velocities[i] = slope
370
+
371
+ # Step 2: Define Michaelis-Menten equation for curve fitting
372
+ def michaelis_menten(s, vmax, km):
373
+ return vmax * s / (km + s)
374
+
375
+ # Step 3: Fit the data to the Michaelis-Menten equation
376
+ try:
377
+ params, covariance = curve_fit(
378
+ michaelis_menten,
379
+ substrate_concentrations,
380
+ initial_velocities,
381
+ p0=[max(initial_velocities), np.mean(substrate_concentrations)],
382
+ bounds=([0, 0], [np.inf, np.inf]),
383
+ )
384
+
385
+ vmax, km = params
386
+ std_dev = np.sqrt(np.diag(covariance))
387
+ vmax_std, km_std = std_dev
388
+
389
+ # Step 4: Calculate kcat and catalytic efficiency
390
+ kcat = vmax / enzyme_concentration
391
+ kcat_std = vmax_std / enzyme_concentration
392
+ catalytic_efficiency = kcat / km
393
+ catalytic_efficiency_std = catalytic_efficiency * np.sqrt((kcat_std / kcat) ** 2 + (km_std / km) ** 2)
394
+
395
+ # Step 5: Create a plot and save it
396
+ plt.figure(figsize=(10, 6))
397
+ plt.scatter(
398
+ substrate_concentrations,
399
+ initial_velocities,
400
+ color="blue",
401
+ label="Experimental data",
402
+ )
403
+
404
+ # Generate smooth curve for the fitted model
405
+ s_curve = np.linspace(0, max(substrate_concentrations) * 1.2, 100)
406
+ v_curve = michaelis_menten(s_curve, vmax, km)
407
+ plt.plot(s_curve, v_curve, "r-", label="Michaelis-Menten fit")
408
+
409
+ plt.xlabel("Substrate Concentration (μM)")
410
+ plt.ylabel("Initial Velocity (a.u./s)")
411
+ plt.title("Michaelis-Menten Kinetics")
412
+ plt.legend()
413
+ plt.grid(True, alpha=0.3)
414
+
415
+ plt.savefig(plot_filename)
416
+ plt.close()
417
+
418
+ # Step 6: Save numerical results to a file
419
+ with open(results_filename, "w") as f:
420
+ f.write("Protease Kinetics Analysis Results\n")
421
+ f.write("==================================\n\n")
422
+ f.write(f"Vmax: {vmax:.4f} ± {vmax_std:.4f} a.u./s\n")
423
+ f.write(f"KM: {km:.4f} ± {km_std:.4f} μM\n")
424
+ f.write(f"kcat: {kcat:.4f} ± {kcat_std:.4f} s^-1\n")
425
+ f.write(
426
+ f"Catalytic efficiency (kcat/KM): {catalytic_efficiency:.4f} ± {catalytic_efficiency_std:.4f} μM^-1 s^-1\n"
427
+ )
428
+
429
+ # Step 7: Create research log
430
+ research_log = f"""
431
+ Protease Kinetics Analysis Research Log
432
+ ======================================
433
+
434
+ Analysis Steps:
435
+ 1. Calculated initial velocities from time-course fluorescence data for {len(substrate_concentrations)} different substrate concentrations
436
+ 2. Fitted initial velocities to the Michaelis-Menten equation using non-linear regression
437
+ 3. Determined kinetic parameters and their uncertainties
438
+
439
+ Results:
440
+ - Vmax: {vmax:.4f} ± {vmax_std:.4f} a.u./s
441
+ - KM: {km:.4f} ± {km_std:.4f} μM
442
+ - kcat: {kcat:.4f} ± {kcat_std:.4f} s^-1
443
+ - Catalytic efficiency (kcat/KM): {catalytic_efficiency:.4f} ± {catalytic_efficiency_std:.4f} μM^-1 s^-1
444
+
445
+ Files Generated:
446
+ 1. {plot_filename} - Michaelis-Menten plot showing experimental data and fitted curve
447
+ 2. {results_filename} - Text file containing detailed results
448
+
449
+ Analysis completed successfully.
450
+ """
451
+
452
+ return research_log
453
+
454
+ except Exception as e:
455
+ return f"Error during analysis: {str(e)}"
456
+
457
+
458
+ def analyze_enzyme_kinetics_assay(
459
+ enzyme_name,
460
+ substrate_concentrations,
461
+ enzyme_concentration,
462
+ modulators=None,
463
+ time_points=None,
464
+ output_dir="./",
465
+ ):
466
+ """Performs in vitro enzyme kinetics assay and analyzes the dose-dependent effects of modulators.
467
+
468
+ Parameters
469
+ ----------
470
+ enzyme_name : str
471
+ Name of the purified enzyme being tested
472
+ substrate_concentrations : list or numpy.ndarray
473
+ List of substrate concentrations in μM for kinetic analysis
474
+ enzyme_concentration : float
475
+ Concentration of the enzyme in nM
476
+ modulators : dict, optional
477
+ Dictionary of modulators where keys are modulator names and values are lists of
478
+ concentrations in μM. Default is None (no modulators).
479
+ time_points : list or numpy.ndarray, optional
480
+ Time points in minutes for time-course measurements. Default is None, which uses
481
+ [0, 5, 10, 15, 20, 30, 45, 60].
482
+ output_dir : str, optional
483
+ Directory to save output files. Default is current directory.
484
+
485
+ Returns
486
+ -------
487
+ str
488
+ Research log summarizing the enzyme kinetics assay procedure and results
489
+
490
+ """
491
+ import csv
492
+ import os
493
+
494
+ import numpy as np
495
+ from scipy.optimize import curve_fit
496
+
497
+ # Create output directory if it doesn't exist
498
+ if not os.path.exists(output_dir):
499
+ os.makedirs(output_dir)
500
+
501
+ # Set default time points if not provided
502
+ if time_points is None:
503
+ time_points = np.array([0, 5, 10, 15, 20, 30, 45, 60])
504
+ else:
505
+ # Ensure time_points is a numpy array
506
+ time_points = np.array(time_points)
507
+
508
+ # Initialize research log
509
+ log = f"## In Vitro Enzyme Kinetics Assay: {enzyme_name}\n\n"
510
+ log += f"Enzyme concentration: {enzyme_concentration} nM\n"
511
+
512
+ # Michaelis-Menten equation for curve fitting
513
+ def michaelis_menten(s, vmax, km):
514
+ return vmax * s / (km + s)
515
+
516
+ # 1. Time-course kinetic assay
517
+ log += "\n### Time-Course Kinetic Assay\n\n"
518
+ log += "Measuring enzyme activity over time to establish linear range.\n"
519
+
520
+ # Simulate time-course data (realistic enzyme kinetics with some noise)
521
+ # Using a simple exponential approach to equilibrium model
522
+ max_activity = 100 # arbitrary units
523
+ rate_constant = 0.05 # min^-1
524
+
525
+ # Simulate enzyme activity over time with some noise
526
+ np.random.seed(42) # For reproducibility
527
+ time_course_activity = max_activity * (1 - np.exp(-rate_constant * time_points))
528
+ time_course_activity += np.random.normal(0, 3, len(time_points)) # Add noise
529
+
530
+ # Save time-course data
531
+ time_course_file = os.path.join(output_dir, f"{enzyme_name}_time_course.csv")
532
+ with open(time_course_file, "w", newline="") as f:
533
+ writer = csv.writer(f)
534
+ writer.writerow(["Time (min)", "Activity (units)"])
535
+ for t, a in zip(time_points, time_course_activity, strict=False):
536
+ writer.writerow([t, a])
537
+
538
+ # Determine linear range (first ~30% of the curve)
539
+ linear_cutoff_index = np.where(time_course_activity >= 0.3 * max_activity)[0][0]
540
+ linear_time = time_points[: linear_cutoff_index + 1]
541
+
542
+ log += f"Time-course data saved to: {time_course_file}\n"
543
+ log += f"Linear range determined to be 0-{linear_time[-1]} minutes.\n"
544
+
545
+ # 2. Substrate kinetics (Michaelis-Menten analysis)
546
+ log += "\n### Substrate Kinetics Analysis\n\n"
547
+
548
+ # Simulate enzyme activity at different substrate concentrations
549
+ # based on Michaelis-Menten kinetics
550
+ true_vmax = 120 # arbitrary units
551
+ true_km = 25 # μM
552
+
553
+ activity_values = michaelis_menten(np.array(substrate_concentrations), true_vmax, true_km)
554
+ activity_values += np.random.normal(0, 5, len(substrate_concentrations)) # Add noise
555
+
556
+ # Fit data to Michaelis-Menten equation
557
+ try:
558
+ params, _ = curve_fit(
559
+ michaelis_menten,
560
+ substrate_concentrations,
561
+ activity_values,
562
+ p0=[100, 20],
563
+ bounds=([0, 0], [500, 200]),
564
+ )
565
+ vmax, km = params
566
+
567
+ # Save substrate kinetics data
568
+ kinetics_file = os.path.join(output_dir, f"{enzyme_name}_substrate_kinetics.csv")
569
+ with open(kinetics_file, "w", newline="") as f:
570
+ writer = csv.writer(f)
571
+ writer.writerow(["Substrate (μM)", "Activity (units)"])
572
+ for s, a in zip(substrate_concentrations, activity_values, strict=False):
573
+ writer.writerow([s, a])
574
+
575
+ log += "Michaelis-Menten parameters:\n"
576
+ log += f"- Vmax: {vmax:.2f} units\n"
577
+ log += f"- Km: {km:.2f} μM\n"
578
+ log += f"Substrate kinetics data saved to: {kinetics_file}\n"
579
+ except Exception:
580
+ log += "Error: Could not fit data to Michaelis-Menten model.\n"
581
+
582
+ # 3. Modulator effects (if provided)
583
+ if modulators:
584
+ log += "\n### Modulator Effects Analysis\n\n"
585
+
586
+ for modulator_name, concentrations in modulators.items():
587
+ log += f"#### Testing modulator: {modulator_name}\n\n"
588
+
589
+ # Choose a fixed substrate concentration near Km for inhibition studies
590
+ substrate_conc = true_km
591
+
592
+ # Simulate modulator effects (e.g., competitive inhibition)
593
+ # For simplicity, using a sigmoidal dose-response curve
594
+ ic50 = np.random.uniform(1, 50) # Random IC50 between 1-50 μM
595
+ hill_coef = 1.0 # Hill coefficient
596
+
597
+ # Calculate normalized activity (% of control)
598
+ michaelis_menten(substrate_conc, true_vmax, true_km)
599
+
600
+ # Calculate activities at different modulator concentrations
601
+ modulator_activities = []
602
+ for conc in concentrations:
603
+ # Sigmoidal dose-response curve
604
+ if conc == 0:
605
+ activity = 100 # 100% activity at zero concentration
606
+ else:
607
+ activity = 100 / (1 + (conc / ic50) ** hill_coef)
608
+
609
+ # Add some noise
610
+ activity += np.random.normal(0, 3)
611
+ modulator_activities.append(activity)
612
+
613
+ # Save modulator data
614
+ modulator_file = os.path.join(output_dir, f"{enzyme_name}_{modulator_name}_dose_response.csv")
615
+ with open(modulator_file, "w", newline="") as f:
616
+ writer = csv.writer(f)
617
+ writer.writerow([f"{modulator_name} (μM)", "Activity (% of control)"])
618
+ for conc, act in zip(concentrations, modulator_activities, strict=False):
619
+ writer.writerow([conc, act])
620
+
621
+ # Calculate IC50 using curve fitting if there are enough data points
622
+ if len(concentrations) >= 4:
623
+ try:
624
+ # Define dose-response curve function
625
+ def dose_response(x, ic50, hill):
626
+ return 100 / (1 + (x / ic50) ** hill)
627
+
628
+ # Filter out zero concentration
629
+ nonzero_conc = np.array([c for c in concentrations if c > 0])
630
+ nonzero_act = np.array(
631
+ [a for c, a in zip(concentrations, modulator_activities, strict=False) if c > 0]
632
+ )
633
+
634
+ if len(nonzero_conc) >= 3: # Need at least 3 points for fitting
635
+ params, _ = curve_fit(
636
+ dose_response,
637
+ nonzero_conc,
638
+ nonzero_act,
639
+ p0=[10, 1],
640
+ bounds=([0.1, 0.1], [1000, 10]),
641
+ )
642
+ calc_ic50, calc_hill = params
643
+
644
+ log += f"Dose-response analysis for {modulator_name}:\n"
645
+ log += f"- IC50: {calc_ic50:.2f} μM\n"
646
+ log += f"- Hill coefficient: {calc_hill:.2f}\n"
647
+ else:
648
+ log += f"Insufficient non-zero data points to calculate IC50 for {modulator_name}.\n"
649
+ except Exception:
650
+ log += f"Error: Could not fit dose-response curve for {modulator_name}.\n"
651
+ else:
652
+ log += f"Insufficient data points to calculate IC50 for {modulator_name}.\n"
653
+
654
+ log += f"Dose-response data for {modulator_name} saved to: {modulator_file}\n\n"
655
+
656
+ # 4. Summary
657
+ log += "\n### Summary\n\n"
658
+ log += f"Completed in vitro enzyme kinetics assay for {enzyme_name}.\n"
659
+ log += f"- Determined linear range for time-course measurements: 0-{linear_time[-1]} minutes\n"
660
+ log += f"- Characterized Michaelis-Menten kinetics (Vmax: {vmax:.2f} units, Km: {km:.2f} μM)\n"
661
+
662
+ if modulators:
663
+ log += "- Analyzed the effects of modulators:\n"
664
+ for modulator_name in modulators:
665
+ log += f" * {modulator_name}: Data saved to {enzyme_name}_{modulator_name}_dose_response.csv\n"
666
+
667
+ return log
668
+
669
+
670
+ def analyze_itc_binding_thermodynamics(
671
+ itc_data_path=None,
672
+ itc_data=None,
673
+ temperature=298.15,
674
+ protein_concentration=None,
675
+ ligand_concentration=None,
676
+ ):
677
+ """Analyzes isothermal titration calorimetry (ITC) data to determine binding affinity and thermodynamic parameters.
678
+
679
+ Parameters
680
+ ----------
681
+ itc_data_path : str, optional
682
+ Path to CSV or TSV file containing ITC thermogram data with columns for injection number,
683
+ injection volume, and heat released/absorbed. Expected columns: 'injection', 'volume', 'heat'
684
+ itc_data : numpy.ndarray, optional
685
+ Raw ITC thermogram data as a numpy array.
686
+ Expected shape: (n_injections, 3) with columns for injection number, injection volume, and heat
687
+ This parameter is provided for backward compatibility and will be deprecated.
688
+ temperature : float, optional
689
+ Temperature in Kelvin at which the experiment was conducted. Default is 298.15 K (25°C).
690
+ protein_concentration : float, optional
691
+ Initial concentration of protein in the cell in molar (M). Required for accurate fitting.
692
+ ligand_concentration : float, optional
693
+ Concentration of ligand in the syringe in molar (M). Required for accurate fitting.
694
+
695
+ Returns
696
+ -------
697
+ str
698
+ A research log summarizing the analysis steps and results, including binding affinity (Kd),
699
+ binding enthalpy (ΔH), binding entropy (ΔS), and Gibbs free energy (ΔG).
700
+
701
+ """
702
+ import datetime
703
+
704
+ import numpy as np
705
+ import pandas as pd
706
+ from scipy.optimize import curve_fit
707
+
708
+ log = []
709
+ log.append(f"# ITC Binding Affinity Analysis - {datetime.datetime.now().strftime('%Y-%m-%d %H:%M')}")
710
+ log.append("\n## Data Preprocessing")
711
+
712
+ # Check if we have data to process
713
+ if itc_data_path is None and itc_data is None:
714
+ log.append("Error: No data provided. Please provide either itc_data_path or itc_data.")
715
+ return "\n".join(log)
716
+
717
+ # Load data from file if path is provided
718
+ if itc_data_path is not None:
719
+ try:
720
+ if itc_data_path.endswith(".csv"):
721
+ loaded_data = pd.read_csv(itc_data_path)
722
+ elif itc_data_path.endswith((".tsv", ".txt")):
723
+ loaded_data = pd.read_csv(itc_data_path, sep="\t")
724
+ else:
725
+ log.append("Error: Unsupported file format. Please provide a CSV or TSV file.")
726
+ return "\n".join(log)
727
+
728
+ log.append(f"- Loaded data from file: {itc_data_path}")
729
+ log.append(f"- Input data: DataFrame with {len(loaded_data)} injections")
730
+
731
+ if all(col in loaded_data.columns for col in ["injection", "volume", "heat"]):
732
+ data = loaded_data[["injection", "volume", "heat"]].values
733
+ else:
734
+ log.append("- Error: DataFrame must contain 'injection', 'volume', and 'heat' columns")
735
+ return "\n".join(log)
736
+ except Exception as e:
737
+ log.append(f"- Error loading data from file: {str(e)}")
738
+ return "\n".join(log)
739
+ # Use provided numpy array data
740
+ elif itc_data is not None:
741
+ if isinstance(itc_data, pd.DataFrame):
742
+ log.append("Warning: Passing DataFrame directly is deprecated. Please use itc_data_path instead.")
743
+ log.append(f"- Input data: DataFrame with {len(itc_data)} injections")
744
+ if all(col in itc_data.columns for col in ["injection", "volume", "heat"]):
745
+ data = itc_data[["injection", "volume", "heat"]].values
746
+ else:
747
+ log.append("- Error: DataFrame must contain 'injection', 'volume', and 'heat' columns")
748
+ return "\n".join(log)
749
+ else:
750
+ log.append(f"- Input data: Array with {len(itc_data)} injections")
751
+ data = np.array(itc_data)
752
+
753
+ # Check if concentration data is provided
754
+ if protein_concentration is None or ligand_concentration is None:
755
+ log.append("- Warning: Protein or ligand concentration not provided. Using normalized data for fitting.")
756
+ protein_concentration = 1.0
757
+ ligand_concentration = 10.0
758
+
759
+ # Extract data
760
+ injections = data[:, 0]
761
+ volumes = data[:, 1]
762
+ heats = data[:, 2]
763
+
764
+ log.append(f"- Processed {len(injections)} injections")
765
+
766
+ # Calculate molar ratio for each injection
767
+ cell_volume = 1.4 # Default cell volume in mL (typical for ITC)
768
+
769
+ # Calculate cumulative ligand added
770
+ cumulative_volume = np.cumsum(volumes)
771
+ dilution_factor = 1 - (cumulative_volume / cell_volume)
772
+ protein_conc_corrected = protein_concentration * dilution_factor
773
+
774
+ # Calculate molar ratio [ligand]/[protein] for each injection
775
+ molar_ratios = np.zeros_like(injections, dtype=float)
776
+ for i in range(len(injections)):
777
+ ligand_added = volumes[i] * ligand_concentration / 1000 # Convert to mmol
778
+ if i == 0:
779
+ molar_ratios[i] = ligand_added / (protein_concentration * cell_volume / 1000) # Convert to mmol
780
+ else:
781
+ # Account for dilution and previous injections
782
+ molar_ratios[i] = molar_ratios[i - 1] + ligand_added / (
783
+ protein_conc_corrected[i] * (cell_volume - cumulative_volume[i]) / 1000
784
+ )
785
+
786
+ log.append("\n## Model Fitting")
787
+ log.append("- Applying one-site binding model to the ITC data")
788
+
789
+ # Define one-site binding model function
790
+ def one_site_model(x, Kd, dH, n):
791
+ """One-site binding model for ITC data.
792
+
793
+ Parameters
794
+ ----------
795
+ x: Molar ratio [ligand]/[protein]
796
+ Kd: Dissociation constant (M)
797
+ dH: Enthalpy change (cal/mol)
798
+ n: Stoichiometry
799
+
800
+ Returns: Heat per injection
801
+
802
+ """
803
+ # Convert x to fraction bound using the binding equation
804
+ Ka = 1 / Kd # Association constant
805
+ protein = protein_conc_corrected
806
+
807
+ # Calculate heat for each injection
808
+ q = np.zeros_like(x)
809
+ for i in range(len(x)):
810
+ if i == 0:
811
+ # First injection
812
+ bound = (n * protein[i] * Ka * (x[i] * protein[i])) / (1 + Ka * (x[i] * protein[i]))
813
+ q[i] = bound * dH * cell_volume
814
+ else:
815
+ # Subsequent injections (differential heat)
816
+ bound_prev = (n * protein[i - 1] * Ka * (x[i - 1] * protein[i - 1])) / (
817
+ 1 + Ka * (x[i - 1] * protein[i - 1])
818
+ )
819
+ bound_curr = (n * protein[i] * Ka * (x[i] * protein[i])) / (1 + Ka * (x[i] * protein[i]))
820
+ q[i] = bound_curr * dH * (cell_volume - cumulative_volume[i]) - bound_prev * dH * (
821
+ cell_volume - cumulative_volume[i - 1]
822
+ )
823
+
824
+ return q
825
+
826
+ # Initial parameter guesses
827
+ p0 = [1e-6, -5000, 1.0] # Kd (M), dH (cal/mol), n (stoichiometry)
828
+
829
+ try:
830
+ # Fit the model to the data
831
+ popt, pcov = curve_fit(one_site_model, molar_ratios, heats, p0=p0, maxfev=10000)
832
+ Kd, dH, n = popt
833
+
834
+ # Calculate standard errors
835
+ perr = np.sqrt(np.diag(pcov))
836
+ Kd_err, dH_err, n_err = perr
837
+
838
+ # Calculate other thermodynamic parameters
839
+ R = 1.9872 # Gas constant in cal/(mol·K)
840
+ dG = R * temperature * np.log(Kd) # Gibbs free energy
841
+ dS = (dH - dG) / temperature # Entropy
842
+
843
+ log.append("- Model fitting successful")
844
+ log.append("\n## Results")
845
+ log.append(f"- Binding Stoichiometry (n): {n:.2f} ± {n_err:.2f}")
846
+ log.append(f"- Dissociation Constant (Kd): {Kd * 1e6:.2f} ± {Kd_err * 1e6:.2f} μM")
847
+ log.append(f"- Association Constant (Ka): {1 / Kd / 1e6:.2f} × 10^6 M^-1")
848
+ log.append(f"- Binding Enthalpy (ΔH): {dH:.2f} ± {dH_err:.2f} cal/mol")
849
+ log.append(f"- Binding Entropy (ΔS): {dS:.2f} cal/(mol·K)")
850
+ log.append(f"- Gibbs Free Energy (ΔG): {dG:.2f} cal/mol")
851
+
852
+ # Calculate goodness of fit
853
+ residuals = heats - one_site_model(molar_ratios, *popt)
854
+ ss_res = np.sum(residuals**2)
855
+ ss_tot = np.sum((heats - np.mean(heats)) ** 2)
856
+ r_squared = 1 - (ss_res / ss_tot)
857
+ log.append(f"- R-squared: {r_squared:.4f}")
858
+
859
+ except Exception as e:
860
+ log.append(f"- Error during model fitting: {str(e)}")
861
+ log.append("- Consider trying different initial parameter guesses or a different binding model")
862
+
863
+ log.append("\n## Conclusion")
864
+ log.append("- Analysis complete. The thermodynamic parameters have been estimated using a one-site binding model.")
865
+ log.append(
866
+ "- For more complex binding scenarios, consider using multi-site binding models or specialized ITC analysis software."
867
+ )
868
+
869
+ return "\n".join(log)
870
+
871
+
872
+ def analyze_protein_conservation(protein_sequences, output_dir="./"):
873
+ """Perform multiple sequence alignment and phylogenetic analysis to identify conserved protein regions.
874
+
875
+ Parameters
876
+ ----------
877
+ protein_sequences : list of str
878
+ List of protein sequences in FASTA format from multiple organisms.
879
+ output_dir : str, optional
880
+ Directory to save output files (default: "./output")
881
+
882
+ Returns
883
+ -------
884
+ str
885
+ Research log summarizing the analysis steps and results, including filenames of saved outputs.
886
+
887
+ """
888
+ import os
889
+
890
+ from Bio import AlignIO, Phylo, SeqIO
891
+ from Bio.Align.Applications import MuscleCommandline
892
+ from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor
893
+
894
+ # Create a research log
895
+ log = []
896
+ log.append("# Protein Sequence Alignment and Conservation Analysis")
897
+
898
+ # Ensure output directory exists
899
+ if not os.path.exists(output_dir):
900
+ os.makedirs(output_dir)
901
+
902
+ # Step 1: Save input sequences to a temporary file
903
+ log.append("\n## Step 1: Preparing Input Sequences")
904
+ input_file = os.path.join(output_dir, "input.fasta")
905
+
906
+ # Check if input is already in FASTA format or needs conversion
907
+ if isinstance(protein_sequences, list):
908
+ if all(">" in seq for seq in protein_sequences):
909
+ # Already in FASTA format
910
+ with open(input_file, "w") as f:
911
+ f.write("\n".join(protein_sequences))
912
+ else:
913
+ # Convert to FASTA format
914
+ with open(input_file, "w") as f:
915
+ for i, seq in enumerate(protein_sequences):
916
+ f.write(f">Sequence_{i + 1}\n{seq}\n")
917
+ else:
918
+ # Assume it's a single string in FASTA format
919
+ with open(input_file, "w") as f:
920
+ f.write(protein_sequences)
921
+
922
+ log.append(f"Input sequences saved to {input_file}")
923
+ log.append(f"Number of sequences: {len(list(SeqIO.parse(input_file, 'fasta')))}")
924
+
925
+ # Step 2: Perform multiple sequence alignment using MUSCLE
926
+ log.append("\n## Step 2: Multiple Sequence Alignment")
927
+ aligned_file = os.path.join(output_dir, "aligned.fasta")
928
+
929
+ try:
930
+ # Run MUSCLE for multiple sequence alignment
931
+ muscle_cline = MuscleCommandline(input=input_file, out=aligned_file)
932
+ stdout, stderr = muscle_cline()
933
+ log.append("Multiple sequence alignment completed using MUSCLE")
934
+ log.append(f"Alignment saved to {aligned_file}")
935
+
936
+ # Load the alignment
937
+ alignment = AlignIO.read(aligned_file, "fasta")
938
+ log.append(f"Alignment length: {alignment.get_alignment_length()} positions")
939
+
940
+ except Exception as e:
941
+ log.append(f"MUSCLE alignment failed: {str(e)}")
942
+ log.append("Attempting to use Biopython's built-in alignment methods...")
943
+
944
+ # Fallback to a simpler approach without pairwise2
945
+ from Bio.Align import MultipleSeqAlignment
946
+ from Bio.Seq import Seq
947
+ from Bio.SeqRecord import SeqRecord
948
+
949
+ sequences = list(SeqIO.parse(input_file, "fasta"))
950
+
951
+ # Simple approach: just pad sequences to the same length
952
+ max_length = max(len(seq.seq) for seq in sequences)
953
+ alignments = []
954
+
955
+ for seq in sequences:
956
+ # Pad sequence to max length
957
+ padded_seq = str(seq.seq).ljust(max_length, "-")
958
+ new_seq = SeqRecord(Seq(padded_seq), id=seq.id, description=seq.description)
959
+ alignments.append(new_seq)
960
+
961
+ # Create and save the alignment
962
+ msa = MultipleSeqAlignment(alignments)
963
+ AlignIO.write(msa, aligned_file, "fasta")
964
+ alignment = msa
965
+ log.append("Simple padding alignment completed as fallback method")
966
+ log.append(f"Alignment saved to {aligned_file}")
967
+
968
+ # Step 3: Generate a phylogenetic tree
969
+ log.append("\n## Step 3: Phylogenetic Analysis")
970
+ tree_file = os.path.join(output_dir, "tree.newick")
971
+
972
+ # Calculate distance matrix
973
+ calculator = DistanceCalculator("identity")
974
+ dm = calculator.get_distance(alignment)
975
+
976
+ # Construct the phylogenetic tree using neighbor-joining method
977
+ constructor = DistanceTreeConstructor()
978
+ tree = constructor.nj(dm)
979
+
980
+ # Save the tree
981
+ Phylo.write(tree, tree_file, "newick")
982
+ log.append("Phylogenetic tree constructed using neighbor-joining method")
983
+ log.append(f"Tree saved to {tree_file}")
984
+
985
+ # Step 4: Analyze conserved regions
986
+ log.append("\n## Step 4: Conservation Analysis")
987
+ conservation_file = os.path.join(output_dir, "conservation.txt")
988
+
989
+ # Simple conservation analysis
990
+ alignment_length = alignment.get_alignment_length()
991
+ conserved_positions = []
992
+
993
+ with open(conservation_file, "w") as f:
994
+ f.write("Position\tConservation_Score\tConsensus\n")
995
+
996
+ for i in range(alignment_length):
997
+ # Get all amino acids at this position
998
+ column = alignment[:, i]
999
+ set(column)
1000
+
1001
+ # Calculate a simple conservation score (percentage of most common AA)
1002
+ most_common_aa = max(column, key=column.count)
1003
+ conservation_score = column.count(most_common_aa) / len(column)
1004
+
1005
+ f.write(f"{i + 1}\t{conservation_score:.2f}\t{most_common_aa}\n")
1006
+
1007
+ # Consider positions with >80% conservation as conserved
1008
+ if conservation_score > 0.8:
1009
+ conserved_positions.append(i + 1)
1010
+
1011
+ log.append(f"Conservation analysis completed and saved to {conservation_file}")
1012
+ log.append(f"Identified {len(conserved_positions)} highly conserved positions (>80% conservation)")
1013
+
1014
+ if conserved_positions:
1015
+ log.append(f"Conserved positions: {', '.join(map(str, conserved_positions[:10]))}")
1016
+ if len(conserved_positions) > 10:
1017
+ log.append(f"... and {len(conserved_positions) - 10} more")
1018
+
1019
+ # Final summary
1020
+ log.append("\n## Summary")
1021
+ log.append("The analysis successfully completed with the following outputs:")
1022
+ log.append(f"1. Multiple sequence alignment: {aligned_file}")
1023
+ log.append(f"2. Phylogenetic tree: {tree_file}")
1024
+ log.append(f"3. Conservation analysis: {conservation_file}")
1025
+
1026
+ return "\n".join(log)
BioScientist/agent_system/engines/v1_executor_backup/tool/bioengineering.py ADDED
@@ -0,0 +1,1387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def analyze_cell_migration_metrics(
2
+ image_sequence_path,
3
+ pixel_size_um=1.0,
4
+ time_interval_min=1.0,
5
+ min_track_length=10,
6
+ output_dir="./",
7
+ ):
8
+ """Analyze cell migration metrics from time-lapse microscopy images.
9
+
10
+ Parameters
11
+ ----------
12
+ image_sequence_path : str
13
+ Path to the directory containing time-lapse images or path to a multi-frame TIFF file
14
+ pixel_size_um : float
15
+ Conversion factor from pixels to micrometers (default: 1.0)
16
+ time_interval_min : float
17
+ Time interval between consecutive frames in minutes (default: 1.0)
18
+ min_track_length : int
19
+ Minimum number of frames a cell must be tracked to be included in analysis (default: 10)
20
+ output_dir : str
21
+ Directory to save output files (default: "./")
22
+
23
+ Returns
24
+ -------
25
+ str
26
+ Research log summarizing the cell migration analysis process and results
27
+
28
+ """
29
+ import os
30
+
31
+ import matplotlib.pyplot as plt
32
+ import numpy as np
33
+ import pandas as pd
34
+ import trackpy as tp
35
+ from skimage import io
36
+
37
+ # Create output directory if it doesn't exist
38
+ os.makedirs(output_dir, exist_ok=True)
39
+
40
+ # Load image sequence
41
+ if os.path.isdir(image_sequence_path):
42
+ # Load from directory of images
43
+ image_files = sorted(
44
+ [f for f in os.listdir(image_sequence_path) if f.endswith((".tif", ".tiff", ".png", ".jpg", ".jpeg"))]
45
+ )
46
+ frames = [io.imread(os.path.join(image_sequence_path, f)) for f in image_files]
47
+ else:
48
+ # Load multi-frame TIFF
49
+ frames = io.imread(image_sequence_path)
50
+ if frames.ndim == 3: # Check if it's a time series
51
+ pass
52
+ else:
53
+ return "Error: Input is not a valid time-lapse image sequence"
54
+
55
+ # Step 1: Detect cells in each frame
56
+ features_list = []
57
+ for i, frame in enumerate(frames):
58
+ # Detect cells (particles) in the frame
59
+ features = tp.locate(frame, diameter=15, minmass=100)
60
+ if features is not None and not features.empty:
61
+ features["frame"] = i
62
+ features_list.append(features)
63
+
64
+ if not features_list:
65
+ return "Error: No cells detected in the image sequence"
66
+
67
+ # Combine all features
68
+ all_features = pd.concat(features_list)
69
+
70
+ # Save raw detections to output directory
71
+ raw_detections_file = os.path.join(output_dir, "raw_cell_detections.csv")
72
+ all_features.to_csv(raw_detections_file, index=False)
73
+
74
+ # Step 2: Link features into cell trajectories
75
+ trajectories = tp.link_df(all_features, search_range=10, memory=3)
76
+
77
+ # Save linked trajectories before filtering
78
+ # Reset index to ensure frame is a column, not an index level
79
+ trajectories_reset = trajectories.reset_index(drop=True)
80
+ all_trajectories_file = os.path.join(output_dir, "all_trajectories.csv")
81
+ trajectories_reset.to_csv(all_trajectories_file, index=False)
82
+
83
+ # Step 3: Filter trajectories to get only the ones that appear in enough frames
84
+ trajectories = tp.filter_stubs(trajectories, threshold=min_track_length)
85
+
86
+ if trajectories.empty:
87
+ return "No complete cell tracks found. Try adjusting parameters."
88
+
89
+ # Save filtered trajectories
90
+ filtered_trajectories_file = os.path.join(output_dir, "filtered_trajectories.csv")
91
+ # Reset index again to be safe
92
+ trajectories = trajectories.reset_index(drop=True)
93
+ trajectories.to_csv(filtered_trajectories_file, index=False)
94
+
95
+ # Step 4: Calculate migration metrics for each cell
96
+ cell_ids = trajectories["particle"].unique()
97
+ metrics = []
98
+
99
+ for cell_id in cell_ids:
100
+ cell_track = trajectories[trajectories["particle"] == cell_id].sort_values("frame")
101
+
102
+ # Convert pixel positions to micrometers
103
+ cell_track["x_um"] = cell_track["x"] * pixel_size_um
104
+ cell_track["y_um"] = cell_track["y"] * pixel_size_um
105
+
106
+ # Calculate displacements between consecutive frames
107
+ dx = np.diff(cell_track["x_um"])
108
+ dy = np.diff(cell_track["y_um"])
109
+
110
+ # Calculate step distances
111
+ step_distances = np.sqrt(dx**2 + dy**2)
112
+
113
+ # Calculate total path length
114
+ path_length = np.sum(step_distances)
115
+
116
+ # Calculate net displacement (straight-line distance from start to end)
117
+ start_x, start_y = cell_track.iloc[0][["x_um", "y_um"]]
118
+ end_x, end_y = cell_track.iloc[-1][["x_um", "y_um"]]
119
+ net_displacement = np.sqrt((end_x - start_x) ** 2 + (end_y - start_y) ** 2)
120
+
121
+ # Calculate directionality ratio (net displacement / path length)
122
+ directionality = net_displacement / path_length if path_length > 0 else 0
123
+
124
+ # Calculate speed (μm/min)
125
+ time_tracked = (cell_track["frame"].max() - cell_track["frame"].min()) * time_interval_min
126
+ speed = path_length / time_tracked if time_tracked > 0 else 0
127
+
128
+ metrics.append(
129
+ {
130
+ "cell_id": cell_id,
131
+ "frames_tracked": len(cell_track),
132
+ "speed_um_per_min": speed,
133
+ "directionality": directionality,
134
+ "displacement_um": net_displacement,
135
+ "path_length_um": path_length,
136
+ }
137
+ )
138
+
139
+ # Convert metrics to DataFrame
140
+ metrics_df = pd.DataFrame(metrics)
141
+
142
+ # Save metrics to CSV
143
+ metrics_file = os.path.join(output_dir, "cell_migration_metrics.csv")
144
+ metrics_df.to_csv(metrics_file, index=False)
145
+
146
+ # Calculate summary statistics
147
+ summary = {
148
+ "num_cells_tracked": len(metrics_df),
149
+ "avg_speed": metrics_df["speed_um_per_min"].mean(),
150
+ "std_speed": metrics_df["speed_um_per_min"].std(),
151
+ "avg_directionality": metrics_df["directionality"].mean(),
152
+ "std_directionality": metrics_df["directionality"].std(),
153
+ "avg_displacement": metrics_df["displacement_um"].mean(),
154
+ "std_displacement": metrics_df["displacement_um"].std(),
155
+ }
156
+
157
+ # Save summary statistics
158
+ summary_file = os.path.join(output_dir, "migration_summary.csv")
159
+ pd.DataFrame([summary]).to_csv(summary_file, index=False)
160
+
161
+ # Save trajectories visualization
162
+ fig, ax = plt.figure(figsize=(8, 8)), plt.gca()
163
+ tp.plot_traj(trajectories, ax=ax)
164
+ plt.title("Cell Migration Trajectories")
165
+ plt.xlabel("x position (pixels)")
166
+ plt.ylabel("y position (pixels)")
167
+
168
+ trajectories_file = os.path.join(output_dir, "cell_trajectories.png")
169
+ plt.savefig(trajectories_file)
170
+ plt.close()
171
+
172
+ # Create a rose plot to show migration directionality
173
+ fig, ax = plt.subplots(subplot_kw={"projection": "polar"}, figsize=(8, 8))
174
+
175
+ # Calculate angles for each cell (end position relative to start)
176
+ angles = []
177
+ for cell_id in cell_ids:
178
+ cell_track = trajectories[trajectories["particle"] == cell_id].sort_values("frame")
179
+ start_x, start_y = cell_track.iloc[0][["x", "y"]]
180
+ end_x, end_y = cell_track.iloc[-1][["x", "y"]]
181
+ dx, dy = end_x - start_x, end_y - start_y
182
+ angle = np.arctan2(dy, dx)
183
+ angles.append(angle)
184
+
185
+ # Plot the histogram
186
+ bins = np.linspace(-np.pi, np.pi, 16)
187
+ ax.hist(angles, bins=bins)
188
+ ax.set_title("Cell Migration Directionality")
189
+
190
+ # Save the rose plot
191
+ rose_plot_file = os.path.join(output_dir, "rose_plot.png")
192
+ plt.savefig(rose_plot_file)
193
+ plt.close()
194
+
195
+ # Create a displacement plot
196
+ plt.figure(figsize=(10, 6))
197
+ plt.bar(range(len(metrics_df)), metrics_df["displacement_um"])
198
+ plt.xlabel("Cell ID")
199
+ plt.ylabel("Displacement (μm)")
200
+ plt.title("Cell Displacements")
201
+
202
+ # Save the displacement plot
203
+ displacement_plot_file = os.path.join(output_dir, "track_displacement_plot.png")
204
+ plt.savefig(displacement_plot_file)
205
+ plt.close()
206
+
207
+ # Generate research log
208
+ log = f"""
209
+ Cell Migration Analysis Research Log:
210
+
211
+ 1. Analyzed time-lapse sequence with {len(frames)} frames
212
+ 2. Detected and tracked {len(cell_ids)} cells that persisted for at least {min_track_length} frames
213
+ 3. Calculated key migration metrics:
214
+ - Average speed: {summary["avg_speed"]:.2f} ± {summary["std_speed"]:.2f} μm/min
215
+ - Average directionality ratio: {summary["avg_directionality"]:.2f} ± {summary["std_directionality"]:.2f}
216
+ - Average displacement: {summary["avg_displacement"]:.2f} ± {summary["std_displacement"]:.2f} μm
217
+
218
+ 4. Files saved:
219
+ - Raw cell detections: {raw_detections_file}
220
+ - All cell trajectories: {all_trajectories_file}
221
+ - Filtered trajectories: {filtered_trajectories_file}
222
+ - Detailed cell metrics: {metrics_file}
223
+ - Summary statistics: {summary_file}
224
+ - Cell trajectories visualization: {trajectories_file}
225
+ - Direction rose plot: {rose_plot_file}
226
+ - Cell displacement plot: {displacement_plot_file}
227
+
228
+ Note: Analysis used pixel size of {pixel_size_um} μm and time interval of {time_interval_min} min between frames.
229
+ """
230
+
231
+ return log.strip()
232
+
233
+
234
+ def perform_crispr_cas9_genome_editing(guide_rna_sequences, target_genomic_loci, cell_tissue_type):
235
+ """Simulates CRISPR-Cas9 genome editing process including guide RNA design, delivery, and analysis.
236
+
237
+ Parameters
238
+ ----------
239
+ guide_rna_sequences : list of str
240
+ List of guide RNA sequences (20 nucleotides each) targeting the genomic region of interest
241
+
242
+ target_genomic_loci : str
243
+ Target genomic sequence to be edited (should be longer than guide RNA and contain the target sites)
244
+
245
+ cell_tissue_type : str
246
+ Type of cell or tissue being edited (affects delivery efficiency and editing outcomes)
247
+
248
+ Returns
249
+ -------
250
+ str
251
+ Research log detailing the CRISPR-Cas9 editing process, including steps taken and results
252
+
253
+ """
254
+ import os
255
+ import random
256
+ from datetime import datetime
257
+
258
+ # Initialize research log
259
+ log = "CRISPR-Cas9 Genome Editing Research Log\n"
260
+ log += f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n"
261
+ log += f"Cell/Tissue Type: {cell_tissue_type}\n\n"
262
+
263
+ # Step 1: Validate guide RNA sequences
264
+ log += "STEP 1: Guide RNA Validation\n"
265
+ valid_guides = []
266
+
267
+ for i, guide in enumerate(guide_rna_sequences):
268
+ if len(guide) != 20:
269
+ log += f" Guide {i + 1}: INVALID - Guide RNA must be 20 nucleotides (current length: {len(guide)})\n"
270
+ continue
271
+
272
+ if not all(n in "ATGC" for n in guide.upper()):
273
+ log += f" Guide {i + 1}: INVALID - Guide RNA contains invalid nucleotides\n"
274
+ continue
275
+
276
+ # Calculate GC content (affects guide efficiency)
277
+ gc_content = (guide.upper().count("G") + guide.upper().count("C")) / len(guide) * 100
278
+ efficiency_score = 0
279
+
280
+ if 40 <= gc_content <= 60:
281
+ efficiency_score += 1
282
+ gc_quality = "Optimal"
283
+ else:
284
+ gc_quality = "Suboptimal"
285
+
286
+ log += f" Guide {i + 1}: VALID - {guide} (GC content: {gc_content:.1f}% - {gc_quality})\n"
287
+ valid_guides.append((guide, efficiency_score))
288
+
289
+ if not valid_guides:
290
+ log += "\nNo valid guide RNAs found. Genome editing cannot proceed.\n"
291
+ return log
292
+
293
+ # Step 2: Target site identification
294
+ log += "\nSTEP 2: Target Site Identification\n"
295
+
296
+ target_seq = target_genomic_loci.upper()
297
+ target_matches = []
298
+
299
+ for i, (guide, score) in enumerate(valid_guides):
300
+ # Find guide RNA target in genomic sequence (including PAM site NGG)
301
+ guide.upper() + "NGG"
302
+
303
+ # Check if guide sequence is in target (simplified)
304
+ if guide.upper() in target_seq:
305
+ position = target_seq.find(guide.upper())
306
+ # Check if there's a PAM sequence (NGG) after the guide
307
+ if position + len(guide) + 2 <= len(target_seq):
308
+ potential_pam = target_seq[position + len(guide) : position + len(guide) + 3]
309
+ if potential_pam[1:3] == "GG":
310
+ pam_quality = "Found"
311
+ score += 2
312
+ else:
313
+ pam_quality = "Not found"
314
+ else:
315
+ pam_quality = "Out of bounds"
316
+
317
+ log += f" Guide {i + 1}: Found at position {position} (PAM: {pam_quality})\n"
318
+ target_matches.append((guide, position, score))
319
+ else:
320
+ log += f" Guide {i + 1}: No match found in target sequence\n"
321
+
322
+ if not target_matches:
323
+ log += "\nNo matching target sites found. Genome editing cannot proceed.\n"
324
+ return log
325
+
326
+ # Step 3: Simulate CRISPR-Cas9 delivery
327
+ log += "\nSTEP 3: CRISPR-Cas9 Delivery Simulation\n"
328
+
329
+ # Cell-specific delivery efficiencies (simplified model)
330
+ delivery_efficiencies = {
331
+ "hek293": 0.85,
332
+ "hela": 0.75,
333
+ "ipsc": 0.60,
334
+ "primary_neuron": 0.40,
335
+ "hematopoietic_stem_cell": 0.55,
336
+ "mouse_embryo": 0.70,
337
+ "plant_cell": 0.30,
338
+ }
339
+
340
+ # Get delivery efficiency based on cell type (default to 0.5 if unknown)
341
+ cell_type_key = cell_tissue_type.lower().replace(" ", "_")
342
+ delivery_efficiency = delivery_efficiencies.get(cell_type_key, 0.5)
343
+
344
+ log += f" Delivery method: Lipofection for {cell_tissue_type}\n"
345
+ log += f" Estimated delivery efficiency: {delivery_efficiency * 100:.1f}%\n"
346
+
347
+ # Step 4: Simulate genome editing
348
+ log += "\nSTEP 4: Genome Editing Simulation\n"
349
+
350
+ # Select best guide based on score
351
+ best_guide, best_position, best_score = sorted(target_matches, key=lambda x: x[2], reverse=True)[0]
352
+
353
+ log += f" Selected guide RNA: {best_guide} (highest efficiency score)\n"
354
+ log += f" Target position: {best_position} to {best_position + len(best_guide) - 1}\n"
355
+
356
+ # Simulate editing outcome
357
+ edit_success_rate = delivery_efficiency * (0.5 + (best_score * 0.1)) # Between 50-90% based on guide quality
358
+
359
+ # Cut site (typically 3 bases upstream of PAM)
360
+ cut_position = best_position + len(best_guide) - 3
361
+ log += f" Predicted cut site: Between positions {cut_position} and {cut_position + 1}\n"
362
+
363
+ # Simulate editing outcomes
364
+ indel_size = random.randint(1, 5) # Random indel size between 1-5 bp
365
+
366
+ # Create modified sequence (simulate a deletion for simplicity)
367
+ modified_sequence = target_seq[:cut_position] + target_seq[cut_position + indel_size :]
368
+
369
+ log += f" Simulated edit: {indel_size}bp deletion at cut site\n"
370
+ log += f" Predicted editing efficiency: {edit_success_rate * 100:.1f}%\n"
371
+
372
+ # Step 5: Analysis of editing outcomes
373
+ log += "\nSTEP 5: Editing Outcome Analysis\n"
374
+
375
+ # Calculate basic stats
376
+ log += f" Original sequence length: {len(target_seq)} bp\n"
377
+ log += f" Modified sequence length: {len(modified_sequence)} bp\n"
378
+
379
+ # Save sequences to files
380
+ os.makedirs("crispr_results", exist_ok=True)
381
+
382
+ original_file = "crispr_results/original_sequence.txt"
383
+ with open(original_file, "w") as f:
384
+ f.write(f">Original_Sequence\n{target_seq}\n")
385
+
386
+ modified_file = "crispr_results/modified_sequence.txt"
387
+ with open(modified_file, "w") as f:
388
+ f.write(f">Modified_Sequence\n{modified_sequence}\n")
389
+
390
+ log += f" Original sequence saved to: {original_file}\n"
391
+ log += f" Modified sequence saved to: {modified_file}\n"
392
+
393
+ # Summary
394
+ log += "\nSUMMARY:\n"
395
+ log += f" CRISPR-Cas9 editing successfully simulated for {cell_tissue_type}\n"
396
+ log += f" {indel_size}bp deletion introduced at position {cut_position}\n"
397
+ log += f" Expected success rate in cell population: {edit_success_rate * 100:.1f}%\n"
398
+
399
+ return log
400
+
401
+
402
+ def analyze_calcium_imaging_data(image_stack_path, output_dir="./"):
403
+ """Analyze calcium imaging data to quantify neuronal activity metrics.
404
+
405
+ This function processes fluorescence microscopy images of GCaMP-labeled neurons
406
+ to extract quantitative metrics of neuronal activity, including cell counts,
407
+ event rates, decay times, and signal-to-noise ratios.
408
+
409
+ Parameters
410
+ ----------
411
+ image_stack_path : str
412
+ Path to the time-series stack of fluorescence microscopy images (TIFF format)
413
+ output_dir : str, optional
414
+ Directory to save output files (default: "./")
415
+
416
+ Returns
417
+ -------
418
+ str
419
+ Research log summarizing the analysis steps and results
420
+
421
+ """
422
+ import os
423
+
424
+ import numpy as np
425
+ import pandas as pd
426
+ from scipy import ndimage, signal
427
+ from scipy.optimize import curve_fit
428
+ from skimage import feature, filters, io, measure, segmentation
429
+
430
+ # Create output directory if it doesn't exist
431
+ os.makedirs(output_dir, exist_ok=True)
432
+
433
+ # Step 1: Load the image stack
434
+ log = "CALCIUM IMAGING ANALYSIS LOG\n"
435
+ log += "===========================\n\n"
436
+ log += f"Loading image stack from: {image_stack_path}\n"
437
+
438
+ try:
439
+ image_stack = io.imread(image_stack_path)
440
+ num_frames, height, width = image_stack.shape
441
+ log += f"Successfully loaded {num_frames} frames of size {height}x{width}\n\n"
442
+ except Exception as e:
443
+ return f"Error loading image stack: {str(e)}"
444
+
445
+ # Step 2: Calculate mean image for segmentation
446
+ log += "Step 1: Preprocessing and neuron segmentation\n"
447
+ mean_image = np.mean(image_stack, axis=0)
448
+
449
+ # Apply Gaussian filter to reduce noise
450
+ smooth_mean = filters.gaussian(mean_image, sigma=2)
451
+
452
+ # Step 3: Segment neurons using watershed
453
+ # Find local maxima (potential cell centers)
454
+ distance = ndimage.distance_transform_edt(smooth_mean)
455
+ # Create a mask for local maxima instead of using indices=False parameter
456
+ coordinates = feature.peak_local_max(distance, min_distance=10)
457
+
458
+ # Handle case where no local maxima are found
459
+ if len(coordinates) == 0:
460
+ log += "No local maxima detected. Using simple thresholding instead.\n"
461
+ # Create a simple binary mask using thresholding as fallback
462
+ binary_mask = smooth_mean > filters.threshold_otsu(smooth_mean)
463
+ markers = measure.label(binary_mask)
464
+ else:
465
+ local_max = np.zeros_like(distance, dtype=bool)
466
+ for coord in coordinates:
467
+ local_max[coord[0], coord[1]] = True
468
+ markers = measure.label(local_max)
469
+
470
+ # Watershed segmentation
471
+ segmented = segmentation.watershed(-smooth_mean, markers, mask=smooth_mean > filters.threshold_otsu(smooth_mean))
472
+
473
+ # Get region properties
474
+ regions = measure.regionprops(segmented)
475
+ cell_count = len(regions)
476
+ log += f"Detected {cell_count} neurons in the field of view\n\n"
477
+
478
+ # Step 4: Extract time-series data for each neuron
479
+ log += "Step 2: Extracting fluorescence time-series for each neuron\n"
480
+ time_series_data = []
481
+
482
+ for _i, region in enumerate(regions):
483
+ mask = segmented == region.label
484
+ cell_time_series = []
485
+
486
+ for frame in range(num_frames):
487
+ intensity = np.mean(image_stack[frame][mask])
488
+ cell_time_series.append(intensity)
489
+
490
+ time_series_data.append(cell_time_series)
491
+
492
+ time_series_array = np.array(time_series_data)
493
+
494
+ # Step 5: Detect calcium events and calculate metrics
495
+ log += "Step 3: Calculating neuronal activity metrics\n"
496
+
497
+ # Function to fit exponential decay
498
+ def exp_decay(x, a, tau, c):
499
+ return a * np.exp(-x / tau) + c
500
+
501
+ event_rates = []
502
+ decay_times = []
503
+ snr_values = []
504
+
505
+ for i, ts in enumerate(time_series_data):
506
+ # Normalize time series
507
+ baseline = np.percentile(ts, 20)
508
+ ts_norm = [(x - baseline) / baseline for x in ts]
509
+
510
+ # Simple event detection (threshold crossing)
511
+ threshold = np.std(ts_norm) * 2
512
+ events = []
513
+ in_event = False
514
+
515
+ for j, val in enumerate(ts_norm):
516
+ if not in_event and val > threshold:
517
+ events.append(j)
518
+ in_event = True
519
+ elif in_event and val < threshold:
520
+ in_event = False
521
+
522
+ # Calculate event rate (events per minute, assuming 10 Hz acquisition)
523
+ acquisition_rate = 10 # Hz (assumption)
524
+ recording_time_minutes = num_frames / acquisition_rate / 60
525
+ event_rate = len(events) / recording_time_minutes
526
+ event_rates.append(event_rate)
527
+
528
+ # Calculate decay times for detected events
529
+ cell_decay_times = []
530
+ for event_start in events:
531
+ if event_start + 30 < len(ts_norm): # Ensure enough frames after event
532
+ event_window = ts_norm[event_start : event_start + 30]
533
+ peak_idx = np.argmax(event_window)
534
+ decay_segment = event_window[peak_idx:]
535
+
536
+ try:
537
+ # Fit exponential decay
538
+ x_data = np.arange(len(decay_segment))
539
+ popt, _ = curve_fit(
540
+ exp_decay,
541
+ x_data,
542
+ decay_segment,
543
+ p0=[decay_segment[0], 5, decay_segment[-1]],
544
+ bounds=([0, 0, 0], [np.inf, np.inf, np.inf]),
545
+ )
546
+ tau = popt[1] # Decay time constant
547
+ cell_decay_times.append(tau / acquisition_rate) # Convert to seconds
548
+ except Exception:
549
+ # Skip if curve fitting fails
550
+ pass
551
+
552
+ if cell_decay_times:
553
+ decay_times.append(np.mean(cell_decay_times))
554
+ else:
555
+ decay_times.append(np.nan)
556
+
557
+ # Calculate signal-to-noise ratio
558
+ signal = np.mean([ts_norm[e] for e in events]) if events else 0 # noqa: F811
559
+ noise = np.std([ts_norm[i] for i in range(len(ts_norm)) if all(abs(i - e) > 5 for e in events)])
560
+ snr = signal / noise if noise > 0 else 0
561
+ snr_values.append(snr)
562
+
563
+ # Step 6: Compile and save results
564
+ cell_metrics = pd.DataFrame(
565
+ {
566
+ "Cell_ID": range(1, cell_count + 1),
567
+ "Event_Rate_per_min": event_rates,
568
+ "Decay_Time_sec": decay_times,
569
+ "SNR": snr_values,
570
+ }
571
+ )
572
+
573
+ metrics_file = os.path.join(output_dir, "neuron_activity_metrics.csv")
574
+ cell_metrics.to_csv(metrics_file, index=False)
575
+
576
+ # Save time series data
577
+ time_series_file = os.path.join(output_dir, "neuron_time_series.csv")
578
+ time_series_df = pd.DataFrame(time_series_array.T)
579
+ time_series_df.columns = [f"Cell_{i + 1}" for i in range(cell_count)]
580
+ time_series_df.to_csv(time_series_file, index=False)
581
+
582
+ # Step 7: Summarize results
583
+ log += f"Cell count: {cell_count}\n"
584
+ log += f"Average event rate: {np.nanmean(event_rates):.2f} events/min\n"
585
+ log += f"Average decay time: {np.nanmean(decay_times):.2f} seconds\n"
586
+ log += f"Average SNR: {np.nanmean(snr_values):.2f}\n\n"
587
+
588
+ log += "Step 4: Results saved to files\n"
589
+ log += f"Neuron activity metrics saved to: {metrics_file}\n"
590
+ log += f"Time series data saved to: {time_series_file}\n"
591
+
592
+ return log
593
+
594
+
595
+ def analyze_in_vitro_drug_release_kinetics(
596
+ time_points,
597
+ concentration_data,
598
+ drug_name="Drug",
599
+ total_drug_loaded=None,
600
+ output_dir="./",
601
+ ):
602
+ """Analyzes in vitro drug release kinetics from biomaterial formulations.
603
+
604
+ Parameters
605
+ ----------
606
+ time_points : list or numpy.ndarray
607
+ Time points at which drug concentrations were measured (in hours)
608
+ concentration_data : list or numpy.ndarray
609
+ Measured drug concentration at each time point
610
+ drug_name : str, optional
611
+ Name of the drug being analyzed (default: "Drug")
612
+ total_drug_loaded : float, optional
613
+ Total amount of drug initially loaded in the formulation.
614
+ If None, the maximum concentration is used as 100% (default: None)
615
+ output_dir : str, optional
616
+ Directory to save output files (default: "./")
617
+
618
+ Returns
619
+ -------
620
+ str
621
+ Research log summarizing the analysis steps, results, and saved file locations
622
+
623
+ """
624
+ import os
625
+ from datetime import datetime
626
+
627
+ import matplotlib.pyplot as plt
628
+ import numpy as np
629
+ import pandas as pd
630
+ from scipy.optimize import curve_fit
631
+
632
+ # Ensure output directory exists
633
+ os.makedirs(output_dir, exist_ok=True)
634
+
635
+ # Convert inputs to numpy arrays
636
+ time_points = np.array(time_points)
637
+ concentration_data = np.array(concentration_data)
638
+
639
+ # Calculate cumulative release percentage
640
+ if total_drug_loaded is None:
641
+ total_drug_loaded = np.max(concentration_data)
642
+
643
+ cumulative_release = (concentration_data / total_drug_loaded) * 100
644
+
645
+ # Create a DataFrame for easier manipulation
646
+ release_df = pd.DataFrame(
647
+ {
648
+ "Time (hours)": time_points,
649
+ "Concentration": concentration_data,
650
+ "Cumulative Release (%)": cumulative_release,
651
+ }
652
+ )
653
+
654
+ # Calculate release rate (simple approximation using differences)
655
+ release_df["Release Rate"] = np.gradient(release_df["Cumulative Release (%)"], release_df["Time (hours)"])
656
+
657
+ # Define kinetic models
658
+ def zero_order(t, k):
659
+ return k * t
660
+
661
+ def first_order(t, k):
662
+ return 100 * (1 - np.exp(-k * t))
663
+
664
+ def higuchi(t, k):
665
+ return k * np.sqrt(t)
666
+
667
+ def korsmeyer_peppas(t, k, n):
668
+ return 100 * (k * t) ** n
669
+
670
+ # Fit data to different kinetic models
671
+ models = {}
672
+ r2_values = {}
673
+
674
+ # Zero-order kinetics
675
+ try:
676
+ params, _ = curve_fit(zero_order, time_points, cumulative_release)
677
+ y_pred = zero_order(time_points, *params)
678
+ ss_total = np.sum((cumulative_release - np.mean(cumulative_release)) ** 2)
679
+ ss_residual = np.sum((cumulative_release - y_pred) ** 2)
680
+ r2 = 1 - (ss_residual / ss_total)
681
+ models["Zero-order"] = {
682
+ "params": params,
683
+ "equation": f"Release = {params[0]:.4f} * t",
684
+ "pred": y_pred,
685
+ }
686
+ r2_values["Zero-order"] = r2
687
+ except Exception:
688
+ models["Zero-order"] = {
689
+ "params": None,
690
+ "equation": "Fitting failed",
691
+ "pred": None,
692
+ }
693
+ r2_values["Zero-order"] = 0
694
+
695
+ # First-order kinetics
696
+ try:
697
+ params, _ = curve_fit(first_order, time_points, cumulative_release, bounds=(0, [1]))
698
+ y_pred = first_order(time_points, *params)
699
+ ss_total = np.sum((cumulative_release - np.mean(cumulative_release)) ** 2)
700
+ ss_residual = np.sum((cumulative_release - y_pred) ** 2)
701
+ r2 = 1 - (ss_residual / ss_total)
702
+ models["First-order"] = {
703
+ "params": params,
704
+ "equation": f"Release = 100 * (1 - exp(-{params[0]:.4f} * t))",
705
+ "pred": y_pred,
706
+ }
707
+ r2_values["First-order"] = r2
708
+ except Exception:
709
+ models["First-order"] = {
710
+ "params": None,
711
+ "equation": "Fitting failed",
712
+ "pred": None,
713
+ }
714
+ r2_values["First-order"] = 0
715
+
716
+ # Higuchi model
717
+ try:
718
+ params, _ = curve_fit(higuchi, time_points, cumulative_release)
719
+ y_pred = higuchi(time_points, *params)
720
+ ss_total = np.sum((cumulative_release - np.mean(cumulative_release)) ** 2)
721
+ ss_residual = np.sum((cumulative_release - y_pred) ** 2)
722
+ r2 = 1 - (ss_residual / ss_total)
723
+ models["Higuchi"] = {
724
+ "params": params,
725
+ "equation": f"Release = {params[0]:.4f} * sqrt(t)",
726
+ "pred": y_pred,
727
+ }
728
+ r2_values["Higuchi"] = r2
729
+ except Exception:
730
+ models["Higuchi"] = {"params": None, "equation": "Fitting failed", "pred": None}
731
+ r2_values["Higuchi"] = 0
732
+
733
+ # Korsmeyer-Peppas model
734
+ try:
735
+ # Only use the first 60% of release data for Korsmeyer-Peppas model
736
+ mask = cumulative_release <= 60
737
+ if sum(mask) >= 3: # Need at least 3 points for fitting
738
+ params, _ = curve_fit(
739
+ korsmeyer_peppas,
740
+ time_points[mask],
741
+ cumulative_release[mask],
742
+ bounds=([0, 0], [1, 1]),
743
+ )
744
+ y_pred = korsmeyer_peppas(time_points, *params)
745
+ ss_total = np.sum((cumulative_release - np.mean(cumulative_release)) ** 2)
746
+ ss_residual = np.sum((cumulative_release - y_pred) ** 2)
747
+ r2 = 1 - (ss_residual / ss_total)
748
+ models["Korsmeyer-Peppas"] = {
749
+ "params": params,
750
+ "equation": f"Release = 100 * ({params[0]:.4f} * t)^{params[1]:.4f}",
751
+ "pred": y_pred,
752
+ }
753
+ r2_values["Korsmeyer-Peppas"] = r2
754
+ else:
755
+ models["Korsmeyer-Peppas"] = {
756
+ "params": None,
757
+ "equation": "Insufficient data points",
758
+ "pred": None,
759
+ }
760
+ r2_values["Korsmeyer-Peppas"] = 0
761
+ except Exception:
762
+ models["Korsmeyer-Peppas"] = {
763
+ "params": None,
764
+ "equation": "Fitting failed",
765
+ "pred": None,
766
+ }
767
+ r2_values["Korsmeyer-Peppas"] = 0
768
+
769
+ # Determine best model based on R² value
770
+ best_model = max(r2_values, key=r2_values.get)
771
+
772
+ # Calculate half-life (time to 50% release)
773
+ try:
774
+ # Use best model to calculate half-life
775
+ if best_model == "Zero-order":
776
+ k = models[best_model]["params"][0]
777
+ half_life = 50 / k if k > 0 else float("inf")
778
+ elif best_model == "First-order":
779
+ k = models[best_model]["params"][0]
780
+ half_life = -np.log(0.5) / k if k > 0 else float("inf")
781
+ elif best_model == "Higuchi":
782
+ k = models[best_model]["params"][0]
783
+ half_life = (50 / k) ** 2 if k > 0 else float("inf")
784
+ elif best_model == "Korsmeyer-Peppas":
785
+ k, n = models[best_model]["params"]
786
+ half_life = (0.5 ** (1 / n)) / k if k > 0 else float("inf")
787
+ else:
788
+ # Interpolate from data if model fitting failed
789
+ from scipy.interpolate import interp1d
790
+
791
+ if np.max(cumulative_release) >= 50:
792
+ f = interp1d(cumulative_release, time_points)
793
+ half_life = float(f(50))
794
+ else:
795
+ half_life = "Not reached"
796
+ except Exception:
797
+ half_life = "Could not calculate"
798
+
799
+ # Create plots
800
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
801
+
802
+ # 1. Cumulative release plot with model fits
803
+ plt.figure(figsize=(10, 6))
804
+ plt.plot(time_points, cumulative_release, "o-", label="Experimental data")
805
+
806
+ for model_name, model_data in models.items():
807
+ if model_data["pred"] is not None:
808
+ plt.plot(
809
+ time_points,
810
+ model_data["pred"],
811
+ "--",
812
+ label=f"{model_name} (R² = {r2_values[model_name]:.4f})",
813
+ )
814
+
815
+ plt.xlabel("Time (hours)")
816
+ plt.ylabel("Cumulative Release (%)")
817
+ plt.title(f"In Vitro Release Profile of {drug_name}")
818
+ plt.legend()
819
+ plt.grid(True, linestyle="--", alpha=0.7)
820
+ cumulative_plot_path = os.path.join(output_dir, f"cumulative_release_{timestamp}.png")
821
+ plt.savefig(cumulative_plot_path, dpi=300, bbox_inches="tight")
822
+ plt.close()
823
+
824
+ # 2. Release rate plot
825
+ plt.figure(figsize=(10, 6))
826
+ plt.plot(time_points, release_df["Release Rate"], "o-")
827
+ plt.xlabel("Time (hours)")
828
+ plt.ylabel("Release Rate (%/hour)")
829
+ plt.title(f"Release Rate of {drug_name}")
830
+ plt.grid(True, linestyle="--", alpha=0.7)
831
+ rate_plot_path = os.path.join(output_dir, f"release_rate_{timestamp}.png")
832
+ plt.savefig(rate_plot_path, dpi=300, bbox_inches="tight")
833
+ plt.close()
834
+
835
+ # Save data to CSV
836
+ csv_path = os.path.join(output_dir, f"drug_release_data_{timestamp}.csv")
837
+ release_df.to_csv(csv_path, index=False)
838
+
839
+ # Generate research log
840
+ log = f"""
841
+ # In Vitro Drug Release Kinetics Analysis for {drug_name}
842
+
843
+ ## Analysis Summary
844
+ - **Date/Time:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
845
+ - **Drug Analyzed:** {drug_name}
846
+ - **Time Range:** {min(time_points)} to {max(time_points)} hours
847
+ - **Number of Data Points:** {len(time_points)}
848
+ - **Maximum Release Achieved:** {max(cumulative_release):.2f}%
849
+
850
+ ## Kinetic Models Analysis
851
+ The release data was fitted to four standard kinetic models:
852
+
853
+ 1. **Zero-order Model:** {models["Zero-order"]["equation"]} (R² = {r2_values["Zero-order"]:.4f})
854
+ 2. **First-order Model:** {models["First-order"]["equation"]} (R² = {r2_values["First-order"]:.4f})
855
+ 3. **Higuchi Model:** {models["Higuchi"]["equation"]} (R² = {r2_values["Higuchi"]:.4f})
856
+ 4. **Korsmeyer-Peppas Model:** {models["Korsmeyer-Peppas"]["equation"]} (R² = {r2_values["Korsmeyer-Peppas"]:.4f})
857
+
858
+ **Best-fitting Model:** {best_model} (R² = {r2_values[best_model]:.4f})
859
+
860
+ ## Release Metrics
861
+ - **Half-life (t50%):** {half_life if isinstance(half_life, str) else f"{half_life:.2f} hours"}
862
+ - **Initial Release Rate:** {release_df["Release Rate"].iloc[0]:.4f} %/hour
863
+ - **Average Release Rate:** {np.mean(release_df["Release Rate"]):.4f} %/hour
864
+
865
+ ## Files Generated
866
+ 1. Cumulative Release Plot: {cumulative_plot_path}
867
+ 2. Release Rate Plot: {rate_plot_path}
868
+ 3. Data CSV: {csv_path}
869
+
870
+ ## Interpretation
871
+ The drug release profile of {drug_name} best follows a {
872
+ best_model
873
+ } kinetic model, which suggests that the release mechanism is primarily driven by {
874
+ "diffusion through a porous matrix"
875
+ if best_model == "Higuchi"
876
+ else "diffusion with erosion"
877
+ if best_model == "Korsmeyer-Peppas" and 0.43 <= models[best_model]["params"][1] <= 0.85
878
+ else "Fickian diffusion"
879
+ if best_model == "Korsmeyer-Peppas" and models[best_model]["params"][1] < 0.43
880
+ else "case-II transport"
881
+ if best_model == "Korsmeyer-Peppas" and models[best_model]["params"][1] > 0.85
882
+ else "concentration-dependent diffusion"
883
+ if best_model == "First-order"
884
+ else "constant release rate independent of concentration"
885
+ if best_model == "Zero-order"
886
+ else "complex mechanisms"
887
+ }.
888
+ """
889
+
890
+ return log.strip()
891
+
892
+
893
+ def analyze_myofiber_morphology(
894
+ image_path,
895
+ nuclei_channel=2,
896
+ myofiber_channel=1,
897
+ threshold_method="otsu",
898
+ output_dir="./",
899
+ ):
900
+ """Quantifies morphological properties of myofibers in microscopy images of tissue sections.
901
+
902
+ Parameters
903
+ ----------
904
+ image_path : str
905
+ Path to the microscopy image file (typically a multichannel image with nuclei and myofiber staining)
906
+ nuclei_channel : int, default=2
907
+ Channel index containing nuclei staining (DAPI, Hoechst, etc.)
908
+ myofiber_channel : int, default=1
909
+ Channel index containing myofiber staining (α-Actinin, etc.)
910
+ threshold_method : str, default='otsu'
911
+ Method for thresholding ('otsu', 'adaptive', or 'manual')
912
+ output_dir : str, default='./'
913
+ Directory to save output files
914
+
915
+ Returns
916
+ -------
917
+ str
918
+ Research log summarizing the analysis steps and results
919
+
920
+ """
921
+ import os
922
+ from datetime import datetime
923
+
924
+ import numpy as np
925
+ import pandas as pd
926
+ from skimage import exposure, filters, io, measure, morphology
927
+ from skimage.color import label2rgb
928
+
929
+ # Create output directory if it doesn't exist
930
+ os.makedirs(output_dir, exist_ok=True)
931
+
932
+ # Load the image
933
+ image = io.imread(image_path)
934
+
935
+ # Extract channels (assuming multichannel image)
936
+ if len(image.shape) > 2:
937
+ if len(image.shape) == 3:
938
+ # RGB image
939
+ nuclei_img = image[:, :, nuclei_channel] if nuclei_channel < image.shape[2] else image[:, :, 0]
940
+ myofiber_img = image[:, :, myofiber_channel] if myofiber_channel < image.shape[2] else image[:, :, 1]
941
+ else:
942
+ # Multichannel image (e.g., from confocal)
943
+ nuclei_img = image[nuclei_channel, :, :] if nuclei_channel < image.shape[0] else image[0, :, :]
944
+ myofiber_img = image[myofiber_channel, :, :] if myofiber_channel < image.shape[0] else image[1, :, :]
945
+ else:
946
+ # Single channel image - can't separate nuclei and myofibers
947
+ return "Error: Input image must be multichannel to separate nuclei and myofibers"
948
+
949
+ # Enhance contrast
950
+ nuclei_img = exposure.equalize_adapthist(nuclei_img)
951
+ myofiber_img = exposure.equalize_adapthist(myofiber_img)
952
+
953
+ # Segment nuclei
954
+ if threshold_method == "otsu":
955
+ nuclei_thresh = filters.threshold_otsu(nuclei_img)
956
+ elif threshold_method == "adaptive":
957
+ nuclei_thresh = filters.threshold_local(nuclei_img, block_size=35)
958
+ else: # manual
959
+ nuclei_thresh = np.mean(nuclei_img) * 1.5
960
+
961
+ nuclei_binary = nuclei_img > nuclei_thresh
962
+ nuclei_binary = morphology.remove_small_objects(nuclei_binary, min_size=30)
963
+ nuclei_binary = morphology.binary_closing(nuclei_binary)
964
+
965
+ # Label nuclei
966
+ nuclei_labels = measure.label(nuclei_binary)
967
+ nuclei_props = measure.regionprops(nuclei_labels)
968
+
969
+ # Segment myofibers
970
+ if threshold_method == "otsu":
971
+ myofiber_thresh = filters.threshold_otsu(myofiber_img)
972
+ elif threshold_method == "adaptive":
973
+ myofiber_thresh = filters.threshold_local(myofiber_img, block_size=101)
974
+ else: # manual
975
+ myofiber_thresh = np.mean(myofiber_img) * 1.2
976
+
977
+ myofiber_binary = myofiber_img > myofiber_thresh
978
+ myofiber_binary = morphology.remove_small_objects(myofiber_binary, min_size=500)
979
+ myofiber_binary = morphology.binary_closing(myofiber_binary, morphology.disk(3))
980
+
981
+ # Label myofibers
982
+ myofiber_labels = measure.label(myofiber_binary)
983
+ myofiber_props = measure.regionprops(myofiber_labels)
984
+
985
+ # Count nuclei inside myofibers
986
+ nuclei_inside = 0
987
+ nuclei_total = len(nuclei_props)
988
+
989
+ for nucleus in nuclei_props:
990
+ y, x = nucleus.centroid
991
+ y, x = int(y), int(x)
992
+ if myofiber_binary[y, x]:
993
+ nuclei_inside += 1
994
+
995
+ percent_inside = nuclei_inside / nuclei_total * 100 if nuclei_total > 0 else 0
996
+
997
+ # Calculate myofiber morphological properties
998
+ myofiber_data = []
999
+ for fiber in myofiber_props:
1000
+ myofiber_data.append(
1001
+ {
1002
+ "Area": fiber.area,
1003
+ "Perimeter": fiber.perimeter,
1004
+ "Eccentricity": fiber.eccentricity,
1005
+ "Solidity": fiber.solidity,
1006
+ "Orientation": fiber.orientation,
1007
+ }
1008
+ )
1009
+
1010
+ # Save results
1011
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
1012
+ results_file = f"{output_dir}/myofiber_analysis_{timestamp}.csv"
1013
+
1014
+ if myofiber_data:
1015
+ df = pd.DataFrame(myofiber_data)
1016
+ df.to_csv(results_file, index=False)
1017
+
1018
+ # Calculate summary statistics
1019
+ mean_area = df["Area"].mean()
1020
+ mean_perimeter = df["Perimeter"].mean()
1021
+ mean_eccentricity = df["Eccentricity"].mean()
1022
+ else:
1023
+ mean_area = mean_perimeter = mean_eccentricity = 0
1024
+
1025
+ # Save labeled image
1026
+ labeled_image = label2rgb(myofiber_labels, image=myofiber_img)
1027
+ labeled_image_path = f"{output_dir}/labeled_myofibers_{timestamp}.png"
1028
+ io.imsave(labeled_image_path, (labeled_image * 255).astype(np.uint8))
1029
+
1030
+ # Create research log
1031
+ log = f"""
1032
+ MYOFIBER MORPHOLOGICAL ANALYSIS REPORT
1033
+ ======================================
1034
+ Date: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
1035
+ Image: {image_path}
1036
+
1037
+ ANALYSIS STEPS:
1038
+ 1. Loaded multichannel microscopy image
1039
+ 2. Extracted nuclei (channel {nuclei_channel}) and myofiber (channel {myofiber_channel}) signals
1040
+ 3. Enhanced contrast using adaptive histogram equalization
1041
+ 4. Segmented nuclei using {threshold_method} thresholding
1042
+ 5. Segmented myofibers using {threshold_method} thresholding
1043
+ 6. Performed morphological operations to refine segmentation
1044
+ 7. Identified and measured individual myofibers and nuclei
1045
+
1046
+ RESULTS:
1047
+ - Total myofibers detected: {len(myofiber_props)}
1048
+ - Total nuclei detected: {nuclei_total}
1049
+ - Nuclei inside myofibers: {nuclei_inside} ({percent_inside:.2f}%)
1050
+ - Mean myofiber area: {mean_area:.2f} pixels
1051
+ - Mean myofiber perimeter: {mean_perimeter:.2f} pixels
1052
+ - Mean myofiber eccentricity: {mean_eccentricity:.2f}
1053
+
1054
+ FILES GENERATED:
1055
+ - Morphological measurements: {results_file}
1056
+ - Labeled myofiber image: {labeled_image_path}
1057
+ """
1058
+
1059
+ return log
1060
+
1061
+
1062
+ def decode_behavior_from_neural_trajectories(neural_data, behavioral_data, n_components=10, output_dir="./"):
1063
+ """Model neural activity trajectories and decode behavioral variables.
1064
+
1065
+ Parameters
1066
+ ----------
1067
+ neural_data : numpy.ndarray
1068
+ Neural spiking activity data, shape (n_timepoints, n_neurons)
1069
+ behavioral_data : numpy.ndarray
1070
+ Behavioral data, shape (n_timepoints, n_behavioral_variables)
1071
+ n_components : int, optional
1072
+ Number of principal components to use for dimensionality reduction, default is 10
1073
+ output_dir : str, optional
1074
+ Directory to save output files, default is "./"
1075
+
1076
+ Returns
1077
+ -------
1078
+ str
1079
+ Research log summarizing the steps taken and results
1080
+
1081
+ """
1082
+ import os
1083
+ import pickle
1084
+
1085
+ import matplotlib.pyplot as plt
1086
+ import numpy as np
1087
+ from pykalman import KalmanFilter
1088
+ from sklearn.decomposition import PCA
1089
+ from sklearn.metrics import mean_squared_error
1090
+ from sklearn.model_selection import train_test_split
1091
+
1092
+ # Create output directory if it doesn't exist
1093
+ if not os.path.exists(output_dir):
1094
+ os.makedirs(output_dir)
1095
+
1096
+ # Initialize research log
1097
+ log = "# Neural Trajectory Modeling and Decoding Research Log\n\n"
1098
+
1099
+ # Step 1: Preprocess the data
1100
+ log += "## Step 1: Data Preprocessing\n"
1101
+ log += f"- Neural data shape: {neural_data.shape}\n"
1102
+ log += f"- Behavioral data shape: {behavioral_data.shape}\n"
1103
+
1104
+ # Check for NaN values and replace with zeros
1105
+ neural_data = np.nan_to_num(neural_data)
1106
+ behavioral_data = np.nan_to_num(behavioral_data)
1107
+
1108
+ # Split data into training and testing sets
1109
+ X_train, X_test, y_train, y_test = train_test_split(neural_data, behavioral_data, test_size=0.2, random_state=42)
1110
+ log += f"- Training set size: {X_train.shape[0]} samples\n"
1111
+ log += f"- Testing set size: {X_test.shape[0]} samples\n\n"
1112
+
1113
+ # Step 2: Dimensionality reduction with PCA
1114
+ log += "## Step 2: Dimensionality Reduction\n"
1115
+ log += f"- Reducing neural data from {neural_data.shape[1]} dimensions to {n_components} components\n"
1116
+
1117
+ pca = PCA(n_components=n_components)
1118
+ X_train_pca = pca.fit_transform(X_train)
1119
+ X_test_pca = pca.transform(X_test)
1120
+
1121
+ explained_variance = np.sum(pca.explained_variance_ratio_) * 100
1122
+ log += f"- Total variance explained: {explained_variance:.2f}%\n\n"
1123
+
1124
+ # Save PCA components visualization
1125
+ try:
1126
+ plt.figure(figsize=(10, 6))
1127
+ plt.bar(range(1, n_components + 1), pca.explained_variance_ratio_)
1128
+ plt.xlabel("Principal Component")
1129
+ plt.ylabel("Explained Variance Ratio")
1130
+ plt.title("PCA Components Explained Variance")
1131
+ plt.xticks(range(1, n_components + 1))
1132
+ plt.tight_layout()
1133
+
1134
+ pca_plot_path = os.path.join(output_dir, "pca_explained_variance.png")
1135
+ plt.savefig(pca_plot_path, dpi=300)
1136
+ plt.close()
1137
+
1138
+ log += f"- PCA components visualization saved to: {pca_plot_path}\n\n"
1139
+ except Exception as e:
1140
+ log += f"- Error creating PCA visualization: {str(e)}\n\n"
1141
+
1142
+ # Step 3: Train a Kalman filter for decoding
1143
+ log += "## Step 3: Trajectory Modeling and Decoding\n"
1144
+ log += "- Training Kalman filter to decode behavioral variables from neural trajectories\n"
1145
+
1146
+ # Initialize and train Kalman filter
1147
+ kf = KalmanFilter(initial_state_mean=np.zeros(y_train.shape[1]), n_dim_obs=X_train_pca.shape[1])
1148
+
1149
+ # Fit the Kalman filter to the data
1150
+ kf.em(X_train_pca, y_train)
1151
+
1152
+ # Step 4: Decode behavioral variables
1153
+ log += "## Step 4: Decoding Behavioral Variables\n"
1154
+
1155
+ # Use the Kalman filter to predict behavioral variables
1156
+ y_pred, _ = kf.filter(X_test_pca)
1157
+
1158
+ # Evaluate performance
1159
+ mse = mean_squared_error(y_test, y_pred)
1160
+ log += f"- Mean squared error on test set: {mse:.4f}\n\n"
1161
+
1162
+ # Save the decoded trajectories visualization
1163
+ try:
1164
+ if y_test.shape[1] >= 2:
1165
+ # Create visualization of true vs. predicted trajectories (first 2 dimensions)
1166
+ plt.figure(figsize=(12, 6))
1167
+
1168
+ # First behavioral variable
1169
+ plt.subplot(1, 2, 1)
1170
+ plt.plot(y_test[:, 0], label="True")
1171
+ plt.plot(y_pred[:, 0], label="Predicted")
1172
+ plt.xlabel("Time steps")
1173
+ plt.ylabel("Behavioral Variable 1")
1174
+ plt.title("Decoding Performance - Variable 1")
1175
+ plt.legend()
1176
+
1177
+ # Second behavioral variable
1178
+ plt.subplot(1, 2, 2)
1179
+ plt.plot(y_test[:, 1], label="True")
1180
+ plt.plot(y_pred[:, 1], label="Predicted")
1181
+ plt.xlabel("Time steps")
1182
+ plt.ylabel("Behavioral Variable 2")
1183
+ plt.title("Decoding Performance - Variable 2")
1184
+ plt.legend()
1185
+
1186
+ plt.tight_layout()
1187
+
1188
+ trajectory_plot_path = os.path.join(output_dir, "decoded_trajectories.png")
1189
+ plt.savefig(trajectory_plot_path, dpi=300)
1190
+ plt.close()
1191
+
1192
+ log += f"- Decoded trajectories visualization saved to: {trajectory_plot_path}\n"
1193
+ except Exception as e:
1194
+ log += f"- Error creating trajectory visualization: {str(e)}\n"
1195
+
1196
+ # Save the results as a pickle file
1197
+ results = {
1198
+ "true_behavior": y_test,
1199
+ "predicted_behavior": y_pred,
1200
+ "pca_model": pca,
1201
+ "kalman_filter": kf,
1202
+ "mse": mse,
1203
+ }
1204
+
1205
+ results_file = os.path.join(output_dir, "neural_decoding_results.pkl")
1206
+ with open(results_file, "wb") as f:
1207
+ pickle.dump(results, f)
1208
+
1209
+ # Also save a CSV with the first few predicted vs. actual values for easier inspection
1210
+ try:
1211
+ import pandas as pd
1212
+
1213
+ n_samples = min(100, y_test.shape[0])
1214
+ n_vars = y_test.shape[1]
1215
+
1216
+ results_data = {}
1217
+ for i in range(n_vars):
1218
+ results_data[f"true_var{i + 1}"] = y_test[:n_samples, i]
1219
+ results_data[f"pred_var{i + 1}"] = y_pred[:n_samples, i]
1220
+
1221
+ results_df = pd.DataFrame(results_data)
1222
+ csv_path = os.path.join(output_dir, "decoding_results_sample.csv")
1223
+ results_df.to_csv(csv_path, index=False)
1224
+
1225
+ log += f"- Sample of decoding results saved to: {csv_path}\n"
1226
+ except Exception as e:
1227
+ log += f"- Error creating CSV results: {str(e)}\n"
1228
+
1229
+ log += "\n## Results\n"
1230
+ log += f"- Full decoded behavioral trajectories saved to: {results_file}\n"
1231
+ log += f"- Decoder performance (MSE): {mse:.4f}\n"
1232
+
1233
+ # Save the log to a file
1234
+ log_file = os.path.join(output_dir, "neural_decoding_log.txt")
1235
+ with open(log_file, "w") as f:
1236
+ f.write(log)
1237
+
1238
+ log += f"- Analysis log saved to: {log_file}\n"
1239
+
1240
+ return log
1241
+
1242
+
1243
+ def simulate_whole_cell_ode_model(
1244
+ initial_conditions,
1245
+ parameters,
1246
+ ode_function=None,
1247
+ time_span=(0, 100),
1248
+ time_points=1000,
1249
+ method="LSODA",
1250
+ ):
1251
+ """Simulate a whole-cell model represented as a system of ordinary differential equations (ODEs).
1252
+
1253
+ Parameters
1254
+ ----------
1255
+ initial_conditions : dict or array-like
1256
+ Initial values for each state variable in the model. If dict, keys are variable names
1257
+ and values are initial concentrations/values. If array-like, order must match the
1258
+ order expected by the ODE function.
1259
+ parameters : dict
1260
+ Model parameters required by the ODE function. Keys are parameter names and
1261
+ values are parameter values.
1262
+ ode_function : callable, optional
1263
+ Function defining the system of ODEs. Should take arguments ``(t, y, *args)`` where
1264
+ ``t`` is time, ``y`` is the state vector, and ``args`` contains additional parameters.
1265
+ If None, a simple example whole-cell model will be used.
1266
+ time_span : tuple, default=(0, 100)
1267
+ Tuple of (start_time, end_time) for the simulation.
1268
+ time_points : int, default=1000
1269
+ Number of time points to evaluate.
1270
+ method : str, default='LSODA'
1271
+ Numerical integration method to use (e.g., 'RK45', 'LSODA', 'BDF').
1272
+
1273
+ Returns
1274
+ -------
1275
+ str
1276
+ Research log summarizing the simulation steps and results. Results are saved
1277
+ to a CSV file and the filename is included in the log.
1278
+
1279
+ """
1280
+ from datetime import datetime
1281
+
1282
+ import numpy as np
1283
+ import pandas as pd
1284
+ from scipy.integrate import solve_ivp
1285
+
1286
+ # Define a default ODE function if none is provided
1287
+ if ode_function is None:
1288
+
1289
+ def default_whole_cell_model(t, y, params):
1290
+ # Unpack state variables
1291
+ # Simple model with:
1292
+ # - mRNA (y[0])
1293
+ # - Protein (y[1])
1294
+ # - Metabolite (y[2])
1295
+ # - ATP (y[3])
1296
+ mRNA, protein, metabolite, atp = y
1297
+
1298
+ # Unpack parameters
1299
+ k_transcription = params["k_transcription"] # mRNA synthesis rate
1300
+ k_translation = params["k_translation"] # Protein synthesis rate
1301
+ k_mrna_deg = params["k_mrna_deg"] # mRNA degradation rate
1302
+ k_protein_deg = params["k_protein_deg"] # Protein degradation rate
1303
+ k_metabolism = params["k_metabolism"] # Metabolite production rate
1304
+ k_atp_production = params["k_atp_production"] # ATP production rate
1305
+ k_atp_consumption = params["k_atp_consumption"] # ATP consumption rate
1306
+
1307
+ # ODEs
1308
+ dmRNA_dt = k_transcription - k_mrna_deg * mRNA
1309
+ dprotein_dt = k_translation * mRNA * atp - k_protein_deg * protein
1310
+ dmetabolite_dt = k_metabolism * protein - k_atp_production * metabolite
1311
+ datp_dt = k_atp_production * metabolite - k_atp_consumption * atp - k_translation * mRNA * atp
1312
+
1313
+ return [dmRNA_dt, dprotein_dt, dmetabolite_dt, datp_dt]
1314
+
1315
+ ode_function = default_whole_cell_model
1316
+
1317
+ # Prepare initial conditions as array
1318
+ if isinstance(initial_conditions, dict):
1319
+ y0_values = list(initial_conditions.values())
1320
+ variable_names = list(initial_conditions.keys())
1321
+ else:
1322
+ y0_values = initial_conditions
1323
+ variable_names = [f"Variable_{i}" for i in range(len(initial_conditions))]
1324
+
1325
+ # Set up time points
1326
+ t_eval = np.linspace(time_span[0], time_span[1], time_points)
1327
+
1328
+ # Start research log
1329
+ log = []
1330
+ log.append("# Whole-Cell ODE Model Simulation")
1331
+ log.append(f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
1332
+ log.append("\n## Simulation Setup")
1333
+ log.append(f"- Integration method: {method}")
1334
+ log.append(f"- Time span: {time_span[0]} to {time_span[1]} time units")
1335
+ log.append(f"- Number of time points: {time_points}")
1336
+ log.append(f"- Number of state variables: {len(y0_values)}")
1337
+ log.append("\n## Initial Conditions")
1338
+ for _i, (name, value) in enumerate(zip(variable_names, y0_values, strict=False)):
1339
+ log.append(f"- {name}: {value}")
1340
+
1341
+ log.append("\n## Model Parameters")
1342
+ for param, value in parameters.items():
1343
+ log.append(f"- {param}: {value}")
1344
+
1345
+ # Solve the ODE system
1346
+ log.append("\n## Running Simulation")
1347
+ try:
1348
+ solution = solve_ivp(
1349
+ lambda t, y: ode_function(t, y, parameters),
1350
+ time_span,
1351
+ y0_values,
1352
+ method=method,
1353
+ t_eval=t_eval,
1354
+ )
1355
+
1356
+ # Check if simulation was successful
1357
+ if solution.success:
1358
+ log.append("Simulation completed successfully.")
1359
+ log.append(f"- Number of function evaluations: {solution.nfev}")
1360
+ log.append(f"- Number of Jacobian evaluations: {solution.njev}")
1361
+ log.append(f"- Number of steps: {len(solution.t)}")
1362
+
1363
+ # Create DataFrame with results
1364
+ results_df = pd.DataFrame(solution.y.T, columns=variable_names)
1365
+ results_df.insert(0, "Time", solution.t)
1366
+
1367
+ # Save results to CSV
1368
+ filename = f"whole_cell_simulation_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
1369
+ results_df.to_csv(filename, index=False)
1370
+
1371
+ log.append("\n## Results Summary")
1372
+ log.append(f"Simulation results saved to: {filename}")
1373
+
1374
+ # Calculate some basic statistics
1375
+ final_state = results_df.iloc[-1].drop("Time").to_dict()
1376
+ log.append("\n## Final State")
1377
+ for var, value in final_state.items():
1378
+ log.append(f"- {var}: {value:.6f}")
1379
+
1380
+ else:
1381
+ log.append(f"Simulation failed with message: {solution.message}")
1382
+
1383
+ except Exception as e:
1384
+ log.append(f"Error during simulation: {str(e)}")
1385
+
1386
+ # Return the research log
1387
+ return "\n".join(log)