Two-Stage Pipeline¶
The TwoStagePipeline class separates data preprocessing from LLM annotation.
Overview¶
Stage 1 (Preprocess) Stage 2 (Annotate)
-------------------- ------------------
DEG files ─────┐ intermediate.csv
│ │
Pathway files ─┼──► intermediate.csv ──► LLM ──► final_output.csv
│
Config file ───┘
Class Reference¶
gs2txt.pipeline.TwoStagePipeline
¶
Two-stage processing pipeline for gene set annotation.
This pipeline separates data preprocessing from LLM annotation, allowing users to: 1. Preprocess data without API access (stage 1) 2. Review intermediate results before annotation 3. Run annotation separately when API is available (stage 2)
Examples:
>>> # Stage 1: Preprocess with base directories (no API needed)
>>> # config.yaml contains: deg_dir="deg/", pathway_dirs=["GO/", "KEGG/"]
>>> TwoStagePipeline.preprocess(
... config_file="config.yaml",
... output_file="intermediate.csv",
... deg_base_dir="/data/project1/", # -> /data/project1/deg/
... pathway_base_dir="/data/project1/" # -> /data/project1/GO/, etc.
... )
>>> # Stage 1: Preprocess with absolute paths in config (backward compatible)
>>> TwoStagePipeline.preprocess(
... config_file="config.yaml",
... output_file="intermediate.csv"
... )
>>> # Stage 2: Annotate (API needed)
>>> TwoStagePipeline.annotate(
... intermediate_file="intermediate.csv",
... output_file="output.csv",
... config_file="config.yaml"
... )
Source code in gs2txt/pipeline.py
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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 | |
Functions¶
annotate(intermediate_file, output_file, config_file=None, test=False, checkpoint_interval=100)
staticmethod
¶
Stage 2: Generate annotations using LLM.
Reads intermediate results from stage 1, calls LLM to generate annotations, and saves final results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
intermediate_file
|
str
|
Path to intermediate CSV from preprocess stage. |
required |
output_file
|
str
|
Path to save final results CSV. |
required |
config_file
|
str
|
Path to YAML config file. If None, uses default config. |
None
|
test
|
bool
|
If True, only process the first 3 rows (for testing). Default: False |
False
|
checkpoint_interval
|
int
|
Save intermediate results every N records to prevent data loss. Default: 100. Set to 0 to disable checkpointing. |
100
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Final results with columns: gs, annotation, pathways, PPIs, Final_prompt |
Examples:
>>> # Normal annotation
>>> TwoStagePipeline.annotate(
... intermediate_file="intermediate.csv",
... output_file="output.csv",
... config_file="config.yaml"
... )
>>> # Test mode: only process first 3 rows
>>> TwoStagePipeline.annotate(
... intermediate_file="intermediate.csv",
... output_file="output.csv",
... test=True
... )
>>> # Custom checkpoint interval
>>> TwoStagePipeline.annotate(
... intermediate_file="intermediate.csv",
... output_file="output.csv",
... checkpoint_interval=50 # Save every 50 records
... )
Source code in gs2txt/pipeline.py
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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | |
preprocess(config_file, output_file='intermediate.csv', deg_base_dir=None, pathway_base_dir=None, ppi_context=None, test=False, checkpoint_interval=100)
staticmethod
¶
Stage 1: Preprocess DEG and enrichment data.
Scans DEG folder, finds matching pathway files in multiple folders, filters them according to config, builds prompts, and saves intermediate results for later annotation.
This method: 1. Scans deg_dir for all CSV files 2. For each DEG file, finds matching pathway files in all pathway_dirs 3. Merges and deduplicates pathways from all sources 4. Builds prompts and saves intermediate results
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_file
|
str
|
Path to YAML config file with input paths (deg_dir, pathway_dirs) |
required |
output_file
|
str
|
Path to save intermediate results CSV |
'intermediate.csv'
|
deg_base_dir
|
str
|
Base directory for DEG files. If provided, the final DEG path will be: deg_base_dir / config.deg_dir If None, config.deg_dir is used as-is (backward compatible) |
None
|
pathway_base_dir
|
str
|
Base directory for pathway files. If provided, the final pathway paths will be: pathway_base_dir / each pathway_dir in config If None, pathway_dirs are used as-is (backward compatible) |
None
|
ppi_context
|
dict
|
Dictionary mapping gene set names to PPI context strings |
None
|
test
|
bool
|
If True, only process the first 3 DEG files (for testing). Default: False |
False
|
checkpoint_interval
|
int
|
Save intermediate results every N records to prevent data loss. Default: 100. Set to 0 to disable checkpointing. |
100
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Intermediate results with columns: gs, genes, pathways, ppis, final_prompt |
Examples:
>>> # With base directories (relative paths in config)
>>> # config.yaml contains: deg_dir="deg/", pathway_dirs=["GO/", "KEGG/"]
>>> TwoStagePipeline.preprocess(
... config_file="config.yaml",
... output_file="intermediate.csv",
... deg_base_dir="/data/project1/", # -> /data/project1/deg/
... pathway_base_dir="/data/project1/" # -> /data/project1/GO/, etc.
... )
>>> # Without base directories (absolute paths in config, backward compatible)
>>> # config.yaml contains: deg_dir="/abs/path/deg/", pathway_dirs=["/abs/path/GO/"]
>>> TwoStagePipeline.preprocess(
... config_file="config.yaml",
... output_file="intermediate.csv"
... )
>>> # Test mode: only process first 3 files
>>> TwoStagePipeline.preprocess(
... config_file="config.yaml",
... output_file="intermediate.csv",
... test=True
... )
Source code in gs2txt/pipeline.py
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | |
Methods¶
preprocess_batch()¶
Batch preprocess multiple DEG files with multiple pathway sources.
@staticmethod
def preprocess_batch(
config_file: str,
output_file: str = "intermediate.csv",
ppi_context: Optional[Dict[str, str]] = None
) -> pd.DataFrame
Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
config_file |
str |
Required | Path to YAML config |
output_file |
str |
"intermediate.csv" |
Output path |
ppi_context |
Dict[str, str] |
None |
PPI context per gene set |
Example¶
from gs2txt.pipeline import TwoStagePipeline
TwoStagePipeline.preprocess_batch(
config_file="config.yaml",
output_file="intermediate.csv",
ppi_context={
"sample1": "Hub genes: TP53, BRCA1",
"sample2": "Hub genes: CD4, IL2"
}
)
preprocess()¶
Preprocess a single DEG file with grouped clusters.
@staticmethod
def preprocess(
deg_file: str,
enrichment_dir: str,
output_file: str,
config_file: Optional[str] = None,
group_column: str = "cluster",
ppi_context: Optional[Dict[str, str]] = None
) -> pd.DataFrame
Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
deg_file |
str |
Required | Path to DEG CSV |
enrichment_dir |
str |
Required | Path to enrichment directory |
output_file |
str |
Required | Output path |
config_file |
str |
None |
Path to config (optional) |
group_column |
str |
"cluster" |
Column for grouping |
ppi_context |
Dict[str, str] |
None |
PPI context per cluster |
Example¶
TwoStagePipeline.preprocess(
deg_file="deg.csv",
enrichment_dir="enrichment/",
output_file="intermediate.csv",
config_file="config.yaml",
group_column="cluster"
)
annotate()¶
Generate annotations using LLM.
@staticmethod
def annotate(
intermediate_file: str,
output_file: str,
config_file: Optional[str] = None
) -> pd.DataFrame
Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
intermediate_file |
str |
Required | Path to intermediate CSV |
output_file |
str |
Required | Output path |
config_file |
str |
None |
Path to config |
Example¶
TwoStagePipeline.annotate(
intermediate_file="intermediate.csv",
output_file="final_output.csv",
config_file="config.yaml"
)
Configuration¶
YAML Config Structure¶
# Input paths (for batch mode)
input:
deg_dir: "./data/deg/"
pathway_dirs:
- "./data/GO/"
- "./data/KEGG/"
# Gene filtering
gene_filter:
pvalue_threshold: 0.05
log2fc_threshold: 1.0
pvalue_column: "pvalue"
log2fc_column: "logFC"
max_gene_num: 60
# Pathway filtering
pathway_filter:
pvalue_threshold: 0.05
pvalue_column: "Adjusted P-value"
term_column: "Term"
max_pathway_num: 10
# LLM configuration
llm:
provider: "litellm"
model_id: "gpt-4"
temperature: 0.0
base_url: "https://your-server.com/"
api_key_env: "LITELLM_API_KEY"
PipelineConfig Class¶
from gs2txt.config_loader import PipelineConfig
# Load from YAML
config = PipelineConfig.from_yaml("config.yaml")
# Use defaults
config = PipelineConfig.default()
# Save config
config.save_yaml("config_backup.yaml")
# Access attributes
print(config.max_gene_num)
print(config.llm_provider)
File Formats¶
DEG File (Input)¶
Pathway File (Input)¶
Intermediate File (Stage 1 Output)¶
gs,genes,pathways,ppis,final_prompt
sample1,"TP53,BRCA1","DNA damage,Cell cycle","Hub: TP53","Your task..."
Final Output (Stage 2 Output)¶
gs,annotation,pathways,PPIs,Final_prompt
sample1,"This gene set is involved in...","DNA damage","Hub: TP53","Your task..."
Workflow Examples¶
Batch Processing¶
# Stage 1: Preprocess all samples
TwoStagePipeline.preprocess_batch(
config_file="config.yaml",
output_file="intermediate.csv"
)
# Review intermediate.csv here
# Stage 2: Annotate
TwoStagePipeline.annotate(
intermediate_file="intermediate.csv",
output_file="final_output.csv",
config_file="config.yaml"
)
Single File Processing¶
# Stage 1
TwoStagePipeline.preprocess(
deg_file="clustered_deg.csv",
enrichment_dir="enrichment/",
output_file="intermediate.csv",
group_column="cluster"
)
# Stage 2
TwoStagePipeline.annotate(
intermediate_file="intermediate.csv",
output_file="final_output.csv"
)
Error Handling¶
try:
TwoStagePipeline.preprocess_batch(
config_file="config.yaml",
output_file="intermediate.csv"
)
except FileNotFoundError as e:
print(f"Missing file: {e}")
except ValueError as e:
print(f"Configuration error: {e}")
Common errors:
FileNotFoundError: DEG directory or config file not foundValueError: Missing required columns or invalid configuration- LLM errors during annotation stage