-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflowRNAanalysis.py
More file actions
executable file
·323 lines (280 loc) · 11.3 KB
/
Copy pathflowRNAanalysis.py
File metadata and controls
executable file
·323 lines (280 loc) · 11.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
#!/usr/bin/env python3
import argparse
import getpass
import logging
import sys
from typing import Dict, List, Tuple
import requests
import numpy as np
import re
from flowbio import Client
# -------------------------
# CLI Usage - python3 ./flowRNAanalysis.py --pid ######### --filter sample_name 'STAU2_HepG2.*$' -n #ofbatches --start-batch 1 --end-batch 10
# -------------------------
def parse_args():
p = argparse.ArgumentParser(description="Run Flow.bio RNA-seq analysis (fetch + client-side filter by sample name)")
p.add_argument("--pid", "--PID", dest="project_id", required=True,
help="Flow.bio Project ID (string)")
p.add_argument("--filter", nargs=2, metavar=("KEY", "VALUE"), default=None,
help='Metadata filter. Supported now: --filter sample_name "<regex>"')
p.add_argument("-n", "--num-chunks", type=int, default=1,
help="Split selected samples into N executions using numpy.array_split (default: 1)")
p.add_argument("--start-batch", type=int, default=1,
help="Start execution from batch number (1-based, default: 1)")
p.add_argument("--end-batch", type=int, default=None,
help="End execution at batch number (1-based, default: all batches)")
return p.parse_args()
# -------------------------
# Logging
# -------------------------
def setup_logging():
logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)-8s | %(message)s")
# -------------------------
# CLIP pipeline settings
# -------------------------
PIPELINE_RNA = {
"prep_execution_id": "538918850957626478",
"pipeline_id": "583494301973770088",
"pipeline_version": "3.12",
}
# -------------------------
# HTTP helpers
# -------------------------
API_BASE = "https://api.flow.bio"
def login(session: requests.Session) -> str:
username = input("Enter your username: ")
password = getpass.getpass("Enter your password: ")
r = session.post(f"{API_BASE}/login", json={"username": username, "password": password}, timeout=30)
_raise_for_status(r)
data = r.json()
if "token" not in data:
raise RuntimeError("Invalid username or password (no token in response)")
return data["token"]
def _raise_for_status(resp: requests.Response):
try:
resp.raise_for_status()
except requests.HTTPError as e:
msg = f"HTTP {resp.status_code} error: {resp.text}"
raise requests.HTTPError(msg) from e
# -------------------------
# Flow.bio queries
# -------------------------
def fetch_all_project_samples(session: requests.Session, token: str, project_id: str, page_size: int = 100) -> List[Dict]:
headers = {"Authorization": f"Bearer {token}"}
page = 1
collected: List[Dict] = []
while True:
logging.debug("Fetching project samples page=%d count=%d", page, page_size)
r = session.get(
f"{API_BASE}/projects/{project_id}/samples",
params={"page": page, "count": page_size},
headers=headers,
timeout=30,
)
_raise_for_status(r)
payload = r.json()
samples = payload.get("samples", [])
if not samples:
break
collected.extend(samples)
if len(samples) < page_size:
break
page += 1
logging.info("Fetched %d samples from project %s", len(collected), project_id)
return collected
def fetch_prep_execution(session: requests.Session, token: str, prep_execution_id: str) -> Dict:
headers = {"Authorization": f"Bearer {token}"}
r = session.get(f"{API_BASE}/executions/{prep_execution_id}", headers=headers, timeout=30)
_raise_for_status(r)
return r.json()
# -------------------------
# File binding
# -------------------------
FILE_MAP = {
# Core genome references
"fasta": "Homo_sapiens.GRCh38.fasta",
"gtf": "Homo_sapiens.GRCh38.109.gtf",
# RNA-seq specific references and indices
"gene_bed": "Homo_sapiens.GRCh38.109.bed",
"transcript_fasta": "genome.transcripts.fa",
"splicesites": "Homo_sapiens.GRCh38.109.splice_sites.txt",
# Aligner / quant indices (directories)
"star_index": "star",
"rsem_index": "rsem",
"hisat2_index": "hisat2",
"salmon_index": "salmon",
}
def build_data_params_from_execution(execution: Dict, file_map: Dict[str, str]) -> Dict[str, str]:
inputs = list((execution.get("data_params") or {}).values())
all_files = inputs[:]
for proc_ex in execution.get("process_executions", []):
all_files.extend(proc_ex.get("downstream_data", []))
idx: Dict[str, Dict] = {}
for f in all_files:
fn = f.get("filename")
if fn and fn not in idx:
idx[fn] = f
missing: List[Tuple[str, str]] = []
data_params: Dict[str, str] = {}
for param_name, expected_filename in file_map.items():
match = idx.get(expected_filename)
if not match:
missing.append((param_name, expected_filename))
continue
data_params[param_name] = match["id"]
if missing:
msg = "\n".join([f" - {p}: {fn}" for p, fn in missing])
raise RuntimeError(f"Missing required reference files:\n{msg}")
return data_params
# -------------------------
# Client-side filter (sample_name glob)
# -------------------------
def filter_by_sample_name(samples: List[Dict], regex_expr: str | None) -> List[Dict]:
if not regex_expr:
return samples
try:
pattern = re.compile(regex_expr)
except re.error as e:
raise SystemExit(f"Invalid regex for sample_name: {e}")
matched = [s for s in samples if pattern.search((s.get("name") or ""))]
logging.info("Filter sample_name=%r matched %d / %d samples", regex_expr, len(matched), len(samples))
return matched
# -------------------------
# Main
# -------------------------
def main():
args = parse_args()
setup_logging()
project_id = args.project_id
# RNA pipeline settings
prep_execution_id = PIPELINE_RNA["prep_execution_id"]
pipeline_name = "RNA-Seq" # Using standard RNA-Seq pipeline name
pipeline_version = PIPELINE_RNA["pipeline_version"]
nextflow_version = "24.04.2"
# Initialize flowbio client (for submission only)
client = Client()
# REST session & auth for discovery endpoints
session = requests.Session()
token = login(session)
# Prep execution & reference files via REST
ex = fetch_prep_execution(session, token, prep_execution_id)
data_params = build_data_params_from_execution(ex, FILE_MAP)
# Fetch all samples for the project via REST
project_samples = fetch_all_project_samples(session, token, project_id, page_size=100)
# Parse --filter
name_regex = None
if args.filter:
key, value = args.filter
if key.lower() != "sample_name":
raise SystemExit("Only --filter sample_name \"<regex>\" is supported in this iteration.")
name_regex = value
selected = filter_by_sample_name(project_samples, name_regex)
# Print filtered list
print(f"\nFiltered {len(selected)} samples:")
for s in selected:
print(f" {s['id']}: {s['name']}")
if not selected:
raise SystemExit("No samples selected after applying filter.")
# Split into N execution batches
n_chunks = max(1, int(args.num_chunks))
chunks = [list(chunk) for chunk in np.array_split(np.array(selected, dtype=object), n_chunks)]
logging.info("Prepared %d execution batch(es)", len(chunks))
# Determine which batches to execute
start_batch = max(1, args.start_batch)
end_batch = args.end_batch if args.end_batch is not None else len(chunks)
end_batch = min(end_batch, len(chunks))
if start_batch > len(chunks):
raise SystemExit(f"Start batch {start_batch} exceeds total batches {len(chunks)}")
logging.info("Will execute batches %d to %d (out of %d total batches)", start_batch, end_batch, len(chunks))
# Build and submit one execution per chunk in the specified range
run_urls = []
for i, chunk in enumerate(chunks, start=1):
# Skip batches outside the specified range
if i < start_batch or i > end_batch:
logging.info("Skipping batch %d (not in range %d-%d)", i, start_batch, end_batch)
continue
# Build sample_params in the format expected by flowbio
sample_params = {}
for s in chunk:
sample_params[s["id"]] = {
"group": s.get("name", ""),
"replicate": "1",
}
# Pipeline parameters (RNA-seq specific)
params = {
# UMI
#"with_umi": "true",
"umitools_extract_method": "string",
"umitools_bc_pattern": "NNNNN",
"skip_umi_extract": "false",
"umitools_dedup_stats": "false",
"save_umi_intermeds": "false",
# Annotation/grouping
"gencode": "false",
"gtf_extra_attributes": "gene_name",
"gtf_group_features": "gene_id",
"featurecounts_group_type": "gene_biotype",
"featurecounts_feature_type": "exon",
# Align/quant
"aligner": "star_salmon",
"pseudo_aligner": "",
"bam_csi_index": "false",
"star_ignore_sjdbgtf": "false",
"stringtie_ignore_gtf": "false",
"save_unaligned": "false",
"save_align_intermeds": "false",
"skip_markduplicates": "false",
"skip_alignment": "false",
"skip_pseudo_alignment": "false",
# Trimming
"trimmer": "trimgalore",
"skip_trimming": "false",
"save_trimmed": "false",
# rRNA options
"remove_ribo_rna": "false",
"ribo_database_manifest": "./assets/rrna-db-defaults.txt",
"save_non_ribo_reads": "false",
# QC
"deseq2_vst": "true",
"skip_bigwig": "false",
"skip_stringtie": "false",
"skip_fastqc": "false",
"skip_preseq": "true",
"skip_qualimap": "false",
"skip_rseqc": "false",
"skip_biotype_qc": "false",
"skip_deseq2_qc": "false",
"skip_multiqc": "false",
"skip_qc": "false",
}
if i == 1:
proceed = input("Submit? (y/n): ").strip().lower()
if proceed != "y":
logging.info("Aborted by user.")
sys.exit(0)
try:
# Use flowbio client to run pipeline
execution = client.run_pipeline(
name=pipeline_name,
version=pipeline_version,
nextflow_version=nextflow_version,
params=params,
data_params=data_params,
sample_params={"samples": sample_params}
)
run_id = execution.get("id")
if not run_id:
raise RuntimeError(f"Submission succeeded but no run id in response: {execution}")
url = f"https://app.flow.bio/executions/{run_id}"
run_urls.append(url)
print(f"Batch {i}: {url}")
except Exception as e:
logging.error("Failed to submit batch %d: %s", i, e)
continue
logging.info("Completed submission of %d batches", len(run_urls))
if __name__ == "__main__":
try:
main()
except Exception as e:
logging.error("%s", e)
sys.exit(1)