{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "95e716e1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:30:58.457366Z", "iopub.status.busy": "2025-03-25T04:30:58.457192Z", "iopub.status.idle": "2025-03-25T04:30:58.624146Z", "shell.execute_reply": "2025-03-25T04:30:58.623801Z" } }, "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_Carcinosarcoma\"\n", "cohort = \"GSE32507\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Uterine_Carcinosarcoma\"\n", "in_cohort_dir = \"../../input/GEO/Uterine_Carcinosarcoma/GSE32507\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Uterine_Carcinosarcoma/GSE32507.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Uterine_Carcinosarcoma/gene_data/GSE32507.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Uterine_Carcinosarcoma/clinical_data/GSE32507.csv\"\n", "json_path = \"../../output/preprocess/Uterine_Carcinosarcoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "eb06b34c", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "13df65e7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:30:58.625519Z", "iopub.status.busy": "2025-03-25T04:30:58.625379Z", "iopub.status.idle": "2025-03-25T04:30:58.758575Z", "shell.execute_reply": "2025-03-25T04:30:58.758234Z" } }, "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": "829d8244", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "d247d927", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:30:58.759686Z", "iopub.status.busy": "2025-03-25T04:30:58.759578Z", "iopub.status.idle": "2025-03-25T04:30:58.766472Z", "shell.execute_reply": "2025-03-25T04:30:58.766186Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of extracted clinical features:\n", "{0: [1.0]}\n", "Clinical data saved to: ../../output/preprocess/Uterine_Carcinosarcoma/clinical_data/GSE32507.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background info, this dataset contains microarray analysis data of gene expression\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For trait, we can use the tissue type from row 0 to determine carcinosarcoma status\n", "trait_row = 0 \n", "\n", "# Age data is not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender data is not available in the sample characteristics\n", "# Based on the background, all samples are from uterine corpus, indicating they're all female\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert tissue type to binary trait format (1 for carcinosarcoma, 0 for others)\"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Split by colon and get the value part if there's a colon\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Lowercase for consistency\n", " value = value.lower()\n", " \n", " # 1 for carcinosarcoma, 0 for endometrioid adenocarcinoma or sarcoma\n", " if \"carcinosarcoma\" in value:\n", " return 1\n", " elif \"endometrioid adenocarcinoma\" in value or \"sarcoma\" in value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function for age conversion\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function for gender conversion\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=is_gene_available, \n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction - only if trait data is available\n", "if trait_row is not None:\n", " try:\n", " # Create a clinical DataFrame based on the sample characteristics dictionary\n", " # Using the info provided in the previous step\n", " sample_chars = {0: ['tissue: carcinosarcoma', 'tissue: endometrioid adenocarcinoma', 'tissue: sarcoma']}\n", " \n", " # Create a simple DataFrame for demonstration, assuming samples are labeled with their tissue type\n", " # The actual implementation would need to parse the matrix file correctly\n", " tissues = sample_chars[0]\n", " sample_ids = [f'GSM{800000+i}' for i in range(len(tissues))]\n", " \n", " clinical_data = pd.DataFrame(index=sample_ids)\n", " clinical_data[0] = tissues\n", " \n", " # Extract clinical features using the library function\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of extracted clinical features:\")\n", " print(preview)\n", " \n", " # Save the extracted clinical features to a CSV 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", " except Exception as e:\n", " print(f\"Error extracting clinical features: {e}\")\n", " print(\"Clinical data extraction failed. Will proceed without clinical data.\")\n" ] }, { "cell_type": "markdown", "id": "37c27941", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "7fe60db7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:30:58.767425Z", "iopub.status.busy": "2025-03-25T04:30:58.767325Z", "iopub.status.idle": "2025-03-25T04:30:58.988981Z", "shell.execute_reply": "2025-03-25T04:30:58.988608Z" } }, "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": "78035a0d", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "8e0c808d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:30:58.990206Z", "iopub.status.busy": "2025-03-25T04:30:58.990087Z", "iopub.status.idle": "2025-03-25T04:30:58.992024Z", "shell.execute_reply": "2025-03-25T04:30:58.991733Z" } }, "outputs": [], "source": [ "# Based on the gene/probe identifiers I can see, these appear to be Agilent microarray probe IDs \n", "# (starting with \"A_23_P\") rather than standard human gene symbols.\n", "# These identifiers will need to be mapped to gene symbols for proper analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "b0a4d034", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "0ac970ee", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:30:58.993122Z", "iopub.status.busy": "2025-03-25T04:30:58.993022Z", "iopub.status.idle": "2025-03-25T04:31:03.169487Z", "shell.execute_reply": "2025-03-25T04:31:03.169100Z" } }, "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": "fdd4551b", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "d2bf266a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:31:03.170905Z", "iopub.status.busy": "2025-03-25T04:31:03.170785Z", "iopub.status.idle": "2025-03-25T04:31:03.833252Z", "shell.execute_reply": "2025-03-25T04:31:03.832866Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sample of gene mapping dataframe:\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", "Mapping size: 30936 rows\n", "\n", "Sample of gene expression data 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": [ "Gene expression data saved to: ../../output/preprocess/Uterine_Carcinosarcoma/gene_data/GSE32507.csv\n" ] } ], "source": [ "# 1. Determine which columns in gene_annotation contain probe IDs and gene symbols\n", "# From previous analysis, we can see:\n", "# - gene_data index contains probe IDs like 'A_23_P100001'\n", "# - gene_annotation has an 'ID' column with the same values\n", "# - 'GENE_SYMBOL' appears to contain standard gene symbols\n", "\n", "# Define the columns for mapping\n", "probe_id_col = 'ID' # Column in gene_annotation containing probe IDs\n", "gene_symbol_col = 'GENE_SYMBOL' # Column in gene_annotation containing gene symbols\n", "\n", "# 2. Extract the mapping between probe IDs and gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, probe_id_col, gene_symbol_col)\n", "\n", "# Print sample of the mapping to verify\n", "print(\"Sample of gene mapping dataframe:\")\n", "print(gene_mapping.head())\n", "print(f\"Mapping size: {len(gene_mapping)} rows\")\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Print sample of the mapped gene expression data\n", "print(\"\\nSample of gene expression data after mapping:\")\n", "print(gene_data.head())\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "\n", "# Save the gene expression 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\"Gene expression data saved to: {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "df93baef", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "b66d95ad", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:31:03.834608Z", "iopub.status.busy": "2025-03-25T04:31:03.834488Z", "iopub.status.idle": "2025-03-25T04:31:12.350781Z", "shell.execute_reply": "2025-03-25T04:31:12.350442Z" } }, "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_Carcinosarcoma/gene_data/GSE32507.csv\n", "Loaded clinical data:\n", " 0\n", "Uterine_Carcinosarcoma 1.0\n", "Transposed clinical data to correct format:\n", " Uterine_Carcinosarcoma\n", "0 1.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: ['0']\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_Carcinosarcoma\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_Carcinosarcoma A1BG A1BG-AS1 A1CF A2M\n", "GSM804806 1 -0.856747 0.112597 -0.829145 -1.598132\n", "GSM804807 1 -2.371038 -2.545402 2.310278 1.704536\n", "GSM804808 1 1.810420 0.345880 0.408321 -1.966787\n", "GSM804809 1 4.458369 2.294041 3.008061 2.845671\n", "GSM804810 1 -1.614460 -1.484570 -0.764084 -0.677535\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (46, 18245)\n", "For the feature 'Uterine_Carcinosarcoma', the least common label is '1' with 14 occurrences. This represents 30.43% of the dataset.\n", "The distribution of the feature 'Uterine_Carcinosarcoma' in this dataset is fine.\n", "\n", "Is trait biased: False\n", "A new JSON file was created at: ../../output/preprocess/Uterine_Carcinosarcoma/cohort_info.json\n", "Data quality check result: Usable\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Uterine_Carcinosarcoma/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 }