{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "686d0db4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:46:12.445430Z", "iopub.status.busy": "2025-03-25T03:46:12.445325Z", "iopub.status.idle": "2025-03-25T03:46:12.611754Z", "shell.execute_reply": "2025-03-25T03:46:12.611413Z" } }, "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 = \"Rectal_Cancer\"\n", "cohort = \"GSE109057\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Rectal_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Rectal_Cancer/GSE109057\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Rectal_Cancer/GSE109057.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Rectal_Cancer/gene_data/GSE109057.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Rectal_Cancer/clinical_data/GSE109057.csv\"\n", "json_path = \"../../output/preprocess/Rectal_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "13d79464", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "2f74101c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:46:12.613170Z", "iopub.status.busy": "2025-03-25T03:46:12.613028Z", "iopub.status.idle": "2025-03-25T03:46:12.829610Z", "shell.execute_reply": "2025-03-25T03:46:12.829270Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptome analysis by expression microarrays of rectal cancer derived from the Cancer Institute Hospital of Japanese Foundation for Cancer Research\"\n", "!Series_summary\t\"We performed the expression microrarray experiments for mRNA of rectal cancer tissue.\"\n", "!Series_overall_design\t\"Messenger RNA were extracted from primary tumor of 90 rectal cancer patients, hybridized and scanned with Affymetrix PrimeView Human Gene Expression Array. There are 91 samples because one sample was hybridized twice, once in each batch, and is represented by GSM2928780 and GSM2928794.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: rectal cancer'], 1: ['Sex: M', 'Sex: F'], 2: ['age: 35 <= age < 40', 'age: 30 <= age < 35', 'age: 55 <= age < 60', 'age: 45 <= age < 50', 'age: 65 <= age < 70', 'age: 75 <= age < 80', 'age: 70 <= age < 75', 'age: 60 <= age < 65', 'age: 50 <= age < 55', 'age: 80 <= age < 85', 'age: 40 <= age < 45'], 3: ['batch: Batch 1', 'batch: Batch 2']}\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": "cd2dfc76", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "1780f85d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:46:12.830740Z", "iopub.status.busy": "2025-03-25T03:46:12.830634Z", "iopub.status.idle": "2025-03-25T03:46:12.844674Z", "shell.execute_reply": "2025-03-25T03:46:12.844399Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview:\n", "{'GSM2928730': [1.0, 37.5, 1.0], 'GSM2928731': [1.0, 32.5, 1.0], 'GSM2928732': [1.0, 57.5, 1.0], 'GSM2928733': [1.0, 47.5, 1.0], 'GSM2928734': [1.0, 67.5, 0.0], 'GSM2928735': [1.0, 77.5, 1.0], 'GSM2928736': [1.0, 57.5, 1.0], 'GSM2928737': [1.0, 47.5, 1.0], 'GSM2928738': [1.0, 72.5, 1.0], 'GSM2928739': [1.0, 62.5, 1.0], 'GSM2928740': [1.0, 52.5, 1.0], 'GSM2928741': [1.0, 32.5, 1.0], 'GSM2928742': [1.0, 67.5, 1.0], 'GSM2928743': [1.0, 47.5, 1.0], 'GSM2928744': [1.0, 67.5, 1.0], 'GSM2928745': [1.0, 57.5, 1.0], 'GSM2928746': [1.0, 47.5, 1.0], 'GSM2928747': [1.0, 47.5, 1.0], 'GSM2928748': [1.0, 72.5, 1.0], 'GSM2928749': [1.0, 67.5, 1.0], 'GSM2928750': [1.0, 47.5, 1.0], 'GSM2928751': [1.0, 67.5, 1.0], 'GSM2928752': [1.0, 67.5, 0.0], 'GSM2928753': [1.0, 57.5, 1.0], 'GSM2928754': [1.0, 52.5, 1.0], 'GSM2928755': [1.0, 67.5, 1.0], 'GSM2928756': [1.0, 47.5, 1.0], 'GSM2928757': [1.0, 62.5, 1.0], 'GSM2928758': [1.0, 62.5, 1.0], 'GSM2928759': [1.0, 67.5, 0.0], 'GSM2928760': [1.0, 62.5, 1.0], 'GSM2928761': [1.0, 67.5, 0.0], 'GSM2928762': [1.0, 57.5, 1.0], 'GSM2928763': [1.0, 57.5, 1.0], 'GSM2928764': [1.0, 62.5, 1.0], 'GSM2928765': [1.0, 52.5, 1.0], 'GSM2928766': [1.0, 82.5, 0.0], 'GSM2928767': [1.0, 57.5, 0.0], 'GSM2928768': [1.0, 47.5, 0.0], 'GSM2928769': [1.0, 72.5, 1.0], 'GSM2928770': [1.0, 42.5, 1.0], 'GSM2928771': [1.0, 67.5, 0.0], 'GSM2928772': [1.0, 62.5, 1.0], 'GSM2928773': [1.0, 57.5, 1.0], 'GSM2928774': [1.0, 62.5, 1.0], 'GSM2928775': [1.0, 52.5, 1.0], 'GSM2928776': [1.0, 52.5, 1.0], 'GSM2928777': [1.0, 62.5, 0.0], 'GSM2928778': [1.0, 47.5, 1.0], 'GSM2928779': [1.0, 62.5, 1.0], 'GSM2928780': [1.0, 67.5, 1.0], 'GSM2928781': [1.0, 67.5, 1.0], 'GSM2928782': [1.0, 67.5, 1.0], 'GSM2928783': [1.0, 62.5, 1.0], 'GSM2928784': [1.0, 77.5, 0.0], 'GSM2928785': [1.0, 62.5, 0.0], 'GSM2928786': [1.0, 57.5, 1.0], 'GSM2928787': [1.0, 62.5, 0.0], 'GSM2928788': [1.0, 57.5, 0.0], 'GSM2928789': [1.0, 77.5, 0.0], 'GSM2928790': [1.0, 62.5, 0.0], 'GSM2928791': [1.0, 47.5, 1.0], 'GSM2928792': [1.0, 62.5, 1.0], 'GSM2928793': [1.0, 62.5, 1.0], 'GSM2928794': [1.0, 67.5, 1.0], 'GSM2928795': [1.0, 47.5, 0.0], 'GSM2928796': [1.0, 32.5, 1.0], 'GSM2928797': [1.0, 47.5, 1.0], 'GSM2928798': [1.0, 52.5, 0.0], 'GSM2928799': [1.0, 57.5, 1.0], 'GSM2928800': [1.0, 67.5, 1.0], 'GSM2928801': [1.0, 47.5, 1.0], 'GSM2928802': [1.0, 62.5, 0.0], 'GSM2928803': [1.0, 52.5, 0.0], 'GSM2928804': [1.0, 72.5, 0.0], 'GSM2928805': [1.0, 67.5, 1.0], 'GSM2928806': [1.0, 57.5, 0.0], 'GSM2928807': [1.0, 62.5, 0.0], 'GSM2928808': [1.0, 47.5, 0.0], 'GSM2928809': [1.0, 42.5, 1.0], 'GSM2928810': [1.0, 37.5, 0.0], 'GSM2928811': [1.0, 72.5, 0.0], 'GSM2928812': [1.0, 72.5, 1.0], 'GSM2928813': [1.0, 72.5, 1.0], 'GSM2928814': [1.0, 77.5, 0.0], 'GSM2928815': [1.0, 77.5, 0.0], 'GSM2928816': [1.0, 72.5, 1.0], 'GSM2928817': [1.0, 62.5, 1.0], 'GSM2928818': [1.0, 37.5, 1.0], 'GSM2928819': [1.0, 52.5, 1.0], 'GSM2928820': [1.0, 72.5, 1.0]}\n", "Clinical data saved to ../../output/preprocess/Rectal_Cancer/clinical_data/GSE109057.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on background information, this dataset contains gene expression data from Affymetrix arrays\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Rectal Cancer is the trait we're studying, and it's available in row 0\n", "trait_row = 0\n", "\n", "# Gender data is available in row 1\n", "gender_row = 1\n", "\n", "# Age data is available in row 2\n", "age_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " # All samples are rectal cancer \"tissue: rectal cancer\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after colon\n", " parts = value.split(\": \")\n", " if len(parts) < 2:\n", " return None\n", " \n", " tissue = parts[1].strip()\n", " if \"rectal cancer\" in tissue.lower():\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_gender(value):\n", " # Gender data in format \"Sex: M\" or \"Sex: F\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after colon\n", " parts = value.split(\": \")\n", " if len(parts) < 2:\n", " return None\n", " \n", " gender = parts[1].strip()\n", " if gender == 'M':\n", " return 1\n", " elif gender == 'F':\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " # Age data in format \"age: X <= age < Y\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " # Extract the value after colon\n", " parts = value.split(\": \")\n", " if len(parts) < 2:\n", " return None\n", " \n", " age_range = parts[1].strip()\n", " # Extract the lower and upper bounds of the age range\n", " try:\n", " age_parts = age_range.split(\" \")\n", " lower_bound = int(age_parts[0])\n", " upper_bound = int(age_parts[-1])\n", " # Return the midpoint of the age range\n", " return (lower_bound + upper_bound) / 2\n", " except:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# trait_row is not None, so is_trait_available should be True\n", "is_trait_available = trait_row is not None\n", "\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# Since trait_row is not None, we proceed with clinical feature extraction\n", "if trait_row is not None:\n", " # Extract clinical features\n", " 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 and save clinical data\n", " print(\"Clinical Data Preview:\")\n", " print(preview_df(clinical_df))\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save clinical data to CSV\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": "259cabe1", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "2606920f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:46:12.845694Z", "iopub.status.busy": "2025-03-25T03:46:12.845593Z", "iopub.status.idle": "2025-03-25T03:46:13.215570Z", "shell.execute_reply": "2025-03-25T03:46:13.215202Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at',\n", " '11715104_s_at', '11715105_at', '11715106_x_at', '11715107_s_at',\n", " '11715108_x_at', '11715109_at', '11715110_at', '11715111_s_at',\n", " '11715112_at', '11715113_x_at', '11715114_x_at', '11715115_s_at',\n", " '11715116_s_at', '11715117_x_at', '11715118_s_at', '11715119_s_at'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the file paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "9e0f8f4c", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "94682d46", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:46:13.216852Z", "iopub.status.busy": "2025-03-25T03:46:13.216733Z", "iopub.status.idle": "2025-03-25T03:46:13.218560Z", "shell.execute_reply": "2025-03-25T03:46:13.218284Z" } }, "outputs": [], "source": [ "# These appear to be probe set IDs from an Affymetrix microarray platform, not human gene symbols.\n", "# The format \"11715100_at\" is typical of Affymetrix probe identifiers.\n", "# These will need to be mapped to standard human gene symbols for analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "49f7a5e2", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "b55cc2b8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:46:13.219537Z", "iopub.status.busy": "2025-03-25T03:46:13.219437Z", "iopub.status.idle": "2025-03-25T03:46:25.748864Z", "shell.execute_reply": "2025-03-25T03:46:25.748471Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array', 'Human Genome PrimeView Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16', '30-Mar-16'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database'], 'Transcript ID(Array Design)': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Target Description': ['g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g22748780 /TID=g22748780 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g22748780 /REP_ORG=Homo sapiens', 'g30039713 /TID=g30039713 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g30039713 /REP_ORG=Homo sapiens'], 'GB_ACC': [nan, nan, nan, nan, nan], 'GI': [21264570.0, 21264570.0, 21264570.0, 22748780.0, 30039713.0], 'Representative Public ID': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Archival UniGene Cluster': ['---', '---', '---', '---', '---'], 'UniGene ID': ['Hs.247813', 'Hs.247813', 'Hs.247813', 'Hs.465643', 'Hs.352515'], 'Genome Version': ['February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)'], 'Alignments': ['chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr19:4639529-5145579 (+) // 48.53 // p13.3', 'chr17:72920369-72929640 (+) // 100.0 // q25.1'], 'Gene Title': ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g', 'tumor necrosis factor, alpha-induced protein 8-like 1', 'otopetrin 2'], 'Gene Symbol': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2'], 'Chromosomal Location': ['chr6p22.2', 'chr6p22.2', 'chr6p22.2', 'chr19p13.3', 'chr17q25.1'], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000273983 /// OTTHUMG00000014436', 'ENSG00000185361 /// OTTHUMG00000182013', 'ENSG00000183034 /// OTTHUMG00000179215'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '615869', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575 /// XP_005259544 /// XP_011525982', 'NP_835454 /// XP_011523781'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362 /// XM_005259487 /// XM_011527680', 'NM_178160 /// XM_011525479'], 'Gene Ontology Biological Process': ['0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0000183 // chromatin silencing at rDNA // traceable author statement /// 0002230 // positive regulation of defense response to virus by host // inferred from mutant phenotype /// 0006325 // chromatin organization // traceable author statement /// 0006334 // nucleosome assembly // inferred from direct assay /// 0006334 // nucleosome assembly // inferred from mutant phenotype /// 0006335 // DNA replication-dependent nucleosome assembly // inferred from direct assay /// 0007264 // small GTPase mediated signal transduction // traceable author statement /// 0007596 // blood coagulation // traceable author statement /// 0010467 // gene expression // traceable author statement /// 0031047 // gene silencing by RNA // traceable author statement /// 0032776 // DNA methylation on cytosine // traceable author statement /// 0040029 // regulation of gene expression, epigenetic // traceable author statement /// 0044267 // cellular protein metabolic process // traceable author statement /// 0045814 // negative regulation of gene expression, epigenetic // traceable author statement /// 0051290 // protein heterotetramerization // inferred from direct assay /// 0060968 // regulation of gene silencing // inferred from direct assay /// 0098792 // xenophagy // inferred from mutant phenotype', '0032007 // negative regulation of TOR signaling // not recorded /// 0032007 // negative regulation of TOR signaling // inferred from sequence or structural similarity', '---'], 'Gene Ontology Cellular Component': ['0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0000228 // nuclear chromosome // inferred from direct assay /// 0000786 // nucleosome // inferred from direct assay /// 0000788 // nuclear nucleosome // inferred from direct assay /// 0005576 // extracellular region // traceable author statement /// 0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // traceable author statement /// 0005694 // chromosome // inferred from electronic annotation /// 0016020 // membrane // inferred from direct assay /// 0043234 // protein complex // inferred from direct assay /// 0070062 // extracellular exosome // inferred from direct assay', '0005737 // cytoplasm // not recorded /// 0005737 // cytoplasm // inferred from sequence or structural similarity', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0042393 // histone binding // inferred from physical interaction /// 0046982 // protein heterodimerization activity // inferred from electronic annotation', '0005515 // protein binding // inferred from physical interaction', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR007125 // Histone H2A/H2B/H3 // 9.3E-34 /// IPR007125 // Histone H2A/H2B/H3 // 1.7E-37', 'IPR008477 // Protein of unknown function DUF758 // 8.4E-86 /// IPR008477 // Protein of unknown function DUF758 // 6.8E-90', 'IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 9.4E-43 /// IPR004878 // Otopetrin // 3.9E-18 /// IPR004878 // Otopetrin // 3.8E-20 /// IPR004878 // Otopetrin // 5.2E-16'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 4 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 9 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 6 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'ENST00000614378(11),NM_003534(11),OTTHUMT00000040099(11),uc003nhi.3', 'BC017672(11),BC044250(9),ENST00000327473(11),ENST00000536716(11),NM_001167942(11),NM_152362(11),OTTHUMT00000458662(11),uc002max.3,uc021une.1', 'ENST00000331427(11),ENST00000580223(11),NM_178160(11),OTTHUMT00000445306(11),uc010wrp.2,XM_011525479(11)'], 'Transcript Assignments': ['ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000029819 // cdna:genscan chromosome:GRCh38:6:26270974:26271384:-1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'ENST00000614378 // ensembl_havana_transcript:known chromosome:GRCh38:6:26269405:26271815:-1 gene:ENSG00000273983 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // --- /// OTTHUMT00000040099 // otter:known chromosome:VEGA61:6:26269405:26271815:-1 gene:OTTHUMG00000014436 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc003nhi.3 // --- // ucsc_genes // 11 // ---', 'BC017672 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone MGC:17791 IMAGE:3885999), complete cds. // gb // 11 // --- /// BC044250 // accn=BC044250 class=mRNAlike lncRNA name=Human lncRNA ref=JounralRNA transcriptId=673 cpcScore=-0.1526100 cnci=-0.1238602 // noncode // 9 // --- /// BC044250 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // ensembl_havana_transcript:known chromosome:GRCh38:19:4639518:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000536716 // ensembl:known chromosome:GRCh38:19:4640017:4655568:1 gene:ENSG00000185361 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_001167942 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 1, mRNA. // refseq // 11 // --- /// NM_152362 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 2, mRNA. // refseq // 11 // --- /// NONHSAT060631 // Non-coding transcript identified by NONCODE: Exonic // noncode // 9 // --- /// OTTHUMT00000458662 // otter:known chromosome:VEGA61:19:4639518:4655568:1 gene:OTTHUMG00000182013 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc002max.3 // --- // ucsc_genes // 11 // --- /// uc021une.1 // --- // ucsc_genes // 11 // ---', 'ENST00000331427 // ensembl:known chromosome:GRCh38:17:74924275:74933911:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// ENST00000580223 // havana:known chromosome:GRCh38:17:74924603:74933912:1 gene:ENSG00000183034 gene_biotype:protein_coding transcript_biotype:protein_coding // ensembl // 11 // --- /// GENSCAN00000013715 // cdna:genscan chromosome:GRCh38:17:74924633:74933545:1 transcript_biotype:protein_coding // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // --- /// OTTHUMT00000445306 // otter:known chromosome:VEGA61:17:74924603:74933912:1 gene:OTTHUMG00000179215 gene_biotype:protein_coding transcript_biotype:protein_coding // vega // 11 // --- /// uc010wrp.2 // --- // ucsc_genes // 11 // --- /// XM_011525479 // PREDICTED: Homo sapiens otopetrin 2 (OTOP2), transcript variant X1, mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['---', '---', 'GENSCAN00000029819 // ensembl // 4 // Cross Hyb Matching Probes', '---', '---'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\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": "baddc99a", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "0370eecd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:46:25.750123Z", "iopub.status.busy": "2025-03-25T03:46:25.749994Z", "iopub.status.idle": "2025-03-25T03:46:26.181913Z", "shell.execute_reply": "2025-03-25T03:46:26.181583Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview (first 5 rows):\n", " ID Gene\n", "0 11715100_at HIST1H3G\n", "1 11715101_s_at HIST1H3G\n", "2 11715102_x_at HIST1H3G\n", "3 11715103_x_at TNFAIP8L1\n", "4 11715104_s_at OTOP2\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data preview (first 10 genes):\n", "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS',\n", " 'AACS', 'AACSP1'],\n", " dtype='object', name='Gene')\n", "\n", "Gene data shape: (19963, 91)\n" ] } ], "source": [ "# 1. Based on the preview, it looks like:\n", "# - 'ID' column in gene_annotation contains the same probe IDs as seen in the gene expression data\n", "# - 'Gene Symbol' column contains the gene symbols we want to map to\n", "\n", "# 2. Get a gene mapping dataframe by extracting these two columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "\n", "# Print a preview of the mapping data for verification\n", "print(\"Gene mapping preview (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Convert probe-level measurements to gene expression data by applying the gene mapping\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Print the first 10 gene symbols to verify the conversion\n", "print(\"\\nGene data preview (first 10 genes):\")\n", "print(gene_data.index[:10])\n", "\n", "# Print the shape of the converted dataset\n", "print(f\"\\nGene data shape: {gene_data.shape}\")\n" ] }, { "cell_type": "markdown", "id": "7d8dbdac", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "f906846f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:46:26.183217Z", "iopub.status.busy": "2025-03-25T03:46:26.183103Z", "iopub.status.idle": "2025-03-25T03:46:27.391910Z", "shell.execute_reply": "2025-03-25T03:46:27.391559Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (19758, 91)\n", "First few normalized gene symbols: ['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AACSP1']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Rectal_Cancer/gene_data/GSE109057.csv\n", "Clinical features loaded from ../../output/preprocess/Rectal_Cancer/clinical_data/GSE109057.csv\n", "Clinical features shape: (3, 91)\n", "Linked data shape: (94, 19849)\n", "First few columns: ['GSM2928730', 'GSM2928731', 'GSM2928732', 'GSM2928733', 'GSM2928734']\n", "Columns in linked_data: ['GSM2928730', 'GSM2928731', 'GSM2928732', 'GSM2928733', 'GSM2928734']\n", "Using trait column: GSM2928730\n", "Shape after handling missing values: (3, 91)\n", "For the feature 'GSM2928730', the least common label is '37.5' with 1 occurrences. This represents 33.33% of the dataset.\n", "The distribution of the feature 'GSM2928730' in this dataset is fine.\n", "\n", "A new JSON file was created at: ../../output/preprocess/Rectal_Cancer/cohort_info.json\n", "Linked data saved to ../../output/preprocess/Rectal_Cancer/GSE109057.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(f\"First few normalized gene symbols: {list(normalized_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", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# Get clinical data from previous step\n", "# Load the clinical features from the saved file\n", "clinical_file_path = out_clinical_data_file\n", "if os.path.exists(clinical_file_path):\n", " clinical_features = pd.read_csv(clinical_file_path)\n", " print(f\"Clinical features loaded from {clinical_file_path}\")\n", " print(f\"Clinical features shape: {clinical_features.shape}\")\n", "else:\n", " # If file doesn't exist, we need to extract it again\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=2,\n", " convert_trait=convert_trait,\n", " age_row=3,\n", " convert_age=convert_age,\n", " gender_row=None,\n", " convert_gender=None\n", " )\n", " print(f\"Clinical features re-extracted\")\n", " print(f\"Clinical features shape: {clinical_features.shape}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features.T, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(f\"First few columns: {list(linked_data.columns[:5])}\")\n", "\n", "# Check what columns are available in the linked data\n", "print(f\"Columns in linked_data: {list(linked_data.columns[:5])}\")\n", "\n", "# 3. Handle missing values in the linked data\n", "# Find the correct trait column name (it should be the first column)\n", "trait_column = linked_data.columns[0]\n", "print(f\"Using trait column: {trait_column}\")\n", "\n", "linked_data_processed = handle_missing_values(linked_data, trait_column)\n", "print(f\"Shape after handling missing values: {linked_data_processed.shape}\")\n", "\n", "# Add validation check - if no samples remain, note the issue\n", "if linked_data_processed.shape[0] == 0:\n", " print(\"No samples remain after handling missing values. The dataset cannot be processed further.\")\n", " is_trait_biased = True # Mark as biased since we can't use it\n", " unbiased_linked_data = linked_data_processed\n", "else:\n", " # 4. Determine whether the trait and demographic features are severely biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_processed, trait_column)\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=\"Dataset contains gene expression data from rectal cancer patients with treatment response data (sensitive/resistant).\"\n", ")\n", "\n", "# 6. Save the data if it's usable\n", "if is_usable:\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 }