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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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a9077b62",
   "metadata": {},
   "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 = \"Celiac_Disease\"\n",
    "cohort = \"GSE112102\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Celiac_Disease\"\n",
    "in_cohort_dir = \"../../input/GEO/Celiac_Disease/GSE112102\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Celiac_Disease/GSE112102.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Celiac_Disease/gene_data/GSE112102.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Celiac_Disease/clinical_data/GSE112102.csv\"\n",
    "json_path = \"../../output/preprocess/Celiac_Disease/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea494e7c",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f33c9d95",
   "metadata": {},
   "outputs": [],
   "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": "fc79e0b1",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c871202",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Analyze gene expression data availability\n",
    "is_gene_available = True  # Based on the Series_summary, this dataset contains gene expression data\n",
    "\n",
    "# 2. Analyze variable availability and conversion functions\n",
    "# 2.1 Identify rows for trait, age, and gender\n",
    "trait_row = 1  # The trait information is in row 1 (group: CeD, control, FDR)\n",
    "age_row = 2    # Age information is in row 2\n",
    "gender_row = 4  # Gender information is in row 4\n",
    "\n",
    "# 2.2 Define conversion functions\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait values to binary (1 for CeD, 0 for control, None for FDR)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    if value.lower() == 'ced':\n",
    "        return 1  # Celiac Disease\n",
    "    elif value.lower() == 'control':\n",
    "        return 0  # Control\n",
    "    else:\n",
    "        return None  # FDR (First Degree Relatives) are neither cases nor controls\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age values to continuous numeric values\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    try:\n",
    "        return float(value)\n",
    "    except (ValueError, TypeError):\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender values to binary (0 for Female, 1 for Male)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    if ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    if value.lower() == 'female':\n",
    "        return 0\n",
    "    elif value.lower() == 'male':\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# 3. Save metadata for initial filtering\n",
    "is_trait_available = trait_row is not None\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 trait data is available\n",
    "if trait_row is not None:\n",
    "    # Get the clinical data by filtering and processing\n",
    "    clinical_df = 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 the extracted clinical data\n",
    "    print(\"Preview of extracted clinical data:\")\n",
    "    print(preview_df(clinical_df))\n",
    "    \n",
    "    # Save clinical data to CSV file\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    clinical_df.to_csv(out_clinical_data_file, index=False)\n",
    "    print(f\"Clinical data saved to: {out_clinical_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9bf6594",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f0e6d5e",
   "metadata": {},
   "outputs": [],
   "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": "2f7c9c58",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e69d07b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# These identifiers begin with \"ILMN_\" which indicates they are Illumina probe IDs,\n",
    "# specifically from an Illumina BeadArray microarray platform.\n",
    "# These are not human gene symbols but rather probe identifiers that need to be\n",
    "# mapped to gene symbols for biological interpretation.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a615f808",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9bb14b3",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "gene_annotation = get_gene_annotation(soft_file)\n",
    "\n",
    "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n",
    "print(\"Gene annotation preview:\")\n",
    "print(preview_df(gene_annotation))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c119e2c7",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "58e2c871",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Identify the columns for mapping\n",
    "# From the gene annotation preview, we can see that 'ID' contains the probe identifiers (ILMN_*) \n",
    "# and 'Symbol' contains the gene symbols\n",
    "prob_col = 'ID'  # Column with probe IDs matching the gene expression data index\n",
    "gene_col = 'Symbol'  # Column with gene symbols\n",
    "\n",
    "# 2. Create the gene mapping dataframe\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n",
    "print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
    "print(\"Gene mapping preview:\")\n",
    "print(preview_df(gene_mapping))\n",
    "\n",
    "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "print(f\"Gene expression data after mapping - shape: {gene_data.shape}\")\n",
    "print(\"First 5 genes in the mapped data:\")\n",
    "print(gene_data.index[:5])\n",
    "\n",
    "# Save the gene expression data to CSV\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Gene expression data saved to: {out_gene_data_file}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cea372c",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "052096f6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
    "print(\"First 10 normalized gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Load the clinical data that was saved in Step 2\n",
    "clinical_data = pd.read_csv(out_clinical_data_file)\n",
    "\n",
    "# Convert to proper format for linking\n",
    "clinical_df = pd.DataFrame()\n",
    "sample_ids = clinical_data.columns\n",
    "\n",
    "# Create proper clinical dataframe with samples as columns and features as rows\n",
    "clinical_df[trait] = clinical_data.iloc[0]\n",
    "clinical_df['Age'] = clinical_data.iloc[1]\n",
    "clinical_df['Gender'] = clinical_data.iloc[2]\n",
    "clinical_df.index = [trait, 'Age', 'Gender']\n",
    "clinical_df.columns = sample_ids\n",
    "\n",
    "print(f\"Clinical data shape: {clinical_df.shape}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(preview_df(clinical_df))\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data)\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])\n",
    "\n",
    "# Transpose linked data to have samples as rows and features as columns\n",
    "linked_data = linked_data.T\n",
    "\n",
    "print(\"After transposing:\")\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "print(\"Actual column names in linked_data:\", linked_data.columns.tolist()[:10])  # Show first 10 columns\n",
    "\n",
    "# 4. Handle missing values\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 5. Check for bias in features\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 6. Validate and save cohort information\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,\n",
    "    note=\"Dataset contains gene expression data from Celiac Disease patients and controls.\"\n",
    ")\n",
    "\n",
    "# 7. Save the linked data if usable\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset is not usable for analysis. No linked data file saved.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7d49f29",
   "metadata": {},
   "source": [
    "### Step 8: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2a897ffd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Normalize gene symbols in the gene expression data\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n",
    "print(\"First 10 normalized gene symbols:\")\n",
    "print(gene_data.index[:10])\n",
    "\n",
    "# Save the normalized gene data\n",
    "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
    "gene_data.to_csv(out_gene_data_file)\n",
    "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
    "\n",
    "# 2. Load the clinical data from Step 2\n",
    "clinical_data_path = out_clinical_data_file\n",
    "clinical_data = pd.read_csv(clinical_data_path)\n",
    "print(f\"Loaded clinical data from {clinical_data_path}\")\n",
    "\n",
    "# Create a proper clinical DataFrame with rows as features and columns as samples\n",
    "# First, get column names from the CSV (these are the sample IDs)\n",
    "sample_ids = clinical_data.columns.tolist()\n",
    "# Extract and prepare the clinical features\n",
    "trait_values = clinical_data.iloc[0].values\n",
    "age_values = clinical_data.iloc[1].values\n",
    "gender_values = clinical_data.iloc[2].values\n",
    "\n",
    "# Create DataFrame with correct format for linking\n",
    "clinical_df = pd.DataFrame({\n",
    "    trait: trait_values,\n",
    "    'Age': age_values,\n",
    "    'Gender': gender_values\n",
    "}, index=sample_ids).T\n",
    "\n",
    "print(f\"Clinical data shape: {clinical_df.shape}\")\n",
    "print(\"Clinical data preview:\")\n",
    "print(clinical_df.iloc[:, :5])  # Show first 5 columns\n",
    "\n",
    "# 3. Link clinical and genetic data\n",
    "linked_data = pd.concat([clinical_df, gene_data], axis=0)\n",
    "print(f\"Linked data shape after concatenation: {linked_data.shape}\")\n",
    "\n",
    "# Transpose to have samples as rows and features as columns\n",
    "linked_data = linked_data.T\n",
    "print(f\"Linked data shape after transpose: {linked_data.shape}\")\n",
    "print(\"Linked data preview (first 5 rows, 5 columns):\")\n",
    "print(linked_data.iloc[:5, :5])\n",
    "\n",
    "# 4. Handle missing values\n",
    "linked_data = handle_missing_values(linked_data, trait)\n",
    "print(f\"Data shape after handling missing values: {linked_data.shape}\")\n",
    "\n",
    "# 5. Check for bias in features\n",
    "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "\n",
    "# 6. Validate and save cohort information\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,\n",
    "    note=\"Dataset contains gene expression data from Celiac Disease patients and controls. FDR samples were excluded from the trait analysis.\"\n",
    ")\n",
    "\n",
    "# 7. Save the linked data if usable\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(\"Dataset is not usable for analysis. No linked data file saved.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}