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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
|
| 4 |
+
# CRISPR Screen Analysis Pipeline
|
| 5 |
+
# Data: Human Brunello library screen (APR-246 drug sensitivity)
|
| 6 |
+
# Samples: T0 (baseline), T8_Drug (APR-246 treated), T8_Vehicle (DMSO control)
|
| 7 |
+
#
|
| 8 |
+
# DAG Structure (depth=10, convergence=4):
|
| 9 |
+
#
|
| 10 |
+
# [T0.fq]──────────[Drug.fq]──────────[Vehicle.fq]
|
| 11 |
+
# │ │ │
|
| 12 |
+
# fastqc fastqc fastqc (Step 1: QC)
|
| 13 |
+
# │ │ │
|
| 14 |
+
# cutadapt cutadapt cutadapt (Step 2: Trim)
|
| 15 |
+
# │ │ │
|
| 16 |
+
# └──────────────────┼────────────────────┘
|
| 17 |
+
# │
|
| 18 |
+
# mageck count (Step 3: CONVERGE #1)
|
| 19 |
+
# ╱ │ ╲
|
| 20 |
+
# mageck test mageck test mageck mle (Step 4: 3-way parallel)
|
| 21 |
+
# (drug/T0) (veh/T0) (all conditions)
|
| 22 |
+
# ╲ │ ╱
|
| 23 |
+
# merge rankings (Step 5: CONVERGE #2)
|
| 24 |
+
# ╱ ╲
|
| 25 |
+
# drug-specific count QC metrics (Step 6: parallel)
|
| 26 |
+
# hit analysis + gini index
|
| 27 |
+
# ╲ ╱
|
| 28 |
+
# pathway enrichment (Step 7: CONVERGE #3)
|
| 29 |
+
# │
|
| 30 |
+
# hit classification (Step 8)
|
| 31 |
+
# │
|
| 32 |
+
# final report (Step 9: CONVERGE #4 w/ multiqc)
|
| 33 |
+
# │
|
| 34 |
+
# report.csv (Step 10)
|
| 35 |
+
|
| 36 |
+
THREADS=$(( $(nproc) > 8 ? 8 : $(nproc) ))
|
| 37 |
+
WORKDIR="$(cd "$(dirname "$0")" && pwd)"
|
| 38 |
+
cd "$WORKDIR"
|
| 39 |
+
|
| 40 |
+
DATA="${WORKDIR}/data"
|
| 41 |
+
REF="${WORKDIR}/reference"
|
| 42 |
+
OUT="${WORKDIR}/outputs"
|
| 43 |
+
RESULTS="${WORKDIR}/results"
|
| 44 |
+
|
| 45 |
+
mkdir -p "${OUT}/fastqc_raw" "${OUT}/fastqc_trimmed" "${OUT}/trimmed"
|
| 46 |
+
mkdir -p "${OUT}/count" "${OUT}/rra_drug" "${OUT}/rra_vehicle" "${OUT}/mle"
|
| 47 |
+
mkdir -p "${OUT}/comparison" "${OUT}/multiqc" "${RESULTS}"
|
| 48 |
+
|
| 49 |
+
LIBRARY="${REF}/library.tsv"
|
| 50 |
+
|
| 51 |
+
# Vector backbone containing the sgRNA cassette
|
| 52 |
+
# Reads have: [variable prefix]ACCG[20bp sgRNA]GTTT[scaffold]
|
| 53 |
+
# 5' trim sequence for cutadapt (linked adapter)
|
| 54 |
+
VECTOR_5="CTTGTGGAAAGGACGAAACACCG"
|
| 55 |
+
SCAFFOLD_3="GTTTTAGAGCTAGAAATAGCAAGTT"
|
| 56 |
+
|
| 57 |
+
# ============================================================================
|
| 58 |
+
# Step 1: FastQC on raw reads (parallel per sample)
|
| 59 |
+
# ============================================================================
|
| 60 |
+
echo "[Step 1] Running FastQC on raw reads..."
|
| 61 |
+
for fq in "${DATA}"/T*.fastq.gz; do
|
| 62 |
+
BASENAME=$(basename "$fq" .fastq.gz)
|
| 63 |
+
if [ ! -f "${OUT}/fastqc_raw/${BASENAME}_fastqc.html" ]; then
|
| 64 |
+
fastqc -t "${THREADS}" -o "${OUT}/fastqc_raw" "$fq" &
|
| 65 |
+
fi
|
| 66 |
+
done
|
| 67 |
+
wait
|
| 68 |
+
echo "[Step 1] FastQC raw done."
|
| 69 |
+
|
| 70 |
+
# ============================================================================
|
| 71 |
+
# Step 2: Cutadapt — extract sgRNA from vector context (parallel per sample)
|
| 72 |
+
# Uses linked adapter: trims 5' vector then 3' scaffold, keeping just the sgRNA
|
| 73 |
+
# ============================================================================
|
| 74 |
+
echo "[Step 2] Extracting sgRNA sequences with cutadapt..."
|
| 75 |
+
for fq in "${DATA}"/T*.fastq.gz; do
|
| 76 |
+
BASENAME=$(basename "$fq" .fastq.gz)
|
| 77 |
+
TRIMMED="${OUT}/trimmed/${BASENAME}_trimmed.fastq.gz"
|
| 78 |
+
if [ ! -f "$TRIMMED" ]; then
|
| 79 |
+
cutadapt \
|
| 80 |
+
-g "${VECTOR_5}...${SCAFFOLD_3}" \
|
| 81 |
+
-e 0.15 \
|
| 82 |
+
--discard-untrimmed \
|
| 83 |
+
--minimum-length 18 \
|
| 84 |
+
--maximum-length 24 \
|
| 85 |
+
-o "$TRIMMED" \
|
| 86 |
+
"$fq" \
|
| 87 |
+
> "${OUT}/trimmed/${BASENAME}_cutadapt.log" 2>&1 &
|
| 88 |
+
fi
|
| 89 |
+
done
|
| 90 |
+
wait
|
| 91 |
+
echo "[Step 2] Trimming done."
|
| 92 |
+
|
| 93 |
+
# ============================================================================
|
| 94 |
+
# Step 2b: FastQC on trimmed reads
|
| 95 |
+
# ============================================================================
|
| 96 |
+
echo "[Step 2b] Running FastQC on trimmed reads..."
|
| 97 |
+
for fq in "${OUT}/trimmed"/*_trimmed.fastq.gz; do
|
| 98 |
+
BASENAME=$(basename "$fq" .fastq.gz)
|
| 99 |
+
if [ ! -f "${OUT}/fastqc_trimmed/${BASENAME}_fastqc.html" ]; then
|
| 100 |
+
fastqc -t "${THREADS}" -o "${OUT}/fastqc_trimmed" "$fq" &
|
| 101 |
+
fi
|
| 102 |
+
done
|
| 103 |
+
wait
|
| 104 |
+
echo "[Step 2b] FastQC trimmed done."
|
| 105 |
+
|
| 106 |
+
# ============================================================================
|
| 107 |
+
# Step 3: MAGeCK count — CONVERGE all 3 samples (CONVERGENCE #1)
|
| 108 |
+
# ============================================================================
|
| 109 |
+
echo "[Step 3] Running MAGeCK count (convergence #1: all samples)..."
|
| 110 |
+
if [ ! -f "${OUT}/count/screen.count.txt" ]; then
|
| 111 |
+
mageck count \
|
| 112 |
+
-l "$LIBRARY" \
|
| 113 |
+
-n "${OUT}/count/screen" \
|
| 114 |
+
--sample-label "T0,Drug,Vehicle" \
|
| 115 |
+
--fastq \
|
| 116 |
+
"${OUT}/trimmed/T0_control_trimmed.fastq.gz" \
|
| 117 |
+
"${OUT}/trimmed/T8_drug_trimmed.fastq.gz" \
|
| 118 |
+
"${OUT}/trimmed/T8_vehicle_trimmed.fastq.gz" \
|
| 119 |
+
--norm-method median \
|
| 120 |
+
2>&1 | tee "${OUT}/count/mageck_count.log"
|
| 121 |
+
fi
|
| 122 |
+
echo "[Step 3] MAGeCK count done."
|
| 123 |
+
|
| 124 |
+
# ============================================================================
|
| 125 |
+
# Step 4a: MAGeCK test (RRA) — Drug vs T0
|
| 126 |
+
# ============================================================================
|
| 127 |
+
echo "[Step 4a] Running MAGeCK test (RRA): Drug vs T0..."
|
| 128 |
+
if [ ! -f "${OUT}/rra_drug/drug_vs_t0.gene_summary.txt" ]; then
|
| 129 |
+
mageck test \
|
| 130 |
+
-k "${OUT}/count/screen.count.txt" \
|
| 131 |
+
-t Drug \
|
| 132 |
+
-c T0 \
|
| 133 |
+
-n "${OUT}/rra_drug/drug_vs_t0" \
|
| 134 |
+
--gene-lfc-method alphamedian \
|
| 135 |
+
2>&1 | tee "${OUT}/rra_drug/mageck_test_drug.log"
|
| 136 |
+
fi
|
| 137 |
+
|
| 138 |
+
# ============================================================================
|
| 139 |
+
# Step 4b: MAGeCK test (RRA) — Vehicle vs T0
|
| 140 |
+
# ============================================================================
|
| 141 |
+
echo "[Step 4b] Running MAGeCK test (RRA): Vehicle vs T0..."
|
| 142 |
+
if [ ! -f "${OUT}/rra_vehicle/vehicle_vs_t0.gene_summary.txt" ]; then
|
| 143 |
+
mageck test \
|
| 144 |
+
-k "${OUT}/count/screen.count.txt" \
|
| 145 |
+
-t Vehicle \
|
| 146 |
+
-c T0 \
|
| 147 |
+
-n "${OUT}/rra_vehicle/vehicle_vs_t0" \
|
| 148 |
+
--gene-lfc-method alphamedian \
|
| 149 |
+
2>&1 | tee "${OUT}/rra_vehicle/mageck_test_vehicle.log"
|
| 150 |
+
fi
|
| 151 |
+
|
| 152 |
+
# ============================================================================
|
| 153 |
+
# Step 4c: MAGeCK MLE — multi-condition modeling
|
| 154 |
+
# ============================================================================
|
| 155 |
+
echo "[Step 4c] Running MAGeCK MLE..."
|
| 156 |
+
# Create design matrix for MLE
|
| 157 |
+
DESIGN="${OUT}/mle/design_matrix.txt"
|
| 158 |
+
if [ ! -f "$DESIGN" ]; then
|
| 159 |
+
cat > "$DESIGN" << 'DESIGN_EOF'
|
| 160 |
+
Samples baseline drug vehicle
|
| 161 |
+
T0 1 0 0
|
| 162 |
+
Drug 1 1 0
|
| 163 |
+
Vehicle 1 0 1
|
| 164 |
+
DESIGN_EOF
|
| 165 |
+
fi
|
| 166 |
+
|
| 167 |
+
if [ ! -f "${OUT}/mle/screen_mle.gene_summary.txt" ]; then
|
| 168 |
+
mageck mle \
|
| 169 |
+
-k "${OUT}/count/screen.count.txt" \
|
| 170 |
+
-d "$DESIGN" \
|
| 171 |
+
-n "${OUT}/mle/screen_mle" \
|
| 172 |
+
2>&1 | tee "${OUT}/mle/mageck_mle.log"
|
| 173 |
+
fi
|
| 174 |
+
echo "[Step 4] All three analysis methods done."
|
| 175 |
+
|
| 176 |
+
# ============================================================================
|
| 177 |
+
# Step 5: Merge rankings — CONVERGENCE #2 (multi-method)
|
| 178 |
+
# ============================================================================
|
| 179 |
+
echo "[Step 5] Merging rankings from RRA and MLE (convergence #2)..."
|
| 180 |
+
python3 << 'MERGE_PY'
|
| 181 |
+
import csv
|
| 182 |
+
import os
|
| 183 |
+
|
| 184 |
+
OUT = os.environ.get("OUT", "outputs")
|
| 185 |
+
|
| 186 |
+
# Load RRA drug results
|
| 187 |
+
rra_drug_genes = {}
|
| 188 |
+
with open(f"{OUT}/rra_drug/drug_vs_t0.gene_summary.txt") as f:
|
| 189 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 190 |
+
for row in reader:
|
| 191 |
+
rra_drug_genes[row['id']] = {
|
| 192 |
+
'neg_rank': int(row['neg|rank']),
|
| 193 |
+
'neg_fdr': float(row['neg|fdr']),
|
| 194 |
+
'neg_lfc': float(row['neg|lfc']),
|
| 195 |
+
'pos_rank': int(row['pos|rank']),
|
| 196 |
+
'pos_fdr': float(row['pos|fdr']),
|
| 197 |
+
'pos_lfc': float(row['pos|lfc']),
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
# Load RRA vehicle results
|
| 201 |
+
rra_veh_genes = {}
|
| 202 |
+
with open(f"{OUT}/rra_vehicle/vehicle_vs_t0.gene_summary.txt") as f:
|
| 203 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 204 |
+
for row in reader:
|
| 205 |
+
rra_veh_genes[row['id']] = {
|
| 206 |
+
'neg_rank': int(row['neg|rank']),
|
| 207 |
+
'neg_fdr': float(row['neg|fdr']),
|
| 208 |
+
'neg_lfc': float(row['neg|lfc']),
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
# Load MLE results
|
| 212 |
+
mle_genes = {}
|
| 213 |
+
mle_file = f"{OUT}/mle/screen_mle.gene_summary.txt"
|
| 214 |
+
if os.path.exists(mle_file):
|
| 215 |
+
with open(mle_file) as f:
|
| 216 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 217 |
+
for row in reader:
|
| 218 |
+
gene = row['Gene']
|
| 219 |
+
# MLE has drug|beta, drug|fdr columns
|
| 220 |
+
try:
|
| 221 |
+
mle_genes[gene] = {
|
| 222 |
+
'drug_beta': float(row.get('drug|beta', 0)),
|
| 223 |
+
'drug_fdr': float(row.get('drug|fdr', 1)),
|
| 224 |
+
}
|
| 225 |
+
except (ValueError, KeyError):
|
| 226 |
+
pass
|
| 227 |
+
|
| 228 |
+
# Merge: identify concordant hits
|
| 229 |
+
concordance = {}
|
| 230 |
+
for gene in rra_drug_genes:
|
| 231 |
+
rra_neg_fdr = rra_drug_genes[gene]['neg_fdr']
|
| 232 |
+
rra_neg_rank = rra_drug_genes[gene]['neg_rank']
|
| 233 |
+
mle_fdr = mle_genes.get(gene, {}).get('drug_fdr', 1.0)
|
| 234 |
+
mle_beta = mle_genes.get(gene, {}).get('drug_beta', 0.0)
|
| 235 |
+
veh_neg_fdr = rra_veh_genes.get(gene, {}).get('neg_fdr', 1.0)
|
| 236 |
+
concordance[gene] = {
|
| 237 |
+
'rra_neg_rank': rra_neg_rank,
|
| 238 |
+
'rra_neg_fdr': rra_neg_fdr,
|
| 239 |
+
'rra_neg_lfc': rra_drug_genes[gene]['neg_lfc'],
|
| 240 |
+
'mle_beta': mle_beta,
|
| 241 |
+
'mle_fdr': mle_fdr,
|
| 242 |
+
'veh_neg_fdr': veh_neg_fdr,
|
| 243 |
+
'drug_specific': rra_neg_fdr < 0.25 and veh_neg_fdr >= 0.25,
|
| 244 |
+
'concordant': rra_neg_fdr < 0.25 and mle_fdr < 0.25,
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
# Write merged results
|
| 248 |
+
os.makedirs(f"{OUT}/comparison", exist_ok=True)
|
| 249 |
+
with open(f"{OUT}/comparison/merged_rankings.tsv", 'w') as f:
|
| 250 |
+
f.write("gene\trra_neg_rank\trra_neg_fdr\trra_neg_lfc\tmle_beta\tmle_fdr\tveh_neg_fdr\tdrug_specific\tconcordant\n")
|
| 251 |
+
for gene, data in sorted(concordance.items(), key=lambda x: x[1]['rra_neg_rank']):
|
| 252 |
+
f.write(f"{gene}\t{data['rra_neg_rank']}\t{data['rra_neg_fdr']:.6f}\t{data['rra_neg_lfc']:.4f}\t"
|
| 253 |
+
f"{data['mle_beta']:.4f}\t{data['mle_fdr']:.6f}\t{data['veh_neg_fdr']:.6f}\t"
|
| 254 |
+
f"{data['drug_specific']}\t{data['concordant']}\n")
|
| 255 |
+
|
| 256 |
+
print(f"Merged {len(concordance)} genes")
|
| 257 |
+
drug_specific = sum(1 for g in concordance.values() if g['drug_specific'])
|
| 258 |
+
concordant = sum(1 for g in concordance.values() if g['concordant'])
|
| 259 |
+
print(f"Drug-specific: {drug_specific}, Concordant (RRA+MLE): {concordant}")
|
| 260 |
+
MERGE_PY
|
| 261 |
+
echo "[Step 5] Ranking merge done."
|
| 262 |
+
|
| 263 |
+
# ============================================================================
|
| 264 |
+
# Step 6a: Drug-specific hit analysis (parallel)
|
| 265 |
+
# ============================================================================
|
| 266 |
+
echo "[Step 6a] Identifying drug-specific hits..."
|
| 267 |
+
python3 << 'DRUG_SPEC_PY'
|
| 268 |
+
import csv
|
| 269 |
+
import os
|
| 270 |
+
|
| 271 |
+
OUT = os.environ.get("OUT", "outputs")
|
| 272 |
+
|
| 273 |
+
# Read merged rankings
|
| 274 |
+
drug_specific_genes = []
|
| 275 |
+
with open(f"{OUT}/comparison/merged_rankings.tsv") as f:
|
| 276 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 277 |
+
for row in reader:
|
| 278 |
+
if row['drug_specific'] == 'True':
|
| 279 |
+
drug_specific_genes.append({
|
| 280 |
+
'gene': row['gene'],
|
| 281 |
+
'rra_neg_fdr': float(row['rra_neg_fdr']),
|
| 282 |
+
'rra_neg_lfc': float(row['rra_neg_lfc']),
|
| 283 |
+
'veh_neg_fdr': float(row['veh_neg_fdr']),
|
| 284 |
+
})
|
| 285 |
+
|
| 286 |
+
drug_specific_genes.sort(key=lambda x: x['rra_neg_fdr'])
|
| 287 |
+
|
| 288 |
+
with open(f"{OUT}/comparison/drug_specific_hits.tsv", 'w') as f:
|
| 289 |
+
f.write("gene\trra_neg_fdr\trra_neg_lfc\tveh_neg_fdr\n")
|
| 290 |
+
for g in drug_specific_genes:
|
| 291 |
+
f.write(f"{g['gene']}\t{g['rra_neg_fdr']:.6f}\t{g['rra_neg_lfc']:.4f}\t{g['veh_neg_fdr']:.6f}\n")
|
| 292 |
+
|
| 293 |
+
print(f"Drug-specific hits: {len(drug_specific_genes)}")
|
| 294 |
+
DRUG_SPEC_PY
|
| 295 |
+
|
| 296 |
+
# ============================================================================
|
| 297 |
+
# Step 6b: Count QC metrics and Gini index (parallel)
|
| 298 |
+
# ============================================================================
|
| 299 |
+
echo "[Step 6b] Computing count QC metrics..."
|
| 300 |
+
python3 << 'QC_PY'
|
| 301 |
+
import csv
|
| 302 |
+
import math
|
| 303 |
+
import os
|
| 304 |
+
|
| 305 |
+
OUT = os.environ.get("OUT", "outputs")
|
| 306 |
+
|
| 307 |
+
# Read count table
|
| 308 |
+
counts = {"T0": [], "Drug": [], "Vehicle": []}
|
| 309 |
+
total_sgrnas = 0
|
| 310 |
+
with open(f"{OUT}/count/screen.count.txt") as f:
|
| 311 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 312 |
+
for row in reader:
|
| 313 |
+
total_sgrnas += 1
|
| 314 |
+
counts["T0"].append(int(row["T0"]))
|
| 315 |
+
counts["Drug"].append(int(row["Drug"]))
|
| 316 |
+
counts["Vehicle"].append(int(row["Vehicle"]))
|
| 317 |
+
|
| 318 |
+
def gini(values):
|
| 319 |
+
"""Compute Gini index of a distribution."""
|
| 320 |
+
sorted_vals = sorted(values)
|
| 321 |
+
n = len(sorted_vals)
|
| 322 |
+
if n == 0 or sum(sorted_vals) == 0:
|
| 323 |
+
return 0.0
|
| 324 |
+
cumsum = 0
|
| 325 |
+
total = sum(sorted_vals)
|
| 326 |
+
gini_sum = 0
|
| 327 |
+
for i, v in enumerate(sorted_vals):
|
| 328 |
+
cumsum += v
|
| 329 |
+
gini_sum += (2 * (i + 1) - n - 1) * v
|
| 330 |
+
return gini_sum / (n * total)
|
| 331 |
+
|
| 332 |
+
qc = {}
|
| 333 |
+
for sample in ["T0", "Drug", "Vehicle"]:
|
| 334 |
+
vals = counts[sample]
|
| 335 |
+
qc[f"total_counts_{sample.lower()}"] = sum(vals)
|
| 336 |
+
qc[f"zero_count_sgrnas_{sample.lower()}"] = sum(1 for v in vals if v == 0)
|
| 337 |
+
qc[f"gini_index_{sample.lower()}"] = round(gini(vals), 4)
|
| 338 |
+
qc[f"median_count_{sample.lower()}"] = sorted(vals)[len(vals) // 2]
|
| 339 |
+
|
| 340 |
+
qc["total_sgrnas"] = total_sgrnas
|
| 341 |
+
|
| 342 |
+
with open(f"{OUT}/comparison/count_qc.tsv", 'w') as f:
|
| 343 |
+
for k, v in qc.items():
|
| 344 |
+
f.write(f"{k}\t{v}\n")
|
| 345 |
+
print(f" {k}: {v}")
|
| 346 |
+
|
| 347 |
+
print(f"QC metrics computed for {total_sgrnas} sgRNAs")
|
| 348 |
+
QC_PY
|
| 349 |
+
|
| 350 |
+
# ============================================================================
|
| 351 |
+
# Step 7: Pathway enrichment — CONVERGENCE #3 (drug-specific + QC)
|
| 352 |
+
# ============================================================================
|
| 353 |
+
echo "[Step 7] Running pathway enrichment (convergence #3)..."
|
| 354 |
+
python3 << 'PATHWAY_PY'
|
| 355 |
+
import csv
|
| 356 |
+
import os
|
| 357 |
+
from collections import defaultdict
|
| 358 |
+
|
| 359 |
+
OUT = os.environ.get("OUT", "outputs")
|
| 360 |
+
|
| 361 |
+
# Load gene rankings
|
| 362 |
+
gene_ranks = {}
|
| 363 |
+
with open(f"{OUT}/comparison/merged_rankings.tsv") as f:
|
| 364 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 365 |
+
for row in reader:
|
| 366 |
+
gene_ranks[row['gene']] = {
|
| 367 |
+
'rank': int(row['rra_neg_rank']),
|
| 368 |
+
'fdr': float(row['rra_neg_fdr']),
|
| 369 |
+
'lfc': float(row['rra_neg_lfc']),
|
| 370 |
+
}
|
| 371 |
+
|
| 372 |
+
# Simple enrichment: categorize genes by essentiality based on screen results
|
| 373 |
+
categories = {
|
| 374 |
+
'essential_drug': [], # Depleted in drug (FDR < 0.25)
|
| 375 |
+
'essential_common': [], # Depleted in both drug and vehicle
|
| 376 |
+
'enriched_drug': [], # Enriched in drug
|
| 377 |
+
'neutral': [],
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
with open(f"{OUT}/comparison/merged_rankings.tsv") as f:
|
| 381 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 382 |
+
for row in reader:
|
| 383 |
+
gene = row['gene']
|
| 384 |
+
drug_fdr = float(row['rra_neg_fdr'])
|
| 385 |
+
veh_fdr = float(row['veh_neg_fdr'])
|
| 386 |
+
|
| 387 |
+
if drug_fdr < 0.25 and veh_fdr < 0.25:
|
| 388 |
+
categories['essential_common'].append(gene)
|
| 389 |
+
elif drug_fdr < 0.25:
|
| 390 |
+
categories['essential_drug'].append(gene)
|
| 391 |
+
else:
|
| 392 |
+
categories['neutral'].append(gene)
|
| 393 |
+
|
| 394 |
+
# Write pathway/category summary
|
| 395 |
+
with open(f"{OUT}/comparison/gene_categories.tsv", 'w') as f:
|
| 396 |
+
f.write("category\tcount\ttop_genes\n")
|
| 397 |
+
for cat, genes in categories.items():
|
| 398 |
+
top = ','.join(genes[:5]) if genes else 'none'
|
| 399 |
+
f.write(f"{cat}\t{len(genes)}\t{top}\n")
|
| 400 |
+
print(f" {cat}: {len(genes)} genes")
|
| 401 |
+
|
| 402 |
+
print("Gene categorization done.")
|
| 403 |
+
PATHWAY_PY
|
| 404 |
+
|
| 405 |
+
# ============================================================================
|
| 406 |
+
# Step 8: Hit classification with multi-method consensus
|
| 407 |
+
# ============================================================================
|
| 408 |
+
echo "[Step 8] Classifying hits with multi-method consensus..."
|
| 409 |
+
python3 << 'CLASSIFY_PY'
|
| 410 |
+
import csv
|
| 411 |
+
import os
|
| 412 |
+
|
| 413 |
+
OUT = os.environ.get("OUT", "outputs")
|
| 414 |
+
|
| 415 |
+
# Read merged rankings
|
| 416 |
+
hits = []
|
| 417 |
+
with open(f"{OUT}/comparison/merged_rankings.tsv") as f:
|
| 418 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 419 |
+
for row in reader:
|
| 420 |
+
gene = row['gene']
|
| 421 |
+
rra_fdr = float(row['rra_neg_fdr'])
|
| 422 |
+
mle_fdr = float(row['mle_fdr'])
|
| 423 |
+
rra_lfc = float(row['rra_neg_lfc'])
|
| 424 |
+
veh_fdr = float(row['veh_neg_fdr'])
|
| 425 |
+
|
| 426 |
+
# Classification tiers
|
| 427 |
+
if rra_fdr < 0.05 and mle_fdr < 0.05:
|
| 428 |
+
tier = "high_confidence"
|
| 429 |
+
elif rra_fdr < 0.25 or mle_fdr < 0.25:
|
| 430 |
+
tier = "moderate_confidence"
|
| 431 |
+
else:
|
| 432 |
+
tier = "not_significant"
|
| 433 |
+
|
| 434 |
+
hits.append({
|
| 435 |
+
'gene': gene,
|
| 436 |
+
'rra_fdr': rra_fdr,
|
| 437 |
+
'mle_fdr': mle_fdr,
|
| 438 |
+
'rra_lfc': rra_lfc,
|
| 439 |
+
'tier': tier,
|
| 440 |
+
'drug_specific': rra_fdr < 0.25 and veh_fdr >= 0.25,
|
| 441 |
+
})
|
| 442 |
+
|
| 443 |
+
# Sort by tier then RRA FDR
|
| 444 |
+
tier_order = {'high_confidence': 0, 'moderate_confidence': 1, 'not_significant': 2}
|
| 445 |
+
hits.sort(key=lambda x: (tier_order[x['tier']], x['rra_fdr']))
|
| 446 |
+
|
| 447 |
+
with open(f"{OUT}/comparison/classified_hits.tsv", 'w') as f:
|
| 448 |
+
f.write("gene\ttier\trra_neg_fdr\tmle_fdr\trra_neg_lfc\tdrug_specific\n")
|
| 449 |
+
for h in hits:
|
| 450 |
+
f.write(f"{h['gene']}\t{h['tier']}\t{h['rra_fdr']:.6f}\t{h['mle_fdr']:.6f}\t"
|
| 451 |
+
f"{h['rra_lfc']:.4f}\t{h['drug_specific']}\n")
|
| 452 |
+
|
| 453 |
+
high = sum(1 for h in hits if h['tier'] == 'high_confidence')
|
| 454 |
+
moderate = sum(1 for h in hits if h['tier'] == 'moderate_confidence')
|
| 455 |
+
drug_spec = sum(1 for h in hits if h['drug_specific'])
|
| 456 |
+
print(f"High confidence: {high}, Moderate: {moderate}, Drug-specific: {drug_spec}")
|
| 457 |
+
CLASSIFY_PY
|
| 458 |
+
|
| 459 |
+
# ============================================================================
|
| 460 |
+
# Step 9: MultiQC report — CONVERGENCE #4 (QC + analysis)
|
| 461 |
+
# ============================================================================
|
| 462 |
+
echo "[Step 9] Running MultiQC (convergence #4)..."
|
| 463 |
+
if [ ! -f "${OUT}/multiqc/multiqc_report.html" ]; then
|
| 464 |
+
multiqc \
|
| 465 |
+
"${OUT}/fastqc_raw" "${OUT}/fastqc_trimmed" "${OUT}/trimmed" \
|
| 466 |
+
-o "${OUT}/multiqc" \
|
| 467 |
+
--force \
|
| 468 |
+
2>&1 | tail -3
|
| 469 |
+
fi
|
| 470 |
+
|
| 471 |
+
# ============================================================================
|
| 472 |
+
# Step 10: Generate final report.csv
|
| 473 |
+
# ============================================================================
|
| 474 |
+
echo "[Step 10] Generating final report..."
|
| 475 |
+
python3 << 'REPORT_PY'
|
| 476 |
+
import csv
|
| 477 |
+
import os
|
| 478 |
+
|
| 479 |
+
OUT = os.environ.get("OUT", "outputs")
|
| 480 |
+
RESULTS = os.environ.get("RESULTS", "results")
|
| 481 |
+
|
| 482 |
+
report = []
|
| 483 |
+
|
| 484 |
+
# --- Count QC metrics ---
|
| 485 |
+
with open(f"{OUT}/comparison/count_qc.tsv") as f:
|
| 486 |
+
for line in f:
|
| 487 |
+
parts = line.strip().split('\t')
|
| 488 |
+
if len(parts) == 2:
|
| 489 |
+
report.append((parts[0], parts[1]))
|
| 490 |
+
|
| 491 |
+
# --- Read mageck count log for mapping stats ---
|
| 492 |
+
count_log = f"{OUT}/count/screen.count_normalized.txt"
|
| 493 |
+
if os.path.exists(f"{OUT}/count/screen.countsummary.txt"):
|
| 494 |
+
with open(f"{OUT}/count/screen.countsummary.txt") as f:
|
| 495 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 496 |
+
for row in reader:
|
| 497 |
+
label = row.get('Label', '')
|
| 498 |
+
reads = row.get('Reads', '0')
|
| 499 |
+
mapped = row.get('Mapped', '0')
|
| 500 |
+
pct = row.get('Percentage', '0')
|
| 501 |
+
report.append((f"mapped_reads_{label.lower()}", mapped))
|
| 502 |
+
report.append((f"mapping_pct_{label.lower()}", pct))
|
| 503 |
+
|
| 504 |
+
# --- RRA Drug results ---
|
| 505 |
+
with open(f"{OUT}/rra_drug/drug_vs_t0.gene_summary.txt") as f:
|
| 506 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 507 |
+
genes = list(reader)
|
| 508 |
+
|
| 509 |
+
# Top depleted gene (negative selection)
|
| 510 |
+
genes_neg = sorted(genes, key=lambda x: float(x['neg|rank']))
|
| 511 |
+
if genes_neg:
|
| 512 |
+
report.append(("top_depleted_gene_rra", genes_neg[0]['id']))
|
| 513 |
+
report.append(("top_depleted_fdr_rra", genes_neg[0]['neg|fdr']))
|
| 514 |
+
report.append(("top_depleted_lfc_rra", genes_neg[0]['neg|lfc']))
|
| 515 |
+
|
| 516 |
+
# Top enriched gene (positive selection)
|
| 517 |
+
genes_pos = sorted(genes, key=lambda x: float(x['pos|rank']))
|
| 518 |
+
if genes_pos:
|
| 519 |
+
report.append(("top_enriched_gene_rra", genes_pos[0]['id']))
|
| 520 |
+
report.append(("top_enriched_fdr_rra", genes_pos[0]['pos|fdr']))
|
| 521 |
+
|
| 522 |
+
# Count significant genes
|
| 523 |
+
num_dep = sum(1 for g in genes if float(g['neg|fdr']) < 0.25)
|
| 524 |
+
num_enr = sum(1 for g in genes if float(g['pos|fdr']) < 0.25)
|
| 525 |
+
report.append(("num_depleted_genes_fdr25_rra", str(num_dep)))
|
| 526 |
+
report.append(("num_enriched_genes_fdr25_rra", str(num_enr)))
|
| 527 |
+
|
| 528 |
+
# --- MLE results ---
|
| 529 |
+
mle_file = f"{OUT}/mle/screen_mle.gene_summary.txt"
|
| 530 |
+
if os.path.exists(mle_file):
|
| 531 |
+
with open(mle_file) as f:
|
| 532 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 533 |
+
mle_genes = list(reader)
|
| 534 |
+
if mle_genes:
|
| 535 |
+
# Sort by drug|fdr
|
| 536 |
+
try:
|
| 537 |
+
mle_sorted = sorted(mle_genes, key=lambda x: float(x.get('drug|fdr', 1)))
|
| 538 |
+
report.append(("top_gene_mle", mle_sorted[0].get('Gene', 'NA')))
|
| 539 |
+
report.append(("top_gene_mle_fdr", mle_sorted[0].get('drug|fdr', 'NA')))
|
| 540 |
+
report.append(("top_gene_mle_beta", mle_sorted[0].get('drug|beta', 'NA')))
|
| 541 |
+
num_mle_sig = sum(1 for g in mle_genes if float(g.get('drug|fdr', 1)) < 0.25)
|
| 542 |
+
report.append(("num_significant_mle_fdr25", str(num_mle_sig)))
|
| 543 |
+
except (ValueError, KeyError):
|
| 544 |
+
pass
|
| 545 |
+
|
| 546 |
+
# --- Vehicle results ---
|
| 547 |
+
with open(f"{OUT}/rra_vehicle/vehicle_vs_t0.gene_summary.txt") as f:
|
| 548 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 549 |
+
veh_genes = list(reader)
|
| 550 |
+
num_veh_dep = sum(1 for g in veh_genes if float(g['neg|fdr']) < 0.25)
|
| 551 |
+
report.append(("num_depleted_genes_vehicle_fdr25", str(num_veh_dep)))
|
| 552 |
+
|
| 553 |
+
# --- Concordance ---
|
| 554 |
+
with open(f"{OUT}/comparison/classified_hits.tsv") as f:
|
| 555 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 556 |
+
classified = list(reader)
|
| 557 |
+
high_conf = sum(1 for h in classified if h['tier'] == 'high_confidence')
|
| 558 |
+
moderate_conf = sum(1 for h in classified if h['tier'] == 'moderate_confidence')
|
| 559 |
+
drug_specific = sum(1 for h in classified if h['drug_specific'] == 'True')
|
| 560 |
+
report.append(("high_confidence_hits", str(high_conf)))
|
| 561 |
+
report.append(("moderate_confidence_hits", str(moderate_conf)))
|
| 562 |
+
report.append(("drug_specific_depleted_genes", str(drug_specific)))
|
| 563 |
+
|
| 564 |
+
# --- Drug-specific top gene ---
|
| 565 |
+
with open(f"{OUT}/comparison/drug_specific_hits.tsv") as f:
|
| 566 |
+
reader = csv.DictReader(f, delimiter='\t')
|
| 567 |
+
drug_hits = list(reader)
|
| 568 |
+
if drug_hits:
|
| 569 |
+
report.append(("top_drug_specific_gene", drug_hits[0]['gene']))
|
| 570 |
+
report.append(("top_drug_specific_fdr", drug_hits[0]['rra_neg_fdr']))
|
| 571 |
+
|
| 572 |
+
# Write final report
|
| 573 |
+
with open(f"{RESULTS}/report.csv", 'w') as f:
|
| 574 |
+
f.write("metric,value\n")
|
| 575 |
+
for m, v in report:
|
| 576 |
+
f.write(f"{m},{v}\n")
|
| 577 |
+
|
| 578 |
+
print(f"Report written with {len(report)} metrics")
|
| 579 |
+
for m, v in report:
|
| 580 |
+
print(f" {m}: {v}")
|
| 581 |
+
REPORT_PY
|
| 582 |
+
|
| 583 |
+
echo ""
|
| 584 |
+
echo "========================================="
|
| 585 |
+
echo " CRISPR Screen Analysis Complete!"
|
| 586 |
+
echo "========================================="
|
| 587 |
+
echo ""
|
| 588 |
+
cat "${RESULTS}/report.csv"
|