Repository navigation
Expand file tree
/
Copy pathedgepython_server.py
More file actions
2723 lines (2308 loc) · 94.3 KB
/
Copy pathedgepython_server.py
File metadata and controls
2723 lines (2308 loc) · 94.3 KB
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
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This code was written by Claude (Anthropic). The project was directed by Lior Pachter.
"""
edgePython MCP Server — Differential expression analysis via tool calls.
Wraps edgePython's core pipeline so AI agents can run RNA-seq DE analysis
step-by-step: load data → filter → normalize → estimate dispersions →
fit model → test contrasts → get results → generate plots.
Usage:
python3 edgepython_server.py
"""
import os
import sys
import re
import numpy as np
import pandas as pd
from typing import Optional
from fastmcp import FastMCP
from statsmodels.stats.multitest import multipletests
# Ensure edgePython is importable
_edgepython_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _edgepython_root not in sys.path:
sys.path.insert(0, _edgepython_root)
import edgepython as ep
# ---------------------------------------------------------------------------
# Server + state
# ---------------------------------------------------------------------------
mcp = FastMCP(
"edgepython",
instructions=(
"RNA-seq differential expression analysis server powered by edgePython. "
"Bulk workflow: load_data → filter_genes → normalize → set_design → "
"estimate_dispersion (or estimate_glm_robust_dispersion) → "
"voom_transform (optional) → fit_model → test_contrast → "
"get_top_genes / generate_plot / gene_set_test. Quantifier output "
"(salmon, kallisto, lr-kallisto, oarfish, RSEM): load_quant. DTU: "
"load_quant → estimate_dispersion → dtu_diff_splice_dge or "
"dtu_splice_variants. Methylation: load_bismark → fit_bin_model → "
"test_bin → get_top_genes. "
"Single-cell workflow: load_sc_data → fit_sc_model → test_sc_coef → get_sc_top_genes. "
"Use describe() or describe_sc() to see current pipeline state."
),
)
# Module-level state — mutated by tools across a session.
_state: dict = {
"dgelist": None, # Current DGEList
"design": None, # Design matrix (ndarray)
"design_info": None, # Column names for the design matrix
"fit": None, # Fitted QL-GLM (DGEGLM-like dict)
"glm_fit": None, # Fitted GLM (non-QL)
"results": {}, # name → DGELRT-like dict
"last_result": None, # Name of most recent test result
"voom": None, # Most recent voom/voomLmFit output dict
"filtered": False,
"normalized": False,
"dispersions_estimated": False,
"feature_level": "unknown", # inferred: gene | transcript | unknown
"feature_level_note": None,
"analysis_context": "unknown", # inferred: bulk | single_cell_10x | single_cell | unknown
"analysis_context_note": None,
}
def _require(key: str, label: str):
"""Raise if a pipeline stage hasn't been completed yet."""
if _state[key] is None:
raise ValueError(
f"No {label} available. Run the appropriate step first."
)
def _gene_name(row):
"""Extract gene name from a top_tags result row."""
# top_tags prepends gene annotation columns; check for GeneID first
for col in ("GeneID", "gene_id", "gene_name", "Symbol"):
if col in row.index:
return str(row[col])
# Fall back to row index
return str(row.name)
def _infer_feature_level(feature_ids: Optional[list]) -> tuple[str, str]:
"""Heuristically infer feature level from row IDs."""
if not feature_ids:
return "unknown", "unknown (no feature IDs found)"
ids = [str(x).strip() for x in feature_ids if str(x).strip()]
if not ids:
return "unknown", "unknown (no non-empty feature IDs found)"
# Sample up to 500 IDs for a lightweight heuristic.
ids = ids[:500]
n = len(ids)
tx_patterns = (
r"(^|[|_.-])ENST\d+",
r"(^|[|_.-])NM_\d+",
r"(^|[|_.-])NR_\d+",
r"(^|[|_.-])XM_\d+",
r"(^|[|_.-])XR_\d+",
r"\btx\d+\b",
r"\btranscript\b",
r"\bisoform\b",
)
gene_patterns = (
r"(^|[|_.-])ENSG\d+",
r"(^|[|_.-])FBgn\d+",
r"(^|[|_.-])WBGene\d+",
)
tx_hits = 0
gene_hits = 0
for s in ids:
if any(re.search(p, s, flags=re.IGNORECASE) for p in tx_patterns):
tx_hits += 1
if any(re.search(p, s, flags=re.IGNORECASE) for p in gene_patterns):
gene_hits += 1
tx_frac = tx_hits / n
gene_frac = gene_hits / n
# Bias to gene-level when uncertain (edgePython default use case).
if tx_frac >= 0.10 and tx_hits >= 5:
return "transcript", f"transcript/isoform-like IDs ({tx_hits}/{n})"
if gene_frac >= 0.10 and gene_hits >= 5:
return "gene", f"gene-like IDs ({gene_hits}/{n})"
return "gene", "gene-level assumed (IDs do not strongly indicate transcript-level)"
def _infer_analysis_context(
source: Optional[str] = None,
data_input: Optional[object] = None,
sample_names: Optional[list] = None,
default_bulk: bool = False,
) -> tuple[str, str]:
"""Heuristically infer sequencing/analysis context."""
src = (source or "").strip().lower()
# Flatten potential path-like clues.
clues = []
if isinstance(data_input, (list, tuple)):
clues.extend([str(x).lower() for x in data_input])
elif data_input is not None:
clues.append(str(data_input).lower())
clue_text = " ".join(clues)
# Strong single-cell/10x signals.
if src == "10x" or "10x" in clue_text or "cellranger" in clue_text:
return "single_cell_10x", "10x/cellranger-like source/path"
if src == "anndata" or any(s.endswith('.h5ad') for s in clues):
# Could be 10x-derived or non-10x single-cell.
if "10x" in clue_text or "cellranger" in clue_text:
return "single_cell_10x", "AnnData with 10x/cellranger-like clues"
return "single_cell", "AnnData source/path"
# SMART-seq / random-primed style clues -> bulk-like transcriptome input.
if any(k in clue_text for k in ("smartseq", "smart-seq", "smart_seq", "random primed", "random_primed", "random-primed")):
return "bulk", "SMART-seq/random-primed-like clues"
# Source families typically used for bulk transcript quantification.
if src in {"kallisto", "salmon", "rsem", "oarfish", "table", "matrix", "dataframe", "sparse", "rds"}:
return "bulk", f"source='{src}' typically bulk/pseudobulk-like"
# Sample-name heuristic for 10x-like barcodes.
if sample_names:
names = [str(x) for x in sample_names]
if names:
barcode_hits = 0
for n in names:
s = n.strip()
if re.fullmatch(r"[ACGT]{8,}(?:-\d+)?", s):
barcode_hits += 1
frac = barcode_hits / len(names)
if len(names) >= 100 and frac >= 0.5:
return "single_cell_10x", f"sample names look like 10x barcodes ({barcode_hits}/{len(names)})"
if default_bulk:
return "bulk", "bulk assumed from count-matrix workflow"
return "unknown", "insufficient clues"
def _is_bulk_like_context() -> bool:
return _state.get("analysis_context") == "bulk"
def _gene_level_warning() -> Optional[str]:
"""Soft warning shown only for likely bulk/random-primed contexts."""
if _state.get("feature_level") == "gene" and _is_bulk_like_context():
return (
"Note: This appears to be gene-level DE in a bulk/random-primed-like context. "
"If transcript/isoform quantifications are available, consider isoform-level "
"analysis to avoid masking isoform-specific changes."
)
return None
def _append_gene_level_warning(lines: list) -> None:
warn = _gene_level_warning()
if warn:
lines.extend(["", warn])
def _resolve_gene_exon_ids(
d: dict,
gene_column: Optional[str] = None,
exon_column: Optional[str] = None,
):
"""Resolve gene/exon IDs from DGEList gene annotation or fallback IDs."""
genes = d.get("genes")
if genes is None:
gene_ids = d.get("_gene_ids")
if gene_ids is None:
raise ValueError("No gene annotation available; provide DGEList genes with GeneID.")
gene_ids = np.asarray(gene_ids)
exon_ids = np.arange(len(gene_ids))
return gene_ids, exon_ids
gdf = genes if isinstance(genes, pd.DataFrame) else pd.DataFrame(genes)
if gene_column is not None:
if gene_column not in gdf.columns:
raise ValueError(f"gene_column '{gene_column}' not found in gene annotation.")
gene_ids = gdf[gene_column].astype(str).values
else:
found = None
for col in ("GeneID", "geneid", "gene_id", "Gene", "EnsG"):
if col in gdf.columns:
found = col
break
if found is None:
raise ValueError("Could not infer gene IDs. Set gene_column explicitly.")
gene_ids = gdf[found].astype(str).values
if exon_column is not None:
if exon_column not in gdf.columns:
raise ValueError(f"exon_column '{exon_column}' not found in gene annotation.")
exon_ids = gdf[exon_column].astype(str).values
else:
found = None
for col in ("ExonID", "exonid", "exon_id", "TranscriptID", "transcript_id"):
if col in gdf.columns:
found = col
break
if found is not None:
exon_ids = gdf[found].astype(str).values
elif not isinstance(gdf.index, pd.RangeIndex):
exon_ids = gdf.index.astype(str).values
else:
exon_ids = np.arange(len(gene_ids))
return np.asarray(gene_ids), np.asarray(exon_ids)
# ---------------------------------------------------------------------------
# Tool 1: load_data
# ---------------------------------------------------------------------------
@mcp.tool()
def load_data(
counts_path: str,
sample_info_path: Optional[str] = None,
group_column: Optional[str] = None,
separator: Optional[str] = None,
) -> str:
"""Load a count matrix (and optional sample metadata) to create a DGEList.
Args:
counts_path: Path to count matrix file (TSV/CSV). Genes as rows,
samples as columns. First column is gene IDs.
sample_info_path: Optional path to sample metadata file (TSV/CSV).
Must have a column matching sample names in the count matrix.
group_column: Column in sample info to use as group factor.
Auto-detected if not provided.
separator: Column separator ('\\t' or ','). Auto-detected from
file extension if not provided.
"""
# Auto-detect separator
if separator is None:
separator = "," if counts_path.endswith(".csv") else "\t"
# Read counts
counts_df = pd.read_csv(counts_path, sep=separator, index_col=0)
gene_ids = list(counts_df.index)
sample_names = list(counts_df.columns)
counts = counts_df.values.astype(np.float64)
genes_df = pd.DataFrame({"GeneID": gene_ids})
# Read sample info if provided
group = None
samples_df = None
if sample_info_path is not None:
sep2 = "," if sample_info_path.endswith(".csv") else "\t"
samples_df = pd.read_csv(sample_info_path, sep=sep2)
# Try to align rows to sample order
for col in samples_df.columns:
vals = [str(v) for v in samples_df[col]]
if set(sample_names).issubset(set(vals)):
samples_df = samples_df.set_index(col).loc[sample_names].reset_index()
break
# Extract group
if group_column is not None:
group = list(samples_df[group_column].astype(str))
else:
# Auto-detect: first column with few unique values
for col in samples_df.columns:
n_unique = samples_df[col].nunique()
if 2 <= n_unique <= len(sample_names) // 2:
group = list(samples_df[col].astype(str))
group_column = col
break
dgelist = ep.make_dgelist(
counts=counts,
group=group,
genes=genes_df,
samples=samples_df,
)
# Attach sample/gene names for display
dgelist["_sample_names"] = sample_names
dgelist["_gene_ids"] = gene_ids
level, level_note = _infer_feature_level(gene_ids)
context, context_note = _infer_analysis_context(
source=None,
data_input=counts_path,
sample_names=sample_names,
default_bulk=True,
)
_state["dgelist"] = dgelist
_state["feature_level"] = level
_state["feature_level_note"] = level_note
_state["analysis_context"] = context
_state["analysis_context_note"] = context_note
_state["filtered"] = False
_state["normalized"] = False
_state["dispersions_estimated"] = False
_state["design"] = None
_state["design_info"] = None
_state["fit"] = None
_state["glm_fit"] = None
_state["results"] = {}
_state["last_result"] = None
_state["voom"] = None
# Build summary
lib_sizes = dgelist["samples"]["lib.size"].values
lines = [
f"Loaded {counts.shape[0]:,} genes × {counts.shape[1]} samples",
f"Samples: {', '.join(sample_names)}",
]
if group is not None:
from collections import Counter
gc = Counter(group)
lines.append(f"Groups ({group_column}): " + ", ".join(
f"{k} (n={v})" for k, v in gc.items()
))
lines.append(
f"Library sizes: {int(lib_sizes.min()):,} – {int(lib_sizes.max()):,} "
f"(median {int(np.median(lib_sizes)):,})"
)
if _state.get("feature_level_note"):
lines.append(f"Feature level: {_state['feature_level']} ({_state['feature_level_note']})")
if _state.get("analysis_context_note"):
lines.append(f"Context: {_state['analysis_context']} ({_state['analysis_context_note']})")
_append_gene_level_warning(lines)
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Tool 1b: load_data_auto
# ---------------------------------------------------------------------------
@mcp.tool()
def load_data_auto(
data: Optional[str] = None,
data_list: Optional[list] = None,
source: Optional[str] = None,
format: Optional[str] = None,
path: Optional[str] = None,
group: Optional[list] = None,
labels: Optional[list] = None,
columns: Optional[list] = None,
sep: str = "\t",
obs_col: Optional[str] = None,
layer: Optional[str] = None,
ngibbs: int = 100,
divide: bool = False,
verbose: bool = True,
) -> str:
"""Load data using edgePython's flexible read_data() loader.
Args:
data: Path to file/dir or other supported value. If data_list is provided,
this is ignored.
data_list: Optional list of paths (e.g. quantification dirs).
source: Data source (kallisto, lr_kallisto, salmon, oarfish, rsem,
10x, table, anndata, rds, sparse, matrix, dataframe).
Auto-detected if None. For quantifier output with edgeR 5.0's
annotation and gene-level summaries, use load_quant().
format: Source-specific format (e.g. 'h5' or 'tsv' for kallisto).
path: Base path prefix for relative paths.
group: Optional group assignments.
labels: Optional sample labels.
columns: For table format: (gene_id_col, count_col) 0-based indices.
sep: Field separator for table/CSV files.
obs_col: For AnnData: column in .obs to use as group factor.
layer: For AnnData: layer name to use instead of .X.
ngibbs: For RSEM: number of Gibbs samples per sample.
divide: For quantifier output: divide counts by the estimated
overdispersions. Default False.
verbose: Print progress messages.
"""
if data_list is not None:
data_input = data_list
elif data is not None:
data_input = data
else:
raise ValueError("Provide data or data_list.")
dgelist = ep.read_data(
data_input,
source=source,
format=format,
path=path,
group=group,
labels=labels,
columns=columns,
sep=sep,
obs_col=obs_col,
layer=layer,
ngibbs=ngibbs,
divide=divide,
verbose=verbose,
)
lines = _register_loaded(dgelist, source=source, data_input=data_input)
return "\n".join(lines)
def _feature_ids(dgelist) -> Optional[list]:
"""Feature IDs from the gene annotation columns, or its row names."""
gdf = dgelist.get("genes")
if gdf is None:
return None
for col in ("GeneID", "gene_id", "gene_name", "Symbol"):
if col in gdf.columns:
return list(gdf[col].astype(str))
if not isinstance(gdf.index, pd.RangeIndex):
return [str(x) for x in gdf.index]
return None
def _register_loaded(dgelist, source=None, data_input=None) -> list:
"""Make a loaded DGEList the current data, clearing downstream state,
and return summary lines."""
_state["dgelist"] = dgelist
_state["filtered"] = False
_state["normalized"] = False
_state["dispersions_estimated"] = False
_state["design"] = None
_state["design_info"] = None
_state["fit"] = None
_state["glm_fit"] = None
_state["results"] = {}
_state["last_result"] = None
_state["voom"] = None
counts = dgelist["counts"]
gene_ids = _feature_ids(dgelist)
if gene_ids is not None:
dgelist["_gene_ids"] = gene_ids
sample_names = None
if dgelist.get("samples") is not None:
sdf = dgelist["samples"]
if sdf.index is not None and len(sdf.index) == counts.shape[1]:
sample_names = [str(x) for x in sdf.index]
if sample_names is not None:
dgelist["_sample_names"] = sample_names
level, level_note = _infer_feature_level(gene_ids)
context, context_note = _infer_analysis_context(
source=source,
data_input=data_input,
sample_names=sample_names,
default_bulk=False,
)
_state["feature_level"] = level
_state["feature_level_note"] = level_note
_state["analysis_context"] = context
_state["analysis_context_note"] = context_note
lines = [f"Loaded {counts.shape[0]:,} genes × {counts.shape[1]} samples"]
if sample_names is not None:
lines.append(f"Samples: {', '.join(sample_names)}")
if _state.get("feature_level_note"):
lines.append(f"Feature level: {_state['feature_level']} ({_state['feature_level_note']})")
if _state.get("analysis_context_note"):
lines.append(f"Context: {_state['analysis_context']} ({_state['analysis_context_note']})")
_append_gene_level_warning(lines)
return lines
# ---------------------------------------------------------------------------
# Tool 1c: load_quant
# ---------------------------------------------------------------------------
_QUANT_READERS = {
"salmon": (ep.catch_salmon, ep.catch_salmon_gene),
"kallisto": (ep.catch_kallisto, ep.catch_kallisto_gene),
"lr_kallisto": (ep.catch_lr_kallisto, ep.catch_lr_kallisto_gene),
"oarfish": (ep.catch_oarfish, ep.catch_oarfish_gene),
"rsem": (ep.catch_rsem, ep.catch_rsem_gene),
}
@mcp.tool()
def load_quant(
source: str,
paths: Optional[list] = None,
parent_dir: Optional[str] = None,
level: str = "transcript",
tx2gene_path: Optional[str] = None,
divide: bool = True,
group: Optional[list] = None,
verbose: bool = False,
) -> str:
"""Load quantifier output with edgeR 5.0's catch* readers.
Transcript-level counts are divided by the overdispersions estimated from
bootstrap or Gibbs samples (Baldoni et al. 2024), and Gencode transcript
names are unpacked into annotation columns (EnsG, TxName, GeneName, ...),
which dtu_diff_splice_dge and dtu_splice_variants use as gene IDs.
Gene-level loading sums the counts within genes.
Args:
source: 'salmon', 'kallisto', 'lr_kallisto', 'oarfish' or 'rsem'.
paths: Sample directories (salmon, kallisto), file prefixes (oarfish)
or isoforms.results files (rsem). Not used for lr_kallisto.
parent_dir: Directory holding the samples (alternative to paths;
required for lr_kallisto, holding the quant-tcc output).
level: 'transcript' (default) or 'gene'.
tx2gene_path: For level='gene': TSV/CSV whose first two columns map
transcript IDs to gene IDs. Not needed for Gencode transcript
names, or for rsem, which uses its genes.results files.
divide: Divide transcript counts by their overdispersions. Default True.
group: Optional group assignment for each sample.
verbose: Print progress messages.
"""
if source not in _QUANT_READERS:
raise ValueError(f"source must be one of: {', '.join(_QUANT_READERS)}")
if level not in ("transcript", "gene"):
raise ValueError("level must be 'transcript' or 'gene'.")
tx_reader, gene_reader = _QUANT_READERS[source]
if source == "lr_kallisto":
if parent_dir is None:
raise ValueError("lr_kallisto requires parent_dir.")
kwargs = {"parent_dir": parent_dir}
else:
if paths is None and parent_dir is None:
raise ValueError("Provide paths or parent_dir.")
key = {"oarfish": "prefixes", "rsem": "files"}.get(source, "sample_dirs")
kwargs = {"parent_dir": parent_dir, key: paths}
if level == "gene":
if tx2gene_path is not None:
if source == "rsem":
raise ValueError("rsem gene-level loading uses its genes.results files; omit tx2gene_path.")
sep = "," if tx2gene_path.endswith(".csv") else "\t"
kwargs["tx2gene"] = pd.read_csv(tx2gene_path, sep=sep)
dgelist = gene_reader(divide=divide, verbose=verbose, **kwargs)
else:
dgelist = tx_reader(divide=divide, verbose=verbose, **kwargs)
if group is not None:
if len(group) != dgelist["counts"].shape[1]:
raise ValueError(f"group has {len(group)} values for {dgelist['counts'].shape[1]} samples.")
dgelist["samples"]["group"] = pd.Categorical([str(g) for g in group])
lines = _register_loaded(dgelist, source=source, data_input=paths or parent_dir)
od = dgelist.get("genes")
if od is not None and "Overdispersion" in od.columns:
vals = od["Overdispersion"].to_numpy(dtype=float)
lines.insert(1, (
f"Overdispersion: median {np.nanmedian(vals):.3g}, "
f"range {np.nanmin(vals):.3g}–{np.nanmax(vals):.3g}"
+ (" (counts divided)" if dgelist.get("divided.counts") else "")
))
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Tool 2: describe
# ---------------------------------------------------------------------------
@mcp.tool()
def describe() -> str:
"""Report the current state of the analysis pipeline."""
lines = []
d = _state["dgelist"]
if d is None:
return "No data loaded. Use load_data() first."
counts = d["counts"]
lines.append(f"Data: {counts.shape[0]:,} genes × {counts.shape[1]} samples")
lines.append(f"Samples: {', '.join(d.get('_sample_names', [str(i) for i in range(counts.shape[1])]))}")
lines.append(f"Filtered: {'yes' if _state['filtered'] else 'no'}")
lines.append(f"Normalized: {'yes' if _state['normalized'] else 'no'}")
if _state["normalized"]:
nf = d["samples"]["norm.factors"].values
lines.append(f" Norm factors: {', '.join(f'{v:.4f}' for v in nf)}")
lines.append(f"Dispersions estimated: {'yes' if _state['dispersions_estimated'] else 'no'}")
fl = _state.get("feature_level", "unknown")
note = _state.get("feature_level_note")
if note:
lines.append(f"Feature level: {fl} ({note})")
else:
lines.append(f"Feature level: {fl}")
cx = _state.get("analysis_context", "unknown")
cx_note = _state.get("analysis_context_note")
if cx_note:
lines.append(f"Context: {cx} ({cx_note})")
else:
lines.append(f"Context: {cx}")
if _state["dispersions_estimated"]:
cd = d.get("common.dispersion")
if cd is not None:
lines.append(f" Common dispersion: {cd:.4f} (BCV: {np.sqrt(cd):.4f})")
if _state["design"] is not None:
dm = _state["design"]
lines.append(f"Design: {dm.shape[1]} coefficients — {', '.join(_state['design_info'])}")
if _state["fit"] is not None:
fit = _state["fit"]
pdf = fit.get("df.prior")
if pdf is not None:
if np.isscalar(pdf):
lines.append(f"Model fitted (QL): prior df = {pdf:.2f}")
else:
lines.append(f"Model fitted (QL): median prior df = {np.median(pdf):.2f}")
if _state["voom"] is not None:
vw = _state["voom"].get("weights")
if vw is not None:
lines.append(
f"Voom weights: {vw.shape[0]:,}×{vw.shape[1]}, "
f"range {np.nanmin(vw):.3g}–{np.nanmax(vw):.3g}"
)
if _state["results"]:
lines.append(f"Test results: {', '.join(_state['results'].keys())}")
else:
lines.append("No test results yet.")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Tool 2b: reset_state
# ---------------------------------------------------------------------------
@mcp.tool()
def reset_state() -> str:
"""Reset all pipeline state."""
_state["dgelist"] = None
_state["design"] = None
_state["design_info"] = None
_state["fit"] = None
_state["glm_fit"] = None
_state["results"] = {}
_state["last_result"] = None
_state["voom"] = None
_state["filtered"] = False
_state["normalized"] = False
_state["dispersions_estimated"] = False
_state["feature_level"] = "unknown"
_state["feature_level_note"] = None
_state["analysis_context"] = "unknown"
_state["analysis_context_note"] = None
return "State cleared."
# ---------------------------------------------------------------------------
# Tool 3: filter_genes
# ---------------------------------------------------------------------------
@mcp.tool()
def filter_genes(
min_count: Optional[float] = None,
min_total_count: Optional[float] = None,
preset: Optional[str] = None,
max_n_samples: Optional[float] = None,
) -> str:
"""Filter out lowly-expressed genes using edgeR's filterByExpr logic.
Uses adaptive CPM thresholds based on library sizes and group structure.
Args:
min_count: Minimum count threshold (used to derive CPM cutoff).
Default: 10, or as set by preset.
min_total_count: Minimum total count across all samples. Default: 15,
or as set by preset.
preset: edgeR 5.0 preset thresholds: 'stringent', 'moderate' or
'lenient'. Overrides min_count and min_total_count.
max_n_samples: Cap on the number of samples a feature must be
expressed in (edgeR 5.0 default 40).
"""
_require("dgelist", "DGEList")
d = _state["dgelist"]
group = d["samples"].get("group")
keep = ep.filter_by_expr(
d, group=group, min_count=min_count, min_total_count=min_total_count,
preset=preset, max_n_samples=max_n_samples,
)
n_before = d["counts"].shape[0]
n_after = int(keep.sum())
# Apply filter
d["counts"] = d["counts"][keep]
if "genes" in d and d["genes"] is not None:
d["genes"] = d["genes"].iloc[keep.nonzero()[0]].reset_index(drop=True)
gene_ids = d.get("_gene_ids")
if gene_ids is not None:
d["_gene_ids"] = [gene_ids[i] for i in range(n_before) if keep[i]]
# Clear downstream state
_state["dispersions_estimated"] = False
_state["fit"] = None
_state["glm_fit"] = None
_state["results"] = {}
_state["last_result"] = None
_state["voom"] = None
_state["filtered"] = True
# Recompute lib sizes after filtering
d["samples"]["lib.size"] = d["counts"].sum(axis=0).astype(np.float64)
return (
f"Filtered: {n_before:,} → {n_after:,} genes "
f"({n_before - n_after:,} removed)"
)
# ---------------------------------------------------------------------------
# Tool 4: normalize
# ---------------------------------------------------------------------------
@mcp.tool()
def normalize(method: str = "TMM") -> str:
"""Apply library-size normalization.
Args:
method: Normalization method. One of 'TMM' (default), 'TMMwsp',
'RLE', 'upperquartile', or 'none'.
"""
_require("dgelist", "DGEList")
d = _state["dgelist"]
d = ep.calc_norm_factors(d, method=method)
_state["dgelist"] = d
_state["normalized"] = True
_state["voom"] = None
nf = d["samples"]["norm.factors"].values
eff = d["samples"]["lib.size"].values * nf
lines = [
f"Normalization: {method}",
"Sample | Norm Factor | Effective Lib Size",
"-------|------------|-------------------",
]
names = d.get("_sample_names", [f"S{i+1}" for i in range(len(nf))])
for i, name in enumerate(names):
lines.append(f"{name} | {nf[i]:.4f} | {int(eff[i]):,}")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Tool 4b: normalize_chip — ChIP-Seq normalization to input
# ---------------------------------------------------------------------------
@mcp.tool()
def normalize_chip(
input_csv: str,
dispersion: float = 0.01,
niter: int = 6,
loss: str = "p",
) -> str:
"""Normalize ChIP-Seq counts to input control and test for enrichment.
Reads input control counts from a CSV file and normalizes the currently
loaded ChIP response counts against them, setting offsets for downstream
GLM fitting.
Args:
input_csv: Path to a CSV/TSV file of input control counts with the
same genes (rows) and samples (columns) as the loaded data.
dispersion: Negative binomial dispersion (default 0.01).
niter: Number of iterations for scaling-factor estimation.
loss: Loss function — 'p' (cumulative probabilities) or 'z' (z-value).
"""
_require("dgelist", "DGEList")
d = _state["dgelist"]
sep = "\t" if input_csv.endswith(".tsv") else ","
inp_df = pd.read_csv(input_csv, sep=sep, index_col=0)
inp_mat = inp_df.values.astype(np.float64)
if inp_mat.shape[0] != d["counts"].shape[0]:
raise ValueError(
f"Row count mismatch: input has {inp_mat.shape[0]} rows but "
f"loaded data has {d['counts'].shape[0]} genes."
)
d = ep.calc_norm_offsets_for_chip(
inp_mat, d, dispersion=dispersion, niter=niter, loss=loss,
)
_state["dgelist"] = d
_state["voom"] = None
lines = [
f"ChIP normalization applied (dispersion={dispersion}, loss='{loss}').",
f"Offset matrix set ({d['offset'].shape[0]:,} genes × "
f"{d['offset'].shape[1]} samples).",
]
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Tool 4c: chip_enrichment_test — per-sample ChIP enrichment p-values
# ---------------------------------------------------------------------------
@mcp.tool()
def chip_enrichment_test(
input_csv: str,
sample: int = 0,
dispersion: float = 0.01,
niter: int = 6,
n_top: int = 20,
) -> str:
"""Test for ChIP-Seq enrichment relative to input for one sample.
Returns the top enriched features ranked by p-value.
Args:
input_csv: Path to input control counts (CSV/TSV).
sample: Sample index (0-based) to test.
dispersion: Negative binomial dispersion.
niter: Number of iterations.
n_top: Number of top enriched features to report.
"""
_require("dgelist", "DGEList")
d = _state["dgelist"]
sep = "\t" if input_csv.endswith(".tsv") else ","
inp_df = pd.read_csv(input_csv, sep=sep, index_col=0)
inp_mat = inp_df.values.astype(np.float64)
if sample < 0 or sample >= d["counts"].shape[1]:
raise ValueError(f"sample must be 0..{d['counts'].shape[1]-1}")
out = ep.normalize_chip_to_input(
inp_mat[:, sample], d["counts"][:, sample],
dispersion=dispersion, niter=niter,
)
gene_ids = d.get("_gene_ids")
if gene_ids is None:
gene_ids = [str(i) for i in range(d["counts"].shape[0])]
order = np.argsort(out['p_value'])
n_show = min(n_top, len(order))
names = d.get("_sample_names", [f"S{i}" for i in range(d["counts"].shape[1])])
lines = [
f"ChIP enrichment test — sample '{names[sample]}'",
f"Scaling factor: {out['scaling_factor']:.4f}",
f"Proportion enriched: {out['prop_enriched']:.4f}",
"",
f"Top {n_show} enriched features:",
"Gene | p-value | mid-p",
"-----|---------|------",
]
for i in range(n_show):
idx = order[i]
lines.append(
f"{gene_ids[idx]} | {out['p_value'][idx]:.4e} | "
f"{out['pmid_value'][idx]:.4e}"
)
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Tool 5: set_design
# ---------------------------------------------------------------------------
@mcp.tool()
def set_design(formula: str) -> str:
"""Set the experimental design using an R-style formula.
Args:
formula: R-style formula, e.g. '~ 0 + group', '~ group + batch'.
Variables must match column names in the sample metadata.
"""
_require("dgelist", "DGEList")
d = _state["dgelist"]
# Build data for patsy
samples = d.get("samples")
if samples is None:
raise ValueError("No sample metadata — load sample info with load_data().")
design = ep.model_matrix(formula, data=samples)
# Extract column names from patsy
import patsy
dinfo = patsy.dmatrix(formula, data=samples, return_type="dataframe")
col_names = list(dinfo.columns)
_state["design"] = design
_state["design_info"] = col_names
# Clear downstream
_state["fit"] = None
_state["glm_fit"] = None
_state["results"] = {}
_state["last_result"] = None
_state["voom"] = None
lines = [
f"Design matrix: {design.shape[0]} samples × {design.shape[1]} coefficients",
f"Columns: {', '.join(col_names)}",
f"Rank: {np.linalg.matrix_rank(design)}",
]
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Tool 5b: set_design_matrix
# ---------------------------------------------------------------------------
@mcp.tool()
def set_design_matrix(matrix: list, columns: list) -> str:
"""Set the design matrix directly.
Args:
matrix: 2D list of floats with shape (samples, coefficients).
columns: Column names for the design matrix.
"""
_require("dgelist", "DGEList")
d = _state["dgelist"]
counts = d["counts"]
design = np.asarray(matrix, dtype=np.float64)
if design.ndim != 2:
raise ValueError("Design matrix must be 2D.")
if design.shape[0] != counts.shape[1]:
raise ValueError(
f"Design has {design.shape[0]} rows but data has {counts.shape[1]} samples."
)
if len(columns) != design.shape[1]:
raise ValueError(
f"Design has {design.shape[1]} columns but {len(columns)} column names provided."
)
_state["design"] = design
_state["design_info"] = list(columns)
_state["fit"] = None
_state["glm_fit"] = None
_state["results"] = {}
_state["last_result"] = None
_state["voom"] = None
lines = [
f"Design matrix set: {design.shape[0]} samples × {design.shape[1]} coefficients",
f"Columns: {', '.join(columns)}",
f"Rank: {np.linalg.matrix_rank(design)}",
]
return "\n".join(lines)