File size: 9,347 Bytes
bff2f94 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | """
Pathway reasoning question generator for BioGRPO.
Generates verifiable QA pairs from GeneLab fGSEA pathway data.
Each question has structured ground truth for scoring by the verifier stack.
"""
from typing import List, Dict, Set
from dataclasses import dataclass, field
from biorlhf.data.genelabloader import (
get_consensus_directions,
get_disagreeing_pathways,
get_pathway_directions,
load_nes_conservation,
TISSUE_MISSIONS,
)
@dataclass
class GRPOQuestion:
"""A question with verifiable ground truth for GRPO training."""
prompt: str
ground_truth: Dict
tissue: str
db: str
question_type: str # "direction", "comparison", "consistency", "uncertainty"
applicable_verifiers: List[str]
difficulty: str # "easy", "medium", "hard"
metadata: Dict = field(default_factory=dict)
def _clean_pathway_name(pathway: str) -> str:
"""HALLMARK_OXIDATIVE_PHOSPHORYLATION β Oxidative Phosphorylation"""
for prefix in ("HALLMARK_", "KEGG_", "REACTOME_", "MITOCARTA_"):
pathway = pathway.replace(prefix, "")
return pathway.replace("_", " ").title()
# ββ Question generators ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def generate_direction_questions(
tissue: str,
db: str = "hallmark",
padj_threshold: float = 0.05,
) -> List[GRPOQuestion]:
"""Generate V1-targetable questions about pathway direction."""
consensus = get_consensus_directions(tissue, db, min_missions=2, padj_threshold=padj_threshold)
questions: List[GRPOQuestion] = []
for pathway, info in consensus.items():
pw = _clean_pathway_name(pathway)
n_agree = info["n_agree"]
# Type 1: Direct direction question (easy/medium)
questions.append(GRPOQuestion(
prompt=(
f"In mouse {tissue} tissue during spaceflight, is the "
f"{pw} pathway upregulated or downregulated based on "
f"gene set enrichment analysis? "
f"Provide your confidence level."
),
ground_truth={
"pathway": pathway,
"direction": info["direction"],
"n_supporting_missions": n_agree,
"expected_confidence": "high" if n_agree >= 3 else "medium",
},
tissue=tissue,
db=db,
question_type="direction",
applicable_verifiers=["V1", "V4"],
difficulty="easy" if n_agree >= 3 else "medium",
))
# Type 2: Mechanistic reasoning question (medium/hard)
direction_word = "activation" if info["direction"] == "UP" else "suppression"
questions.append(GRPOQuestion(
prompt=(
f"Explain the biological significance of {pw} pathway "
f"{direction_word} in mouse {tissue} under spaceflight conditions. "
f"What mechanisms might drive this change? "
f"State your confidence in the direction and magnitude."
),
ground_truth={
"pathway": pathway,
"direction": info["direction"],
"n_supporting_missions": n_agree,
"requires_mechanism": True,
"expected_confidence": "medium",
},
tissue=tissue,
db=db,
question_type="direction",
applicable_verifiers=["V1", "V2", "V4"],
difficulty="medium" if n_agree >= 3 else "hard",
))
return questions
def generate_comparison_questions(
db: str = "hallmark",
padj_threshold: float = 0.05,
) -> List[GRPOQuestion]:
"""Generate cross-tissue comparison questions (V1 + V3 targetable)."""
questions: List[GRPOQuestion] = []
# Collect consensus directions across tissues (exclude skin subsites for cleaner Qs)
tissue_dirs: Dict[str, Dict[str, Dict]] = {}
comparison_tissues = ["liver", "gastrocnemius", "kidney", "thymus", "eye"]
for tissue in comparison_tissues:
consensus = get_consensus_directions(tissue, db, min_missions=2, padj_threshold=padj_threshold)
if consensus:
tissue_dirs[tissue] = consensus
if len(tissue_dirs) < 2:
return questions
# Find pathways in 2+ tissues
all_pathways: Set[str] = set()
for dirs in tissue_dirs.values():
all_pathways.update(dirs.keys())
for pathway in sorted(all_pathways):
tissues_with = {
t: d[pathway]
for t, d in tissue_dirs.items()
if pathway in d
}
if len(tissues_with) < 2:
continue
pw = _clean_pathway_name(pathway)
tissue_list = sorted(tissues_with.keys())
directions_set = {info["direction"] for info in tissues_with.values()}
is_consistent = len(directions_set) == 1
questions.append(GRPOQuestion(
prompt=(
f"Compare the response of the {pw} pathway to spaceflight "
f"across {', '.join(tissue_list)} tissues in mice. "
f"Is the direction of change consistent or tissue-specific? "
f"Explain the biological basis for any differences."
),
ground_truth={
"pathway": pathway,
"tissue_directions": {
t: info["direction"] for t, info in tissues_with.items()
},
"is_consistent": is_consistent,
"n_tissues": len(tissues_with),
},
tissue="multi",
db=db,
question_type="comparison",
applicable_verifiers=["V1", "V3", "V4"],
difficulty="hard",
))
return questions
def generate_uncertainty_questions(
tissue: str,
db: str = "hallmark",
padj_threshold: float = 0.05,
) -> List[GRPOQuestion]:
"""Generate questions where missions disagree β model should express uncertainty."""
disagreeing = get_disagreeing_pathways(tissue, db, padj_threshold)
questions: List[GRPOQuestion] = []
for pathway, info in disagreeing.items():
pw = _clean_pathway_name(pathway)
questions.append(GRPOQuestion(
prompt=(
f"Is the {pw} pathway consistently activated or suppressed "
f"in mouse {tissue} across different spaceflight missions? "
f"How confident are you in the direction of change?"
),
ground_truth={
"pathway": pathway,
"missions_up": info["missions_up"],
"missions_down": info["missions_down"],
"missions_ns": info["missions_ns"],
"correct_behavior": "context_dependent",
"expected_confidence": "low",
},
tissue=tissue,
db=db,
question_type="uncertainty",
applicable_verifiers=["V1", "V4"],
difficulty="hard",
))
return questions
def generate_conservation_questions(
db: str = "hallmark",
) -> List[GRPOQuestion]:
"""Generate questions about NES conservation across missions."""
conservation = load_nes_conservation(db)
if not conservation:
return []
questions: List[GRPOQuestion] = []
data = conservation.get("data", conservation)
for tissue, info in data.items():
if not isinstance(info, dict):
continue
mean_r = info.get("nes_mean_r")
if mean_r is None:
continue
if mean_r > 0.5:
conservation_level = "highly conserved"
expected_conf = "high"
elif mean_r > 0.2:
conservation_level = "moderately conserved"
expected_conf = "medium"
else:
conservation_level = "poorly conserved"
expected_conf = "medium"
questions.append(GRPOQuestion(
prompt=(
f"How conserved are pathway-level responses to spaceflight "
f"across different missions in mouse {tissue}? "
f"Are the enrichment patterns reproducible?"
),
ground_truth={
"tissue": tissue,
"nes_mean_r": mean_r,
"conservation_level": conservation_level,
"expected_confidence": expected_conf,
"key_facts": [
f"Mean pairwise NES correlation across missions is {mean_r:.3f}",
f"Pathway responses in {tissue} are {conservation_level}",
],
},
tissue=tissue,
db=db,
question_type="direction",
applicable_verifiers=["V2", "V4"],
difficulty="medium",
))
return questions
def generate_all_questions(db: str = "hallmark") -> List[GRPOQuestion]:
"""Generate the full question set from GeneLab data."""
all_q: List[GRPOQuestion] = []
for tissue in TISSUE_MISSIONS:
all_q.extend(generate_direction_questions(tissue, db))
all_q.extend(generate_uncertainty_questions(tissue, db))
all_q.extend(generate_comparison_questions(db))
all_q.extend(generate_conservation_questions(db))
return all_q
|