jkh commited on
Commit
6219a11
·
verified ·
1 Parent(s): afaea93

Upload data_processing.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. data_processing.py +742 -0
data_processing.py ADDED
@@ -0,0 +1,742 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Phase 3: Data Processing for Aging Fly Cell Atlas (AFCA)
4
+ ========================================================
5
+
6
+ Processes the H5AD files into HuggingFace-compatible parquet files:
7
+ - Expression matrix (sparse -> dense conversion with chunking)
8
+ - Sample metadata (cell-level information)
9
+ - Feature metadata (gene information)
10
+ - Dimensionality reduction projections (PCA, UMAP, t-SNE)
11
+ - Unstructured metadata (all additional data)
12
+
13
+ Processing Strategy:
14
+ - Process head and body datasets separately to avoid OOM
15
+ - Use chunking for large expression matrices
16
+ - Optimize data types for efficiency
17
+ - Apply pandas index bug fixes
18
+ - Save intermediate results to avoid data loss
19
+ - CLI interface for selective processing
20
+
21
+ Requirements:
22
+ - Memory-efficient processing for 566K × 16K matrices
23
+ - Sparse matrix handling for efficiency
24
+ - Proper data type optimization
25
+ """
26
+
27
+ import logging
28
+ import json
29
+ import time
30
+ from pathlib import Path
31
+ from typing import Dict, Any, Optional, List, Set
32
+ import shutil
33
+ import gc
34
+ import os
35
+ import psutil
36
+
37
+ import numpy as np
38
+ import pandas as pd
39
+ import scanpy as sc
40
+ from scipy import sparse
41
+ import pyarrow.parquet as pq
42
+ import typer
43
+ from typing_extensions import Annotated
44
+ import warnings
45
+
46
+ # Configure scanpy
47
+ sc.settings.verbosity = 3
48
+ sc.settings.set_figure_params(dpi=80, facecolor='white')
49
+
50
+ # Setup logging
51
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
52
+ logger = logging.getLogger(__name__)
53
+
54
+ app = typer.Typer(help="Process Aging Fly Cell Atlas data into HuggingFace format")
55
+
56
+ def get_memory_usage() -> float:
57
+ """Get current memory usage in GB"""
58
+ return psutil.virtual_memory().used / (1024**3)
59
+
60
+ def log_memory_status(stage: str) -> None:
61
+ """Log current memory status"""
62
+ memory_gb = get_memory_usage()
63
+ available_gb = psutil.virtual_memory().available / (1024**3)
64
+ logger.info(f"{stage} - Memory: {memory_gb:.1f}GB used, {available_gb:.1f}GB available")
65
+
66
+ def make_json_serializable(obj: Any) -> Any:
67
+ """Convert numpy arrays and other non-serializable objects for JSON"""
68
+ if isinstance(obj, np.ndarray):
69
+ return obj.tolist()
70
+ elif isinstance(obj, dict):
71
+ return {k: make_json_serializable(v) for k, v in obj.items()}
72
+ elif isinstance(obj, (list, tuple)):
73
+ return [make_json_serializable(i) for i in obj]
74
+ elif isinstance(obj, (np.integer, np.floating)):
75
+ return obj.item()
76
+ else:
77
+ return obj
78
+
79
+ def log_memory_usage(stage: str, adata: sc.AnnData) -> None:
80
+ """Log memory usage and dataset info"""
81
+ memory_mb = adata.X.data.nbytes / 1024**2 if sparse.issparse(adata.X) else adata.X.nbytes / 1024**2
82
+ logger.info(f"{stage}: Shape {adata.shape}, Memory: {memory_mb:.1f}MB")
83
+
84
+ def save_stage_result(output_dir: Path, tissue: str, stage: str, result: Dict[str, Any]) -> None:
85
+ """Save intermediate results for each stage"""
86
+ result_file = output_dir / f"{tissue}_{stage}_result.json"
87
+ with open(result_file, 'w') as f:
88
+ json.dump(result, f, indent=2)
89
+ logger.info(f"💾 Saved {stage} result for {tissue}")
90
+
91
+ def load_stage_result(output_dir: Path, tissue: str, stage: str) -> Optional[Dict[str, Any]]:
92
+ """Load existing stage result if available"""
93
+ result_file = output_dir / f"{tissue}_{stage}_result.json"
94
+ if result_file.exists():
95
+ with open(result_file, 'r') as f:
96
+ result = json.load(f)
97
+ logger.info(f"📖 Loaded existing {stage} result for {tissue}")
98
+ return result
99
+ return None
100
+
101
+ def get_completed_stages(output_dir: Path, tissue: str) -> Set[str]:
102
+ """Get list of completed stages for a tissue"""
103
+ stages = {'expression', 'sample_metadata', 'feature_metadata', 'projections', 'unstructured'}
104
+ completed = set()
105
+
106
+ for stage in stages:
107
+ if load_stage_result(output_dir, tissue, stage) is not None:
108
+ completed.add(stage)
109
+
110
+ if completed:
111
+ logger.info(f"🔄 Found completed stages for {tissue}: {', '.join(sorted(completed))}")
112
+
113
+ return completed
114
+
115
+ def fix_pandas_index_column_bug(parquet_file: Path) -> bool:
116
+ """
117
+ Fix the pandas __index_level_0__ bug in parquet files
118
+
119
+ This is a known bug in pandas/PyArrow where pandas saves the index as an extra
120
+ '__index_level_0__' column when writing to parquet format.
121
+ This is a known upstream issue with no planned fix
122
+
123
+ References:
124
+ - https://github.com/pandas-dev/pandas/issues/51664
125
+ - https://github.com/pola-rs/polars/issues/7291
126
+
127
+ Args:
128
+ parquet_file: Path to the parquet file to fix
129
+
130
+ Returns:
131
+ bool: True if fix was applied successfully, False otherwise
132
+ """
133
+ logger.info(f"🔧 Checking for pandas __index_level_0__ bug in {parquet_file.name}")
134
+
135
+ try:
136
+ # Check if the bug exists
137
+ pf = pq.ParquetFile(parquet_file)
138
+ schema_names = pf.schema_arrow.names
139
+
140
+ if '__index_level_0__' not in schema_names:
141
+ logger.info("✅ No __index_level_0__ column found - file is clean")
142
+ return True
143
+
144
+ logger.warning(f"🐛 Found pandas __index_level_0__ bug - fixing...")
145
+ logger.info(f" Current columns: {len(schema_names)} (expected: {len(schema_names)-1})")
146
+
147
+ # Create backup
148
+ backup_file = parquet_file.with_suffix('.backup.parquet')
149
+ if not backup_file.exists():
150
+ shutil.copy2(parquet_file, backup_file)
151
+ logger.info(f"📦 Backup created: {backup_file.name}")
152
+
153
+ # Apply fix using PyArrow
154
+ table = pq.read_table(parquet_file)
155
+
156
+ # Filter out the problematic column
157
+ columns_to_keep = [name for name in table.column_names if name != '__index_level_0__']
158
+ clean_table = table.select(columns_to_keep)
159
+
160
+ # Write clean table to temporary file first
161
+ temp_file = parquet_file.with_suffix('.temp.parquet')
162
+ pq.write_table(clean_table, temp_file, compression='snappy')
163
+
164
+ # Verify the fix
165
+ temp_pf = pq.ParquetFile(temp_file)
166
+ temp_schema_names = temp_pf.schema_arrow.names
167
+
168
+ if '__index_level_0__' not in temp_schema_names:
169
+ # Replace original with fixed version
170
+ shutil.move(temp_file, parquet_file)
171
+ logger.info(f"✅ Fixed pandas __index_level_0__ bug")
172
+ logger.info(f" Column count: {len(schema_names)} → {len(temp_schema_names)}")
173
+ return True
174
+ else:
175
+ # Fix failed, clean up
176
+ temp_file.unlink()
177
+ logger.error("❌ Fix verification failed")
178
+ return False
179
+
180
+ except Exception as e:
181
+ logger.error(f"❌ Error fixing pandas index bug: {e}")
182
+ return False
183
+
184
+ def process_expression_matrix(adata: sc.AnnData, tissue: str, output_dir: Path,
185
+ aggressive_chunking: bool = False) -> Dict[str, Any]:
186
+ """
187
+ Process and save expression matrix with chunking to avoid OOM
188
+
189
+ Strategy:
190
+ - Check sparsity and memory requirements
191
+ - Use aggressive chunking for body dataset
192
+ - Convert to float32 for efficiency
193
+ - More frequent garbage collection
194
+ """
195
+ logger.info(f"Starting expression matrix processing for {tissue}...")
196
+ log_memory_usage(f"Expression matrix ({tissue})", adata)
197
+ log_memory_status("Before expression processing")
198
+
199
+ # Calculate memory requirements for dense conversion
200
+ dense_memory_gb = (adata.n_obs * adata.n_vars * 4) / (1024**3) # float32 = 4 bytes
201
+ sparsity = 1.0 - (adata.X.nnz / (adata.n_obs * adata.n_vars))
202
+
203
+ logger.info(f"Dense conversion would require: {dense_memory_gb:.2f}GB")
204
+ logger.info(f"Current sparsity: {sparsity:.2%}")
205
+
206
+ output_file = output_dir / f"aging_fly_{tissue}_expression.parquet"
207
+
208
+ # Determine chunk size based on tissue and available memory
209
+ available_memory_gb = psutil.virtual_memory().available / (1024**3)
210
+
211
+ if tissue == 'body' or aggressive_chunking:
212
+ # More aggressive chunking for body dataset
213
+ chunk_size = min(2000, max(500, int(available_memory_gb * 100))) # Scale with available memory
214
+ logger.warning(f"🚨 Using aggressive chunking for {tissue} (chunk_size={chunk_size})")
215
+ else:
216
+ chunk_size = 5000
217
+
218
+ logger.info(f"Processing expression matrix in chunks (size: {chunk_size})...")
219
+ chunks = []
220
+
221
+ for i in range(0, adata.n_obs, chunk_size):
222
+ end_idx = min(i + chunk_size, adata.n_obs)
223
+ chunk = adata[i:end_idx, :].copy()
224
+
225
+ if sparse.issparse(chunk.X):
226
+ chunk_dense = chunk.X.toarray().astype(np.float32)
227
+ else:
228
+ chunk_dense = chunk.X.astype(np.float32)
229
+
230
+ chunk_df = pd.DataFrame(
231
+ chunk_dense,
232
+ index=chunk.obs_names,
233
+ columns=chunk.var_names
234
+ )
235
+ chunks.append(chunk_df)
236
+
237
+ chunk_num = i//chunk_size + 1
238
+ total_chunks = (adata.n_obs-1)//chunk_size + 1
239
+ logger.info(f"Processed chunk {chunk_num}/{total_chunks}")
240
+
241
+ # More aggressive cleanup for body dataset
242
+ del chunk, chunk_dense
243
+ if tissue == 'body' or aggressive_chunking:
244
+ gc.collect() # Force GC every chunk
245
+
246
+ # Memory check for body dataset
247
+ if tissue == 'body':
248
+ current_memory_gb = get_memory_usage()
249
+ if current_memory_gb > 24: # Warning at 24GB
250
+ logger.warning(f"⚠️ High memory usage: {current_memory_gb:.1f}GB")
251
+ # Force garbage collection
252
+ gc.collect()
253
+
254
+ # Combine chunks
255
+ logger.info("Combining chunks...")
256
+ log_memory_status("Before combining chunks")
257
+
258
+ expression_df = pd.concat(chunks, axis=0)
259
+ del chunks # Free memory immediately
260
+ gc.collect()
261
+
262
+ log_memory_status("After combining chunks")
263
+
264
+ # Save with compression
265
+ logger.info(f"Saving expression matrix: {expression_df.shape}")
266
+ expression_df.to_parquet(output_file, compression='snappy')
267
+
268
+ # Apply pandas __index_level_0__ bug fix
269
+ fix_success = fix_pandas_index_column_bug(output_file)
270
+
271
+ stats = {
272
+ 'file': str(output_file),
273
+ 'shape': list(expression_df.shape),
274
+ 'memory_gb': dense_memory_gb,
275
+ 'sparsity_percent': sparsity * 100,
276
+ 'dtype': str(expression_df.dtypes.iloc[0]),
277
+ 'pandas_index_bug_fixed': fix_success,
278
+ 'chunk_size_used': chunk_size,
279
+ 'aggressive_chunking': aggressive_chunking
280
+ }
281
+
282
+ logger.info(f"✅ Expression matrix saved: {expression_df.shape}")
283
+ del expression_df
284
+ gc.collect()
285
+ log_memory_status("After expression processing")
286
+ return stats
287
+
288
+ def process_sample_metadata(adata: sc.AnnData, tissue: str, output_dir: Path) -> Dict[str, Any]:
289
+ """Process and save sample (cell) metadata"""
290
+ logger.info(f"Processing sample metadata for {tissue}...")
291
+
292
+ sample_metadata = adata.obs.copy()
293
+
294
+ # Verify critical columns exist
295
+ critical_cols = ['age', 'sex', 'afca_annotation', 'afca_annotation_broad']
296
+ missing_cols = [col for col in critical_cols if col not in sample_metadata.columns]
297
+
298
+ if missing_cols:
299
+ logger.warning(f"Missing critical columns: {missing_cols}")
300
+ else:
301
+ logger.info("✅ All critical metadata columns present")
302
+
303
+ # Add tissue column
304
+ sample_metadata['tissue'] = tissue
305
+
306
+ # Add standardized age column if needed
307
+ if 'age_numeric' not in sample_metadata.columns and 'age' in sample_metadata.columns:
308
+ # Convert age to numeric
309
+ sample_metadata['age_numeric'] = pd.to_numeric(sample_metadata['age'], errors='coerce')
310
+ logger.info("Added numeric age column")
311
+
312
+ # Optimize data types
313
+ for col in sample_metadata.columns:
314
+ if sample_metadata[col].dtype == 'object':
315
+ # Convert categorical strings to category type for efficiency
316
+ if sample_metadata[col].nunique() < len(sample_metadata) * 0.5:
317
+ sample_metadata[col] = sample_metadata[col].astype('category')
318
+
319
+ output_file = output_dir / f"aging_fly_{tissue}_sample_metadata.parquet"
320
+ sample_metadata.to_parquet(output_file, compression='snappy')
321
+
322
+ stats = {
323
+ 'file': str(output_file),
324
+ 'shape': list(sample_metadata.shape),
325
+ 'columns': list(sample_metadata.columns),
326
+ 'missing_columns': missing_cols,
327
+ 'age_groups': sample_metadata['age'].value_counts().to_dict() if 'age' in sample_metadata.columns else {},
328
+ 'cell_types': sample_metadata['afca_annotation'].value_counts().head(10).to_dict() if 'afca_annotation' in sample_metadata.columns else {},
329
+ 'sex_distribution': sample_metadata['sex'].value_counts().to_dict() if 'sex' in sample_metadata.columns else {}
330
+ }
331
+
332
+ logger.info(f"✅ Sample metadata saved: {sample_metadata.shape}")
333
+ return stats
334
+
335
+ def process_feature_metadata(adata: sc.AnnData, tissue: str, output_dir: Path) -> Dict[str, Any]:
336
+ """Process and save feature (gene) metadata"""
337
+ logger.info(f"Processing feature metadata for {tissue}...")
338
+
339
+ feature_metadata = adata.var.copy()
340
+
341
+ # Ensure gene IDs are present
342
+ if 'gene_ids' not in feature_metadata.columns:
343
+ feature_metadata['gene_ids'] = feature_metadata.index
344
+ logger.info("Added gene_ids column from index")
345
+
346
+ # Check for gene symbols and other annotations
347
+ symbol_cols = [col for col in feature_metadata.columns if 'symbol' in col.lower()]
348
+ if symbol_cols:
349
+ logger.info(f"Gene symbol columns found: {symbol_cols}")
350
+
351
+ output_file = output_dir / f"aging_fly_{tissue}_feature_metadata.parquet"
352
+ feature_metadata.to_parquet(output_file, compression='snappy')
353
+
354
+ stats = {
355
+ 'file': str(output_file),
356
+ 'shape': list(feature_metadata.shape),
357
+ 'columns': list(feature_metadata.columns),
358
+ 'has_symbols': len(symbol_cols) > 0,
359
+ 'symbol_columns': symbol_cols
360
+ }
361
+
362
+ logger.info(f"✅ Feature metadata saved: {feature_metadata.shape}")
363
+ return stats
364
+
365
+ def process_projections(adata: sc.AnnData, tissue: str, output_dir: Path) -> Dict[str, Any]:
366
+ """Process and save all dimensionality reduction projections"""
367
+ logger.info(f"Processing dimensionality reduction projections for {tissue}...")
368
+
369
+ projection_stats = {}
370
+ available_projections = list(adata.obsm.keys())
371
+ logger.info(f"Available projections: {available_projections}")
372
+
373
+ for proj_name in available_projections:
374
+ if proj_name.startswith('X_'):
375
+ proj_data = adata.obsm[proj_name]
376
+
377
+ # Convert to DataFrame
378
+ proj_df = pd.DataFrame(
379
+ proj_data,
380
+ index=adata.obs_names,
381
+ columns=[f"{proj_name.split('_')[1].upper()}{i+1}" for i in range(proj_data.shape[1])]
382
+ )
383
+
384
+ # Save projection
385
+ output_file = output_dir / f"aging_fly_{tissue}_projection_{proj_name}.parquet"
386
+ proj_df.to_parquet(output_file, compression='snappy')
387
+
388
+ projection_stats[proj_name] = {
389
+ 'file': str(output_file),
390
+ 'shape': list(proj_df.shape),
391
+ 'dimensions': proj_data.shape[1]
392
+ }
393
+
394
+ logger.info(f"✅ Saved {proj_name}: {proj_df.shape}")
395
+ else:
396
+ logger.info(f"Skipping non-projection: {proj_name}")
397
+
398
+ return projection_stats
399
+
400
+ def process_unstructured_metadata(adata: sc.AnnData, tissue: str, output_dir: Path) -> Dict[str, Any]:
401
+ """Process and save unstructured metadata (uns)"""
402
+ logger.info(f"Processing unstructured metadata for {tissue}...")
403
+
404
+ try:
405
+ # Make data JSON serializable
406
+ unstructured_data = make_json_serializable(adata.uns)
407
+
408
+ output_file = output_dir / f"aging_fly_{tissue}_unstructured_metadata.json"
409
+
410
+ with open(output_file, 'w') as f:
411
+ json.dump(unstructured_data, f, indent=2)
412
+
413
+ # Count keys and estimate size
414
+ key_count = len(unstructured_data) if isinstance(unstructured_data, dict) else 0
415
+ file_size_mb = output_file.stat().st_size / (1024**2)
416
+
417
+ stats = {
418
+ 'file': str(output_file),
419
+ 'key_count': key_count,
420
+ 'file_size_mb': round(file_size_mb, 2),
421
+ 'top_keys': list(unstructured_data.keys())[:10] if isinstance(unstructured_data, dict) else []
422
+ }
423
+
424
+ logger.info(f"✅ Unstructured metadata saved: {key_count} keys, {file_size_mb:.1f}MB")
425
+ return stats
426
+
427
+ except Exception as e:
428
+ logger.error(f"Failed to process unstructured metadata: {e}")
429
+ return {'error': str(e)}
430
+
431
+ def process_single_dataset(data_file: Path, tissue: str, output_dir: Path,
432
+ skip_stages: Set[str] = None, aggressive_chunking: bool = False) -> Dict[str, Any]:
433
+ """Process a single H5AD dataset (head or body) with stage resumption"""
434
+ logger.info(f"\n🧬 Processing {tissue.upper()} dataset: {data_file}")
435
+
436
+ if skip_stages is None:
437
+ skip_stages = set()
438
+
439
+ # Check for existing results
440
+ completed_stages = get_completed_stages(output_dir, tissue)
441
+ stages_to_skip = skip_stages.union(completed_stages)
442
+
443
+ if stages_to_skip:
444
+ logger.info(f"⏭️ Skipping stages: {', '.join(sorted(stages_to_skip))}")
445
+
446
+ # Processing results tracking
447
+ processing_results = {
448
+ 'dataset_info': {
449
+ 'tissue': tissue,
450
+ 'file': str(data_file),
451
+ 'processing_time': None,
452
+ 'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
453
+ 'aggressive_chunking': aggressive_chunking
454
+ }
455
+ }
456
+
457
+ # Load existing results
458
+ for stage in ['expression', 'sample_metadata', 'feature_metadata', 'projections', 'unstructured']:
459
+ if stage in completed_stages:
460
+ existing_result = load_stage_result(output_dir, tissue, stage)
461
+ if existing_result:
462
+ processing_results[stage] = existing_result
463
+
464
+ # Load data only if we need to process something
465
+ stages_needed = {'expression', 'sample_metadata', 'feature_metadata', 'projections', 'unstructured'} - stages_to_skip
466
+
467
+ if not stages_needed:
468
+ logger.info(f"✅ All stages already completed for {tissue}")
469
+ return processing_results
470
+
471
+ logger.info(f"Loading {tissue} data from {data_file}...")
472
+ log_memory_status("Before loading data")
473
+
474
+ try:
475
+ adata = sc.read_h5ad(data_file)
476
+ logger.info(f"✅ {tissue.capitalize()} data loaded: {adata.shape}")
477
+ processing_results['dataset_info']['shape'] = list(adata.shape)
478
+ log_memory_usage(f"Initial ({tissue})", adata)
479
+ log_memory_status("After loading data")
480
+ except Exception as e:
481
+ logger.error(f"Failed to load {tissue} data: {e}")
482
+ return {'error': str(e)}
483
+
484
+ start_time = time.time()
485
+
486
+ try:
487
+ # Task 3.1: Expression Matrix
488
+ if 'expression' not in stages_to_skip:
489
+ logger.info(f"\n🧬 Task 3.1: Processing {tissue} Expression Matrix")
490
+ result = process_expression_matrix(adata, tissue, output_dir, aggressive_chunking)
491
+ processing_results['expression'] = result
492
+ save_stage_result(output_dir, tissue, 'expression', result)
493
+
494
+ # Task 3.2: Sample Metadata
495
+ if 'sample_metadata' not in stages_to_skip:
496
+ logger.info(f"\n📊 Task 3.2: Processing {tissue} Sample Metadata")
497
+ result = process_sample_metadata(adata, tissue, output_dir)
498
+ processing_results['sample_metadata'] = result
499
+ save_stage_result(output_dir, tissue, 'sample_metadata', result)
500
+
501
+ # Task 3.3: Feature Metadata
502
+ if 'feature_metadata' not in stages_to_skip:
503
+ logger.info(f"\n🧪 Task 3.3: Processing {tissue} Feature Metadata")
504
+ result = process_feature_metadata(adata, tissue, output_dir)
505
+ processing_results['feature_metadata'] = result
506
+ save_stage_result(output_dir, tissue, 'feature_metadata', result)
507
+
508
+ # Task 3.4: Dimensionality Reductions
509
+ if 'projections' not in stages_to_skip:
510
+ logger.info(f"\n📈 Task 3.4: Processing {tissue} Projections")
511
+ result = process_projections(adata, tissue, output_dir)
512
+ processing_results['projections'] = result
513
+ save_stage_result(output_dir, tissue, 'projections', result)
514
+
515
+ # Task 3.5: Unstructured Metadata
516
+ if 'unstructured' not in stages_to_skip:
517
+ logger.info(f"\n📋 Task 3.5: Processing {tissue} Unstructured Metadata")
518
+ result = process_unstructured_metadata(adata, tissue, output_dir)
519
+ processing_results['unstructured'] = result
520
+ save_stage_result(output_dir, tissue, 'unstructured', result)
521
+
522
+ # Calculate processing time
523
+ processing_time = time.time() - start_time
524
+ processing_results['dataset_info']['processing_time'] = f"{processing_time:.1f}s"
525
+
526
+ logger.info(f"\n✅ {tissue.capitalize()} Processing Complete!")
527
+ logger.info(f"⏱️ Processing time: {processing_time:.1f}s")
528
+
529
+ # Save overall result
530
+ overall_result_file = output_dir / f"{tissue}_overall_result.json"
531
+ with open(overall_result_file, 'w') as f:
532
+ json.dump(processing_results, f, indent=2)
533
+ logger.info(f"💾 Saved overall result for {tissue}")
534
+
535
+ # Clean up memory
536
+ del adata
537
+ gc.collect()
538
+ log_memory_status("After cleanup")
539
+
540
+ return processing_results
541
+
542
+ except Exception as e:
543
+ logger.error(f"{tissue.capitalize()} processing failed: {e}")
544
+ processing_results['error'] = str(e)
545
+
546
+ # Save partial results even on error
547
+ error_result_file = output_dir / f"{tissue}_error_result.json"
548
+ with open(error_result_file, 'w') as f:
549
+ json.dump(processing_results, f, indent=2)
550
+ logger.info(f"💾 Saved partial results despite error")
551
+
552
+ # Clean up memory even on error
553
+ del adata
554
+ gc.collect()
555
+
556
+ return processing_results
557
+
558
+ def combine_metadata_files(output_dir: Path, tissues: List[str]) -> None:
559
+ """Combine metadata files from different tissues"""
560
+ logger.info("\n🔗 Combining metadata files across tissues...")
561
+
562
+ # Combine sample metadata
563
+ sample_dfs = []
564
+ for tissue in tissues:
565
+ sample_file = output_dir / f"aging_fly_{tissue}_sample_metadata.parquet"
566
+ if sample_file.exists():
567
+ df = pd.read_parquet(sample_file)
568
+ sample_dfs.append(df)
569
+ logger.info(f"Loaded {tissue} sample metadata: {df.shape}")
570
+
571
+ if sample_dfs:
572
+ combined_sample_df = pd.concat(sample_dfs, axis=0, ignore_index=False)
573
+ combined_file = output_dir / "aging_fly_combined_sample_metadata.parquet"
574
+ combined_sample_df.to_parquet(combined_file, compression='snappy')
575
+ logger.info(f"✅ Combined sample metadata saved: {combined_sample_df.shape}")
576
+
577
+ # Feature metadata should be identical, so just copy one
578
+ for tissue in tissues:
579
+ feature_file = output_dir / f"aging_fly_{tissue}_feature_metadata.parquet"
580
+ if feature_file.exists():
581
+ combined_feature_file = output_dir / "aging_fly_combined_feature_metadata.parquet"
582
+ shutil.copy2(feature_file, combined_feature_file)
583
+ logger.info(f"✅ Combined feature metadata copied from {tissue}")
584
+ break
585
+
586
+ @app.command()
587
+ def process(
588
+ tissue: Annotated[str, typer.Argument(help="Which tissue to process: 'head', 'body', or 'both'")] = "both",
589
+ skip_expression: Annotated[bool, typer.Option(help="Skip expression matrix processing")] = False,
590
+ skip_metadata: Annotated[bool, typer.Option(help="Skip metadata processing")] = False,
591
+ skip_projections: Annotated[bool, typer.Option(help="Skip projection processing")] = False,
592
+ aggressive_chunking: Annotated[bool, typer.Option(help="Use aggressive chunking (for low memory)")] = False,
593
+ data_dir: Annotated[str, typer.Option(help="Data directory path")] = "data",
594
+ output_dir: Annotated[str, typer.Option(help="Output directory path")] = "processed"
595
+ ) -> None:
596
+ """Process Aging Fly Cell Atlas data into HuggingFace format"""
597
+
598
+ start_time = time.time()
599
+ logger.info("=== Phase 3: Aging Fly Cell Atlas Data Processing Started ===")
600
+
601
+ # Validate tissue parameter
602
+ valid_tissues = {'head', 'body', 'both'}
603
+ if tissue not in valid_tissues:
604
+ logger.error(f"Invalid tissue '{tissue}'. Must be one of: {', '.join(valid_tissues)}")
605
+ raise typer.Exit(1)
606
+
607
+ # Setup paths
608
+ data_path = Path(data_dir)
609
+ output_path = Path(output_dir)
610
+ output_path.mkdir(exist_ok=True)
611
+
612
+ head_file = data_path / "afca_head.h5ad"
613
+ body_file = data_path / "afca_body.h5ad"
614
+
615
+ # Determine which datasets to process
616
+ datasets_to_process = []
617
+ if tissue in ['head', 'both']:
618
+ if head_file.exists():
619
+ datasets_to_process.append(('head', head_file))
620
+ else:
621
+ logger.warning(f"Head file not found: {head_file}")
622
+
623
+ if tissue in ['body', 'both']:
624
+ if body_file.exists():
625
+ datasets_to_process.append(('body', body_file))
626
+ else:
627
+ logger.warning(f"Body file not found: {body_file}")
628
+
629
+ if not datasets_to_process:
630
+ logger.error("No valid datasets found to process")
631
+ raise typer.Exit(1)
632
+
633
+ # Setup skip stages
634
+ skip_stages = set()
635
+ if skip_expression:
636
+ skip_stages.add('expression')
637
+ if skip_metadata:
638
+ skip_stages.update(['sample_metadata', 'feature_metadata', 'unstructured'])
639
+ if skip_projections:
640
+ skip_stages.add('projections')
641
+
642
+ # Process datasets
643
+ all_results = {}
644
+
645
+ for tissue_name, data_file in datasets_to_process:
646
+ logger.info(f"\n{'='*60}")
647
+ logger.info(f"Processing {tissue_name.upper()} dataset")
648
+ logger.info(f"{'='*60}")
649
+
650
+ # Use aggressive chunking for body by default, or if explicitly requested
651
+ use_aggressive = aggressive_chunking or (tissue_name == 'body')
652
+
653
+ results = process_single_dataset(data_file, tissue_name, output_path,
654
+ skip_stages, use_aggressive)
655
+ all_results[tissue_name] = results
656
+
657
+ # Force garbage collection between datasets
658
+ gc.collect()
659
+ log_memory_status(f"After processing {tissue_name}")
660
+
661
+ # Generate summary
662
+ generate_summary(output_path, all_results, start_time)
663
+
664
+ @app.command()
665
+ def summary(
666
+ output_dir: Annotated[str, typer.Option(help="Output directory path")] = "processed"
667
+ ) -> None:
668
+ """Generate summary from existing results without reprocessing"""
669
+
670
+ output_path = Path(output_dir)
671
+ if not output_path.exists():
672
+ logger.error(f"Output directory not found: {output_path}")
673
+ raise typer.Exit(1)
674
+
675
+ logger.info("📊 Generating summary from existing results...")
676
+
677
+ # Load existing results
678
+ all_results = {}
679
+ for tissue in ['head', 'body']:
680
+ overall_result_file = output_path / f"{tissue}_overall_result.json"
681
+ if overall_result_file.exists():
682
+ with open(overall_result_file, 'r') as f:
683
+ all_results[tissue] = json.load(f)
684
+ logger.info(f"✅ Loaded {tissue} results")
685
+ else:
686
+ logger.warning(f"⚠️ No results found for {tissue}")
687
+
688
+ if not all_results:
689
+ logger.error("No existing results found")
690
+ raise typer.Exit(1)
691
+
692
+ generate_summary(output_path, all_results, time.time())
693
+
694
+ def generate_summary(output_path: Path, all_results: Dict[str, Any], start_time: float) -> None:
695
+ """Generate processing summary"""
696
+
697
+ # Combine metadata files if both tissues processed
698
+ tissues = list(all_results.keys())
699
+ if len(tissues) > 1:
700
+ combine_metadata_files(output_path, tissues)
701
+
702
+ # Calculate total processing time
703
+ total_processing_time = time.time() - start_time
704
+
705
+ summary = {
706
+ 'processing_info': {
707
+ 'total_time': f"{total_processing_time:.1f}s",
708
+ 'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
709
+ 'datasets_processed': len(tissues)
710
+ },
711
+ 'results': all_results
712
+ }
713
+
714
+ summary_file = output_path / "phase3_processing_summary.json"
715
+ with open(summary_file, 'w') as f:
716
+ json.dump(summary, f, indent=2)
717
+
718
+ logger.info(f"\n✅ Processing Summary Generated!")
719
+ logger.info(f"⏱️ Total time: {total_processing_time:.1f}s")
720
+ logger.info(f"📄 Summary saved: {summary_file}")
721
+
722
+ # List all created files
723
+ logger.info("\n📁 Created Files:")
724
+ for file_path in sorted(output_path.glob("aging_fly_*.parquet")):
725
+ size_mb = file_path.stat().st_size / (1024**2)
726
+ logger.info(f" {file_path.name} ({size_mb:.1f}MB)")
727
+
728
+ for file_path in sorted(output_path.glob("aging_fly_*.json")):
729
+ size_mb = file_path.stat().st_size / (1024**2)
730
+ logger.info(f" {file_path.name} ({size_mb:.1f}MB)")
731
+
732
+ # Calculate total cells if available
733
+ total_cells = 0
734
+ for tissue_result in all_results.values():
735
+ if 'dataset_info' in tissue_result and 'shape' in tissue_result['dataset_info']:
736
+ total_cells += tissue_result['dataset_info']['shape'][0]
737
+
738
+ if total_cells > 0:
739
+ logger.info(f"\n🎉 Total cells processed: {total_cells:,}")
740
+
741
+ if __name__ == "__main__":
742
+ app()