jkh commited on
Commit
afaea93
ยท
verified ยท
1 Parent(s): 9695895

Upload data_retrieval.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. data_retrieval.py +682 -0
data_retrieval.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Phase 1: Data Retrieval & Setup
4
+ Aging Fly Cell Atlas (AFCA) - GSE218661
5
+
6
+ This script programmatically retrieves h5ad files and metadata from GSE218661
7
+ for the Aging Fly Cell Atlas study. Downloads both head and body data files.
8
+
9
+ Key features:
10
+ - Downloads h5ad files from GEO supplementary files
11
+ - Extracts comprehensive metadata from all available sources
12
+ - Organizes data in proper directory structure
13
+ - Validates downloaded files
14
+ """
15
+
16
+ import os
17
+ import sys
18
+ import requests
19
+ import GEOparse
20
+ import pandas as pd
21
+ import json
22
+ import warnings
23
+ import gzip
24
+ import scanpy as sc
25
+ from pathlib import Path
26
+ from typing import Dict, List, Optional, Tuple
27
+ import time
28
+ from urllib.parse import urlparse
29
+ import hashlib
30
+
31
+ # Suppress warnings for cleaner output
32
+ warnings.filterwarnings('ignore')
33
+
34
+ def setup_directories() -> Dict[str, Path]:
35
+ """Create necessary directory structure for AFCA data."""
36
+
37
+ print("๐Ÿ—‚๏ธ SETTING UP DIRECTORY STRUCTURE")
38
+ print("=" * 50)
39
+
40
+ # Define directory structure
41
+ dirs = {
42
+ 'data': Path('data'),
43
+ 'raw': Path('data/raw'),
44
+ 'processed': Path('processed'),
45
+ 'metadata': Path('data/metadata'),
46
+ 'logs': Path('data/logs'),
47
+ 'supplementary': Path('data/raw/supplementary')
48
+ }
49
+
50
+ # Create directories
51
+ for name, path in dirs.items():
52
+ path.mkdir(exist_ok=True, parents=True)
53
+ print(f" โœ… Created: {path}")
54
+
55
+ return dirs
56
+
57
+ def extract_geo_metadata(accession: str = "GSE218661") -> Dict:
58
+ """Extract comprehensive metadata from GEO using GEOparse."""
59
+
60
+ print(f"\n๐Ÿ“Š EXTRACTING GEO METADATA FOR {accession}")
61
+ print("=" * 50)
62
+
63
+ try:
64
+ # Download GEO metadata
65
+ print(f" ๐Ÿ“ก Connecting to GEO database...")
66
+ gse = GEOparse.get_GEO(geo=accession, destdir="data/metadata/")
67
+
68
+ metadata = {
69
+ 'accession': accession,
70
+ 'title': gse.metadata.get('title', [''])[0],
71
+ 'summary': gse.metadata.get('summary', [''])[0],
72
+ 'overall_design': gse.metadata.get('overall_design', [''])[0],
73
+ 'submission_date': gse.metadata.get('submission_date', [''])[0],
74
+ 'last_update_date': gse.metadata.get('last_update_date', [''])[0],
75
+ 'organism': gse.metadata.get('organism', []),
76
+ 'platform_organism': gse.metadata.get('platform_organism', []),
77
+ 'contact_email': gse.metadata.get('contact_email', [''])[0],
78
+ 'contact_name': gse.metadata.get('contact_name', [''])[0],
79
+ 'contact_institute': gse.metadata.get('contact_institute', [''])[0],
80
+ 'supplementary_file': gse.metadata.get('supplementary_file', []),
81
+ 'relation': gse.metadata.get('relation', []),
82
+ 'sample_count': len(gse.gsms),
83
+ 'platform_count': len(gse.gpls),
84
+ 'samples': {},
85
+ 'platforms': {}
86
+ }
87
+
88
+ # Extract sample metadata
89
+ print(f" ๐Ÿงช Extracting metadata for {len(gse.gsms)} samples...")
90
+ for gsm_name, gsm in gse.gsms.items():
91
+ metadata['samples'][gsm_name] = {
92
+ 'title': gsm.metadata.get('title', [''])[0],
93
+ 'source_name_ch1': gsm.metadata.get('source_name_ch1', [''])[0],
94
+ 'organism_ch1': gsm.metadata.get('organism_ch1', [''])[0],
95
+ 'characteristics_ch1': gsm.metadata.get('characteristics_ch1', []),
96
+ 'treatment_protocol_ch1': gsm.metadata.get('treatment_protocol_ch1', [''])[0],
97
+ 'extract_protocol_ch1': gsm.metadata.get('extract_protocol_ch1', [''])[0],
98
+ 'description': gsm.metadata.get('description', [''])[0],
99
+ 'data_processing': gsm.metadata.get('data_processing', []),
100
+ 'platform_id': gsm.metadata.get('platform_id', [''])[0],
101
+ 'contact_name': gsm.metadata.get('contact_name', [''])[0],
102
+ 'supplementary_file': gsm.metadata.get('supplementary_file', []),
103
+ 'submission_date': gsm.metadata.get('submission_date', [''])[0],
104
+ 'last_update_date': gsm.metadata.get('last_update_date', [''])[0]
105
+ }
106
+
107
+ # Extract platform metadata
108
+ print(f" ๐Ÿ”ฌ Extracting metadata for {len(gse.gpls)} platforms...")
109
+ for gpl_name, gpl in gse.gpls.items():
110
+ metadata['platforms'][gpl_name] = {
111
+ 'title': gpl.metadata.get('title', [''])[0],
112
+ 'organism': gpl.metadata.get('organism', [''])[0],
113
+ 'technology': gpl.metadata.get('technology', [''])[0],
114
+ 'distribution': gpl.metadata.get('distribution', [''])[0],
115
+ 'description': gpl.metadata.get('description', [''])[0],
116
+ 'submission_date': gpl.metadata.get('submission_date', [''])[0],
117
+ 'last_update_date': gpl.metadata.get('last_update_date', [''])[0]
118
+ }
119
+
120
+ print(f" โœ… Successfully extracted metadata for {accession}")
121
+ return metadata, gse
122
+
123
+ except Exception as e:
124
+ print(f" โŒ Error extracting GEO metadata: {e}")
125
+ return {}, None
126
+
127
+ def download_geo_supplementary_files(gse, dirs: Dict[str, Path]) -> Dict[str, bool]:
128
+ """Download supplementary files from GEO which should contain h5ad files."""
129
+
130
+ print("\n๐Ÿ“ฆ DOWNLOADING GEO SUPPLEMENTARY FILES")
131
+ print("=" * 50)
132
+
133
+ supp_dir = dirs['supplementary']
134
+ download_results = {'supplementary_files': False}
135
+
136
+ try:
137
+ print(f" ๐Ÿ“‚ Downloading supplementary files to: {supp_dir}")
138
+
139
+ # Check if files already exist
140
+ existing_files = list(supp_dir.glob('*'))
141
+ if existing_files:
142
+ print(f" โœ… Found {len(existing_files)} existing files in {supp_dir}")
143
+ download_results['supplementary_files'] = True
144
+ else:
145
+ # Download supplementary files
146
+ gse.download_supplementary_files(directory=str(supp_dir))
147
+
148
+ # Check if download was successful
149
+ downloaded_files = list(supp_dir.glob('*'))
150
+ if downloaded_files:
151
+ print(f" โœ… Successfully downloaded {len(downloaded_files)} supplementary files")
152
+ download_results['supplementary_files'] = True
153
+ else:
154
+ print(f" โŒ No supplementary files downloaded")
155
+
156
+ except Exception as e:
157
+ print(f" โŒ Error downloading supplementary files: {e}")
158
+ print(f" ๐Ÿ” You may need to manually download files from:")
159
+ print(f" https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE218661")
160
+
161
+ return download_results
162
+
163
+ def download_h5ad_files_manually(gse, dirs: Dict[str, Path]) -> Dict[str, bool]:
164
+ """Manually download h5ad files using URLs extracted from GEO metadata."""
165
+
166
+ print("\n๐Ÿ“ฅ EXTRACTING H5AD URLS FROM GEO AND DOWNLOADING")
167
+ print("=" * 50)
168
+
169
+ supp_dir = dirs['supplementary']
170
+ download_results = {'h5ad_head': False, 'h5ad_body': False}
171
+
172
+ # Extract supplementary file URLs from GEO metadata
173
+ h5ad_files = {}
174
+
175
+ # Check GSE-level supplementary files
176
+ if hasattr(gse, 'metadata') and 'supplementary_file' in gse.metadata:
177
+ supp_files = gse.metadata['supplementary_file']
178
+ print(f" ๐Ÿ” Found {len(supp_files)} GSE-level supplementary files")
179
+
180
+ for supp_file in supp_files:
181
+ if '.h5ad' in supp_file.lower():
182
+ print(f" ๐Ÿ“„ H5AD file found: {supp_file}")
183
+
184
+ # Determine tissue type from filename
185
+ if 'head' in supp_file.lower():
186
+ tissue = 'head'
187
+ elif 'body' in supp_file.lower():
188
+ tissue = 'body'
189
+ else:
190
+ tissue = 'unknown'
191
+
192
+ # Extract filename from URL
193
+ filename = supp_file.split('/')[-1]
194
+
195
+ # Convert FTP URLs to HTTP URLs for requests compatibility
196
+ url = supp_file
197
+ if url.startswith('ftp://ftp.ncbi.nlm.nih.gov'):
198
+ url = url.replace('ftp://ftp.ncbi.nlm.nih.gov', 'https://ftp.ncbi.nlm.nih.gov')
199
+
200
+ h5ad_files[tissue] = {
201
+ 'url': url,
202
+ 'filename': filename
203
+ }
204
+
205
+ # Also check individual GSM samples for supplementary files
206
+ for gsm_name, gsm in gse.gsms.items():
207
+ if hasattr(gsm, 'metadata') and 'supplementary_file' in gsm.metadata:
208
+ supp_files = gsm.metadata['supplementary_file']
209
+ for supp_file in supp_files:
210
+ if '.h5ad' in supp_file.lower():
211
+ print(f" ๐Ÿ“„ GSM H5AD file found in {gsm_name}: {supp_file}")
212
+
213
+ # Determine tissue type from filename or GSM metadata
214
+ tissue = 'unknown'
215
+ if 'head' in supp_file.lower():
216
+ tissue = 'head'
217
+ elif 'body' in supp_file.lower():
218
+ tissue = 'body'
219
+ elif hasattr(gsm, 'metadata') and 'source_name_ch1' in gsm.metadata:
220
+ source = gsm.metadata['source_name_ch1'][0].lower()
221
+ if 'head' in source:
222
+ tissue = 'head'
223
+ elif 'body' in source:
224
+ tissue = 'body'
225
+
226
+ filename = supp_file.split('/')[-1]
227
+
228
+ # Only add if we don't already have this tissue or if this looks more comprehensive
229
+ if tissue not in h5ad_files or 'combined' in filename.lower():
230
+ # Convert FTP URLs to HTTP URLs for requests compatibility
231
+ url = supp_file
232
+ if url.startswith('ftp://ftp.ncbi.nlm.nih.gov'):
233
+ url = url.replace('ftp://ftp.ncbi.nlm.nih.gov', 'https://ftp.ncbi.nlm.nih.gov')
234
+
235
+ h5ad_files[tissue] = {
236
+ 'url': url,
237
+ 'filename': filename
238
+ }
239
+
240
+ # If no h5ad files found in metadata, construct URLs based on GEO conventions
241
+ if not h5ad_files:
242
+ print(" โš ๏ธ No h5ad files found in GEO metadata, constructing standard URLs...")
243
+ accession = gse.get_accession()
244
+ base_url = f"https://ftp.ncbi.nlm.nih.gov/geo/series/{accession[:-3]}nnn/{accession}/suppl/"
245
+
246
+ h5ad_files = {
247
+ 'head': {
248
+ 'url': f"{base_url}{accession}_adata_head_S_v1.0.h5ad.gz",
249
+ 'filename': f"{accession}_adata_head_S_v1.0.h5ad.gz"
250
+ },
251
+ 'body': {
252
+ 'url': f"{base_url}{accession}_adata_body_S_v1.0.h5ad.gz",
253
+ 'filename': f"{accession}_adata_body_S_v1.0.h5ad.gz"
254
+ }
255
+ }
256
+ print(f" ๐Ÿ”ง Constructed URLs for {accession}")
257
+
258
+ print(f"\n ๐Ÿ“‹ H5AD files to download:")
259
+ for tissue, file_info in h5ad_files.items():
260
+ print(f" ๐Ÿงฌ {tissue.title()}: {file_info['filename']}")
261
+ print(f" URL: {file_info['url']}")
262
+
263
+ # Download each h5ad file
264
+ for tissue, file_info in h5ad_files.items():
265
+ file_path = supp_dir / file_info['filename']
266
+
267
+ if file_path.exists():
268
+ print(f"\n โœ… {tissue.title()} h5ad file already exists: {file_path}")
269
+ download_results[f'h5ad_{tissue}'] = True
270
+ continue
271
+
272
+ try:
273
+ print(f"\n ๐Ÿ“ก Downloading {tissue} h5ad file...")
274
+ print(f" Source: {file_info['url']}")
275
+ print(f" Destination: {file_path}")
276
+
277
+ response = requests.get(file_info['url'], stream=True)
278
+ response.raise_for_status()
279
+
280
+ # Get file size for progress tracking
281
+ total_size = int(response.headers.get('content-length', 0))
282
+
283
+ with open(file_path, 'wb') as f:
284
+ downloaded = 0
285
+ for chunk in response.iter_content(chunk_size=8192):
286
+ if chunk:
287
+ f.write(chunk)
288
+ downloaded += len(chunk)
289
+ if total_size > 0:
290
+ percent = (downloaded / total_size) * 100
291
+ print(f"\r Progress: {percent:.1f}% ({downloaded:,}/{total_size:,} bytes)", end='', flush=True)
292
+
293
+ print(f"\n โœ… Successfully downloaded {tissue} h5ad file: {file_path}")
294
+ download_results[f'h5ad_{tissue}'] = True
295
+
296
+ except Exception as e:
297
+ print(f"\n โŒ Error downloading {tissue} h5ad file: {e}")
298
+ continue
299
+
300
+ return download_results
301
+
302
+ def process_h5ad_files(dirs: Dict[str, Path]) -> Dict[str, any]:
303
+ """Process h5ad files and extract information."""
304
+
305
+ print("\n๐Ÿ”ฌ PROCESSING H5AD FILES")
306
+ print("=" * 50)
307
+
308
+ supp_dir = dirs['supplementary']
309
+ data_dir = dirs['data']
310
+ h5ad_info = {
311
+ 'files_found': [],
312
+ 'files_processed': {},
313
+ 'total_cells': 0,
314
+ 'total_genes': 0,
315
+ 'datasets': {}
316
+ }
317
+
318
+ # Find h5ad files
319
+ h5ad_files = list(supp_dir.glob('*.h5ad'))
320
+ if not h5ad_files:
321
+ # Also check for compressed files
322
+ h5ad_files.extend(list(supp_dir.glob('*.h5ad.gz')))
323
+
324
+ print(f" ๐Ÿ” Found {len(h5ad_files)} h5ad files")
325
+
326
+ for h5ad_file in h5ad_files:
327
+ try:
328
+ print(f" ๐Ÿ“– Processing: {h5ad_file.name}")
329
+
330
+ # Read h5ad file
331
+ if h5ad_file.suffix == '.gz':
332
+ # Handle compressed files
333
+ print(f" ๐Ÿ“‚ Decompressing {h5ad_file.name}")
334
+ with gzip.open(h5ad_file, 'rb') as f_in:
335
+ decompressed_file = h5ad_file.with_suffix('')
336
+ with open(decompressed_file, 'wb') as f_out:
337
+ f_out.write(f_in.read())
338
+ adata = sc.read_h5ad(decompressed_file)
339
+
340
+ # Move to data root with clean name and remove compressed file
341
+ tissue_type = 'unknown'
342
+ filename_lower = h5ad_file.name.lower()
343
+ if 'head' in filename_lower:
344
+ tissue_type = 'head'
345
+ elif 'body' in filename_lower:
346
+ tissue_type = 'body'
347
+
348
+ final_filename = f"afca_{tissue_type}.h5ad"
349
+ final_path = data_dir / final_filename
350
+
351
+ print(f" ๐Ÿ“ Moving to data root: {final_path}")
352
+ decompressed_file.rename(final_path)
353
+
354
+ print(f" ๐Ÿ—‘๏ธ Removing compressed file: {h5ad_file}")
355
+ h5ad_file.unlink()
356
+
357
+ # Update file reference for processing
358
+ h5ad_file = final_path
359
+
360
+ else:
361
+ adata = sc.read_h5ad(h5ad_file)
362
+
363
+ # Extract basic information
364
+ file_info = {
365
+ 'filename': h5ad_file.name,
366
+ 'filepath': str(h5ad_file),
367
+ 'n_obs': adata.n_obs,
368
+ 'n_vars': adata.n_vars,
369
+ 'obs_columns': list(adata.obs.columns),
370
+ 'var_columns': list(adata.var.columns),
371
+ 'uns_keys': list(adata.uns.keys()) if adata.uns else [],
372
+ 'obsm_keys': list(adata.obsm.keys()) if adata.obsm else [],
373
+ 'varm_keys': list(adata.varm.keys()) if adata.varm else [],
374
+ }
375
+
376
+ # Identify tissue type from filename or metadata
377
+ tissue_type = 'unknown'
378
+ filename_lower = h5ad_file.name.lower()
379
+ if 'head' in filename_lower:
380
+ tissue_type = 'head'
381
+ elif 'body' in filename_lower:
382
+ tissue_type = 'body'
383
+ elif 'combined' in filename_lower or 'full' in filename_lower:
384
+ tissue_type = 'combined'
385
+
386
+ file_info['tissue_type'] = tissue_type
387
+
388
+ # Extract age information if available
389
+ if 'age' in adata.obs.columns:
390
+ ages = adata.obs['age'].unique()
391
+ file_info['ages'] = list(ages)
392
+ print(f" ๐Ÿ“… Ages found: {ages}")
393
+
394
+ # Extract cell type information if available
395
+ cell_type_cols = [col for col in adata.obs.columns
396
+ if any(term in col.lower() for term in ['cell_type', 'celltype', 'annotation', 'cluster'])]
397
+ if cell_type_cols:
398
+ file_info['cell_type_columns'] = cell_type_cols
399
+ for col in cell_type_cols[:2]: # Limit to first 2 to avoid too much output
400
+ cell_types = adata.obs[col].unique()
401
+ file_info[f'{col}_unique_values'] = len(cell_types)
402
+ print(f" ๐Ÿงฌ {col}: {len(cell_types)} unique values")
403
+
404
+ h5ad_info['files_processed'][h5ad_file.name] = file_info
405
+ h5ad_info['total_cells'] += adata.n_obs
406
+ h5ad_info['total_genes'] = max(h5ad_info['total_genes'], adata.n_vars)
407
+
408
+ print(f" โœ… Processed: {adata.n_obs:,} cells ร— {adata.n_vars:,} genes")
409
+
410
+ except Exception as e:
411
+ print(f" โŒ Error processing {h5ad_file.name}: {e}")
412
+ continue
413
+
414
+ h5ad_info['files_found'] = [f.name for f in h5ad_files]
415
+
416
+ if h5ad_info['files_processed']:
417
+ print(f"\n ๐Ÿ“Š Summary:")
418
+ print(f" ๐Ÿ“ Files processed: {len(h5ad_info['files_processed'])}")
419
+ print(f" ๐Ÿงฌ Total cells: {h5ad_info['total_cells']:,}")
420
+ print(f" ๐Ÿงฎ Max genes: {h5ad_info['total_genes']:,}")
421
+ print(f" ๐Ÿ“‚ Final h5ad files location: data/")
422
+
423
+ return h5ad_info
424
+
425
+ def create_afca_data_info() -> Dict:
426
+ """Create comprehensive information about AFCA dataset."""
427
+
428
+ print("\n๐Ÿ“‹ CREATING AFCA DATA INFORMATION")
429
+ print("=" * 50)
430
+
431
+ afca_info = {
432
+ 'dataset_name': 'Aging Fly Cell Atlas (AFCA)',
433
+ 'accession': 'GSE218661',
434
+ 'publication': {
435
+ 'title': 'Aging Fly Cell Atlas identifies exhaustive aging features at cellular resolution',
436
+ 'authors': 'Lu, T.-C., Brbiฤ‡, M., Park, Y.-J., et al.',
437
+ 'journal': 'Science',
438
+ 'year': 2023,
439
+ 'volume': 380,
440
+ 'issue': 6650,
441
+ 'doi': '10.1126/science.adg0934'
442
+ },
443
+ 'data_description': {
444
+ 'organism': 'Drosophila melanogaster',
445
+ 'technology': '10x Chromium single-nucleus RNA-seq (snRNA-seq)',
446
+ 'total_nuclei': '868,000+',
447
+ 'cell_types': 163,
448
+ 'ages': ['5d', '30d', '50d', '70d'],
449
+ 'sexes': ['Male', 'Female'],
450
+ 'tissues': ['Head', 'Body']
451
+ },
452
+ 'data_access': {
453
+ 'web_portal': 'https://hongjielilab.org/afca/',
454
+ 'geo_repository': 'https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE218661',
455
+ 'zenodo': 'https://doi.org/10.5281/zenodo.7853649',
456
+ 'cellxgene_head': 'https://cellxgene.cziscience.com/',
457
+ 'cellxgene_body': 'https://cellxgene.cziscience.com/',
458
+ 'cellxgene_combined': 'https://cellxgene.cziscience.com/'
459
+ }
460
+ }
461
+
462
+ print(" โœ… Created comprehensive AFCA dataset information")
463
+ return afca_info
464
+
465
+ def save_metadata_files(metadata: Dict, afca_info: Dict, h5ad_info: Dict, dirs: Dict[str, Path]) -> None:
466
+ """Save all collected metadata to organized files."""
467
+
468
+ print("\n๐Ÿ’พ SAVING METADATA FILES")
469
+ print("=" * 50)
470
+
471
+ try:
472
+ # Save GEO metadata
473
+ geo_file = dirs['metadata'] / 'geo_metadata.json'
474
+ with open(geo_file, 'w', encoding='utf-8') as f:
475
+ json.dump(metadata, f, indent=2, ensure_ascii=False)
476
+ print(f" โœ… Saved GEO metadata: {geo_file}")
477
+
478
+ # Save AFCA dataset information
479
+ afca_file = dirs['metadata'] / 'afca_dataset_info.json'
480
+ with open(afca_file, 'w', encoding='utf-8') as f:
481
+ json.dump(afca_info, f, indent=2, ensure_ascii=False)
482
+ print(f" โœ… Saved AFCA info: {afca_file}")
483
+
484
+ # Save h5ad processing results
485
+ h5ad_file = dirs['metadata'] / 'h5ad_processing_info.json'
486
+ with open(h5ad_file, 'w', encoding='utf-8') as f:
487
+ json.dump(h5ad_info, f, indent=2, ensure_ascii=False)
488
+ print(f" โœ… Saved h5ad info: {h5ad_file}")
489
+
490
+ # Create summary metadata
491
+ summary = {
492
+ 'retrieval_date': pd.Timestamp.now().isoformat(),
493
+ 'accession': metadata.get('accession', 'GSE218661'),
494
+ 'title': metadata.get('title', afca_info['dataset_name']),
495
+ 'organism': afca_info['data_description']['organism'],
496
+ 'total_samples': metadata.get('sample_count', 'Unknown'),
497
+ 'technology': afca_info['data_description']['technology'],
498
+ 'h5ad_files_found': len(h5ad_info.get('files_found', [])),
499
+ 'h5ad_files_processed': len(h5ad_info.get('files_processed', {})),
500
+ 'total_cells_in_h5ad': h5ad_info.get('total_cells', 0),
501
+ 'max_genes_in_h5ad': h5ad_info.get('total_genes', 0)
502
+ }
503
+
504
+ summary_file = dirs['metadata'] / 'retrieval_summary.json'
505
+ with open(summary_file, 'w', encoding='utf-8') as f:
506
+ json.dump(summary, f, indent=2, ensure_ascii=False)
507
+ print(f" โœ… Saved retrieval summary: {summary_file}")
508
+
509
+ # Save sample information as CSV if available
510
+ if metadata.get('samples'):
511
+ samples_data = []
512
+ for gsm_id, sample_info in metadata['samples'].items():
513
+ row = {'sample_id': gsm_id}
514
+ row.update(sample_info)
515
+ # Flatten characteristics list
516
+ if isinstance(sample_info.get('characteristics_ch1'), list):
517
+ for i, char in enumerate(sample_info['characteristics_ch1']):
518
+ row[f'characteristic_{i+1}'] = char
519
+ samples_data.append(row)
520
+
521
+ samples_df = pd.DataFrame(samples_data)
522
+ samples_file = dirs['metadata'] / 'samples_metadata.csv'
523
+ samples_df.to_csv(samples_file, index=False)
524
+ print(f" โœ… Saved samples metadata: {samples_file}")
525
+
526
+ except Exception as e:
527
+ print(f" โŒ Error saving metadata: {e}")
528
+
529
+ def generate_download_instructions() -> str:
530
+ """Generate instructions for manual data download."""
531
+
532
+ instructions = """
533
+ ๐Ÿ”ฝ MANUAL DOWNLOAD INSTRUCTIONS FOR AFCA DATA
534
+ ==============================================
535
+
536
+ 1. GEO Repository (GSE218661) - Primary Source:
537
+ โ€ข Visit: https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE218661
538
+ โ€ข Download supplementary files (look for .h5ad files)
539
+ โ€ข Place in: data/raw/supplementary/
540
+
541
+ 2. AFCA Web Portal (Interactive):
542
+ โ€ข Visit: https://hongjielilab.org/afca/
543
+ โ€ข Access interactive data portal for exploration
544
+
545
+ 3. CellxGene Portal:
546
+ โ€ข Search for "Aging Fly Cell Atlas"
547
+ โ€ข URL: https://cellxgene.cziscience.com/
548
+
549
+ 4. Zenodo Repository (Analysis Code & Data):
550
+ โ€ข Visit: https://doi.org/10.5281/zenodo.7853649
551
+
552
+ Expected h5ad files:
553
+ - Head data: Contains head tissue single-nucleus data
554
+ - Body data: Contains body tissue single-nucleus data
555
+ - Combined data: May contain integrated head+body data
556
+
557
+ After manual download, place files in: data/raw/supplementary/
558
+ Then re-run this script to process the downloaded files.
559
+ """
560
+
561
+ return instructions
562
+
563
+ def main():
564
+ """Main data retrieval workflow for AFCA GSE218661."""
565
+
566
+ print("๐Ÿงฌ AGING FLY CELL ATLAS (AFCA) - DATA RETRIEVAL")
567
+ print("=" * 60)
568
+ print("๐ŸŽฏ Target: GSE218661 (Aging Fly Cell Atlas)")
569
+ print("๐Ÿ“‹ Goal: Download h5ad files and extract comprehensive metadata")
570
+ print()
571
+
572
+ # Setup directories
573
+ dirs = setup_directories()
574
+
575
+ # Extract GEO metadata and get GSE object
576
+ geo_metadata, gse = extract_geo_metadata("GSE218661")
577
+
578
+ if not gse:
579
+ print("โŒ Failed to retrieve GEO metadata. Cannot proceed.")
580
+ sys.exit(1)
581
+
582
+ # Download supplementary files from GEO (this gets the sample directories but not h5ad files)
583
+ download_results = download_geo_supplementary_files(gse, dirs)
584
+
585
+ # Manually download the h5ad files
586
+ h5ad_download_results = download_h5ad_files_manually(gse, dirs)
587
+ download_results.update(h5ad_download_results)
588
+
589
+ # Process h5ad files
590
+ h5ad_info = process_h5ad_files(dirs)
591
+
592
+ # Create comprehensive AFCA information
593
+ afca_info = create_afca_data_info()
594
+
595
+ # Save all metadata
596
+ save_metadata_files(geo_metadata, afca_info, h5ad_info, dirs)
597
+
598
+ # Generate download instructions
599
+ instructions = generate_download_instructions()
600
+ instructions_file = dirs['data'] / 'DOWNLOAD_INSTRUCTIONS.txt'
601
+ with open(instructions_file, 'w') as f:
602
+ f.write(instructions)
603
+
604
+ # Final summary
605
+ print("\n๐ŸŽ‰ DATA RETRIEVAL SUMMARY")
606
+ print("=" * 50)
607
+
608
+ print("๐Ÿ“‚ Directory Structure Created:")
609
+ for name, path in dirs.items():
610
+ print(f" โœ… {name}: {path}")
611
+
612
+ print(f"\n๐Ÿ“Š Download Results:")
613
+ for category, success in download_results.items():
614
+ status = "โœ…" if success else "โŒ"
615
+ print(f" {status} {category}")
616
+
617
+ print(f"\n๐Ÿ”ฌ H5AD Processing Results:")
618
+ print(f" ๐Ÿ“ Files found: {len(h5ad_info.get('files_found', []))}")
619
+ print(f" โœ… Files processed: {len(h5ad_info.get('files_processed', {}))}")
620
+ if h5ad_info.get('total_cells', 0) > 0:
621
+ print(f" ๐Ÿงฌ Total cells: {h5ad_info['total_cells']:,}")
622
+ print(f" ๐Ÿงฎ Max genes: {h5ad_info['total_genes']:,}")
623
+
624
+ print(f"\n๐Ÿ“‹ Metadata Files Created:")
625
+ metadata_files = [
626
+ 'geo_metadata.json',
627
+ 'afca_dataset_info.json',
628
+ 'h5ad_processing_info.json',
629
+ 'retrieval_summary.json',
630
+ 'samples_metadata.csv',
631
+ 'DOWNLOAD_INSTRUCTIONS.txt'
632
+ ]
633
+
634
+ for filename in metadata_files:
635
+ if filename == 'DOWNLOAD_INSTRUCTIONS.txt':
636
+ file_path = dirs['data'] / filename
637
+ else:
638
+ file_path = dirs['metadata'] / filename
639
+ if file_path.exists():
640
+ print(f" โœ… {filename}")
641
+ else:
642
+ print(f" โš ๏ธ {filename} (may not be created)")
643
+
644
+ if not any([download_results.get('h5ad_head', False), download_results.get('h5ad_body', False)]):
645
+ print(f"\nโš ๏ธ H5AD FILES NOT DOWNLOADED")
646
+ print("๐Ÿ“– Please check the manual download function or download directly from:")
647
+ print("๐ŸŒ Head: https://ftp.ncbi.nlm.nih.gov/geo/series/GSE218nnn/GSE218661/suppl/GSE218661_adata_head_S_v1.0.h5ad.gz")
648
+ print("๐ŸŒ Body: https://ftp.ncbi.nlm.nih.gov/geo/series/GSE218nnn/GSE218661/suppl/GSE218661_adata_body_S_v1.0.h5ad.gz")
649
+ else:
650
+ print(f"โœ… Successfully downloaded h5ad files")
651
+
652
+ if h5ad_info.get('files_processed'):
653
+ print(f"โœ… Successfully processed {len(h5ad_info['files_processed'])} h5ad files")
654
+
655
+ # Show tissue breakdown
656
+ tissues = {}
657
+ for filename, info in h5ad_info['files_processed'].items():
658
+ tissue = info.get('tissue_type', 'unknown')
659
+ if tissue not in tissues:
660
+ tissues[tissue] = {'files': 0, 'cells': 0}
661
+ tissues[tissue]['files'] += 1
662
+ tissues[tissue]['cells'] += info.get('n_obs', 0)
663
+
664
+ print(f"\n๐Ÿ“Š Tissue Breakdown:")
665
+ for tissue, stats in tissues.items():
666
+ print(f" ๐Ÿงฌ {tissue.title()}: {stats['files']} files, {stats['cells']:,} cells")
667
+ else:
668
+ print(f"โš ๏ธ No h5ad files found or processed")
669
+ print(" Files may need to be downloaded manually or decompressed")
670
+
671
+ print(f"\n๐ŸŽฏ NEXT STEPS:")
672
+ print(" 1. Verify h5ad files were downloaded successfully")
673
+ print(" 2. Check data/raw/supplementary/ for .h5ad.gz files")
674
+ print(" 3. Run this script again to process downloaded files")
675
+ print(" 4. Run 02_data_exploration.py to analyze the data")
676
+ print(" 5. Visit AFCA web portal for interactive exploration")
677
+
678
+ print(f"\n๐Ÿ’พ All metadata saved to: {dirs['metadata']}")
679
+ print("๐Ÿš€ Ready for data exploration phase!")
680
+
681
+ if __name__ == "__main__":
682
+ main()