{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "14cd57a4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:19.114020Z", "iopub.status.busy": "2025-03-25T04:07:19.113455Z", "iopub.status.idle": "2025-03-25T04:07:19.285959Z", "shell.execute_reply": "2025-03-25T04:07:19.285632Z" } }, "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 = \"Substance_Use_Disorder\"\n", "cohort = \"GSE125681\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Substance_Use_Disorder\"\n", "in_cohort_dir = \"../../input/GEO/Substance_Use_Disorder/GSE125681\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Substance_Use_Disorder/GSE125681.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Substance_Use_Disorder/gene_data/GSE125681.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Substance_Use_Disorder/clinical_data/GSE125681.csv\"\n", "json_path = \"../../output/preprocess/Substance_Use_Disorder/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "da83bdc6", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "7ee9e306", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:19.287342Z", "iopub.status.busy": "2025-03-25T04:07:19.287195Z", "iopub.status.idle": "2025-03-25T04:07:19.322245Z", "shell.execute_reply": "2025-03-25T04:07:19.321926Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Brain Gene Expression Pattern of Individuals with Dual Diagnosis who died by suicide\"\n", "!Series_summary\t\"We compared the gene expression profile in the dorsolateral prefrontal area of subjects with dual diagnosis who died by suicide to the transcriptome of subjects with mood disorders and subjects with substance use disorder who died by suicide.\"\n", "!Series_overall_design\t\"38 samples were collected.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['age: 16', 'age: 17', 'age: 35', 'age: 26', 'age: 33', 'age: 19', 'age: 29', 'age: 18', 'age: 32', 'age: 23', 'age: 34', 'age: 39', 'age: 45', 'age: 58', 'age: 76', 'age: 55', 'age: 31', 'age: 24', 'age: 61', 'age: 90', 'age: 30', 'age: 53', 'age: 22', 'age: 27'], 1: ['gender: Male', 'gender: Female'], 2: ['suicide: Suicide'], 3: ['sud: SUD', 'sud: Without SUD']}\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": "f62bcbaa", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "4d623393", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:19.323387Z", "iopub.status.busy": "2025-03-25T04:07:19.323282Z", "iopub.status.idle": "2025-03-25T04:07:19.333548Z", "shell.execute_reply": "2025-03-25T04:07:19.333236Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'GSM3580113': [1.0, 16.0, 1.0], 'GSM3580114': [1.0, 17.0, 1.0], 'GSM3580115': [1.0, 16.0, 1.0], 'GSM3580117': [1.0, 35.0, 1.0], 'GSM3580120': [1.0, 26.0, 1.0], 'GSM3580121': [1.0, 33.0, 1.0], 'GSM3580122': [1.0, 19.0, 1.0], 'GSM3580124': [1.0, 29.0, 1.0], 'GSM3580126': [0.0, 18.0, 0.0], 'GSM3580128': [0.0, 16.0, 0.0], 'GSM3580129': [0.0, 32.0, 1.0], 'GSM3580130': [0.0, 35.0, 1.0], 'GSM3580133': [0.0, 23.0, 1.0], 'GSM3580135': [0.0, 34.0, 1.0], 'GSM3580136': [1.0, 39.0, 1.0], 'GSM3580137': [0.0, 23.0, 0.0], 'GSM3580139': [1.0, 45.0, 1.0], 'GSM3580140': [0.0, 35.0, 1.0], 'GSM3580141': [0.0, 58.0, 1.0], 'GSM3580143': [0.0, 76.0, 1.0], 'GSM3580144': [1.0, 55.0, 1.0], 'GSM3580145': [0.0, 31.0, 1.0], 'GSM3580146': [0.0, 24.0, 0.0], 'GSM3580148': [1.0, 23.0, 1.0], 'GSM3580149': [1.0, 61.0, 1.0], 'GSM3580150': [1.0, 90.0, 1.0], 'GSM3580151': [1.0, 17.0, 1.0], 'GSM3580153': [1.0, 23.0, 0.0], 'GSM3580154': [1.0, 30.0, 1.0], 'GSM3580158': [0.0, 34.0, 1.0], 'GSM3580164': [0.0, 18.0, 1.0], 'GSM3580167': [0.0, 19.0, 1.0], 'GSM3580168': [0.0, 53.0, 1.0], 'GSM3580169': [1.0, 39.0, 1.0], 'GSM3580171': [1.0, 22.0, 1.0], 'GSM3580172': [0.0, 29.0, 0.0], 'GSM3580174': [1.0, 27.0, 1.0], 'GSM3580175': [0.0, 26.0, 0.0]}\n", "Clinical data saved to ../../output/preprocess/Substance_Use_Disorder/clinical_data/GSE125681.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the title and description, this likely contains gene expression data from the dorsolateral prefrontal area\n", "is_gene_available = True \n", "\n", "# 2.1 Data Availability\n", "# From the sample characteristics, we can identify keys for trait, age, and gender\n", "trait_row = 3 # 'sud' (substance use disorder)\n", "age_row = 0 # 'age'\n", "gender_row = 1 # 'gender'\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: 1 for SUD, 0 for Without SUD\n", " if value.lower() == 'sud':\n", " return 1\n", " elif value.lower() == 'without sud':\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to continuous numeric value\n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: 0 for Female, 1 for Male\n", " if value.lower() == 'male':\n", " return 1\n", " elif value.lower() == 'female':\n", " return 0\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Since trait_row is not None, trait data is available\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\n", "# Since trait_row is not None, we proceed with feature extraction\n", "if trait_row is not None:\n", " # Assume clinical_data is defined from a previous step\n", " try:\n", " selected_clinical_df = geo_select_clinical_features(\n", " 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", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error extracting clinical features: {e}\")\n" ] }, { "cell_type": "markdown", "id": "11e6cb21", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "247cd7ee", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:19.334588Z", "iopub.status.busy": "2025-03-25T04:07:19.334479Z", "iopub.status.idle": "2025-03-25T04:07:19.375084Z", "shell.execute_reply": "2025-03-25T04:07:19.374727Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 62\n", "Header line: \"ID_REF\"\t\"GSM3580113\"\t\"GSM3580114\"\t\"GSM3580115\"\t\"GSM3580117\"\t\"GSM3580120\"\t\"GSM3580121\"\t\"GSM3580122\"\t\"GSM3580124\"\t\"GSM3580126\"\t\"GSM3580128\"\t\"GSM3580129\"\t\"GSM3580130\"\t\"GSM3580133\"\t\"GSM3580135\"\t\"GSM3580136\"\t\"GSM3580137\"\t\"GSM3580139\"\t\"GSM3580140\"\t\"GSM3580141\"\t\"GSM3580143\"\t\"GSM3580144\"\t\"GSM3580145\"\t\"GSM3580146\"\t\"GSM3580148\"\t\"GSM3580149\"\t\"GSM3580150\"\t\"GSM3580151\"\t\"GSM3580153\"\t\"GSM3580154\"\t\"GSM3580158\"\t\"GSM3580164\"\t\"GSM3580167\"\t\"GSM3580168\"\t\"GSM3580169\"\t\"GSM3580171\"\t\"GSM3580172\"\t\"GSM3580174\"\t\"GSM3580175\"\n", "First data line: \"ILMN_1651229\"\t9.284170392\t9.2246201\t9.234463414\t9.044533263\t9.237307192\t9.182889823\t9.208731283\t9.231173219\t9.032337123\t9.410774012\t9.120015038\t9.158365079\t9.322335583\t9.101266675\t9.288959569\t9.21875343\t8.984921045\t9.064043363\t9.284498916\t9.168211134\t9.512112115\t9.097280178\t9.170814536\t9.2760438\t9.193590717\t9.401714598\t9.285201527\t9.496871234\t9.315469914\t9.102376361\t9.081554331\t9.166868296\t9.062749379\t9.39293042\t9.127197288\t9.241455103\t9.22167395\t9.202273196\n", "Index(['ILMN_1651229', 'ILMN_1651262', 'ILMN_1651315', 'ILMN_1651343',\n", " 'ILMN_1651347', 'ILMN_1651354', 'ILMN_1651378', 'ILMN_1651385',\n", " 'ILMN_1651405', 'ILMN_1651429', 'ILMN_1651438', 'ILMN_1651464',\n", " 'ILMN_1651498', 'ILMN_1651504', 'ILMN_1651538', 'ILMN_1651610',\n", " 'ILMN_1651719', 'ILMN_1651735', 'ILMN_1651767', 'ILMN_1651788'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "8480c85c", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "2cff0ca0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:19.376298Z", "iopub.status.busy": "2025-03-25T04:07:19.376184Z", "iopub.status.idle": "2025-03-25T04:07:19.378077Z", "shell.execute_reply": "2025-03-25T04:07:19.377753Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the gene expression data\n", "# The identifiers start with \"ILMN_\" which indicates they are Illumina probe IDs\n", "# These are not standard human gene symbols and need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "54ba0622", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "66e41307", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:19.379175Z", "iopub.status.busy": "2025-03-25T04:07:19.379066Z", "iopub.status.idle": "2025-03-25T04:07:20.291618Z", "shell.execute_reply": "2025-03-25T04:07:20.291211Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining SOFT file structure:\n", "Line 0: ^DATABASE = GeoMiame\n", "Line 1: !Database_name = Gene Expression Omnibus (GEO)\n", "Line 2: !Database_institute = NCBI NLM NIH\n", "Line 3: !Database_web_link = http://www.ncbi.nlm.nih.gov/geo\n", "Line 4: !Database_email = geo@ncbi.nlm.nih.gov\n", "Line 5: ^SERIES = GSE125681\n", "Line 6: !Series_title = Brain Gene Expression Pattern of Individuals with Dual Diagnosis who died by suicide\n", "Line 7: !Series_geo_accession = GSE125681\n", "Line 8: !Series_status = Public on Dec 02 2019\n", "Line 9: !Series_submission_date = Jan 25 2019\n", "Line 10: !Series_last_update_date = Dec 02 2019\n", "Line 11: !Series_pubmed_id = 31774731\n", "Line 12: !Series_summary = We compared the gene expression profile in the dorsolateral prefrontal area of subjects with dual diagnosis who died by suicide to the transcriptome of subjects with mood disorders and subjects with substance use disorder who died by suicide.\n", "Line 13: !Series_overall_design = 38 samples were collected.\n", "Line 14: !Series_type = Expression profiling by array\n", "Line 15: !Series_contributor = Brenda,,Cabrera\n", "Line 16: !Series_contributor = Nancy,,Monroy-Jaramillo\n", "Line 17: !Series_contributor = Gabriel,R,Fries\n", "Line 18: !Series_contributor = Consuelo,,Walss-Bass\n", "Line 19: !Series_contributor = Humberto,,Nicolini\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180, 6510136, 7560739, 1450438, 1240647], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n" ] } ], "source": [ "# 1. Let's first examine the structure of the SOFT file before trying to parse it\n", "import gzip\n", "\n", "# Look at the first few lines of the SOFT file to understand its structure\n", "print(\"Examining SOFT file structure:\")\n", "try:\n", " with gzip.open(soft_file, 'rt') as file:\n", " # Read first 20 lines to understand the file structure\n", " for i, line in enumerate(file):\n", " if i < 20:\n", " print(f\"Line {i}: {line.strip()}\")\n", " else:\n", " break\n", "except Exception as e:\n", " print(f\"Error reading SOFT file: {e}\")\n", "\n", "# 2. Now let's try a more robust approach to extract the gene annotation\n", "# Instead of using the library function which failed, we'll implement a custom approach\n", "try:\n", " # First, look for the platform section which contains gene annotation\n", " platform_data = []\n", " with gzip.open(soft_file, 'rt') as file:\n", " in_platform_section = False\n", " for line in file:\n", " if line.startswith('^PLATFORM'):\n", " in_platform_section = True\n", " continue\n", " if in_platform_section and line.startswith('!platform_table_begin'):\n", " # Next line should be the header\n", " header = next(file).strip()\n", " platform_data.append(header)\n", " # Read until the end of the platform table\n", " for table_line in file:\n", " if table_line.startswith('!platform_table_end'):\n", " break\n", " platform_data.append(table_line.strip())\n", " break\n", " \n", " # If we found platform data, convert it to a DataFrame\n", " if platform_data:\n", " import pandas as pd\n", " import io\n", " platform_text = '\\n'.join(platform_data)\n", " gene_annotation = pd.read_csv(io.StringIO(platform_text), delimiter='\\t', \n", " low_memory=False, on_bad_lines='skip')\n", " print(\"\\nGene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"Could not find platform table in SOFT file\")\n", " \n", " # Try an alternative approach - extract mapping from other sections\n", " with gzip.open(soft_file, 'rt') as file:\n", " for line in file:\n", " if 'ANNOTATION information' in line or 'annotation information' in line:\n", " print(f\"Found annotation information: {line.strip()}\")\n", " if line.startswith('!Platform_title') or line.startswith('!platform_title'):\n", " print(f\"Platform title: {line.strip()}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation: {e}\")\n" ] }, { "cell_type": "markdown", "id": "054f9c12", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "d22c45be", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:20.292950Z", "iopub.status.busy": "2025-03-25T04:07:20.292817Z", "iopub.status.idle": "2025-03-25T04:07:20.479839Z", "shell.execute_reply": "2025-03-25T04:07:20.479458Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Gene': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']}\n", "\n", "Gene expression data preview (after mapping):\n", "Shape: (6421, 38)\n", "First 5 gene symbols: ['A2BP1', 'A2M', 'AACS', 'AADACL1', 'AADAT']\n", "Sample columns: ['GSM3580113', 'GSM3580114', 'GSM3580115', 'GSM3580117', 'GSM3580120']\n", "Gene expression data saved to ../../output/preprocess/Substance_Use_Disorder/gene_data/GSE125681.csv\n" ] } ], "source": [ "# Extract the gene identifier and gene symbol columns from the gene annotation dataframe\n", "# Based on the preview, the 'ID' column in gene_annotation matches the probe IDs in gene_data (both start with ILMN_)\n", "# The 'Symbol' column contains the gene symbols we need to map to\n", "\n", "try:\n", " # Create the mapping dataframe with the ID and Symbol columns\n", " mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", " \n", " # Preview the mapping dataframe\n", " print(\"Gene mapping preview:\")\n", " print(preview_df(mapping_df))\n", " \n", " # Apply the gene mapping to convert from probe-level to gene-level expression\n", " gene_data = apply_gene_mapping(gene_data, mapping_df)\n", " \n", " # Preview the converted gene expression data\n", " print(\"\\nGene expression data preview (after mapping):\")\n", " print(f\"Shape: {gene_data.shape}\")\n", " print(f\"First 5 gene symbols: {gene_data.index[:5].tolist()}\")\n", " print(f\"Sample columns: {gene_data.columns[:5].tolist()}\")\n", " \n", " # Save the gene data to a CSV file\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", " \n", "except Exception as e:\n", " print(f\"Error in gene mapping: {e}\")\n", " # In case of error, try to get the dataframe shape at least\n", " print(f\"Gene expression dataframe shape: {gene_data.shape if 'gene_data' in locals() else 'Not available'}\")\n", " print(f\"Gene annotation dataframe shape: {gene_annotation.shape if 'gene_annotation' in locals() else 'Not available'}\")\n" ] }, { "cell_type": "markdown", "id": "1df94370", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "8eff8b55", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:07:20.481136Z", "iopub.status.busy": "2025-03-25T04:07:20.481005Z", "iopub.status.idle": "2025-03-25T04:07:22.420344Z", "shell.execute_reply": "2025-03-25T04:07:22.420014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (6421, 38)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (6362, 38)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Substance_Use_Disorder/gene_data/GSE125681.csv\n", "Raw clinical data shape: (4, 39)\n", "Clinical features:\n", " GSM3580113 GSM3580114 GSM3580115 GSM3580117 \\\n", "Substance_Use_Disorder 1.0 1.0 1.0 1.0 \n", "Age 16.0 17.0 16.0 35.0 \n", "Gender 1.0 1.0 1.0 1.0 \n", "\n", " GSM3580120 GSM3580121 GSM3580122 GSM3580124 \\\n", "Substance_Use_Disorder 1.0 1.0 1.0 1.0 \n", "Age 26.0 33.0 19.0 29.0 \n", "Gender 1.0 1.0 1.0 1.0 \n", "\n", " GSM3580126 GSM3580128 ... GSM3580154 GSM3580158 \\\n", "Substance_Use_Disorder 0.0 0.0 ... 1.0 0.0 \n", "Age 18.0 16.0 ... 30.0 34.0 \n", "Gender 0.0 0.0 ... 1.0 1.0 \n", "\n", " GSM3580164 GSM3580167 GSM3580168 GSM3580169 \\\n", "Substance_Use_Disorder 0.0 0.0 0.0 1.0 \n", "Age 18.0 19.0 53.0 39.0 \n", "Gender 1.0 1.0 1.0 1.0 \n", "\n", " GSM3580171 GSM3580172 GSM3580174 GSM3580175 \n", "Substance_Use_Disorder 1.0 0.0 1.0 0.0 \n", "Age 22.0 29.0 27.0 26.0 \n", "Gender 1.0 0.0 1.0 0.0 \n", "\n", "[3 rows x 38 columns]\n", "Clinical features saved to ../../output/preprocess/Substance_Use_Disorder/clinical_data/GSE125681.csv\n", "Linked data shape: (38, 6365)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Substance_Use_Disorder Age Gender A2M AACS\n", "GSM3580113 1.0 16.0 1.0 10.694520 8.094176\n", "GSM3580114 1.0 17.0 1.0 10.559792 7.930300\n", "GSM3580115 1.0 16.0 1.0 10.293407 8.178318\n", "GSM3580117 1.0 35.0 1.0 9.205993 7.656801\n", "GSM3580120 1.0 26.0 1.0 10.204496 8.077739\n", "Missing values before handling:\n", " Trait (Substance_Use_Disorder) missing: 0 out of 38\n", " Age missing: 0 out of 38\n", " Gender missing: 0 out of 38\n", " Genes with >20% missing: 0\n", " Samples with >5% missing genes: 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (38, 6365)\n", "For the feature 'Substance_Use_Disorder', the least common label is '0.0' with 18 occurrences. This represents 47.37% of the dataset.\n", "The distribution of the feature 'Substance_Use_Disorder' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 22.25\n", " 50% (Median): 29.0\n", " 75%: 35.0\n", "Min: 16.0\n", "Max: 90.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 7 occurrences. This represents 18.42% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Substance_Use_Disorder/GSE125681.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", "\n", "# Normalize gene symbols using NCBI Gene database\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Check if trait data is available before proceeding with clinical data extraction\n", "if trait_row is None:\n", " print(\"Trait row is None. Cannot extract trait information from clinical data.\")\n", " # Create an empty dataframe for clinical features\n", " clinical_features = pd.DataFrame()\n", " \n", " # Create an empty dataframe for linked data\n", " linked_data = pd.DataFrame()\n", " \n", " # Validate and save cohort info\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, # Trait data is not available\n", " is_biased=True, # Not applicable but required\n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Dataset contains gene expression data but lacks clear trait indicators for {trait} status.\"\n", " )\n", " print(\"Data was determined to be unusable due to missing trait indicators and was not saved\")\n", "else:\n", " try:\n", " # Get the file paths for the matrix file to extract clinical data\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get raw clinical data from the matrix file\n", " _, clinical_raw = get_background_and_clinical_data(matrix_file)\n", " \n", " # Verify clinical data structure\n", " print(\"Raw clinical data shape:\", clinical_raw.shape)\n", " \n", " # Extract clinical features using the defined conversion functions\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_raw,\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", " print(\"Clinical features:\")\n", " print(clinical_features)\n", " \n", " # Save clinical features to file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values\n", " print(\"Missing values before handling:\")\n", " print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", " if 'Age' in linked_data.columns:\n", " print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n", " if 'Gender' in linked_data.columns:\n", " print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n", " \n", " gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n", " print(f\" Genes with >20% missing: {sum(linked_data[gene_cols].isna().mean() > 0.2)}\")\n", " print(f\" Samples with >5% missing genes: {sum(linked_data[gene_cols].isna().mean(axis=1) > 0.05)}\")\n", " \n", " cleaned_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", " \n", " # 5. Evaluate bias in trait and demographic features\n", " is_trait_biased = False\n", " if len(cleaned_data) > 0:\n", " trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", " is_trait_biased = trait_biased\n", " else:\n", " print(\"No data remains after handling missing values.\")\n", " is_trait_biased = True\n", " \n", " # 6. Final validation and save\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_trait_biased, \n", " df=cleaned_data,\n", " note=f\"Dataset contains gene expression data for {trait} analysis.\"\n", " )\n", " \n", " # 7. Save if usable\n", " if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data was determined to be unusable or empty and was not saved\")\n", " \n", " except Exception as e:\n", " print(f\"Error processing data: {e}\")\n", " # Handle the error case by still recording cohort info\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, # Mark as not available due to processing issues\n", " is_biased=True, \n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Error processing data for {trait}: {str(e)}\"\n", " )\n", " print(\"Data was determined to be unusable and was 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 }