{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "2142ee66", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:32:35.603596Z", "iopub.status.busy": "2025-03-25T04:32:35.603370Z", "iopub.status.idle": "2025-03-25T04:32:35.780921Z", "shell.execute_reply": "2025-03-25T04:32:35.780575Z" } }, "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 = \"Uterine_Corpus_Endometrial_Carcinoma\"\n", "cohort = \"GSE32507\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Uterine_Corpus_Endometrial_Carcinoma\"\n", "in_cohort_dir = \"../../input/GEO/Uterine_Corpus_Endometrial_Carcinoma/GSE32507\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/GSE32507.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/gene_data/GSE32507.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/clinical_data/GSE32507.csv\"\n", "json_path = \"../../output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "b8991e42", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "51caf6a0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:32:35.782307Z", "iopub.status.busy": "2025-03-25T04:32:35.782177Z", "iopub.status.idle": "2025-03-25T04:32:35.921413Z", "shell.execute_reply": "2025-03-25T04:32:35.921121Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the cohort directory:\n", "['GSE32507_family.soft.gz', 'GSE32507_series_matrix.txt.gz']\n", "Identified SOFT files: ['GSE32507_family.soft.gz']\n", "Identified matrix files: ['GSE32507_series_matrix.txt.gz']\n", "\n", "Background Information:\n", "!Series_title\t\"Expression profile of carcinosarcoma (CS), endometrioid adenocarcinoma (EC) and sarcoma (US) of uterine corpus\"\n", "!Series_summary\t\"To examine the simlarity of CS, EC and US, we performed microarray analysis of frozen tissues of 46 patients (14 CS, 24 EC and 8 US).\"\n", "!Series_overall_design\t\"Frozen tissues of 46 patients (14CS, 24EC and 8US) were subjected to cDNA microarray analysis.\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: carcinosarcoma', 'tissue: endometrioid adenocarcinoma', 'tissue: sarcoma'], 1: ['carcinosarcoma status: : heterologous', 'carcinosarcoma status: : homologous', nan]}\n" ] } ], "source": [ "# 1. Let's first list the directory contents to understand what files are available\n", "import os\n", "\n", "print(\"Files in the cohort directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# Adapt file identification to handle different naming patterns\n", "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n", "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n", "\n", "# If no files with these patterns are found, look for alternative file types\n", "if not soft_files:\n", " soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "if not matrix_files:\n", " matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "\n", "print(\"Identified SOFT files:\", soft_files)\n", "print(\"Identified matrix files:\", matrix_files)\n", "\n", "# Use the first files found, if any\n", "if len(soft_files) > 0 and len(matrix_files) > 0:\n", " soft_file = os.path.join(in_cohort_dir, soft_files[0])\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n", " print(background_info)\n", " print(\"\\nSample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", "else:\n", " print(\"No appropriate files found in the directory.\")\n" ] }, { "cell_type": "markdown", "id": "5c881d32", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "7163b15f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:32:35.922569Z", "iopub.status.busy": "2025-03-25T04:32:35.922469Z", "iopub.status.idle": "2025-03-25T04:32:35.931284Z", "shell.execute_reply": "2025-03-25T04:32:35.931010Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original trait values:\n", " \"tissue: carcinosarcoma\"\n", " \"tissue: endometrioid adenocarcinoma\"\n", " \"tissue: sarcoma\"\n", "Preview of selected clinical features:\n", "{'Sample_ID': [0.0], 'characteristics_ch1': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/clinical_data/GSE32507.csv\n" ] } ], "source": [ "# Check availability of gene expression data\n", "# This dataset seems to contain gene expression data based on the background information\n", "# mentioning \"cDNA microarray analysis\", so set is_gene_available to True\n", "is_gene_available = True\n", "\n", "# Variable availability and data type conversion\n", "# 1. Trait availability: based on the sample characteristics, tissue type is at key 0\n", "# which differentiates between carcinosarcoma, endometrioid adenocarcinoma, and sarcoma\n", "trait_row = 0\n", "\n", "# 2. Age data: not available in sample characteristics\n", "age_row = None\n", "\n", "# 3. Gender data: not available, and since this is a study about uterine corpus,\n", "# we can assume all patients are female (but we'll set it as unavailable since it's a constant)\n", "gender_row = None\n", "\n", "# Define conversion functions for each variable\n", "def convert_trait(value):\n", " \"\"\"Convert the trait value to a binary variable.\n", " Since we're focused on Uterine_Corpus_Endometrial_Carcinoma, we'll consider\n", " 'endometrioid adenocarcinoma' as our positive class (1) and other types as negative (0).\n", " \"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value if it contains a colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'endometrioid adenocarcinoma' in value.lower():\n", " return 1\n", " else: # carcinosarcoma or sarcoma\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function for converting age.\"\"\"\n", " return None # Not used as age data is not available\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function for converting gender.\"\"\"\n", " return None # Not used as gender data is not available\n", "\n", "# Check if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Save metadata\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# Extract clinical features if trait data is available\n", "if is_trait_available:\n", " try:\n", " # Load all sample characteristics from the matrix file\n", " matrix_file = f\"{in_cohort_dir}/GSE32507_series_matrix.txt.gz\"\n", " \n", " # Create a dictionary to store sample information\n", " sample_data = {}\n", " current_sample_idx = -1\n", " sample_ids = []\n", " \n", " with gzip.open(matrix_file, 'rt') as file:\n", " for line in file:\n", " line = line.strip()\n", " \n", " # Extract sample GEO IDs\n", " if line.startswith('!Sample_geo_accession'):\n", " sample_ids = line.split('\\t')[1:]\n", " for idx, sample_id in enumerate(sample_ids):\n", " sample_data[sample_id] = {}\n", " \n", " # Extract characteristics\n", " elif line.startswith('!Sample_characteristics_ch1'):\n", " characteristics = line.split('\\t')[1:]\n", " \n", " # Match each characteristic to its corresponding sample\n", " for idx, characteristic in enumerate(characteristics):\n", " if idx < len(sample_ids):\n", " sample_id = sample_ids[idx]\n", " \n", " # Append to list of characteristics for this sample\n", " if 'characteristics' not in sample_data[sample_id]:\n", " sample_data[sample_id]['characteristics'] = []\n", " \n", " sample_data[sample_id]['characteristics'].append(characteristic)\n", " \n", " # If we've processed all sample data, stop reading\n", " elif line.startswith('!series_matrix_table_begin'):\n", " break\n", " \n", " # Create a DataFrame to represent our clinical data\n", " clinical_rows = []\n", " \n", " # For each row in the trait_row (key 0 in the sample characteristics)\n", " for sample_id, data in sample_data.items():\n", " if 'characteristics' in data and len(data['characteristics']) > trait_row:\n", " trait_value = data['characteristics'][trait_row]\n", " clinical_rows.append({\n", " 'Sample_ID': sample_id,\n", " 'characteristics_ch1': trait_value\n", " })\n", " \n", " clinical_df = pd.DataFrame(clinical_rows)\n", " \n", " if not clinical_df.empty:\n", " # Print original values for debugging\n", " print(\"Original trait values:\")\n", " for val in clinical_df['characteristics_ch1'].unique():\n", " print(f\" {val}\")\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_df,\n", " trait=trait,\n", " trait_row=0, # Use 0 here because we've already extracted the trait row\n", " convert_trait=convert_trait,\n", " age_row=None,\n", " convert_age=None,\n", " gender_row=None,\n", " convert_gender=None\n", " )\n", " \n", " # Preview the data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\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 the clinical data\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " else:\n", " print(\"No clinical data found in the matrix file.\")\n", " except Exception as e:\n", " print(f\"Error extracting or saving clinical features: {e}\")\n", " import traceback\n", " traceback.print_exc()\n" ] }, { "cell_type": "markdown", "id": "26a3e09a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "1d33866a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:32:35.932306Z", "iopub.status.busy": "2025-03-25T04:32:35.932205Z", "iopub.status.idle": "2025-03-25T04:32:36.153825Z", "shell.execute_reply": "2025-03-25T04:32:36.153458Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n", " '(+)E1A_r60_a135', '(+)E1A_r60_a20', '(+)E1A_r60_a22', '(+)E1A_r60_a97',\n", " '(+)E1A_r60_n11', '(+)E1A_r60_n9', '(+)eQC-39', '(+)eQC-41',\n", " '(+)eQC-42', '(-)3xSLv1', 'A_23_P100001', 'A_23_P100011',\n", " 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100092'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data shape: (41073, 46)\n" ] } ], "source": [ "# Use the helper function to get the proper file paths\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data\n", "try:\n", " gene_data = get_genetic_data(matrix_file_path)\n", " \n", " # Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", " \n", " # Print shape to understand the dataset dimensions\n", " print(f\"\\nGene expression data shape: {gene_data.shape}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "211ae49e", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "57f28652", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:32:36.155076Z", "iopub.status.busy": "2025-03-25T04:32:36.154963Z", "iopub.status.idle": "2025-03-25T04:32:36.156832Z", "shell.execute_reply": "2025-03-25T04:32:36.156558Z" } }, "outputs": [], "source": [ "# Looking at the gene identifiers in the gene expression data\n", "# The identifiers (e.g., \"A_23_P100001\") appear to be Agilent microarray probe IDs, not standard human gene symbols\n", "# These probe IDs need to be mapped to official gene symbols for proper analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "640808c8", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "b4477218", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:32:36.157941Z", "iopub.status.busy": "2025-03-25T04:32:36.157846Z", "iopub.status.idle": "2025-03-25T04:32:40.427626Z", "shell.execute_reply": "2025-03-25T04:32:40.427259Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample of gene expression data (first 5 rows, first 5 columns):\n", " GSM804806 GSM804807 GSM804808 GSM804809 GSM804810\n", "ID \n", "(+)E1A_r60_1 0.187544 1.125378 0.308133 1.549022 0.297386\n", "(+)E1A_r60_3 -0.057653 0.098557 -0.019575 2.112438 0.290960\n", "(+)E1A_r60_a104 0.309965 0.280072 -0.410076 1.748169 -0.370941\n", "(+)E1A_r60_a107 0.291783 1.178800 -0.036704 1.191367 0.090694\n", "(+)E1A_r60_a135 0.274253 1.303301 0.063972 1.639965 0.304410\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Platform information:\n", "!Series_title = Expression profile of carcinosarcoma (CS), endometrioid adenocarcinoma (EC) and sarcoma (US) of uterine corpus\n", "!Platform_title = Agilent-014850 Whole Human Genome Microarray 4x44K G4112F (Probe Name version)\n", "!Platform_description = This multi-pack (4X44K) formatted microarray represents a compiled view of the human genome as it is understood today. The sequence information used to design this product was derived from a broad survey of well known sources such as RefSeq, Goldenpath, Ensembl, Unigene and others. The resulting view of the human genome covers 41K unique genes and transcripts which have been verified and optimized by alignment to the human genome assembly and by Agilent's Empirical Validation process.\n", "!Platform_description =\n", "!Platform_description = *** The ID column includes the Agilent Probe Names. A different version of this platform with the Agilent Feature Extraction feature numbers in the ID column is assigned accession number GPL4133\n", "#DESCRIPTION = Description\n", "ID\tSPOT_ID\tCONTROL_TYPE\tREFSEQ\tGB_ACC\tGENE\tGENE_SYMBOL\tGENE_NAME\tUNIGENE_ID\tENSEMBL_ID\tTIGR_ID\tACCESSION_STRING\tCHROMOSOMAL_LOCATION\tCYTOBAND\tDESCRIPTION\tGO_ID\tSEQUENCE\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n", "!Sample_description = Gene expression data from frozen tumor samples\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation columns:\n", "['ID', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']\n", "\n", "Gene annotation preview:\n", "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'SPOT_ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GB_ACC': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GENE': [400451.0, 10239.0, 9899.0, 348093.0, 57099.0], 'GENE_SYMBOL': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN'], 'GENE_NAME': ['family with sequence similarity 174, member B', 'adaptor-related protein complex 3, sigma 2 subunit', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein with multiple splicing 2', 'apoptosis, caspase activation inhibitor'], 'UNIGENE_ID': ['Hs.27373', 'Hs.632161', 'Hs.21754', 'Hs.436518', 'Hs.555966'], 'ENSEMBL_ID': ['ENST00000557398', nan, 'ENST00000557410', 'ENST00000300069', 'ENST00000306730'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355', 'ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582', 'ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276', 'ref|NM_194272|ens|ENST00000300069|gb|AK127873|gb|AK124123', 'ref|NM_020371|ens|ENST00000306730|gb|AF283508|gb|BC010488'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:90378743-90378684', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein with multiple splicing 2 (RBPMS2), mRNA [NM_194272]', 'Homo sapiens apoptosis, caspase activation inhibitor (AVEN), mRNA [NM_020371]'], 'GO_ID': ['GO:0016020(membrane)|GO:0016021(integral to membrane)', 'GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle)', 'GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse)', 'GO:0000166(nucleotide binding)|GO:0003676(nucleic acid binding)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0005624(membrane fraction)|GO:0006915(apoptosis)|GO:0006916(anti-apoptosis)|GO:0012505(endomembrane system)|GO:0016020(membrane)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA']}\n", "\n", "Matching rows in annotation for sample IDs: 470\n", "\n", "Potential gene symbol columns: ['GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID']\n", "\n", "Is this dataset likely to contain gene expression data? True\n" ] } ], "source": [ "# 1. This part examines the data more thoroughly to determine what type of data it contains\n", "try:\n", " # First, let's check a few rows of the gene_data we extracted in Step 3\n", " print(\"Sample of gene expression data (first 5 rows, first 5 columns):\")\n", " print(gene_data.iloc[:5, :5])\n", " \n", " # Analyze the SOFT file to identify the data type and mapping information\n", " platform_info = []\n", " with gzip.open(soft_file_path, 'rt', encoding='latin-1') as f:\n", " for line in f:\n", " if line.startswith(\"!Platform_title\") or line.startswith(\"!Series_title\") or \"description\" in line.lower():\n", " platform_info.append(line.strip())\n", " \n", " print(\"\\nPlatform information:\")\n", " for line in platform_info:\n", " print(line)\n", " \n", " # Extract the gene annotation using the library function\n", " gene_annotation = get_gene_annotation(soft_file_path)\n", " \n", " # Display column names of the annotation dataframe\n", " print(\"\\nGene annotation columns:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Preview the annotation dataframe\n", " print(\"\\nGene annotation preview:\")\n", " annotation_preview = preview_df(gene_annotation)\n", " print(annotation_preview)\n", " \n", " # Check if ID column exists in the gene_annotation dataframe\n", " if 'ID' in gene_annotation.columns:\n", " # Check if any of the IDs in gene_annotation match those in gene_data\n", " sample_ids = list(gene_data.index[:10])\n", " matching_rows = gene_annotation[gene_annotation['ID'].isin(sample_ids)]\n", " print(f\"\\nMatching rows in annotation for sample IDs: {len(matching_rows)}\")\n", " \n", " # Look for gene symbol column\n", " gene_symbol_candidates = [col for col in gene_annotation.columns if 'gene' in col.lower() or 'symbol' in col.lower() or 'name' in col.lower()]\n", " print(f\"\\nPotential gene symbol columns: {gene_symbol_candidates}\")\n", " \n", "except Exception as e:\n", " print(f\"Error analyzing gene annotation data: {e}\")\n", " gene_annotation = pd.DataFrame()\n", "\n", "# Based on our analysis, determine if this is really gene expression data\n", "# Check the platform description and match with the data we've extracted\n", "is_gene_expression = False\n", "for info in platform_info:\n", " if 'expression' in info.lower() or 'transcript' in info.lower() or 'mrna' in info.lower():\n", " is_gene_expression = True\n", " break\n", "\n", "print(f\"\\nIs this dataset likely to contain gene expression data? {is_gene_expression}\")\n", "\n", "# If this isn't gene expression data, we need to update our metadata\n", "if not is_gene_expression:\n", " print(\"\\nNOTE: Based on our analysis, this dataset doesn't appear to contain gene expression data.\")\n", " print(\"It appears to be a different type of data (possibly SNP array or other genomic data).\")\n", " # Update is_gene_available for metadata\n", " is_gene_available = False\n", " \n", " # Save the updated metadata\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" ] }, { "cell_type": "markdown", "id": "5924eadd", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "2cffc541", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:32:40.429230Z", "iopub.status.busy": "2025-03-25T04:32:40.429109Z", "iopub.status.idle": "2025-03-25T04:32:41.165341Z", "shell.execute_reply": "2025-03-25T04:32:41.165014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample of IDs from gene_annotation:\n", "0 A_23_P100001\n", "1 A_23_P100011\n", "2 A_23_P100022\n", "3 A_23_P100056\n", "4 A_23_P100074\n", "Name: ID, dtype: object\n", "\n", "Sample of IDs from gene_data:\n", "Index(['(+)E1A_r60_1', '(+)E1A_r60_3', '(+)E1A_r60_a104', '(+)E1A_r60_a107',\n", " '(+)E1A_r60_a135'],\n", " dtype='object', name='ID')\n", "\n", "Sample of GENE_SYMBOL from gene_annotation:\n", "0 FAM174B\n", "1 AP3S2\n", "2 SV2B\n", "3 RBPMS2\n", "4 AVEN\n", "Name: GENE_SYMBOL, dtype: object\n", "\n", "Gene mapping dataframe preview:\n", " ID Gene\n", "0 A_23_P100001 FAM174B\n", "1 A_23_P100011 AP3S2\n", "2 A_23_P100022 SV2B\n", "3 A_23_P100056 RBPMS2\n", "4 A_23_P100074 AVEN\n", "Gene mapping shape: (30936, 2)\n", "\n", "Gene expression data preview after mapping:\n", " GSM804806 GSM804807 GSM804808 GSM804809 GSM804810 GSM804811 \\\n", "Gene \n", "A1BG -0.856747 -2.371038 1.810420 4.458369 -1.614460 -2.098005 \n", "A1BG-AS1 0.112597 -2.545402 0.345880 2.294041 -1.484570 -2.047867 \n", "A1CF -0.829145 2.310278 0.408321 3.008061 -0.764084 -0.462802 \n", "A2LD1 -1.253635 -0.850703 0.416278 -0.361847 0.381737 -0.084432 \n", "A2M -1.598132 1.704536 -1.966787 2.845671 -0.677535 -1.352631 \n", "\n", " GSM804812 GSM804813 GSM804814 GSM804815 ... GSM804842 \\\n", "Gene ... \n", "A1BG -1.576633 0.529343 -0.418982 -1.422590 ... -0.535830 \n", "A1BG-AS1 -1.833521 0.289472 -0.083492 -0.891364 ... 0.349333 \n", "A1CF -0.823997 0.913546 1.887642 2.264761 ... 0.949150 \n", "A2LD1 0.035116 -0.644282 -0.681806 0.182972 ... -0.771763 \n", "A2M 0.799846 2.531783 -1.624713 0.691356 ... 0.239463 \n", "\n", " GSM804843 GSM804844 GSM804845 GSM804846 GSM804847 GSM804848 \\\n", "Gene \n", "A1BG 7.746847 4.486059 2.813038 -2.229067 -1.476418 5.057810 \n", "A1BG-AS1 1.197180 2.109467 1.263221 -1.091778 -0.798120 2.082527 \n", "A1CF 0.876769 6.902772 -0.095127 -2.294744 -0.857354 -4.372579 \n", "A2LD1 1.331089 -0.440415 -0.649394 -0.914515 0.690546 1.829183 \n", "A2M 0.176425 0.871290 0.008356 -0.008356 0.070050 2.499900 \n", "\n", " GSM804849 GSM804850 GSM804851 \n", "Gene \n", "A1BG 7.735202 -0.380320 5.506865 \n", "A1BG-AS1 0.933188 0.148014 2.245506 \n", "A1CF -2.487361 -0.084232 -4.068745 \n", "A2LD1 -1.829174 1.403288 1.499497 \n", "A2M -0.278881 1.293716 1.761829 \n", "\n", "[5 rows x 46 columns]\n", "Gene expression data shape after mapping: (18485, 46)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data after normalizing gene symbols:\n", " GSM804806 GSM804807 GSM804808 GSM804809 GSM804810 GSM804811 \\\n", "Gene \n", "A1BG -0.856747 -2.371038 1.810420 4.458369 -1.614460 -2.098005 \n", "A1BG-AS1 0.112597 -2.545402 0.345880 2.294041 -1.484570 -2.047867 \n", "A1CF -0.829145 2.310278 0.408321 3.008061 -0.764084 -0.462802 \n", "A2M -1.598132 1.704536 -1.966787 2.845671 -0.677535 -1.352631 \n", "A2ML1 -0.518708 -0.038120 0.456291 0.202503 0.341105 0.115908 \n", "\n", " GSM804812 GSM804813 GSM804814 GSM804815 ... GSM804842 \\\n", "Gene ... \n", "A1BG -1.576633 0.529343 -0.418982 -1.422590 ... -0.535830 \n", "A1BG-AS1 -1.833521 0.289472 -0.083492 -0.891364 ... 0.349333 \n", "A1CF -0.823997 0.913546 1.887642 2.264761 ... 0.949150 \n", "A2M 0.799846 2.531783 -1.624713 0.691356 ... 0.239463 \n", "A2ML1 -0.303251 0.185458 1.257013 0.833159 ... 0.330738 \n", "\n", " GSM804843 GSM804844 GSM804845 GSM804846 GSM804847 GSM804848 \\\n", "Gene \n", "A1BG 7.746847 4.486059 2.813038 -2.229067 -1.476418 5.057810 \n", "A1BG-AS1 1.197180 2.109467 1.263221 -1.091778 -0.798120 2.082527 \n", "A1CF 0.876769 6.902772 -0.095127 -2.294744 -0.857354 -4.372579 \n", "A2M 0.176425 0.871290 0.008356 -0.008356 0.070050 2.499900 \n", "A2ML1 0.591233 3.242414 0.461115 -0.455732 -0.314194 -1.701203 \n", "\n", " GSM804849 GSM804850 GSM804851 \n", "Gene \n", "A1BG 7.735202 -0.380320 5.506865 \n", "A1BG-AS1 0.933188 0.148014 2.245506 \n", "A1CF -2.487361 -0.084232 -4.068745 \n", "A2M -0.278881 1.293716 1.761829 \n", "A2ML1 -2.183079 -0.342340 -2.171190 \n", "\n", "[5 rows x 46 columns]\n", "Final gene expression data shape: (18244, 46)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/gene_data/GSE32507.csv\n" ] } ], "source": [ "# 1. Based on previous output, the 'ID' column in gene_annotation contains the probe IDs \n", "# that match the indices in gene_data, and 'GENE_SYMBOL' contains the gene symbols we need\n", "\n", "# Check both columns to verify they exist and are appropriate for mapping\n", "print(\"Sample of IDs from gene_annotation:\")\n", "print(gene_annotation['ID'].head())\n", "\n", "print(\"\\nSample of IDs from gene_data:\")\n", "print(gene_data.index[:5])\n", "\n", "print(\"\\nSample of GENE_SYMBOL from gene_annotation:\")\n", "print(gene_annotation['GENE_SYMBOL'].head())\n", "\n", "# 2. Get gene mapping dataframe with ID and GENE_SYMBOL columns\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'GENE_SYMBOL')\n", "print(\"\\nGene mapping dataframe preview:\")\n", "print(gene_mapping.head())\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene-level data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(\"\\nGene expression data preview after mapping:\")\n", "print(gene_data.head())\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "\n", "# Normalized gene symbols for consistency\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(\"\\nGene expression data after normalizing gene symbols:\")\n", "print(gene_data.head())\n", "print(f\"Final gene expression data shape: {gene_data.shape}\")\n", "\n", "# Save the processed gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "4350c073", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "664c00b0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:32:41.166720Z", "iopub.status.busy": "2025-03-25T04:32:41.166602Z", "iopub.status.idle": "2025-03-25T04:32:49.840793Z", "shell.execute_reply": "2025-03-25T04:32:49.840415Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (18244, 46)\n", "First few gene symbols after normalization: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/gene_data/GSE32507.csv\n", "Loaded clinical data:\n", " characteristics_ch1\n", "Sample_ID \n", "0.0 0.0\n", "Transposed clinical data to correct format:\n", "Sample_ID 0.0\n", "characteristics_ch1 0.0\n", "Number of common samples between clinical and genetic data: 0\n", "WARNING: No matching sample IDs between clinical and genetic data.\n", "Clinical data index: ['characteristics_ch1']\n", "Gene data columns: ['GSM804806', 'GSM804807', 'GSM804808', 'GSM804809', 'GSM804810', '...']\n", "Extracted 46 GSM IDs from gene data.\n", "Created new clinical data with matching sample IDs:\n", " Uterine_Corpus_Endometrial_Carcinoma\n", "GSM804806 1\n", "GSM804807 1\n", "GSM804808 1\n", "GSM804809 1\n", "GSM804810 1\n", "Gene data shape for linking (samples as rows): (46, 18244)\n", "Linked data shape: (46, 18245)\n", "Linked data preview (first 5 columns):\n", " Uterine_Corpus_Endometrial_Carcinoma A1BG A1BG-AS1 A1CF \\\n", "GSM804806 1 -0.856747 0.112597 -0.829145 \n", "GSM804807 1 -2.371038 -2.545402 2.310278 \n", "GSM804808 1 1.810420 0.345880 0.408321 \n", "GSM804809 1 4.458369 2.294041 3.008061 \n", "GSM804810 1 -1.614460 -1.484570 -0.764084 \n", "\n", " A2M \n", "GSM804806 -1.598132 \n", "GSM804807 1.704536 \n", "GSM804808 -1.966787 \n", "GSM804809 2.845671 \n", "GSM804810 -0.677535 \n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (46, 18245)\n", "For the feature 'Uterine_Corpus_Endometrial_Carcinoma', the least common label is '1' with 14 occurrences. This represents 30.43% of the dataset.\n", "The distribution of the feature 'Uterine_Corpus_Endometrial_Carcinoma' in this dataset is fine.\n", "\n", "Is trait biased: False\n", "A new JSON file was created at: ../../output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/cohort_info.json\n", "Data quality check result: Usable\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Uterine_Corpus_Endometrial_Carcinoma/GSE32507.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "try:\n", " # Now let's normalize the gene data using the provided function\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " print(f\"First few gene symbols after normalization: {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", "except Exception as e:\n", " print(f\"Error in gene normalization: {e}\")\n", " # If normalization fails, use the original gene data\n", " normalized_gene_data = gene_data\n", " print(\"Using original gene data without normalization\")\n", "\n", "# 2. Load the clinical data - make sure we have the correct format\n", "try:\n", " # Load the clinical data we saved earlier to ensure correct format\n", " clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(\"Loaded clinical data:\")\n", " print(clinical_data.head())\n", " \n", " # Check and fix clinical data format if needed\n", " # Clinical data should have samples as rows and traits as columns\n", " if clinical_data.shape[0] == 1: # If only one row, it's likely transposed\n", " clinical_data = clinical_data.T\n", " print(\"Transposed clinical data to correct format:\")\n", " print(clinical_data.head())\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " # If loading fails, recreate the clinical features\n", " clinical_data = geo_select_clinical_features(\n", " clinical_df, \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", " ).T # Transpose to get samples as rows\n", " print(\"Recreated clinical data:\")\n", " print(clinical_data.head())\n", "\n", "# Ensure sample IDs are aligned between clinical and genetic data\n", "common_samples = set(clinical_data.index).intersection(normalized_gene_data.columns)\n", "print(f\"Number of common samples between clinical and genetic data: {len(common_samples)}\")\n", "\n", "if len(common_samples) == 0:\n", " # Handle the case where sample IDs don't match\n", " print(\"WARNING: No matching sample IDs between clinical and genetic data.\")\n", " print(\"Clinical data index:\", clinical_data.index.tolist())\n", " print(\"Gene data columns:\", list(normalized_gene_data.columns[:5]) + [\"...\"])\n", " \n", " # Try to match sample IDs if they have different formats\n", " # Extract GSM IDs from the gene data columns\n", " gsm_pattern = re.compile(r'GSM\\d+')\n", " gene_samples = []\n", " for col in normalized_gene_data.columns:\n", " match = gsm_pattern.search(str(col))\n", " if match:\n", " gene_samples.append(match.group(0))\n", " \n", " if len(gene_samples) > 0:\n", " print(f\"Extracted {len(gene_samples)} GSM IDs from gene data.\")\n", " normalized_gene_data.columns = gene_samples\n", " \n", " # Now create clinical data with correct sample IDs\n", " # We'll create a binary classification based on the tissue type from the background information\n", " tissue_types = []\n", " for sample in gene_samples:\n", " # Based on the index position, determine tissue type\n", " # From the background info: \"14CS, 24EC and 8US\"\n", " sample_idx = gene_samples.index(sample)\n", " if sample_idx < 14:\n", " tissue_types.append(1) # Carcinosarcoma (CS)\n", " else:\n", " tissue_types.append(0) # Either EC or US\n", " \n", " clinical_data = pd.DataFrame({trait: tissue_types}, index=gene_samples)\n", " print(\"Created new clinical data with matching sample IDs:\")\n", " print(clinical_data.head())\n", "\n", "# 3. Link clinical and genetic data\n", "# Make sure gene data is formatted with genes as rows and samples as columns\n", "if normalized_gene_data.index.name != 'Gene':\n", " normalized_gene_data.index.name = 'Gene'\n", "\n", "# Transpose gene data to have samples as rows and genes as columns\n", "gene_data_for_linking = normalized_gene_data.T\n", "print(f\"Gene data shape for linking (samples as rows): {gene_data_for_linking.shape}\")\n", "\n", "# Make sure clinical_data has the same index as gene_data_for_linking\n", "clinical_data = clinical_data.loc[clinical_data.index.isin(gene_data_for_linking.index)]\n", "gene_data_for_linking = gene_data_for_linking.loc[gene_data_for_linking.index.isin(clinical_data.index)]\n", "\n", "# Now link by concatenating horizontally\n", "linked_data = pd.concat([clinical_data, gene_data_for_linking], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 columns):\")\n", "sample_cols = [trait] + list(linked_data.columns[1:5]) if len(linked_data.columns) > 5 else list(linked_data.columns)\n", "print(linked_data[sample_cols].head())\n", "\n", "# 4. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# Check if we still have data\n", "if linked_data.shape[0] == 0 or linked_data.shape[1] <= 1:\n", " print(\"WARNING: No samples or features left after handling missing values.\")\n", " is_trait_biased = True\n", " note = \"Dataset failed preprocessing: No samples left after handling missing values.\"\n", "else:\n", " # 5. Determine whether the trait and demographic features are biased\n", " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Is trait biased: {is_trait_biased}\")\n", " note = \"This dataset contains gene expression data from uterine corpus tissues, comparing carcinosarcoma with endometrioid adenocarcinoma and sarcoma.\"\n", "\n", "# 6. 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=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not 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", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data not saved due to quality issues.\")" ] } ], "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 }