{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "90430d56", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:05.876102Z", "iopub.status.busy": "2025-03-25T06:12:05.875991Z", "iopub.status.idle": "2025-03-25T06:12:06.039083Z", "shell.execute_reply": "2025-03-25T06:12:06.038762Z" } }, "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 = \"Pheochromocytoma_and_Paraganglioma\"\n", "cohort = \"GSE64957\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Pheochromocytoma_and_Paraganglioma\"\n", "in_cohort_dir = \"../../input/GEO/Pheochromocytoma_and_Paraganglioma/GSE64957\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Pheochromocytoma_and_Paraganglioma/GSE64957.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Pheochromocytoma_and_Paraganglioma/gene_data/GSE64957.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Pheochromocytoma_and_Paraganglioma/clinical_data/GSE64957.csv\"\n", "json_path = \"../../output/preprocess/Pheochromocytoma_and_Paraganglioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "0cd106dc", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "a6c1c345", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:06.040576Z", "iopub.status.busy": "2025-03-25T06:12:06.040414Z", "iopub.status.idle": "2025-03-25T06:12:06.748082Z", "shell.execute_reply": "2025-03-25T06:12:06.747734Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Microarray study of human adrenal zona glomerulosa (ZG), zona fasciculata (ZF) and aldosterone-producing adenomas (APA)\"\n", "!Series_summary\t\"Learn about the transcriptome profiling of zona glomerulosa (ZG), zona fasciculata (ZF) and aldosterone-producing adenomas (APA) in human adrenals\"\n", "!Series_overall_design\t\"21 pairs of zona fasciculata (ZF) and zona glomerulosa (ZG), and 14 paired aldosterone-producing adenomas (APAs) from 14 Conn’s syndrome patients and 7 phaeochromocytoma patients were assayed on the Affymetrix Human Genome U133 Plus 2.0 Array. Laser capture microdissection was used to acquire samples of ZF, ZG and APA as previously described (Azizan EA, et al. J Clin Endocrinol Metab. 2012;97:E819-E829). For differentiation of ZG from ZF, sections were stained with cresyl violet using the LCM Staining Kit (AM1935, Ambion, USA). Data processing and analysis was performed using AffymetrixGeneChip Command Console Software and PartekGenomicSuite 6.5 (Partek Inc., St. Louis, MO). Gene expressions were portrayed as the summarized log-signal of the Robust Multichip Average (RMA) with quantilenormalisation and median polish for probe set summarisation. Validation by qPCR was performed on genes >10 fold up-regulated in zona glomerulosa (compared to zona fasciculata) and >10 fold up-regulated in aldosterone-producing adenomas (compared to zona glomerulosa).\"\n", "Sample Characteristics Dictionary:\n", "{0: [\"disease: Conn's Syndrome\", 'disease: Pheochromocytoma'], 1: ['patient/tissue id: ADR106', 'patient/tissue id: ADR061', 'patient/tissue id: ADR031', 'patient/tissue id: ADR026', 'patient/tissue id: ADR110', 'patient/tissue id: ADR111', 'patient/tissue id: ADR017', 'patient/tissue id: ADR120', 'patient/tissue id: ADR115', 'patient/tissue id: ADR085', 'patient/tissue id: ADR086', 'patient/tissue id: ADR074', 'patient/tissue id: ADR032', 'patient/tissue id: ADR112', 'patient/tissue id: ADR113', 'patient/tissue id: ADR121', 'patient/tissue id: ADR131', 'patient/tissue id: ADR044', 'patient/tissue id: ADR118', 'patient/tissue id: ADR119', 'patient/tissue id: ADR116'], 2: ['tissue: Human adrenal tissue'], 3: ['tissue subtype: Zona Glomerulosa', 'tissue subtype: Zona Fasciculata', 'tissue subtype: Aldosterone-Producing Adenoma']}\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": "858416f5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "3b13a1f6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:06.749425Z", "iopub.status.busy": "2025-03-25T06:12:06.749311Z", "iopub.status.idle": "2025-03-25T06:12:06.760904Z", "shell.execute_reply": "2025-03-25T06:12:06.760637Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Selected Clinical Data Preview:\n", "{'ADR106': [1.0], 'ADR061': [1.0], 'ADR031': [1.0], 'ADR026': [1.0], 'ADR110': [1.0], 'ADR111': [1.0], 'ADR017': [1.0], 'ADR120': [1.0], 'ADR115': [1.0], 'ADR085': [1.0], 'ADR086': [1.0], 'ADR074': [1.0], 'ADR032': [1.0], 'ADR112': [1.0], 'ADR113': [1.0], 'ADR121': [1.0], 'ADR131': [1.0], 'ADR044': [1.0], 'ADR118': [1.0], 'ADR119': [1.0], 'ADR116': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Pheochromocytoma_and_Paraganglioma/clinical_data/GSE64957.csv\n" ] } ], "source": [ "# Analyzing data availability and type\n", "\n", "# 1. Gene Expression Data Availability\n", "# Looking at the background information, the data is mentioned as \"transcriptome profiling\" \n", "# using \"Affymetrix Human Genome U133 Plus 2.0 Array\", which is a gene expression array.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# For trait (Pheochromocytoma), we see in the sample characteristics that disease information is in row 0\n", "trait_row = 0 # Disease information is available in row 0\n", "\n", "# Age information is not explicitly available in the sample characteristics\n", "age_row = None # Age data is not available\n", "\n", "# Gender information is not available in the sample characteristics\n", "gender_row = None # Gender data is not available\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert disease trait values to binary format.\n", " 0 = Not Pheochromocytoma (e.g., Conn's Syndrome)\n", " 1 = Pheochromocytoma\n", " \"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " # Extract the value after colon and strip whitespace\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Check if the value contains \"Pheochromocytoma\"\n", " if \"Pheochromocytoma\" in value:\n", " return 1\n", " elif \"Conn's Syndrome\" in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age values to continuous format.\n", " Since age data is not available, this function is a placeholder.\n", " \"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender values to binary format.\n", " Since gender data is not available, this function is a placeholder.\n", " \"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait availability\n", "is_trait_available = trait_row is not None\n", "# Call validate_and_save_cohort_info for initial filtering\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. Clinical Feature Extraction\n", "# If trait data is available, extract clinical features\n", "if trait_row is not None:\n", " # Create a clinical data DataFrame from the sample characteristics dictionary\n", " # First, create a dictionary to map sample characteristics rows to their values\n", " sample_chars = {0: [\"disease: Conn's Syndrome\", 'disease: Pheochromocytoma'], \n", " 1: ['patient/tissue id: ADR106', 'patient/tissue id: ADR061', 'patient/tissue id: ADR031', \n", " 'patient/tissue id: ADR026', 'patient/tissue id: ADR110', 'patient/tissue id: ADR111', \n", " 'patient/tissue id: ADR017', 'patient/tissue id: ADR120', 'patient/tissue id: ADR115', \n", " 'patient/tissue id: ADR085', 'patient/tissue id: ADR086', 'patient/tissue id: ADR074', \n", " 'patient/tissue id: ADR032', 'patient/tissue id: ADR112', 'patient/tissue id: ADR113', \n", " 'patient/tissue id: ADR121', 'patient/tissue id: ADR131', 'patient/tissue id: ADR044', \n", " 'patient/tissue id: ADR118', 'patient/tissue id: ADR119', 'patient/tissue id: ADR116'], \n", " 2: ['tissue: Human adrenal tissue'], \n", " 3: ['tissue subtype: Zona Glomerulosa', 'tissue subtype: Zona Fasciculata', \n", " 'tissue subtype: Aldosterone-Producing Adenoma']}\n", " \n", " # Extract sample IDs from the patient/tissue id field\n", " sample_ids = []\n", " for tissue_id in sample_chars[1]:\n", " if ':' in tissue_id:\n", " sample_id = tissue_id.split(':', 1)[1].strip()\n", " sample_ids.append(sample_id)\n", " \n", " # Create a DataFrame with sample IDs as columns\n", " clinical_data = pd.DataFrame(columns=sample_ids)\n", " \n", " # Add sample characteristics as rows\n", " for row_idx, values in sample_chars.items():\n", " for value in values:\n", " clinical_data.loc[row_idx] = value\n", " \n", " # Use geo_select_clinical_features to extract and process the clinical features\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 selected clinical data\n", " preview_selected = preview_df(selected_clinical_df)\n", " print(\"Selected Clinical Data Preview:\")\n", " print(preview_selected)\n", " \n", " # Save the selected clinical data to the output file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "5278a719", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "9c64c49b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:06.762023Z", "iopub.status.busy": "2025-03-25T06:12:06.761910Z", "iopub.status.idle": "2025-03-25T06:12:07.828751Z", "shell.execute_reply": "2025-03-25T06:12:07.828393Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['7892501', '7892502', '7892503', '7892504', '7892505', '7892506',\n", " '7892507', '7892508', '7892509', '7892510', '7892511', '7892512',\n", " '7892513', '7892514', '7892515', '7892516', '7892517', '7892518',\n", " '7892519', '7892520'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "0b451cdf", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "048d79d8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:07.830093Z", "iopub.status.busy": "2025-03-25T06:12:07.829954Z", "iopub.status.idle": "2025-03-25T06:12:07.831887Z", "shell.execute_reply": "2025-03-25T06:12:07.831618Z" } }, "outputs": [], "source": [ "# These identifiers appear to be probe IDs from a microarray platform, not human gene symbols\n", "# They are numeric values that don't match the pattern of human gene symbols (which are typically \n", "# alphanumeric and follow naming conventions like HUGO gene symbols)\n", "# Therefore, these identifiers will need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "1dc1071a", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "6dca035e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:07.833090Z", "iopub.status.busy": "2025-03-25T06:12:07.832973Z", "iopub.status.idle": "2025-03-25T06:12:27.303663Z", "shell.execute_reply": "2025-03-25T06:12:27.303269Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['7892501', '7892502', '7892503', '7892504', '7892505'], 'GB_LIST': [nan, nan, nan, nan, nan], 'SPOT_ID': ['control', 'control', 'control', 'control', 'control'], 'seqname': [nan, nan, nan, nan, nan], 'RANGE_GB': [nan, nan, nan, nan, nan], 'RANGE_STRAND': [nan, nan, nan, nan, nan], 'RANGE_START': [nan, nan, nan, nan, nan], 'RANGE_STOP': [nan, nan, nan, nan, nan], 'probe_count': [4.0, 4.0, 4.0, 4.0, 4.0], 'transcript_cluster_id': [nan, nan, nan, nan, nan], 'exon_id': [nan, nan, nan, nan, nan], 'psr_id': [nan, nan, nan, nan, nan], 'gene_assignment': [nan, nan, nan, nan, nan], 'mrna_assignment': ['--- // pos_control // --- // --- // --- // ---', '--- // neg_control // --- // --- // --- // ---', '--- // neg_control // --- // --- // --- // ---', '--- // neg_control // --- // --- // --- // ---', '--- // neg_control // --- // --- // --- // ---'], 'probeset_type': ['normgene->exon', 'normgene->intron', 'normgene->intron', 'normgene->intron', 'normgene->intron']}\n" ] } ], "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": "b3d85da3", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "34d4a13d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:27.305216Z", "iopub.status.busy": "2025-03-25T06:12:27.304947Z", "iopub.status.idle": "2025-03-25T06:12:31.645241Z", "shell.execute_reply": "2025-03-25T06:12:31.644839Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Checking gene assignment column content:\n", "4201 ---\n", "4202 ---\n", "4203 NM_001005240 // OR4F17 /// NM_001004195 // OR4...\n", "4204 NM_207366 // SEPT14 /// ENST00000388975 // SEP...\n", "4205 NM_001005277 // OR4F16 /// NM_001005221 // OR4...\n", "Name: gene_assignment, dtype: object\n", "\n", "Checking mrna assignment column content:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "0 --- // pos_control // --- // --- // --- // ---\n", "1 --- // neg_control // --- // --- // --- // ---\n", "2 --- // neg_control // --- // --- // --- // ---\n", "3 --- // neg_control // --- // --- // --- // ---\n", "4 --- // neg_control // --- // --- // --- // ---\n", "Name: mrna_assignment, dtype: object\n", "\n", "Checking more gene_assignment rows:\n", "4201 ---\n", "4202 ---\n", "4203 NM_001005240 // OR4F17 /// NM_001004195 // OR4...\n", "4204 NM_207366 // SEPT14 /// ENST00000388975 // SEP...\n", "4205 NM_001005277 // OR4F16 /// NM_001005221 // OR4...\n", "4206 ---\n", "4207 ---\n", "4208 AK172782 // GPAM\n", "4209 ---\n", "4210 AK290103 // LOC100287934 /// ENST00000358533 /...\n", "Name: gene_assignment, dtype: object\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Preview of mapping dataframe:\n", "{'ID': ['7896741', '7896743', '7896745', '7896751', '7896755'], 'Gene': ['NM_001005240', 'NM_207366', 'NM_001005277', 'AK172782', 'AK290103']}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Preview of gene expression data after mapping:\n", "{'GSM1584943': [5.19322, 2.44778, 8.66997, 4.13934, 12.31021], 'GSM1584944': [5.45046, 3.41169, 8.03681, 3.18887, 12.07823], 'GSM1584945': [5.47963, 2.96345, 5.81757, 2.700708, 10.18567], 'GSM1584946': [5.08631, 2.84827, 4.33948, 3.6023, 7.43327], 'GSM1584947': [5.0255, 1.81085, 1.78552, 3.12501, 13.66089], 'GSM1584948': [4.99481, 1.34503, 5.21008, 4.69187, 8.881699999999999], 'GSM1584949': [4.38988, 2.7959, 3.90635, 4.5818900000000005, 10.816559999999999], 'GSM1584950': [4.5515, 1.30668, 6.37311, 2.573874, 12.23703], 'GSM1584951': [5.75597, 2.48221, 7.63714, 4.17232, 11.39821], 'GSM1584952': [4.66634, 2.03563, 7.0959, 3.5415900000000002, 13.247710000000001], 'GSM1584953': [4.08473, 2.80823, 7.1104, 3.312735, 13.44574], 'GSM1584954': [4.65597, 2.62894, 7.77417, 3.88112, 11.078420000000001], 'GSM1584955': [4.83007, 1.6533, 7.19232, 2.854, 9.5272], 'GSM1584956': [4.7537, 2.31225, 6.79486, 3.6642200000000003, 9.921710000000001], 'GSM1584957': [5.15069, 2.63069, 7.86271, 3.49065, 12.2788], 'GSM1584958': [5.6779, 3.48396, 4.8525, 5.918990000000001, 13.384979999999999], 'GSM1584959': [5.45994, 2.56022, 7.77609, 3.53988, 12.444859999999998], 'GSM1584960': [5.02227, 5.10146, 8.61644, 3.7250900000000002, 10.027660000000001], 'GSM1584961': [7.15694, 3.28353, 5.86964, 3.4627600000000003, 11.59552], 'GSM1584962': [4.93662, 4.16163, 3.78101, 3.80152, 8.86363], 'GSM1584963': [4.54247, 1.8906, 8.72946, 3.035, 9.31282], 'GSM1584964': [4.25687, 1.94177, 9.05759, 7.65019, 12.3734], 'GSM1584965': [6.83486, 3.64871, 8.56376, 3.2549, 8.4596], 'GSM1584966': [4.98578, 3.92634, 7.43779, 2.98576, 10.03014], 'GSM1584967': [5.31851, 2.45004, 5.99503, 4.32887, 12.488669999999999], 'GSM1584968': [4.57937, 2.17258, 5.20298, 3.49939, 12.24135], 'GSM1584969': [5.06435, 1.76343, 6.22493, 2.8424240000000003, 12.06936], 'GSM1584970': [5.11216, 2.21501, 9.86725, 4.47997, 10.04344], 'GSM1584971': [4.71073, 1.12122, 7.51166, 4.21522, 12.079889999999999], 'GSM1584972': [7.83383, 2.33424, 7.37312, 3.78003, 13.01005], 'GSM1584973': [4.93197, 1.70454, 6.54588, 6.44184, 11.95235], 'GSM1584974': [5.25106, 2.463, 6.30042, 2.77926, 13.31852], 'GSM1584975': [9.19563, 1.61987, 7.04437, 3.63237, 12.84384], 'GSM1584976': [5.68492, 1.63197, 10.8963, 4.1527899999999995, 12.5866], 'GSM1584977': [4.98383, 2.49523, 8.62789, 4.018861, 11.87474], 'GSM1584978': [4.9948, 2.71936, 7.51238, 3.0647900000000003, 9.9727], 'GSM1584979': [5.17826, 1.83596, 6.46475, 4.32372, 11.15141], 'GSM1584980': [4.65262, 2.39274, 6.61039, 3.61001, 12.37033], 'GSM1584981': [5.62855, 2.54855, 5.31857, 3.75798, 13.07025], 'GSM1584982': [4.88716, 1.25307, 4.92766, 4.7898499999999995, 10.98404], 'GSM1584983': [5.01903, 1.63322, 7.55164, 3.01703, 12.21909], 'GSM1584984': [4.82778, 3.54919, 5.53203, 3.2347799999999998, 12.47591], 'GSM1584985': [4.75475, 2.98581, 8.34413, 4.592090000000001, 12.29232], 'GSM1584986': [4.11025, 1.98518, 7.47203, 3.67768, 13.27468], 'GSM1584987': [5.00014, 2.56119, 6.88617, 3.49224, 9.87356], 'GSM1584988': [5.39761, 2.68591, 4.20132, 3.19334, 8.98231], 'GSM1584989': [4.49565, 2.27794, 8.18306, 3.76419, 12.34984], 'GSM1584990': [5.17386, 2.064, 8.19877, 3.50924, 11.09452], 'GSM1584991': [4.92944, 2.05202, 8.00296, 4.38114, 12.98681], 'GSM1584992': [4.6946, 2.76322, 8.08899, 3.74186, 12.40064], 'GSM1584993': [5.01477, 1.46369, 9.88705, 3.73924, 12.72588], 'GSM1584994': [6.0011, 1.75622, 9.44429, 5.03997, 9.99906], 'GSM1584995': [4.54361, 2.22446, 8.57742, 4.49179, 12.90802], 'GSM1584996': [4.87785, 1.18259, 5.49528, 4.70683, 11.267309999999998], 'GSM1584997': [4.83739, 2.50953, 8.11439, 2.808617, 10.367619999999999]}\n" ] } ], "source": [ "# 1. Identify columns for gene mapping\n", "# Based on the preview, the 'ID' column appears to correspond to the probe identifiers\n", "# For gene symbols, we need to extract them from 'gene_assignment' or 'mrna_assignment'\n", "# Let's examine a few more rows to see what's in these columns\n", "\n", "print(\"Checking gene assignment column content:\")\n", "gene_assignment_samples = gene_annotation['gene_assignment'].dropna().head(5)\n", "print(gene_assignment_samples)\n", "\n", "print(\"\\nChecking mrna assignment column content:\")\n", "mrna_assignment_samples = gene_annotation['mrna_assignment'].dropna().head(5)\n", "print(mrna_assignment_samples)\n", "\n", "# 2. Get the gene mapping dataframe\n", "# Based on observation, we need to extract gene symbols from the gene_assignment column\n", "# Let's create a mapping dataframe with ID and gene symbols extracted from gene_assignment\n", "\n", "# First, check if gene_assignment has content in later rows (first few rows were controls)\n", "print(\"\\nChecking more gene_assignment rows:\")\n", "more_gene_samples = gene_annotation.loc[gene_annotation['gene_assignment'].notna(), 'gene_assignment'].head(10)\n", "print(more_gene_samples)\n", "\n", "# Create the mapping dataframe\n", "# It appears 'gene_assignment' contains gene information in the format:\n", "# \"Gene Symbol // Gene Title // Chromosomal Location // ...\"\n", "mapping_df = gene_annotation[['ID', 'gene_assignment']].copy()\n", "\n", "# Clean and process gene_assignment to extract gene symbols\n", "def extract_gene_symbol(gene_assignment_str):\n", " if pd.isna(gene_assignment_str):\n", " return None\n", " # Typically the gene symbol is the first part before //\n", " parts = gene_assignment_str.split(' // ')\n", " if parts and parts[0] != '---':\n", " return parts[0].strip()\n", " return None\n", "\n", "mapping_df['Gene'] = mapping_df['gene_assignment'].apply(extract_gene_symbol)\n", "mapping_df = mapping_df.dropna(subset=['Gene'])\n", "\n", "print(\"\\nPreview of mapping dataframe:\")\n", "print(preview_df(mapping_df[['ID', 'Gene']], n=5))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df[['ID', 'Gene']])\n", "\n", "# Preview the gene expression data\n", "print(\"\\nPreview of gene expression data after mapping:\")\n", "print(preview_df(gene_data, n=5))\n" ] }, { "cell_type": "markdown", "id": "cab6d577", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "a2c6fda2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:12:31.646693Z", "iopub.status.busy": "2025-03-25T06:12:31.646565Z", "iopub.status.idle": "2025-03-25T06:12:31.739077Z", "shell.execute_reply": "2025-03-25T06:12:31.738625Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Pheochromocytoma_and_Paraganglioma/gene_data/GSE64957.csv\n", "Clinical data shape: (1, 21)\n", "Clinical data sample: ADR106 ADR061 ADR031 ADR026 ADR110 \\\n", "Pheochromocytoma_and_Paraganglioma 1.0 1.0 1.0 1.0 1.0 \n", "\n", " ADR111 ADR017 ADR120 ADR115 ADR085 \\\n", "Pheochromocytoma_and_Paraganglioma 1.0 1.0 1.0 1.0 1.0 \n", "\n", " ... ADR074 ADR032 ADR112 ADR113 \\\n", "Pheochromocytoma_and_Paraganglioma ... 1.0 1.0 1.0 1.0 \n", "\n", " ADR121 ADR131 ADR044 ADR118 ADR119 \\\n", "Pheochromocytoma_and_Paraganglioma 1.0 1.0 1.0 1.0 1.0 \n", "\n", " ADR116 \n", "Pheochromocytoma_and_Paraganglioma 1.0 \n", "\n", "[1 rows x 21 columns]\n", "Transposed clinical data shape: (21, 1)\n", "Clinical data sample IDs: ['ADR106', 'ADR061', 'ADR031', 'ADR026', 'ADR110']...\n", "Gene data sample IDs: ['GSM1584943', 'GSM1584944', 'GSM1584945', 'GSM1584946', 'GSM1584947']...\n", "Number of common samples between clinical and gene data: 0\n", "No common samples between clinical and gene data. Cannot proceed with linking.\n", "Abnormality detected in the cohort: GSE64957. Preprocessing failed.\n", "Data quality check failed. The dataset is not suitable for association studies.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\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. Load the clinical data that was created in step 2\n", "clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", "print(f\"Clinical data shape: {clinical_data.shape}\")\n", "print(f\"Clinical data sample: {clinical_data.head()}\")\n", "\n", "# Check if the clinical data needs to be transposed\n", "# The read_csv might have loaded it with samples as columns, but we need samples as rows\n", "if clinical_data.shape[0] == 1: # If there's only one row (trait row)\n", " clinical_data = clinical_data.T\n", " print(f\"Transposed clinical data shape: {clinical_data.shape}\")\n", " \n", "print(f\"Clinical data sample IDs: {list(clinical_data.index)[:5]}...\")\n", "print(f\"Gene data sample IDs: {list(normalized_gene_data.columns)[:5]}...\")\n", "\n", "# Check for sample ID overlap\n", "clinical_samples = set(clinical_data.index)\n", "gene_samples = set(normalized_gene_data.columns)\n", "common_samples = clinical_samples.intersection(gene_samples)\n", "print(f\"Number of common samples between clinical and gene data: {len(common_samples)}\")\n", "\n", "# Filter data to include only common samples\n", "if len(common_samples) > 0:\n", " clinical_data = clinical_data.loc[list(common_samples)]\n", " normalized_gene_data = normalized_gene_data[list(common_samples)]\n", " print(f\"Filtered to {len(common_samples)} common samples\")\n", "\n", " # Create linked data with samples as rows and features (trait + genes) as columns\n", " linked_data = pd.DataFrame(index=common_samples)\n", " linked_data[trait] = clinical_data.values # Add the trait values\n", " \n", " # Add gene expression data (transposing so samples are rows)\n", " gene_data_for_samples = normalized_gene_data[list(common_samples)].T\n", " for gene in normalized_gene_data.index:\n", " linked_data[gene] = gene_data_for_samples[gene]\n", " \n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # 3. Handle missing values in the linked data\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 4. Determine whether the trait and demographic features are severely biased\n", " if linked_data.shape[0] > 0:\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " else:\n", " print(\"No data remains after handling missing values. Dataset cannot be used.\")\n", " is_trait_biased = True\n", " unbiased_linked_data = linked_data\n", "else:\n", " print(\"No common samples between clinical and gene data. Cannot proceed with linking.\")\n", " linked_data = pd.DataFrame()\n", " is_trait_biased = True\n", " unbiased_linked_data = linked_data\n", "\n", "# 5. Conduct quality check and save the 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_trait_biased, \n", " df=unbiased_linked_data,\n", " note=f\"Dataset contains gene expression data for pheochromocytoma samples. Sample overlap between clinical and genetic data: {len(common_samples)}.\"\n", ")\n", "\n", "# 6. Save the data if it's usable\n", "if is_usable and unbiased_linked_data.shape[0] > 0:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " # Save the data\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data quality check failed. The dataset is not suitable for association studies.\")" ] } ], "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 }