File size: 27,092 Bytes
f88156f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "aa4624dc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:30.497571Z",
     "iopub.status.busy": "2025-03-25T07:02:30.497472Z",
     "iopub.status.idle": "2025-03-25T07:02:30.657928Z",
     "shell.execute_reply": "2025-03-25T07:02:30.657589Z"
    }
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n",
    "\n",
    "# Path Configuration\n",
    "from tools.preprocess import *\n",
    "\n",
    "# Processing context\n",
    "trait = \"Breast_Cancer\"\n",
    "cohort = \"GSE249377\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Breast_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Breast_Cancer/GSE249377\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Breast_Cancer/GSE249377.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/GSE249377.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/GSE249377.csv\"\n",
    "json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d0646da5",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2b785d56",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:30.659281Z",
     "iopub.status.busy": "2025-03-25T07:02:30.659137Z",
     "iopub.status.idle": "2025-03-25T07:02:30.843342Z",
     "shell.execute_reply": "2025-03-25T07:02:30.843008Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Exploring the Effects of Experimental Parameters and Data Modeling Approaches on In Vitro Transcriptomic Point-of-Departure Estimates\"\n",
      "!Series_summary\t\"Multiple new approach methods (NAMs) are being developed to rapidly screen large numbers of chemicals to aid in hazard evaluation and risk assessments. High-throughput transcriptomics (HTTr) in human cell lines has been proposed as a first-tier screening approach for determining the types of bioactivity a chemical can cause (activation of specific targets vs. generalized cell stress) and for calculating transcriptional points of departure (tPODs) based on changes in gene expression. In the present study, we examine a range of computational methods to calculate tPODs from HTTr data, using six data sets in which MCF7 cells cultured in two different media formulations were treated with a panel of 44 chemicals for 3 different exposure durations (6, 12, 24 hr).\"\n",
      "!Series_overall_design\t\"Multiple computational approaches for determining tPODs are compared using six HTTr datasets, all generated from a single cell type (MCF7, a breast cancer cell line), but using three different exposure durations and with two different media formulations. Each dataset included 44 chemicals in an eight-point concentration-response.  We previously published a subset of these data (GSE162855) corresponding to one exposure time (6 hrs) and media formulation (DMEM + 10% HI-FBS). In the current study we incorporate additional data for all 5 additional combinations of exposure times (6, 12, and 24 hrs) and media formulations (DMEM + either 10% HI-FBS or 10% charcoal-stripped FBS), and compare results across a broader set of computational approaches for determining an overall transcriptomic point of departure (tPOD) for each chemical.\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['cell line: NA', 'cell line: MCF7'], 1: ['media: NA', 'media: DMEM + 10% HI-FBS', 'media: DMEM + 10% charcoal-stripped FBS'], 2: ['treatment: untreated', 'treatment: 12h exposure of 0.03 uM of Fulvestrant', 'treatment: 12h exposure of 0.3 uM of Atrazine', 'treatment: 12h exposure of 0.3 uM of Butafenacil', 'treatment: 12h exposure of 0.1 uM of Propiconazole', 'treatment: 12h exposure of 1 uM of Tetrac', 'treatment: 12h exposure of 0.3 uM of Cladribine', 'treatment: 12h exposure of 30 uM of Lovastatin', 'treatment: 12h exposure of 0.3 uM of 4-Hydroxytamoxifen', 'treatment: 12h exposure of 3 uM of Butafenacil', 'treatment: 12h exposure of 3 uM of Cypermethrin', 'treatment: 12h exposure of 100 uM of Bifenthrin', 'treatment: 12h exposure of 1 uM of Fulvestrant', 'treatment: 12h exposure of 0.3 uM of Prochloraz', 'treatment: 12h exposure of 1 uM of Reserpine', 'treatment: 12h exposure of 100 uM of Butafenacil', 'treatment: 12h exposure of 10 uM of Amiodarone hydrochloride', 'treatment: 12h exposure of 100 uM of Fomesafen', 'treatment: 12h exposure of 1 uM of Lactofen', 'treatment: 12h exposure of 3 uM of Cladribine', 'treatment: 12h exposure of 0.1 uM of Maneb', 'treatment: 12h exposure of 0.1 uM of Cycloheximide', 'treatment: 12h exposure of 100 uM of Bisphenol B', 'treatment: 12h exposure of 0.3 uM of Clofibrate', 'treatment: 12h exposure of 0.03 uM of Thiram', 'treatment: 12h exposure of 0.3 uM of PFOA', 'treatment: 12h exposure of 100 uM of Simazine', 'treatment: 12h exposure of 0.03 uM of Prochloraz', 'treatment: 12h exposure of 100 uM of Amiodarone hydrochloride', 'treatment: 12h exposure of 0.1 uM of Cyproterone acetate'], 3: ['chemical name: NA', 'chemical name: Fulvestrant', 'chemical name: Atrazine', 'chemical name: Butafenacil', 'chemical name: Propiconazole', 'chemical name: Tetrac', 'chemical name: Cladribine', 'chemical name: Lovastatin', 'chemical name: 4-Hydroxytamoxifen', 'chemical name: Cypermethrin', 'chemical name: Bifenthrin', 'chemical name: Prochloraz', 'chemical name: Reserpine', 'chemical name: Amiodarone hydrochloride', 'chemical name: Fomesafen', 'chemical name: Lactofen', 'chemical name: Maneb', 'chemical name: Cycloheximide', 'chemical name: Bisphenol B', 'chemical name: Clofibrate', 'chemical name: Thiram', 'chemical name: PFOA', 'chemical name: Simazine', 'chemical name: Cyproterone acetate', 'chemical name: Cyproconazole', 'chemical name: Vinclozolin', 'chemical name: 4-Nonylphenol, branched', 'chemical name: Fenofibrate', 'chemical name: Troglitazone', 'chemical name: Farglitazar'], 4: ['chemical sample id: NA', 'chemical sample id: TP0001651F04', 'chemical sample id: TP0001651E05', 'chemical sample id: TP0001651A03', 'chemical sample id: TP0001651B04', 'chemical sample id: TP0001651F01', 'chemical sample id: TP0001651G04', 'chemical sample id: TP0001651G02', 'chemical sample id: TP0001651C02', 'chemical sample id: TP0001651D03', 'chemical sample id: TP0001651E01', 'chemical sample id: TP0001651E03', 'chemical sample id: TP0001651B03', 'chemical sample id: TP0001651B05', 'chemical sample id: TP0001651H03', 'chemical sample id: TP0001651D01', 'chemical sample id: TP0001651H02', 'chemical sample id: TP0001651C06', 'chemical sample id: TP0001651C05', 'chemical sample id: TP0001651D04', 'chemical sample id: TP0001651D05', 'chemical sample id: TP0001651D02', 'chemical sample id: TP0001651C03', 'chemical sample id: TP0001651G05', 'chemical sample id: TP0001651A06', 'chemical sample id: TP0001651G01', 'chemical sample id: TP0001651E02', 'chemical sample id: TP0001651F05', 'chemical sample id: TP0001651B06', 'chemical sample id: TP0001651E04'], 5: ['chemical concentration: NA', 'chemical concentration: 0.03 uM', 'chemical concentration: 0.3 uM', 'chemical concentration: 0.1 uM', 'chemical concentration: 1 uM', 'chemical concentration: 30 uM', 'chemical concentration: 3 uM', 'chemical concentration: 100 uM', 'chemical concentration: 10 uM', 'chemical concentration: 0 uM'], 6: ['dose level: NA', 'dose level: 1', 'dose level: 3', 'dose level: 2', 'dose level: 4', 'dose level: 7', 'dose level: 5', 'dose level: 8', 'dose level: 6', 'dose level: 0'], 7: ['exposure time: NA', 'exposure time: 12h', 'exposure time: 24h', 'exposure time: 6h'], 8: ['assay plate: TC00283154', 'assay plate: TC00283157', 'assay plate: TC00283174', 'assay plate: TC00283179', 'assay plate: TC00283182', 'assay plate: TC00283185', 'assay plate: TC00283191', 'assay plate: TC00283197', 'assay plate: TC00283200', 'assay plate: TC00283203', 'assay plate: TC00283212', 'assay plate: TC00283215', 'assay plate: TC00283221', 'assay plate: TC00283224', 'assay plate: TC00283227'], 9: ['assay plate well: A01', 'assay plate well: A02', 'assay plate well: A03', 'assay plate well: A04', 'assay plate well: A05', 'assay plate well: A06', 'assay plate well: A07', 'assay plate well: A08', 'assay plate well: A09', 'assay plate well: A10', 'assay plate well: A11', 'assay plate well: A12', 'assay plate well: A13', 'assay plate well: A14', 'assay plate well: A15', 'assay plate well: A16', 'assay plate well: A17', 'assay plate well: A18', 'assay plate well: A19', 'assay plate well: A20', 'assay plate well: A21', 'assay plate well: A22', 'assay plate well: A23', 'assay plate well: A24', 'assay plate well: B01', 'assay plate well: B02', 'assay plate well: B03', 'assay plate well: B04', 'assay plate well: B05', 'assay plate well: B06']}\n"
     ]
    }
   ],
   "source": [
    "from tools.preprocess import *\n",
    "# 1. Identify the paths to the SOFT file and the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# 2. Read the matrix file to obtain background information and sample characteristics data\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n",
    "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n",
    "\n",
    "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n",
    "print(\"Background Information:\")\n",
    "print(background_info)\n",
    "print(\"Sample Characteristics Dictionary:\")\n",
    "print(sample_characteristics_dict)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dcc403da",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b27da8b9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:30.844593Z",
     "iopub.status.busy": "2025-03-25T07:02:30.844486Z",
     "iopub.status.idle": "2025-03-25T07:02:30.850704Z",
     "shell.execute_reply": "2025-03-25T07:02:30.850430Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# From the Series summary and overall design, this dataset appears to contain gene expression data\n",
    "# from high-throughput transcriptomics (HTTr) experiments in MCF7 cells\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "# 2.1 Data Availability\n",
    "# There is no explicit trait (breast cancer) information in the sample characteristics\n",
    "# The MCF7 cell line is a breast cancer cell line, but this is a constant across all samples\n",
    "trait_row = None  # No trait variable is available\n",
    "\n",
    "# Age is not available in this dataset as it's a cell line study\n",
    "age_row = None\n",
    "\n",
    "# No gender information is available as this is a cell line study\n",
    "gender_row = None\n",
    "\n",
    "# Define conversion functions for trait data (even though not used in this case)\n",
    "def convert_trait(value):\n",
    "    # Not used in this dataset, but required for the function signature\n",
    "    if value is None or 'NA' in value:\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    return 1 if value.lower() == 'yes' else 0\n",
    "\n",
    "def convert_age(value):\n",
    "    # Not used in this dataset\n",
    "    if value is None or 'NA' in value:\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    try:\n",
    "        return float(value)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    # Not used in this dataset\n",
    "    if value is None or 'NA' in value:\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    return 1 if value.lower() in ['male', 'm'] else 0 if value.lower() in ['female', 'f'] else None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Trait data is not available as trait_row is None\n",
    "is_trait_available = trait_row is not None\n",
    "validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
    "                             is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n",
    "\n",
    "# 4. Clinical Feature Extraction\n",
    "# Skip this step since trait_row is None (no clinical data is available as determined above)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fadacbb2",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "bc7f47fd",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:30.851758Z",
     "iopub.status.busy": "2025-03-25T07:02:30.851657Z",
     "iopub.status.idle": "2025-03-25T07:02:30.858877Z",
     "shell.execute_reply": "2025-03-25T07:02:30.858601Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/Breast_Cancer/GSE249377/GSE249377_family.soft.gz\n",
      "Matrix file: ../../input/GEO/Breast_Cancer/GSE249377/GSE249377_series_matrix.txt.gz\n",
      "Examining matrix file content...\n",
      "Line 0: !Series_title\t\"Exploring the Effects of Experimental Parameters and Data Modeling Approaches on In V...\n",
      "Error examining file: unsupported operand type(s) for +: 'NoneType' and 'int'\n",
      "Gene expression data could not be successfully extracted from this dataset.\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the paths to the SOFT file and the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"SOFT file: {soft_file}\")\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Set gene availability flag\n",
    "is_gene_available = True  # Initially assume gene data is available\n",
    "\n",
    "# First check if the matrix file contains the expected marker and examine file content\n",
    "print(\"Examining matrix file content...\")\n",
    "marker_row = None\n",
    "sample_lines = []\n",
    "\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        for i, line in enumerate(file):\n",
    "            # Store marker position if found\n",
    "            if \"!series_matrix_table_begin\" in line:\n",
    "                marker_row = i\n",
    "                print(f\"Found matrix table marker at line {i}\")\n",
    "            \n",
    "            # Store lines around the marker for inspection\n",
    "            if marker_row is not None and i >= marker_row and i < marker_row + 10:\n",
    "                sample_lines.append(line.strip())\n",
    "            \n",
    "            # Also capture some lines from the beginning\n",
    "            if i < 10:\n",
    "                print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "            \n",
    "            # Don't read the entire file\n",
    "            if i > marker_row + 20 and marker_row is not None:\n",
    "                break\n",
    "            if i > 100 and marker_row is None:\n",
    "                break\n",
    "\n",
    "    if marker_row is not None:\n",
    "        print(\"\\nLines immediately after the marker:\")\n",
    "        for i, line in enumerate(sample_lines):\n",
    "            print(f\"Line {marker_row + i}: {line[:100]}...\")\n",
    "        \n",
    "        # Try a more manual approach to extract the data\n",
    "        data_lines = []\n",
    "        gene_ids = []\n",
    "        with gzip.open(matrix_file, 'rt') as file:\n",
    "            for i, line in enumerate(file):\n",
    "                if i <= marker_row:  # Skip until after the marker\n",
    "                    continue\n",
    "                if line.startswith('!'):  # Skip any remaining comment lines\n",
    "                    continue\n",
    "                if not line.strip():  # Skip empty lines\n",
    "                    continue\n",
    "                \n",
    "                # Found a data line\n",
    "                if i == marker_row + 1:  # This should be the header line\n",
    "                    headers = line.strip().split('\\t')\n",
    "                    print(f\"Found headers: {headers[:5]}... (total: {len(headers)})\")\n",
    "                else:\n",
    "                    parts = line.strip().split('\\t')\n",
    "                    if len(parts) > 1:  # Ensure it's a valid data line\n",
    "                        gene_ids.append(parts[0])\n",
    "                        data_lines.append(parts)\n",
    "\n",
    "                # Don't process too many lines for this test\n",
    "                if len(data_lines) > 100:\n",
    "                    break\n",
    "        \n",
    "        if len(data_lines) > 0:\n",
    "            print(f\"Successfully parsed {len(data_lines)} data lines manually\")\n",
    "            print(f\"First few gene IDs: {gene_ids[:10]}\")\n",
    "            \n",
    "            # Now try the proper extraction\n",
    "            try:\n",
    "                # Try using the library function\n",
    "                gene_data = get_genetic_data(matrix_file)\n",
    "                \n",
    "                if len(gene_data) > 0:\n",
    "                    print(f\"Successfully extracted gene data with shape: {gene_data.shape}\")\n",
    "                    print(\"First 20 gene/probe identifiers:\")\n",
    "                    print(gene_data.index[:20].tolist())\n",
    "                else:\n",
    "                    # If the library function fails, try direct pandas method\n",
    "                    print(\"Library function returned empty data, trying direct pandas method...\")\n",
    "                    gene_data = pd.read_csv(matrix_file, compression='gzip', \n",
    "                                            skiprows=marker_row+1, \n",
    "                                            header=0, \n",
    "                                            sep='\\t', \n",
    "                                            on_bad_lines='skip')\n",
    "                    \n",
    "                    if len(gene_data) > 0:\n",
    "                        id_col = gene_data.columns[0]\n",
    "                        gene_data = gene_data.rename(columns={id_col: 'ID'})\n",
    "                        gene_data.set_index('ID', inplace=True)\n",
    "                        print(f\"Successfully extracted gene data with shape: {gene_data.shape}\")\n",
    "                        print(\"First 20 gene/probe identifiers:\")\n",
    "                        print(gene_data.index[:20].tolist())\n",
    "                    else:\n",
    "                        print(\"Still couldn't extract gene data using pandas.\")\n",
    "                        is_gene_available = False\n",
    "            except Exception as e:\n",
    "                print(f\"Error extracting gene data with standard methods: {e}\")\n",
    "                is_gene_available = False\n",
    "        else:\n",
    "            print(\"No data lines found after the marker\")\n",
    "            is_gene_available = False\n",
    "    else:\n",
    "        print(\"Could not find '!series_matrix_table_begin' marker in the file.\")\n",
    "        is_gene_available = False\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error examining file: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "if not is_gene_available:\n",
    "    print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
    "    # Update the validation record since gene data isn't available\n",
    "    is_trait_available = trait_row is not None\n",
    "    validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
    "                                 is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "060908d5",
   "metadata": {},
   "source": [
    "### Step 4: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ab92883a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:02:30.859849Z",
     "iopub.status.busy": "2025-03-25T07:02:30.859748Z",
     "iopub.status.idle": "2025-03-25T07:02:31.808420Z",
     "shell.execute_reply": "2025-03-25T07:02:31.807759Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SOFT file: ../../input/GEO/Breast_Cancer/GSE249377/GSE249377_family.soft.gz\n",
      "Matrix file: ../../input/GEO/Breast_Cancer/GSE249377/GSE249377_series_matrix.txt.gz\n",
      "Found the matrix table marker at line 84\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Warning: Extracted gene data has 0 rows.\n",
      "Examining file content to diagnose the issue:\n",
      "Line 82: !Sample_relation\t\"SRA: https://www.ncbi.nlm.nih.gov/sra?term=SRX22782419\"\t\"SRA: https://www.ncbi.nlm...\n",
      "Line 83: !Sample_supplementary_file_1\t\"NONE\"\t\"NONE\"\t\"NONE\"\t\"NONE\"\t\"NONE\"\t\"NONE\"\t\"NONE\"\t\"NONE\"\t\"NONE\"\t\"NONE\"\t\"...\n",
      "Line 84: !series_matrix_table_begin...\n",
      "Line 85: \"ID_REF\"\t\"GSM7937728\"\t\"GSM7937729\"\t\"GSM7937730\"\t\"GSM7937731\"\t\"GSM7937732\"\t\"GSM7937733\"\t\"GSM7937734\"\t...\n",
      "Line 86: !series_matrix_table_end...\n",
      "Gene expression data could not be successfully extracted from this dataset.\n"
     ]
    }
   ],
   "source": [
    "# 1. Identify the paths to the SOFT file and the matrix file\n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"SOFT file: {soft_file}\")\n",
    "print(f\"Matrix file: {matrix_file}\")\n",
    "\n",
    "# Set gene availability flag\n",
    "is_gene_available = True  # Initially assume gene data is available\n",
    "\n",
    "# First check if the matrix file contains the expected marker\n",
    "found_marker = False\n",
    "marker_row = None\n",
    "try:\n",
    "    with gzip.open(matrix_file, 'rt') as file:\n",
    "        for i, line in enumerate(file):\n",
    "            if \"!series_matrix_table_begin\" in line:\n",
    "                found_marker = True\n",
    "                marker_row = i\n",
    "                print(f\"Found the matrix table marker at line {i}\")\n",
    "                break\n",
    "    \n",
    "    if not found_marker:\n",
    "        print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
    "        is_gene_available = False\n",
    "        \n",
    "    # If marker was found, try to extract gene data\n",
    "    if is_gene_available:\n",
    "        try:\n",
    "            # Try using the library function\n",
    "            gene_data = get_genetic_data(matrix_file)\n",
    "            \n",
    "            if gene_data.shape[0] == 0:\n",
    "                print(\"Warning: Extracted gene data has 0 rows.\")\n",
    "                is_gene_available = False\n",
    "            else:\n",
    "                print(f\"Gene data shape: {gene_data.shape}\")\n",
    "                # Print the first 20 gene/probe identifiers\n",
    "                print(\"First 20 gene/probe identifiers:\")\n",
    "                print(gene_data.index[:20].tolist())\n",
    "        except Exception as e:\n",
    "            print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
    "            is_gene_available = False\n",
    "    \n",
    "    # If gene data extraction failed, examine file content to diagnose\n",
    "    if not is_gene_available:\n",
    "        print(\"Examining file content to diagnose the issue:\")\n",
    "        try:\n",
    "            with gzip.open(matrix_file, 'rt') as file:\n",
    "                # Print lines around the marker if found\n",
    "                if marker_row is not None:\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i >= marker_row - 2 and i <= marker_row + 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        if i > marker_row + 10:\n",
    "                            break\n",
    "                else:\n",
    "                    # If marker not found, print first 10 lines\n",
    "                    for i, line in enumerate(file):\n",
    "                        if i < 10:\n",
    "                            print(f\"Line {i}: {line.strip()[:100]}...\")\n",
    "                        else:\n",
    "                            break\n",
    "        except Exception as e2:\n",
    "            print(f\"Error examining file: {e2}\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing file: {e}\")\n",
    "    is_gene_available = False\n",
    "\n",
    "# Update validation information if gene data extraction failed\n",
    "if not is_gene_available:\n",
    "    print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
    "    # Update the validation record since gene data isn't available\n",
    "    is_trait_available = False  # We already determined trait data isn't available in step 2\n",
    "    validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
    "                                 is_gene_available=is_gene_available, is_trait_available=is_trait_available)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}