-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path03_data_profiler.py
More file actions
415 lines (338 loc) · 15 KB
/
03_data_profiler.py
File metadata and controls
415 lines (338 loc) · 15 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
#!/usr/bin/env python3
"""
RAPTOR v2.2.0 Example Script: Data Profiler (Module 3)
UPDATED WITH VALIDATION
Demonstrates comprehensive data profiling for ML-based pipeline recommendation.
Extracts 32 statistical features from RNA-seq count matrices.
This is Module 3 of the RAPTOR workflow (Stage 1: Fast Profiling):
M1: Quantify (FASTQ → quick_gene_counts.csv)
M2: Sample QC (Quality Assessment & Outlier Detection)
M3: Profile (Data Profiling - 32 features) ← THIS SCRIPT
M4: Recommend (Pipeline Recommendation)
Input: results/quick_counts/quick_gene_counts.csv (or results/qc/counts_clean.csv)
Output: results/profile.json
Author: Ayeh Bolouki
Email: ayehbolouki1988@gmail.com
License: MIT
"""
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path
# =============================================================================
# CONSTANTS - Architecture Compliant (v2.2.0)
# =============================================================================
DEFAULT_INPUT_COUNTS = "results/quick_counts/quick_gene_counts.csv"
DEFAULT_CLEAN_COUNTS = "results/qc/counts_clean.csv"
DEFAULT_OUTPUT_DIR = "results"
# Check for dependencies
try:
import numpy as np
import pandas as pd
except ImportError:
print("ERROR: numpy and pandas are required")
print("Install with: pip install numpy pandas")
sys.exit(1)
# RAPTOR imports with validation - UPDATED FOR v2.2.0
RAPTOR_AVAILABLE = True
try:
from raptor import (
RNAseqDataProfiler,
DataProfile,
profile_data_quick,
validate_count_matrix,
validate_file_path,
validate_directory_path,
ValidationError
)
except ImportError:
RAPTOR_AVAILABLE = False
print("NOTE: RAPTOR not installed. Running in demo mode only.")
print("Install RAPTOR with: pip install -e .")
# Create dummy classes for demo mode
class RNAseqDataProfiler:
def __init__(self, counts, metadata=None, group_column=None): pass
def run_full_profile(self): return None
class DataProfile:
pass
def profile_data_quick(counts): return {}
def validate_count_matrix(df, **kwargs): pass
def validate_file_path(p, **kwargs): return Path(p)
def validate_directory_path(p, **kwargs): return Path(p)
class ValidationError(ValueError): pass
def print_banner():
"""Print RAPTOR banner."""
print("""
╔══════════════════════════════════════════════════════════════╗
║ 🦖 RAPTOR v2.2.0 - Data Profiler (Module 3) ║
║ ║
║ Extracts 32 Features for ML Pipeline Recommendation ║
║ ✅ WITH INPUT VALIDATION ║
╚══════════════════════════════════════════════════════════════╝
""")
def display_profile_summary(profile):
"""Display profile summary."""
print("\n📊 Data Profile Summary:")
print(" " + "="*70)
if profile is None:
print(" Demo mode - profile would contain 32 features")
print(" " + "="*70)
return
# Helper: works for both DataProfile objects and dicts
def get(key, default='N/A'):
if isinstance(profile, dict):
return profile.get(key, default)
return getattr(profile, key, default)
# Basic Statistics
print(f" Basic Statistics:")
print(f" • n_samples: {get('n_samples')}")
print(f" • n_genes: {get('n_genes', 0):,}")
print(f" • n_groups: {get('n_groups')}")
print(f" • design: {get('design_complexity')}")
print(f" • library_size_mean: {get('library_size_mean', 0):,.0f}")
print(f" • library_size_cv: {get('library_size_cv', 0):.2%}")
print(f" • depth_category: {get('sequencing_depth_category')}")
print(f"\n Gene Detection:")
print(f" • detection_rate: {get('detection_rate', 0):.2%}")
print(f" • reliably_expressed: {get('n_reliably_expressed', 0):,}")
print(f" • highly_expressed: {get('n_highly_expressed', 0):,}")
print(f"\n Expression Distribution (log2):")
print(f" • mean: {get('expression_mean', 0):.2f}")
print(f" • variance: {get('expression_variance', 0):.2f}")
print(f" • skewness: {get('expression_skewness', 0):.2f}")
print(f"\n Dispersion (Critical for Pipeline Selection):")
print(f" • BCV: {get('bcv', 0):.3f} ({get('bcv_category')})")
print(f" • common_dispersion: {get('common_dispersion', 0):.4f}")
print(f" • overdispersion: {get('overdispersion_ratio', 0):.2f} ({get('overdispersion_category')})")
print(f"\n Sparsity:")
print(f" • zero_proportion: {get('zero_proportion', 0):.2%}")
print(f" • sparsity_category: {get('sparsity_category')}")
print(f" • zero_inflated: {get('is_zero_inflated')}")
print(f"\n Quality Indicators:")
print(f" • quality_score: {get('quality_score', 0):.0f}/100")
print(f" • outliers: {get('has_outliers')}")
print(f" • batch_effect: {get('has_batch_effect')}")
print(" " + "="*70)
def run_profiling(counts_file, metadata_file=None, group_column='condition',
output_dir=None, demo=False):
"""
Run data profiling with validation.
NEW: Added comprehensive input validation.
"""
# Validate and load count matrix
try:
print("\n🔍 Validating inputs...")
# Validate count file exists
counts_path = validate_file_path(counts_file, must_exist=True)
print(f" ✓ Count file found: {counts_path}")
# Load counts
counts_df = pd.read_csv(counts_path, index_col=0)
print(f" ✓ Count matrix loaded: {counts_df.shape[0]} genes × {counts_df.shape[1]} samples")
# Validate count matrix structure
validate_count_matrix(counts_df, min_genes=10, min_samples=2)
print(f" ✓ Count matrix validated")
except FileNotFoundError:
print(f"❌ Count file not found: {counts_file}")
print(f" Current directory: {Path.cwd()}")
print(f" Try one of these:")
print(f" - {DEFAULT_INPUT_COUNTS}")
print(f" - {DEFAULT_CLEAN_COUNTS}")
sys.exit(1)
except ValidationError as e:
print(f"❌ Count matrix validation failed: {e}")
sys.exit(1)
except Exception as e:
print(f"❌ Error loading count matrix: {e}")
sys.exit(1)
# Validate and load metadata (optional)
metadata_df = None
if metadata_file:
try:
from raptor import validate_metadata
metadata_path = validate_file_path(metadata_file, must_exist=True)
print(f" ✓ Metadata file found: {metadata_path}")
metadata_df = pd.read_csv(metadata_path)
print(f" ✓ Metadata loaded: {len(metadata_df)} samples")
validate_metadata(metadata_df, counts_df)
print(f" ✓ Metadata validated")
except Exception as e:
print(f"⚠️ Warning: Metadata issue: {e}")
print(f" Continuing without metadata")
metadata_df = None
# Validate output directory
try:
output_path = validate_directory_path(
output_dir or DEFAULT_OUTPUT_DIR,
create_if_missing=True
)
print(f" ✓ Output directory: {output_path}")
except Exception as e:
print(f"❌ Error with output directory: {e}")
sys.exit(1)
# Run profiling
print("\n📊 Running data profiling...")
print(f" Extracting 32 statistical features...")
if not RAPTOR_AVAILABLE or demo:
print(" (Demo mode - showing simulated profile)")
# Enhanced demo profile with all critical fields for Module 4
lib_sizes = counts_df.sum(axis=0)
lib_mean = lib_sizes.mean()
lib_std = lib_sizes.std()
zero_count = (counts_df == 0).sum().sum()
total_values = counts_df.shape[0] * counts_df.shape[1]
profile = type('Profile', (), {
# SAMPLE CHARACTERISTICS (Module 4 needs these!)
'n_samples': counts_df.shape[1],
'n_genes': counts_df.shape[0],
'n_groups': 2,
'min_group_size': max(3, counts_df.shape[1] // 2), # At least 3 per group
'max_group_size': counts_df.shape[1] // 2,
'has_replicates': True,
'has_sufficient_replicates': True,
'design_complexity': 'simple',
# LIBRARY SIZE METRICS
'library_size_mean': float(lib_mean),
'library_size_median': float(lib_sizes.median()),
'library_size_cv': float(lib_std / lib_mean) if lib_mean > 0 else 0.12,
'library_size_range': float(lib_sizes.max() / lib_sizes.min()) if lib_sizes.min() > 0 else 2.5,
'library_size_category': 'moderate',
# EXPRESSION CHARACTERISTICS
'zero_fraction': float(zero_count / total_values),
'sparsity': 0.15,
'low_count_proportion': 0.25, # Affects edgeR score in Module 4
'detection_rate': 0.85,
'expression_mean': 8.5,
'expression_median': 6.2,
# DISPERSION (CRITICAL FOR MODULE 4!)
'bcv': 0.32, # Biological Coefficient of Variation
'bcv_category': 'moderate', # low/moderate/high
'common_dispersion': 0.1024, # bcv^2
'dispersion_mean': 0.15,
'overdispersion_ratio': 1.8,
# QUALITY INDICATORS (Module 4 uses these!)
'has_outliers': False, # Affects edgeR_robust recommendation
'has_batch_effect': False, # Affects DESeq2/limma scoring
'outlier_severity': 'none',
# OTHER METRICS
'total_variance': 125.4,
'n_expressed_genes': int(counts_df.shape[0] * 0.85),
'n_highly_expressed': 856,
'sequencing_depth_category': 'standard'
})()
display_profile_summary(profile)
# Demo results with enhanced structure
results = {
'timestamp': datetime.now().isoformat(),
'raptor_version': '2.2.0',
'module': 'M3',
'mode': 'demo',
'features': {
# Sample characteristics
'n_samples': counts_df.shape[1],
'n_genes': counts_df.shape[0],
'n_groups': 2,
'min_group_size': max(3, counts_df.shape[1] // 2),
# Library metrics
'library_size_mean': float(lib_mean),
'library_size_cv': float(lib_std / lib_mean) if lib_mean > 0 else 0.12,
# Expression
'zero_fraction': float(zero_count / total_values),
'sparsity': 0.15,
'low_count_proportion': 0.25,
# Dispersion (CRITICAL!)
'bcv': 0.32,
'bcv_category': 'moderate',
'common_dispersion': 0.1024,
# Quality
'has_outliers': False,
'has_batch_effect': False,
'design_complexity': 'simple'
}
}
else:
# Real profiling with RAPTOR
profiler = RNAseqDataProfiler(counts_df, metadata_df, group_column)
profile = profiler.run_full_profile()
display_profile_summary(profile)
# Real results
results = profile.to_dict() if hasattr(profile, 'to_dict') else {}
results['timestamp'] = datetime.now().isoformat()
results['raptor_version'] = '2.2.0'
results['module'] = 'M3'
# Save profile
profile_file = output_path / 'profile.json'
with open(profile_file, 'w') as f:
json.dump(results, f, indent=2, default=str)
print(f"\n ✓ Profile saved: {profile_file}")
return results, output_path
def main():
parser = argparse.ArgumentParser(
description='🦖 RAPTOR v2.2.0 Data Profiler (Module 3) - WITH VALIDATION',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Demo mode (uses default data)
python 03_data_profiler.py --demo
# With quick counts
python 03_data_profiler.py \
--counts results/quick_counts/quick_gene_counts.csv
# With clean counts from QC
python 03_data_profiler.py \
--counts results/qc/counts_clean.csv
# With metadata
python 03_data_profiler.py \
--counts results/qc/counts_clean.csv \
--metadata results/quick_counts/sample_info.csv
CLI Equivalent:
raptor profile --counts results/qc/counts_clean.csv
Workflow:
Module 1: raptor quick-count → quick_gene_counts.csv
Module 2: raptor qc → counts_clean.csv
Module 3: THIS SCRIPT → profile.json
Module 4: python 04_recommender.py --profile results/profile.json
Output:
results/profile.json (32 statistical features)
"""
)
parser.add_argument('--counts', '-c',
default=DEFAULT_CLEAN_COUNTS,
help='Count matrix CSV file')
parser.add_argument('--metadata', '-m',
help='Sample metadata CSV file (optional)')
parser.add_argument('--group-column', '-g',
default='condition',
help='Column name for grouping (default: condition)')
parser.add_argument('--output', '-o',
default=DEFAULT_OUTPUT_DIR,
help=f'Output directory (default: {DEFAULT_OUTPUT_DIR})')
parser.add_argument('--demo', action='store_true',
help='Run in demo mode')
args = parser.parse_args()
print_banner()
# Run profiling
results, output_dir = run_profiling(
counts_file=args.counts,
metadata_file=args.metadata,
group_column=args.group_column,
output_dir=args.output,
demo=args.demo
)
# Final summary
print("\n" + "="*70)
print(" ✅ MODULE 3 (DATA PROFILING) COMPLETE!")
print("="*70)
print(f"\n 📂 Output Directory: {output_dir}")
print(f"\n 📊 Output Files:")
print(f" • profile.json - 32 statistical features")
print(f"\n 🔜 Next Steps:")
print(f"\n Module 4 - Pipeline Recommendation:")
print(f" python 04_recommender.py --profile {output_dir}/profile.json")
print(f" ")
print(f" Or use the CLI:")
print(f" raptor recommend --profile {output_dir}/profile.json")
print("\n" + "="*70)
print(" Making free science for everybody around the world 🌍")
print("="*70 + "\n")
if __name__ == '__main__':
main()