File size: 31,937 Bytes
92d2f89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "115d3272",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:07:29.587579Z",
     "iopub.status.busy": "2025-03-25T07:07:29.587474Z",
     "iopub.status.idle": "2025-03-25T07:07:29.748916Z",
     "shell.execute_reply": "2025-03-25T07:07:29.748581Z"
    }
   },
   "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 = \"Cardiovascular_Disease\"\n",
    "cohort = \"GSE256539\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Cardiovascular_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Cardiovascular_Disease/GSE256539\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Cardiovascular_Disease/GSE256539.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Cardiovascular_Disease/gene_data/GSE256539.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE256539.csv\"\n",
    "json_path = \"../../output/preprocess/Cardiovascular_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d625d2e",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f029f5ac",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:07:29.750299Z",
     "iopub.status.busy": "2025-03-25T07:07:29.750156Z",
     "iopub.status.idle": "2025-03-25T07:07:29.873251Z",
     "shell.execute_reply": "2025-03-25T07:07:29.872887Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Background Information:\n",
      "!Series_title\t\"Digital Spatial Profiling identifies distinct molecular signatures of vascular lesions in Pulmonary Arterial Hypertension\"\n",
      "!Series_summary\t\"Idiopathic Pulmonary Arterial Hypertension (IPAH) is a severe human disease, characterized by extensive pulmonary vascular remodeling due to plexiform and obliterative lesions, media hypertrophy, and alterations of adventitia. The objective of the study was to test the hypothesis that microscopic IPAH vascular lesions express unique molecular profiles, which collectively are different from control pulmonary arteries. We used digital spatial transcriptomics to profile the genome-wide differential transcriptomic signature of key pathological lesions (plexiform, obliterative, intima+media hypertrophy, and adventitia) in IPAH lungs (n= 11)  and compared these data to the intima+media and adventitia of control pulmonary artery (n=5). The IPAH lesions and pulmonary artery compartments were defined by the analyses of hematoxylin-eosin stained serial section, aided by labeling with CD31 (for endothelial cells), smooth muscle cell actin (SMA), and CD45 for inflammatory mononuclear cells, also in serial sections. Approximately 12 regions of interest (ROI) were sampled from a histological section of a paraffin-embedded block of each lung, which was selected based on the finding of enrichment for IPAH lesions or control pulmonary arteries. \"\n",
      "!Series_overall_design\t\"A total of 211 ROIs were studied with 149 ROIs representing IPAH lesions with 39 plexiform lesions, 37 obliterative lesions, 36 intima+media hypertrophy, and 37 IPAH adventitia; of 62 ROIs of control lungs, including 34 intima+media and 28 control adventitia. The ROIs were selected largely based on the histopathological identification of each type of lesion (in IPAH lungs) or control pulmonary artery compartments. The selected ROIs were then processed by the GeoMx Nanostring platform, followed by whole genome sequencing.\"\n",
      "!Series_overall_design\t\"\"\n",
      "!Series_overall_design\t\"*** FASTQ raw data files have been requested. ***\"\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['individuial: AH006', 'individuial: AH015', 'individuial: UA013', 'individuial: BA023', 'individuial: BA009', 'individuial: AH014', 'individuial: VA008', 'individuial: UC010', 'individuial: UC007', 'individuial: AH001', 'individuial: VA010', 'individuial: UA005', 'individuial: BA035', 'individuial: CC016', 'individuial: BA021', 'individuial: UM003'], 1: ['batch: plate3', 'batch: plate2', 'batch: plate1', 'batch: hWTA_20210810T192_DSP-1012340068802']}\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": "e8b17af6",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6807228b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:07:29.874498Z",
     "iopub.status.busy": "2025-03-25T07:07:29.874385Z",
     "iopub.status.idle": "2025-03-25T07:07:29.889167Z",
     "shell.execute_reply": "2025-03-25T07:07:29.888876Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Clinical Features Preview:\n",
      "{'GSM8105899': [1.0], 'GSM8105900': [1.0], 'GSM8105901': [1.0], 'GSM8105902': [1.0], 'GSM8105903': [1.0], 'GSM8105904': [1.0], 'GSM8105905': [1.0], 'GSM8105906': [1.0], 'GSM8105907': [1.0], 'GSM8105908': [1.0], 'GSM8105909': [1.0], 'GSM8105910': [1.0], 'GSM8105911': [1.0], 'GSM8105912': [1.0], 'GSM8105913': [1.0], 'GSM8105914': [1.0], 'GSM8105915': [1.0], 'GSM8105916': [1.0], 'GSM8105917': [1.0], 'GSM8105918': [1.0], 'GSM8105919': [1.0], 'GSM8105920': [1.0], 'GSM8105921': [1.0], 'GSM8105922': [1.0], 'GSM8105923': [1.0], 'GSM8105924': [1.0], 'GSM8105925': [1.0], 'GSM8105926': [1.0], 'GSM8105927': [1.0], 'GSM8105928': [1.0], 'GSM8105929': [1.0], 'GSM8105930': [1.0], 'GSM8105931': [1.0], 'GSM8105932': [1.0], 'GSM8105933': [1.0], 'GSM8105934': [1.0], 'GSM8105935': [1.0], 'GSM8105936': [1.0], 'GSM8105937': [1.0], 'GSM8105938': [1.0], 'GSM8105939': [1.0], 'GSM8105940': [1.0], 'GSM8105941': [1.0], 'GSM8105942': [1.0], 'GSM8105943': [1.0], 'GSM8105944': [1.0], 'GSM8105945': [1.0], 'GSM8105946': [1.0], 'GSM8105947': [1.0], 'GSM8105948': [1.0], 'GSM8105949': [1.0], 'GSM8105950': [1.0], 'GSM8105951': [1.0], 'GSM8105952': [1.0], 'GSM8105953': [1.0], 'GSM8105954': [1.0], 'GSM8105955': [1.0], 'GSM8105956': [1.0], 'GSM8105957': [1.0], 'GSM8105958': [1.0], 'GSM8105959': [1.0], 'GSM8105960': [1.0], 'GSM8105961': [1.0], 'GSM8105962': [1.0], 'GSM8105963': [1.0], 'GSM8105964': [1.0], 'GSM8105965': [1.0], 'GSM8105966': [1.0], 'GSM8105967': [1.0], 'GSM8105968': [1.0], 'GSM8105969': [1.0], 'GSM8105970': [1.0], 'GSM8105971': [1.0], 'GSM8105972': [1.0], 'GSM8105973': [1.0], 'GSM8105974': [1.0], 'GSM8105975': [1.0], 'GSM8105976': [1.0], 'GSM8105977': [1.0], 'GSM8105978': [1.0], 'GSM8105979': [1.0], 'GSM8105980': [1.0], 'GSM8105981': [1.0], 'GSM8105982': [1.0], 'GSM8105983': [1.0], 'GSM8105984': [1.0], 'GSM8105985': [1.0], 'GSM8105986': [1.0], 'GSM8105987': [1.0], 'GSM8105988': [1.0], 'GSM8105989': [1.0], 'GSM8105990': [1.0], 'GSM8105991': [1.0], 'GSM8105992': [1.0], 'GSM8105993': [1.0], 'GSM8105994': [1.0], 'GSM8105995': [1.0], 'GSM8105996': [1.0], 'GSM8105997': [1.0], 'GSM8105998': [1.0], 'GSM8105999': [1.0], 'GSM8106000': [1.0], 'GSM8106001': [1.0], 'GSM8106002': [1.0], 'GSM8106003': [1.0], 'GSM8106004': [1.0], 'GSM8106005': [1.0], 'GSM8106006': [1.0], 'GSM8106007': [1.0], 'GSM8106008': [1.0], 'GSM8106009': [1.0], 'GSM8106010': [1.0], 'GSM8106011': [1.0], 'GSM8106012': [1.0], 'GSM8106013': [1.0], 'GSM8106014': [1.0], 'GSM8106015': [1.0], 'GSM8106016': [1.0], 'GSM8106017': [1.0], 'GSM8106018': [1.0], 'GSM8106019': [1.0], 'GSM8106020': [1.0], 'GSM8106021': [1.0], 'GSM8106022': [1.0], 'GSM8106023': [1.0], 'GSM8106024': [1.0], 'GSM8106025': [1.0], 'GSM8106026': [1.0], 'GSM8106027': [1.0], 'GSM8106028': [1.0], 'GSM8106029': [1.0], 'GSM8106030': [1.0], 'GSM8106031': [1.0], 'GSM8106032': [1.0], 'GSM8106033': [1.0], 'GSM8106034': [1.0], 'GSM8106035': [1.0], 'GSM8106036': [1.0], 'GSM8106037': [1.0], 'GSM8106038': [1.0], 'GSM8106039': [1.0], 'GSM8106040': [1.0], 'GSM8106041': [1.0], 'GSM8106042': [1.0], 'GSM8106043': [1.0], 'GSM8106044': [1.0], 'GSM8106045': [1.0], 'GSM8106046': [1.0], 'GSM8106047': [1.0], 'GSM8106048': [1.0], 'GSM8106049': [1.0], 'GSM8106050': [1.0], 'GSM8106051': [1.0], 'GSM8106052': [1.0], 'GSM8106053': [1.0], 'GSM8106054': [1.0], 'GSM8106055': [1.0], 'GSM8106056': [1.0], 'GSM8106057': [1.0], 'GSM8106058': [1.0], 'GSM8106059': [0.0], 'GSM8106060': [0.0], 'GSM8106061': [0.0], 'GSM8106062': [0.0], 'GSM8106063': [0.0], 'GSM8106064': [0.0], 'GSM8106065': [0.0], 'GSM8106066': [0.0], 'GSM8106067': [0.0], 'GSM8106068': [0.0], 'GSM8106069': [0.0], 'GSM8106070': [0.0], 'GSM8106071': [1.0], 'GSM8106072': [1.0], 'GSM8106073': [1.0], 'GSM8106074': [1.0], 'GSM8106075': [1.0], 'GSM8106076': [1.0], 'GSM8106077': [1.0], 'GSM8106078': [1.0], 'GSM8106079': [1.0], 'GSM8106080': [1.0], 'GSM8106081': [1.0], 'GSM8106082': [1.0], 'GSM8106083': [1.0], 'GSM8106084': [1.0], 'GSM8106085': [1.0], 'GSM8106086': [1.0], 'GSM8106087': [1.0], 'GSM8106088': [1.0], 'GSM8106089': [1.0], 'GSM8106090': [1.0], 'GSM8106091': [1.0], 'GSM8106092': [1.0], 'GSM8106093': [1.0], 'GSM8106094': [1.0], 'GSM8106095': [1.0], 'GSM8106096': [1.0], 'GSM8106097': [1.0], 'GSM8106098': [1.0]}\n",
      "Clinical features saved to ../../output/preprocess/Cardiovascular_Disease/clinical_data/GSE256539.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Availability assessment based on background information\n",
    "\n",
    "# This is a gene expression profiling study using digital spatial transcriptomics\n",
    "# The study mentions \"genome-wide differential transcriptomic signature\"\n",
    "# This clearly indicates gene expression data is available\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Clinical feature extraction and conversion functions\n",
    "\n",
    "# From sample characteristics, we need to analyze what data is available\n",
    "# The dictionary shows 'individual' IDs and 'batch' information, but not disease status directly\n",
    "# From the background information, we know this is a case-control study of IPAH vs controls\n",
    "\n",
    "# 2.1 Determine row numbers for clinical features\n",
    "# Looking at the sample characteristics, we can infer trait information from individual IDs\n",
    "trait_row = 0  # We'll infer disease status from individual IDs\n",
    "\n",
    "# Age and gender information are not provided in the sample characteristics\n",
    "age_row = None  # Age data not available\n",
    "gender_row = None  # Gender data not available\n",
    "\n",
    "# 2.2 Define conversion functions for clinical features\n",
    "\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert individual IDs to binary trait values.\n",
    "    Based on the background information, we can infer:\n",
    "    - IPAH patients have IDs with patterns like AH*, VA*, UC*, etc.\n",
    "    - Control samples have IDs with patterns like CC*\n",
    "    \n",
    "    Returns:\n",
    "    - 1 for IPAH cases\n",
    "    - 0 for controls\n",
    "    - None for unclear cases\n",
    "    \"\"\"\n",
    "    if ':' in value:\n",
    "        # Extract the value after the colon and strip whitespace\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Based on the background, control subjects would be in the control pulmonary artery group\n",
    "    # The IDs \"CC*\" appear to be controls based on context and naming convention\n",
    "    if value.startswith('CC'):\n",
    "        return 0  # Control\n",
    "    else:\n",
    "        return 1  # IPAH case\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"\n",
    "    Convert age values to continuous numerical values.\n",
    "    Not implemented as age data is not available.\n",
    "    \"\"\"\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"\n",
    "    Convert gender values to binary (0 for female, 1 for male).\n",
    "    Not implemented as gender data is not available.\n",
    "    \"\"\"\n",
    "    return None\n",
    "\n",
    "# 3. Save initial metadata about dataset usability\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "validate_and_save_cohort_info(\n",
    "    is_final=False,\n",
    "    cohort=cohort,\n",
    "    info_path=json_path,\n",
    "    is_gene_available=is_gene_available,\n",
    "    is_trait_available=is_trait_available\n",
    ")\n",
    "\n",
    "# 4. Extract clinical features if available\n",
    "if trait_row is not None:\n",
    "    # This assumes clinical_data is provided by previous steps\n",
    "    try:\n",
    "        # Load clinical data (this should have been done in previous steps)\n",
    "        # Let's ensure it's available before proceeding\n",
    "        if 'clinical_data' not in locals():\n",
    "            # Try to load from the input directory\n",
    "            clinical_file = os.path.join(in_cohort_dir, \"sample_characteristics.csv\")\n",
    "            if os.path.exists(clinical_file):\n",
    "                clinical_data = pd.read_csv(clinical_file)\n",
    "            else:\n",
    "                # Create from the sample characteristics dictionary if needed\n",
    "                sample_chars_dict = {0: ['individuial: AH006', 'individuial: AH015', 'individuial: UA013', 'individuial: BA023', 'individuial: BA009', 'individuial: AH014', 'individuial: VA008', 'individuial: UC010', 'individuial: UC007', 'individuial: AH001', 'individuial: VA010', 'individuial: UA005', 'individuial: BA035', 'individuial: CC016', 'individuial: BA021', 'individuial: UM003'], \n",
    "                                    1: ['batch: plate3', 'batch: plate2', 'batch: plate1', 'batch: hWTA_20210810T192_DSP-1012340068802']}\n",
    "                clinical_data = pd.DataFrame(sample_chars_dict)\n",
    "        \n",
    "        # Extract clinical features\n",
    "        clinical_features = geo_select_clinical_features(\n",
    "            clinical_df=clinical_data,\n",
    "            trait=trait,\n",
    "            trait_row=trait_row,\n",
    "            convert_trait=convert_trait,\n",
    "            age_row=age_row,\n",
    "            convert_age=convert_age,\n",
    "            gender_row=gender_row,\n",
    "            convert_gender=convert_gender\n",
    "        )\n",
    "        \n",
    "        # Preview and save clinical features\n",
    "        print(\"Clinical Features Preview:\")\n",
    "        print(preview_df(clinical_features))\n",
    "        \n",
    "        # Create directory if it doesn't exist\n",
    "        os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "        \n",
    "        # Save clinical features\n",
    "        clinical_features.to_csv(out_clinical_data_file, index=False)\n",
    "        print(f\"Clinical features saved to {out_clinical_data_file}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error extracting clinical features: {e}\")\n",
    "else:\n",
    "    print(\"Clinical data not available. Skipping clinical feature extraction.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a588583",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "25aeef3b",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:07:29.890249Z",
     "iopub.status.busy": "2025-03-25T07:07:29.890141Z",
     "iopub.status.idle": "2025-03-25T07:07:30.134233Z",
     "shell.execute_reply": "2025-03-25T07:07:30.133891Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Matrix file found: ../../input/GEO/Cardiovascular_Disease/GSE256539/GSE256539_series_matrix.txt.gz\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene data shape: (8273, 220)\n",
      "First 20 gene/probe identifiers:\n",
      "Index(['A2M', 'A4GALT', 'AAAS', 'AACS', 'AAGAB', 'AAK1', 'AAMDC', 'AAMP',\n",
      "       'AARS1', 'AARSD1', 'AATF', 'ABCA10', 'ABCA13', 'ABCA3', 'ABCA6',\n",
      "       'ABCA8', 'ABCB10', 'ABCB9', 'ABCC1', 'ABCC3'],\n",
      "      dtype='object', name='ID')\n"
     ]
    }
   ],
   "source": [
    "# 1. Get the SOFT and matrix file paths again \n",
    "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "print(f\"Matrix file found: {matrix_file}\")\n",
    "\n",
    "# 2. Use the get_genetic_data function from the library to get the gene_data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file)\n",
    "    print(f\"Gene data shape: {gene_data.shape}\")\n",
    "    \n",
    "    # 3. Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89b9c35d",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2077017a",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:07:30.135532Z",
     "iopub.status.busy": "2025-03-25T07:07:30.135411Z",
     "iopub.status.idle": "2025-03-25T07:07:30.137274Z",
     "shell.execute_reply": "2025-03-25T07:07:30.137009Z"
    }
   },
   "outputs": [],
   "source": [
    "# Looking at the gene identifiers in the output, I can see they are already human gene symbols (like A2M, AAAS, ABCC1, etc.)\n",
    "# These are standard HUGO gene symbols, not probe IDs or other identifiers that would need mapping\n",
    "\n",
    "requires_gene_mapping = False\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "428c44c5",
   "metadata": {},
   "source": [
    "### Step 5: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "41986bdc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T07:07:30.138403Z",
     "iopub.status.busy": "2025-03-25T07:07:30.138294Z",
     "iopub.status.idle": "2025-03-25T07:07:36.150465Z",
     "shell.execute_reply": "2025-03-25T07:07:36.150093Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Original gene data shape: (8273, 220)\n",
      "Normalized gene data shape: (8271, 220)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Gene expression data saved to ../../output/preprocess/Cardiovascular_Disease/gene_data/GSE256539.csv\n",
      "Clinical features shape: (1, 220)\n",
      "Clinical features preview:\n",
      "{'GSM8105899': [1.0], 'GSM8105900': [1.0], 'GSM8105901': [1.0], 'GSM8105902': [1.0], 'GSM8105903': [1.0], 'GSM8105904': [1.0], 'GSM8105905': [1.0], 'GSM8105906': [1.0], 'GSM8105907': [1.0], 'GSM8105908': [1.0], 'GSM8105909': [1.0], 'GSM8105910': [1.0], 'GSM8105911': [1.0], 'GSM8105912': [1.0], 'GSM8105913': [1.0], 'GSM8105914': [1.0], 'GSM8105915': [1.0], 'GSM8105916': [1.0], 'GSM8105917': [1.0], 'GSM8105918': [1.0], 'GSM8105919': [1.0], 'GSM8105920': [1.0], 'GSM8105921': [1.0], 'GSM8105922': [1.0], 'GSM8105923': [1.0], 'GSM8105924': [1.0], 'GSM8105925': [1.0], 'GSM8105926': [1.0], 'GSM8105927': [1.0], 'GSM8105928': [1.0], 'GSM8105929': [1.0], 'GSM8105930': [1.0], 'GSM8105931': [1.0], 'GSM8105932': [1.0], 'GSM8105933': [1.0], 'GSM8105934': [1.0], 'GSM8105935': [1.0], 'GSM8105936': [1.0], 'GSM8105937': [1.0], 'GSM8105938': [1.0], 'GSM8105939': [1.0], 'GSM8105940': [1.0], 'GSM8105941': [1.0], 'GSM8105942': [1.0], 'GSM8105943': [1.0], 'GSM8105944': [1.0], 'GSM8105945': [1.0], 'GSM8105946': [1.0], 'GSM8105947': [1.0], 'GSM8105948': [1.0], 'GSM8105949': [1.0], 'GSM8105950': [1.0], 'GSM8105951': [1.0], 'GSM8105952': [1.0], 'GSM8105953': [1.0], 'GSM8105954': [1.0], 'GSM8105955': [1.0], 'GSM8105956': [1.0], 'GSM8105957': [1.0], 'GSM8105958': [1.0], 'GSM8105959': [1.0], 'GSM8105960': [1.0], 'GSM8105961': [1.0], 'GSM8105962': [1.0], 'GSM8105963': [1.0], 'GSM8105964': [1.0], 'GSM8105965': [1.0], 'GSM8105966': [1.0], 'GSM8105967': [1.0], 'GSM8105968': [1.0], 'GSM8105969': [1.0], 'GSM8105970': [1.0], 'GSM8105971': [1.0], 'GSM8105972': [1.0], 'GSM8105973': [1.0], 'GSM8105974': [1.0], 'GSM8105975': [1.0], 'GSM8105976': [1.0], 'GSM8105977': [1.0], 'GSM8105978': [1.0], 'GSM8105979': [1.0], 'GSM8105980': [1.0], 'GSM8105981': [1.0], 'GSM8105982': [1.0], 'GSM8105983': [1.0], 'GSM8105984': [1.0], 'GSM8105985': [1.0], 'GSM8105986': [1.0], 'GSM8105987': [1.0], 'GSM8105988': [1.0], 'GSM8105989': [1.0], 'GSM8105990': [1.0], 'GSM8105991': [1.0], 'GSM8105992': [1.0], 'GSM8105993': [1.0], 'GSM8105994': [1.0], 'GSM8105995': [1.0], 'GSM8105996': [1.0], 'GSM8105997': [1.0], 'GSM8105998': [1.0], 'GSM8105999': [1.0], 'GSM8106000': [1.0], 'GSM8106001': [1.0], 'GSM8106002': [1.0], 'GSM8106003': [1.0], 'GSM8106004': [1.0], 'GSM8106005': [1.0], 'GSM8106006': [1.0], 'GSM8106007': [1.0], 'GSM8106008': [1.0], 'GSM8106009': [1.0], 'GSM8106010': [1.0], 'GSM8106011': [1.0], 'GSM8106012': [1.0], 'GSM8106013': [1.0], 'GSM8106014': [1.0], 'GSM8106015': [1.0], 'GSM8106016': [1.0], 'GSM8106017': [1.0], 'GSM8106018': [1.0], 'GSM8106019': [1.0], 'GSM8106020': [1.0], 'GSM8106021': [1.0], 'GSM8106022': [1.0], 'GSM8106023': [1.0], 'GSM8106024': [1.0], 'GSM8106025': [1.0], 'GSM8106026': [1.0], 'GSM8106027': [1.0], 'GSM8106028': [1.0], 'GSM8106029': [1.0], 'GSM8106030': [1.0], 'GSM8106031': [1.0], 'GSM8106032': [1.0], 'GSM8106033': [1.0], 'GSM8106034': [1.0], 'GSM8106035': [1.0], 'GSM8106036': [1.0], 'GSM8106037': [1.0], 'GSM8106038': [1.0], 'GSM8106039': [1.0], 'GSM8106040': [1.0], 'GSM8106041': [1.0], 'GSM8106042': [1.0], 'GSM8106043': [1.0], 'GSM8106044': [1.0], 'GSM8106045': [1.0], 'GSM8106046': [1.0], 'GSM8106047': [1.0], 'GSM8106048': [1.0], 'GSM8106049': [1.0], 'GSM8106050': [1.0], 'GSM8106051': [1.0], 'GSM8106052': [1.0], 'GSM8106053': [1.0], 'GSM8106054': [1.0], 'GSM8106055': [1.0], 'GSM8106056': [1.0], 'GSM8106057': [1.0], 'GSM8106058': [1.0], 'GSM8106059': [0.0], 'GSM8106060': [0.0], 'GSM8106061': [0.0], 'GSM8106062': [0.0], 'GSM8106063': [0.0], 'GSM8106064': [0.0], 'GSM8106065': [0.0], 'GSM8106066': [0.0], 'GSM8106067': [0.0], 'GSM8106068': [0.0], 'GSM8106069': [0.0], 'GSM8106070': [0.0], 'GSM8106071': [1.0], 'GSM8106072': [1.0], 'GSM8106073': [1.0], 'GSM8106074': [1.0], 'GSM8106075': [1.0], 'GSM8106076': [1.0], 'GSM8106077': [1.0], 'GSM8106078': [1.0], 'GSM8106079': [1.0], 'GSM8106080': [1.0], 'GSM8106081': [1.0], 'GSM8106082': [1.0], 'GSM8106083': [1.0], 'GSM8106084': [1.0], 'GSM8106085': [1.0], 'GSM8106086': [1.0], 'GSM8106087': [1.0], 'GSM8106088': [1.0], 'GSM8106089': [1.0], 'GSM8106090': [1.0], 'GSM8106091': [1.0], 'GSM8106092': [1.0], 'GSM8106093': [1.0], 'GSM8106094': [1.0], 'GSM8106095': [1.0], 'GSM8106096': [1.0], 'GSM8106097': [1.0], 'GSM8106098': [1.0]}\n",
      "Linked data shape: (220, 8272)\n",
      "Linked data preview (first 5 rows, 5 columns):\n",
      "            Cardiovascular_Disease       A2M    A4GALT      AAAS      AACS\n",
      "GSM8105899                     1.0  0.838248 -0.154053 -0.395053 -0.635978\n",
      "GSM8105900                     1.0  0.116291  0.256922 -0.817642 -0.995015\n",
      "GSM8105901                     1.0  0.522361 -0.468963 -0.782454 -0.203852\n",
      "GSM8105902                     1.0 -0.208534 -0.174747 -0.987014 -1.104161\n",
      "GSM8105903                     1.0  0.755866 -0.158793 -1.216798 -0.301321\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data shape after handling missing values: (220, 8272)\n",
      "For the feature 'Cardiovascular_Disease', the least common label is '0.0' with 12 occurrences. This represents 5.45% of the dataset.\n",
      "The distribution of the feature 'Cardiovascular_Disease' in this dataset is fine.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Linked data saved to ../../output/preprocess/Cardiovascular_Disease/GSE256539.csv\n"
     ]
    }
   ],
   "source": [
    "# 1. Normalize gene symbols\n",
    "print(f\"Original gene data shape: {gene_data.shape}\")\n",
    "\n",
    "try:\n",
    "    # Attempt to normalize gene symbols\n",
    "    gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n",
    "    print(f\"Normalized gene data shape: {gene_data_normalized.shape}\")\n",
    "except Exception as e:\n",
    "    print(f\"Gene normalization failed: {e}\")\n",
    "    # If normalization fails, use the original gene data\n",
    "    gene_data_normalized = gene_data.copy()\n",
    "    print(f\"Using original gene data with shape: {gene_data_normalized.shape}\")\n",
    "\n",
    "# Save the gene expression data \n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data_normalized.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Recreate clinical features from scratch\n",
    "def convert_trait(value):\n",
    "    \"\"\"\n",
    "    Convert individual IDs to binary trait values.\n",
    "    Based on the background information:\n",
    "    - IPAH patients have IDs with patterns like AH*, VA*, UC*, etc.\n",
    "    - Control samples have IDs with patterns like CC*\n",
    "    \"\"\"\n",
    "    if ':' in value:\n",
    "        # Extract the value after the colon and strip whitespace\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Based on the background, control subjects would be in the control pulmonary artery group\n",
    "    # The IDs \"CC*\" appear to be controls based on context and naming convention\n",
    "    if value.startswith('CC'):\n",
    "        return 0  # Control\n",
    "    else:\n",
    "        return 1  # IPAH case\n",
    "\n",
    "# Reload clinical data\n",
    "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n",
    "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n",
    "_, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n",
    "\n",
    "try:\n",
    "    # Create clinical features\n",
    "    clinical_features = geo_select_clinical_features(\n",
    "        clinical_df=clinical_data, \n",
    "        trait=trait, \n",
    "        trait_row=0,  # Using individual ID information as identified in Step 2\n",
    "        convert_trait=convert_trait,\n",
    "        age_row=None,  # No age information available\n",
    "        convert_age=None,\n",
    "        gender_row=None,  # No gender information available\n",
    "        convert_gender=None\n",
    "    )\n",
    "    \n",
    "    print(f\"Clinical features shape: {clinical_features.shape}\")\n",
    "    print(\"Clinical features preview:\")\n",
    "    print(preview_df(clinical_features))\n",
    "    \n",
    "    # Save the clinical data\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_features.to_csv(out_clinical_data_file)\n",
    "    \n",
    "    # Check if we have valid clinical data\n",
    "    if clinical_features.isna().all().all():\n",
    "        print(\"Clinical features contain only NaN values. Cannot proceed with linking.\")\n",
    "        raise ValueError(\"No valid clinical data found\")\n",
    "    \n",
    "    # 3. Link clinical and genetic data\n",
    "    linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data_normalized)\n",
    "    print(f\"Linked data shape: {linked_data.shape}\")\n",
    "    print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "    print(linked_data.iloc[:5, :5] if not linked_data.empty else \"Empty DataFrame\")\n",
    "    \n",
    "    # 4. Handle missing values\n",
    "    linked_data_clean = handle_missing_values(linked_data, trait)\n",
    "    print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n",
    "    \n",
    "    # Check if we still have data after handling missing values\n",
    "    if linked_data_clean.shape[0] == 0 or linked_data_clean.shape[1] <= 1:\n",
    "        raise ValueError(\"Dataset is empty after handling missing values\")\n",
    "    \n",
    "    # 5. Check for bias in the dataset\n",
    "    is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n",
    "    \n",
    "    # 6. Conduct final quality validation\n",
    "    is_usable = validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=True,\n",
    "        is_trait_available=True,\n",
    "        is_biased=is_biased,\n",
    "        df=linked_data_clean,\n",
    "        note=\"Dataset contains gene expression data from IPAH (Idiopathic Pulmonary Arterial Hypertension) patients and controls.\"\n",
    "    )\n",
    "    \n",
    "    # 7. Save the linked data if it's usable\n",
    "    if is_usable:\n",
    "        os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "        linked_data_clean.to_csv(out_data_file, index=True)\n",
    "        print(f\"Linked data saved to {out_data_file}\")\n",
    "    else:\n",
    "        print(\"Dataset deemed not usable for associative studies. Linked data not saved.\")\n",
    "\n",
    "except Exception as e:\n",
    "    print(f\"Error in data processing: {e}\")\n",
    "    # Ensure we still validate and record the dataset as not usable\n",
    "    validate_and_save_cohort_info(\n",
    "        is_final=True,\n",
    "        cohort=cohort,\n",
    "        info_path=json_path,\n",
    "        is_gene_available=True,\n",
    "        is_trait_available=False,\n",
    "        is_biased=True,\n",
    "        df=pd.DataFrame(),\n",
    "        note=f\"Processing error: {str(e)}\"\n",
    "    )\n",
    "    print(\"Dataset deemed not usable due to processing errors. Linked data not saved.\")"
   ]
  }
 ],
 "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
}