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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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e600623e",
   "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 = \"Adrenocortical_Cancer\"\n",
    "cohort = \"GSE68950\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Adrenocortical_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Adrenocortical_Cancer/GSE68950\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Adrenocortical_Cancer/GSE68950.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Adrenocortical_Cancer/gene_data/GSE68950.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Adrenocortical_Cancer/clinical_data/GSE68950.csv\"\n",
    "json_path = \"../../output/preprocess/Adrenocortical_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f24deabf",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07caa148",
   "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": "2a866c39",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9e1ad2cb",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "14268501",
   "metadata": {},
   "source": [
    "### Step 3: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9558f493",
   "metadata": {},
   "outputs": [],
   "source": [
    "```python\n",
    "import pandas as pd\n",
    "import os\n",
    "import json\n",
    "import numpy as np\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# Load the clinical data from the raw data file\n",
    "try:\n",
    "    # Try loading from the matrix file directly instead of pkl\n",
    "    matrix_file = os.path.join(in_cohort_dir, \"matrix.csv\")\n",
    "    if os.path.exists(matrix_file):\n",
    "        clinical_data = pd.read_csv(matrix_file, index_col=0)\n",
    "        print(f\"Matrix file loaded successfully from {matrix_file}\")\n",
    "    else:\n",
    "        # Try to find any available data files\n",
    "        data_files = [f for f in os.listdir(in_cohort_dir) if f.endswith(('.txt', '.csv'))]\n",
    "        if data_files:\n",
    "            matrix_file = os.path.join(in_cohort_dir, data_files[0])\n",
    "            clinical_data = pd.read_csv(matrix_file, sep='\\t' if matrix_file.endswith('.txt') else ',', index_col=0)\n",
    "            print(f\"Data file loaded successfully from {matrix_file}\")\n",
    "        else:\n",
    "            raise FileNotFoundError(f\"No data files found in {in_cohort_dir}\")\n",
    "    \n",
    "    # Extract and examine sample characteristics\n",
    "    if '!Sample_characteristics_ch1' in clinical_data.index:\n",
    "        # Characteristics are in the rows\n",
    "        sample_chars = clinical_data.loc[['!Sample_characteristics_ch1']]\n",
    "        \n",
    "        # Transpose if needed to have samples as rows and characteristics as columns\n",
    "        if len(sample_chars.columns) > len(sample_chars.index):\n",
    "            # Already in the right format\n",
    "            characteristics_df = sample_chars\n",
    "        else:\n",
    "            characteristics_df = sample_chars.T\n",
    "        \n",
    "        print(\"Sample characteristics found in the index\")\n",
    "    elif '!Sample_characteristics_ch1' in clinical_data.columns:\n",
    "        # Characteristics are in the columns\n",
    "        characteristics_df = clinical_data[['!Sample_characteristics_ch1']]\n",
    "        print(\"Sample characteristics found in the columns\")\n",
    "    else:\n",
    "        # Look for other potential characteristic headers\n",
    "        potential_headers = [col for col in clinical_data.columns if 'characteristics' in col.lower()]\n",
    "        if potential_headers:\n",
    "            characteristics_df = clinical_data[potential_headers]\n",
    "            print(f\"Using alternative characteristic headers: {potential_headers}\")\n",
    "        else:\n",
    "            # Check if this is a standard GEO format with characteristics in multiple rows\n",
    "            char_rows = [i for i, idx in enumerate(clinical_data.index) if 'characteristics' in str(idx).lower()]\n",
    "            if char_rows:\n",
    "                characteristics_df = clinical_data.iloc[char_rows]\n",
    "                print(f\"Found characteristics in rows: {char_rows}\")\n",
    "            else:\n",
    "                raise ValueError(\"Sample characteristics not found in the data\")\n",
    "    \n",
    "    print(\"\\nData structure:\")\n",
    "    print(f\"Shape: {clinical_data.shape}\")\n",
    "    print(f\"Index: {list(clinical_data.index)[:5]}...\")\n",
    "    print(f\"Columns: {list(clinical_data.columns)[:5]}...\")\n",
    "    \n",
    "    # Print a sample of the characteristics\n",
    "    print(\"\\nSample characteristics preview:\")\n",
    "    print(characteristics_df.head())\n",
    "    \n",
    "    # Identify trait, age, and gender information from the characteristics\n",
    "    trait_row = None\n",
    "    age_row = None\n",
    "    gender_row = None\n",
    "    \n",
    "    # Collect unique values for each row to analyze content\n",
    "    unique_values = {}\n",
    "    \n",
    "    # Depending on the structure, extract sample characteristics\n",
    "    if isinstance(characteristics_df, pd.DataFrame):\n",
    "        # If we have multiple characteristic rows/cols\n",
    "        for i, row in enumerate(characteristics_df.index):\n",
    "            if isinstance(characteristics_df, pd.DataFrame) and len(characteristics_df.columns) > 0:\n",
    "                values = []\n",
    "                for col in characteristics_df.columns:\n",
    "                    val = characteristics_df.loc[row, col]\n",
    "                    if pd.notna(val):\n",
    "                        values.append(str(val))\n",
    "                if values:\n",
    "                    unique_values[i] = \"; \".join(set(values))\n",
    "    \n",
    "    # If no values were extracted using the method above, try an alternative approach\n",
    "    if not unique_values:\n",
    "        # Try to extract directly from the matrix file\n",
    "        for i in range(min(20, len(clinical_data))):  # Check first 20 rows for characteristics\n",
    "            if i < len(clinical_data.index):\n",
    "                row_name = clinical_data.index[i]\n",
    "                if isinstance(row_name, str) and \"characteristics\" in row_name.lower():\n",
    "                    values = clinical_data.iloc[i].astype(str).tolist()\n",
    "                    unique_values[i] = \"; \".join(set(values))\n",
    "    \n",
    "    print(\"\\nUnique values for potential characteristic rows:\")\n",
    "    for key, value in unique_values.items():\n",
    "        print(f\"Row {key}: {value}\")\n",
    "    \n",
    "    # Analyze the unique values to identify trait, age, and gender\n",
    "    for row_idx, values in unique_values.items():\n",
    "        values_lower = values.lower()\n",
    "        \n",
    "        # Identify trait information\n",
    "        if any(term in values_lower for term in [\"diagnosis\", \"tissue\", \"tumor\", \"carcinoma\", \"status\", \"histology\", \"sample type\", \"sample_type\", \"disease\"]):\n",
    "            trait_row = row_idx\n",
    "            print(f\"Found trait row: {row_idx} - {values}\")\n",
    "        \n",
    "        # Identify age information\n",
    "        if \"age\" in values_lower:\n",
    "            age_row = row_idx\n",
    "            print(f\"Found age row: {row_idx} - {values}\")\n",
    "        \n",
    "        # Identify gender/sex information\n",
    "        if any(term in values_lower for term in [\"gender\", \"sex\"]):\n",
    "            gender_row = row_idx\n",
    "            print(f\"Found gender row: {row_idx} - {values}\")\n",
    "        \n",
    "except Exception as e:\n",
    "    print(f\"Error processing data: {e}\")\n",
    "    # Set default values as we couldn't analyze the data\n",
    "    unique_values = {}\n",
    "    trait_row = None\n",
    "    age_row = None\n",
    "    gender_row = None\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# For GEO datasets with GSE prefix, we generally assume they contain gene expression data\n",
    "# unless we see evidence otherwise\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Define conversion functions for each variable\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (0 for normal/control, 1 for cancer/case)\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    value_lower = str(value).lower()\n",
    "    \n",
    "    # Map to binary values for Adrenocortical Cancer\n",
    "    if any(term in value_lower for term in [\"normal\", \"control\", \"healthy\", \"non-tumor\", \"non tumor\", \"adjacent\", \"non-neoplastic\"]):\n",
    "        return 0\n",
    "    elif any(term in value_lower for term in [\"tumor\", \"cancer\", \"carcinoma\", \"adrenocortical\", \"adenoma\", \"adc\", \"acc\", \"malignant\"]):\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous numeric value\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # Try to extract numeric age\n",
    "    import re\n",
    "    age_match = re.search(r'(\\d+)', str(value))\n",
    "    if age_match:\n",
    "        return float(age_match.group(1))\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
    "    if value is None or pd.isna(value):\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after the colon if present\n",
    "    if isinstance(value, str) and \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    value_lower = str(value).lower()\n",
    "    \n",
    "    # Map to binary values\n",
    "    if any(\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a58a1e49",
   "metadata": {},
   "source": [
    "### Step 4: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "71b941dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Check the raw clinical data\n",
    "import os\n",
    "import json\n",
    "import pandas as pd\n",
    "from typing import Optional, Callable, Dict, Any\n",
    "\n",
    "# Let's first check what data we have\n",
    "# Since we need to analyze the clinical_data, let's check if it exists\n",
    "if 'clinical_data' in globals():\n",
    "    print(\"clinical_data exists. Examining its structure...\")\n",
    "    print(f\"Shape: {clinical_data.shape}\")\n",
    "    print(f\"First few rows:\\n{clinical_data.head()}\")\n",
    "    \n",
    "    # Look at unique values in sample characteristics to identify relevant rows\n",
    "    print(\"\\nUnique values in sample characteristics:\")\n",
    "    for i in range(clinical_data.shape[0]):\n",
    "        print(f\"Row {i}: {set(clinical_data.iloc[i, :])}\")\n",
    "else:\n",
    "    print(\"clinical_data variable is not available. We need to load the data first.\")\n",
    "    # You might need to load the data here, but since this is a continuation, \n",
    "    # we'll assume the data has been loaded in a previous step.\n",
    "\n",
    "# Let's first check if this is a gene expression dataset\n",
    "is_gene_available = True  # Based on the assumption this is gene expression data\n",
    "                          # Without detailed data, we're making a best judgment\n",
    "\n",
    "# Define functions to convert trait, age, and gender data\n",
    "def convert_trait(value):\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon if present\n",
    "    if isinstance(value, str) and ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary based on common descriptions\n",
    "    if value.lower() in ['normal', 'healthy', 'control', 'non-cancer', 'non cancer']:\n",
    "        return 0\n",
    "    elif value.lower() in ['cancer', 'tumor', 'adrenocortical cancer', 'acc', 'adrenocortical carcinoma']:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "def convert_age(value):\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon if present\n",
    "    if isinstance(value, str) and ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Try to convert to float\n",
    "    try:\n",
    "        # Remove any non-numeric characters except decimal point\n",
    "        cleaned_value = ''.join(c for c in value if c.isdigit() or c == '.')\n",
    "        age = float(cleaned_value)\n",
    "        return age\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    if pd.isna(value) or value is None:\n",
    "        return None\n",
    "    \n",
    "    # Extract the value after colon if present\n",
    "    if isinstance(value, str) and ':' in value:\n",
    "        value = value.split(':', 1)[1].strip()\n",
    "    \n",
    "    # Convert to binary (0 for female, 1 for male)\n",
    "    if value.lower() in ['female', 'f', 'woman']:\n",
    "        return 0\n",
    "    elif value.lower() in ['male', 'm', 'man']:\n",
    "        return 1\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "# Assuming based on typical GEO datasets:\n",
    "# We need to check if these rows actually contain the needed information\n",
    "trait_row = 1  # Typically disease status is in row 1\n",
    "age_row = None  # Often age data is not provided\n",
    "gender_row = None  # Often gender data is not provided\n",
    "\n",
    "# Check if trait_row is valid (meaning trait data is available)\n",
    "is_trait_available = trait_row is not None\n",
    "\n",
    "# Save metadata using the validate_and_save_cohort_info function\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",
    "# Extract clinical features if trait data is available\n",
    "if trait_row is not None:\n",
    "    selected_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 features\n",
    "    preview = preview_df(selected_clinical_df)\n",
    "    print(\"\\nPreview of extracted clinical features:\")\n",
    "    print(preview)\n",
    "    \n",
    "    # Save the clinical data to the specified file\n",
    "    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
    "    selected_clinical_df.to_csv(out_clinical_data_file, index=True)\n",
    "    print(f\"Clinical data saved to {out_clinical_data_file}\")\n",
    "else:\n",
    "    print(\"Trait data is not available. Skipping clinical feature extraction.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}