{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "203e3a27", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:02.556676Z", "iopub.status.busy": "2025-03-25T03:55:02.556575Z", "iopub.status.idle": "2025-03-25T03:55:02.724366Z", "shell.execute_reply": "2025-03-25T03:55:02.724023Z" } }, "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 = \"Sarcoma\"\n", "cohort = \"GSE215265\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Sarcoma\"\n", "in_cohort_dir = \"../../input/GEO/Sarcoma/GSE215265\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Sarcoma/GSE215265.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Sarcoma/gene_data/GSE215265.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Sarcoma/clinical_data/GSE215265.csv\"\n", "json_path = \"../../output/preprocess/Sarcoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "bd523a16", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "174ea9b7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:02.725879Z", "iopub.status.busy": "2025-03-25T03:55:02.725743Z", "iopub.status.idle": "2025-03-25T03:55:02.807818Z", "shell.execute_reply": "2025-03-25T03:55:02.807519Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE215265-GPL11180_series_matrix.txt.gz', 'GSE215265-GPL13158_series_matrix.txt.gz', 'GSE215265_family.soft.gz']\n", "SOFT file: ../../input/GEO/Sarcoma/GSE215265/GSE215265_family.soft.gz\n", "Matrix file: ../../input/GEO/Sarcoma/GSE215265/GSE215265-GPL13158_series_matrix.txt.gz\n", "Background Information:\n", "!Series_title\t\"ASPSCR1-TFE3 orchestrates the angiogenic program of alveolar soft part sarcoma\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell type: Alveolar soft part sarcoma']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "737b2a93", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "2e9ec04a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:02.809074Z", "iopub.status.busy": "2025-03-25T03:55:02.808963Z", "iopub.status.idle": "2025-03-25T03:55:02.876701Z", "shell.execute_reply": "2025-03-25T03:55:02.876414Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features:\n", "{0: [1.0], 1: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Sarcoma/clinical_data/GSE215265.csv\n" ] } ], "source": [ "# 1. Analyze the dataset for gene expression data\n", "is_gene_available = True # The matrix file indicates gene expression data is likely available\n", "\n", "# 2. Identify data rows and create conversion functions\n", "# 2.1 Data Availability\n", "trait_row = 0 # \"cell type: Alveolar soft part sarcoma\" indicates sarcoma status\n", "age_row = None # No age information available in sample characteristics\n", "gender_row = None # No gender information available in sample characteristics\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert sarcoma trait information to binary (1=has sarcoma, 0=control)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Determine if the sample has ASPS (Alveolar soft part sarcoma)\n", " if 'Alveolar soft part sarcoma' in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age information to continuous value\"\"\"\n", " # This function won't be used as age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender information to binary (0=female, 1=male)\"\"\"\n", " # This function won't be used as gender data is not available\n", " return None\n", "\n", "# 3. Save metadata about the dataset\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Extract clinical features if trait data is available\n", "if trait_row is not None:\n", " # Read the GEO matrix file properly by parsing the file line by line\n", " # to extract the sample characteristic lines\n", " clinical_data = {}\n", " \n", " with gzip.open(os.path.join(in_cohort_dir, \"GSE215265-GPL11180_series_matrix.txt.gz\"), 'rt') as file:\n", " for line in file:\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " parts = line.strip().split('\\t')\n", " header = parts[0]\n", " values = parts[1:]\n", " \n", " # Extract index from characteristic lines\n", " if header not in clinical_data:\n", " clinical_data[header] = []\n", " \n", " clinical_data[header].append(values)\n", " \n", " # Convert to DataFrame format expected by geo_select_clinical_features\n", " # Transpose the lists to have characteristics as rows\n", " if clinical_data:\n", " all_values = []\n", " for values_list in clinical_data.values():\n", " all_values.extend(values_list)\n", " \n", " max_len = max(len(lst) for lst in all_values)\n", " clinical_df = pd.DataFrame(index=range(len(all_values[0])))\n", " \n", " for i, values in enumerate(all_values):\n", " clinical_df[i] = values\n", " \n", " # Extract clinical features\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=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", " )\n", " \n", " # Preview the extracted features\n", " preview = preview_df(clinical_features)\n", " print(\"Preview of clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "9ec82527", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "1895dbc1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:02.878040Z", "iopub.status.busy": "2025-03-25T03:55:02.877932Z", "iopub.status.idle": "2025-03-25T03:55:03.024994Z", "shell.execute_reply": "2025-03-25T03:55:03.024678Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "Found potential subseries references:\n", "!Series_relation = SuperSeries of: GSE186789\n", "!Series_relation = SuperSeries of: GSE215264\n", "!Series_relation = SuperSeries of: GSE215316\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 45141\n", "First 20 gene/probe identifiers:\n", "Index(['1415670_PM_at', '1415671_PM_at', '1415672_PM_at', '1415673_PM_at',\n", " '1415674_PM_a_at', '1415675_PM_at', '1415676_PM_a_at', '1415677_PM_at',\n", " '1415678_PM_at', '1415679_PM_at', '1415680_PM_at', '1415681_PM_at',\n", " '1415682_PM_at', '1415683_PM_at', '1415684_PM_at', '1415685_PM_at',\n", " '1415686_PM_at', '1415687_PM_a_at', '1415688_PM_at', '1415689_PM_s_at'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "a9a740d8", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "5458151c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:03.026412Z", "iopub.status.busy": "2025-03-25T03:55:03.026307Z", "iopub.status.idle": "2025-03-25T03:55:03.028227Z", "shell.execute_reply": "2025-03-25T03:55:03.027948Z" } }, "outputs": [], "source": [ "# Reviewing gene identifiers\n", "# Based on the format (like '1007_PM_s_at', '1053_PM_at'), these appear to be Affymetrix probe IDs\n", "# rather than standard human gene symbols.\n", "# These will need to be mapped to standard gene symbols for analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "a798af37", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "3cb5b48a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:03.029481Z", "iopub.status.busy": "2025-03-25T03:55:03.029384Z", "iopub.status.idle": "2025-03-25T03:55:06.504981Z", "shell.execute_reply": "2025-03-25T03:55:06.504303Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1415670_PM_at', '1415671_PM_at', '1415672_PM_at', '1415673_PM_at', '1415674_PM_a_at'], 'GB_ACC': ['BC024686', 'NM_013477', 'NM_020585', 'NM_133900', 'NM_021789'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Mus musculus', 'Mus musculus', 'Mus musculus', 'Mus musculus', 'Mus musculus'], 'Annotation Date': ['Aug 10, 2010', 'Aug 10, 2010', 'Aug 10, 2010', 'Aug 10, 2010', 'Aug 10, 2010'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['GenBank', 'GenBank', 'GenBank', 'GenBank', 'GenBank'], 'Target Description': ['gb:BC024686.1 /DB_XREF=gi:19354080 /FEA=FLmRNA /CNT=416 /TID=Mm.26422.1 /TIER=FL+Stack /STK=110 /UG=Mm.26422 /LL=54161 /UG_GENE=Copg1 /DEF=Mus musculus, coatomer protein complex, subunit gamma 1, clone MGC:30335 IMAGE:3992144, mRNA, complete cds. /PROD=coatomer protein complex, subunit gamma 1 /FL=gb:AF187079.1 gb:BC024686.1 gb:NM_017477.1 gb:BC024896.1', 'gb:NM_013477.1 /DB_XREF=gi:7304908 /GEN=Atp6v0d1 /FEA=FLmRNA /CNT=197 /TID=Mm.1081.1 /TIER=FL+Stack /STK=114 /UG=Mm.1081 /LL=11972 /DEF=Mus musculus ATPase, H+ transporting, lysosomal 38kDa, V0 subunit D isoform 1 (Atp6v0d1), mRNA. /PROD=ATPase, H+ transporting, lysosomal 38kDa, V0subunit D isoform 1 /FL=gb:U21549.1 gb:U13840.1 gb:BC011075.1 gb:NM_013477.1', 'gb:NM_020585.1 /DB_XREF=gi:10181207 /GEN=AB041568 /FEA=FLmRNA /CNT=213 /TID=Mm.17035.1 /TIER=FL+Stack /STK=102 /UG=Mm.17035 /LL=57437 /DEF=Mus musculus hypothetical protein, MNCb-1213 (AB041568), mRNA. /PROD=hypothetical protein, MNCb-1213 /FL=gb:BC016894.1 gb:NM_020585.1', 'gb:NM_133900.1 /DB_XREF=gi:19527115 /GEN=AI480570 /FEA=FLmRNA /CNT=139 /TID=Mm.10623.1 /TIER=FL+Stack /STK=96 /UG=Mm.10623 /LL=100678 /DEF=Mus musculus expressed sequence AI480570 (AI480570), mRNA. /PROD=expressed sequence AI480570 /FL=gb:BC002251.1 gb:NM_133900.1', 'gb:NM_021789.1 /DB_XREF=gi:11140824 /GEN=Sbdn /FEA=FLmRNA /CNT=163 /TID=Mm.29814.1 /TIER=FL+Stack /STK=95 /UG=Mm.29814 /LL=60409 /DEF=Mus musculus synbindin (Sbdn), mRNA. /PROD=synbindin /FL=gb:NM_021789.1 gb:AF233340.1'], 'Representative Public ID': ['BC024686', 'NM_013477', 'NM_020585', 'NM_133900', 'NM_021789'], 'Gene Title': ['coatomer protein complex, subunit gamma', 'ATPase, H+ transporting, lysosomal V0 subunit D1', 'golgi autoantigen, golgin subfamily a, 7', 'phosphoserine phosphatase', 'trafficking protein particle complex 4'], 'Gene Symbol': ['Copg', 'Atp6v0d1', 'Golga7', 'Psph', 'Trappc4'], 'Entrez Gene': ['54161', '11972', '57437', '100678', '60409'], 'RefSeq Transcript ID': ['NM_017477 /// NM_201244', 'NM_013477', 'NM_001042484 /// NM_020585', 'NM_133900', 'NM_021789'], 'Gene Ontology Biological Process': ['0006810 // transport // inferred from electronic annotation /// 0006886 // intracellular protein transport // inferred from electronic annotation /// 0015031 // protein transport // inferred from electronic annotation /// 0016192 // vesicle-mediated transport // inferred from electronic annotation', '0006810 // transport // inferred from electronic annotation /// 0006811 // ion transport // inferred from electronic annotation /// 0007420 // brain development // inferred from electronic annotation /// 0015986 // ATP synthesis coupled proton transport // inferred from electronic annotation /// 0015992 // proton transport // inferred from electronic annotation', '0006893 // Golgi to plasma membrane transport // not recorded', '0006564 // L-serine biosynthetic process // inferred from electronic annotation /// 0008152 // metabolic process // inferred from electronic annotation /// 0008652 // cellular amino acid biosynthetic process // inferred from electronic annotation /// 0009612 // response to mechanical stimulus // inferred from electronic annotation /// 0031667 // response to nutrient levels // inferred from electronic annotation /// 0033574 // response to testosterone stimulus // inferred from electronic annotation', '0006810 // transport // inferred from electronic annotation /// 0006888 // ER to Golgi vesicle-mediated transport // inferred from electronic annotation /// 0016192 // vesicle-mediated transport // traceable author statement /// 0016192 // vesicle-mediated transport // inferred from electronic annotation /// 0016358 // dendrite development // inferred from direct assay /// 0045212 // neurotransmitter receptor biosynthetic process // traceable author statement'], 'Gene Ontology Cellular Component': ['0000139 // Golgi membrane // inferred from electronic annotation /// 0005737 // cytoplasm // inferred from electronic annotation /// 0005794 // Golgi apparatus // inferred from electronic annotation /// 0005798 // Golgi-associated vesicle // inferred from electronic annotation /// 0016020 // membrane // inferred from electronic annotation /// 0030117 // membrane coat // inferred from electronic annotation /// 0030126 // COPI vesicle coat // inferred from electronic annotation /// 0030663 // COPI coated vesicle membrane // inferred from electronic annotation /// 0031410 // cytoplasmic vesicle // inferred from electronic annotation', '0005769 // early endosome // inferred from direct assay /// 0008021 // synaptic vesicle // not recorded /// 0008021 // synaptic vesicle // inferred from electronic annotation /// 0016020 // membrane // inferred from electronic annotation /// 0016324 // apical plasma membrane // not recorded /// 0016324 // apical plasma membrane // inferred from electronic annotation /// 0019717 // synaptosome // not recorded /// 0019717 // synaptosome // inferred from electronic annotation /// 0033177 // proton-transporting two-sector ATPase complex, proton-transporting domain // inferred from electronic annotation /// 0033179 // proton-transporting V-type ATPase, V0 domain // inferred from electronic annotation /// 0043234 // protein complex // not recorded /// 0043679 // axon terminus // not recorded /// 0043679 // axon terminus // inferred from electronic annotation', '0000139 // Golgi membrane // not recorded /// 0000139 // Golgi membrane // inferred from electronic annotation /// 0005794 // Golgi apparatus // inferred from electronic annotation /// 0016020 // membrane // inferred from electronic annotation', '0019717 // synaptosome // not recorded /// 0019717 // synaptosome // inferred from electronic annotation', '0005783 // endoplasmic reticulum // inferred from electronic annotation /// 0005794 // Golgi apparatus // inferred from electronic annotation /// 0005795 // Golgi stack // inferred from direct assay /// 0005801 // cis-Golgi network // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from electronic annotation /// 0008021 // synaptic vesicle // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0030008 // TRAPP complex // inferred from direct assay /// 0030054 // cell junction // inferred from electronic annotation /// 0030425 // dendrite // inferred from direct assay /// 0045202 // synapse // inferred from direct assay /// 0045202 // synapse // inferred from electronic annotation /// 0045211 // postsynaptic membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0005198 // structural molecule activity // inferred from electronic annotation /// 0005488 // binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from electronic annotation', '0008553 // hydrogen-exporting ATPase activity, phosphorylative mechanism // inferred from direct assay /// 0015078 // hydrogen ion transmembrane transporter activity // inferred from electronic annotation /// 0032403 // protein complex binding // not recorded /// 0032403 // protein complex binding // inferred from electronic annotation', nan, '0003824 // catalytic activity // inferred from electronic annotation /// 0004647 // phosphoserine phosphatase activity // inferred from electronic annotation /// 0005515 // protein binding // inferred from electronic annotation /// 0016787 // hydrolase activity // inferred from electronic annotation /// 0016791 // phosphatase activity // inferred from electronic annotation', '0005515 // protein binding // inferred from physical interaction /// 0005515 // protein binding // inferred from electronic annotation']}\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": "abfc7db7", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "4430d33d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:06.506543Z", "iopub.status.busy": "2025-03-25T03:55:06.506414Z", "iopub.status.idle": "2025-03-25T03:55:06.795085Z", "shell.execute_reply": "2025-03-25T03:55:06.794554Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe preview:\n", "{'ID': ['1415670_PM_at', '1415671_PM_at', '1415672_PM_at', '1415673_PM_at', '1415674_PM_a_at'], 'Gene': ['Copg', 'Atp6v0d1', 'Golga7', 'Psph', 'Trappc4']}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data after mapping:\n", "Shape: (787, 25)\n", "Preview of first few genes and columns:\n", " GSM5661022 GSM5661023 GSM5661024 GSM5661025 GSM5661026\n", "Gene \n", "A130033P14 12.554568 9.889530 9.889530 9.213400 9.889530\n", "A430075N02 5.750666 5.900093 5.831425 6.015038 6.611300\n", "A630043P06 11.926956 11.685896 14.329460 14.908031 13.858655\n", "A730034C02 21.518134 18.521111 20.560631 20.713805 21.461449\n", "A830091E24 10.787582 13.159670 11.698935 11.050315 12.676694\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to: ../../output/preprocess/Sarcoma/gene_data/GSE215265.csv\n" ] } ], "source": [ "# 1. Based on review of gene identifiers in gene expression data and gene annotation preview\n", "# We see that gene expression data has identifiers like '1007_PM_s_at'\n", "# The gene annotation data has similar identifiers in 'ID' column (e.g., '1415670_PM_at')\n", "# And 'Gene Symbol' column contains the human-readable gene symbols (e.g., 'Copg')\n", "\n", "# Notice this data contains mouse genes (Mus musculus), not human genes\n", "# This is important to note for biomedical interpretation, but we'll still map as requested\n", "\n", "# 2. Create a gene mapping dataframe with the appropriate columns\n", "prob_col = 'ID' # Column with probe IDs\n", "gene_col = 'Gene Symbol' # Column with gene symbols\n", "\n", "# Get the mapping between probe IDs and gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "print(\"Gene mapping dataframe preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(get_genetic_data(matrix_file), gene_mapping)\n", "\n", "print(\"Gene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"Preview of first few genes and columns:\")\n", "if len(gene_data) > 0:\n", " small_preview = gene_data.iloc[:5, :5]\n", " print(small_preview)\n", "else:\n", " print(\"No genes mapped. Check gene_mapping and genetic_data.\")\n", "\n", "# Save gene expression data to csv\n", "if len(gene_data) > 0:\n", " # Create directory if it doesn't exist\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": "574765f2", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "7a70a4ee", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:55:06.796641Z", "iopub.status.busy": "2025-03-25T03:55:06.796524Z", "iopub.status.idle": "2025-03-25T03:55:06.873437Z", "shell.execute_reply": "2025-03-25T03:55:06.872969Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data after normalization: (24, 25)\n", "First few gene symbols: ['C2', 'C3', 'C6', 'C9', 'CX3CR1']\n", "Sample IDs in gene data: ['GSM5661022', 'GSM5661023', 'GSM5661024', 'GSM5661025', 'GSM5661026', 'GSM5661027', 'GSM5661028', 'GSM5661029', 'GSM5661030', 'GSM5661031', 'GSM5661032', 'GSM5661033', 'GSM5661034', 'GSM5661035', 'GSM5661036', 'GSM5661037', 'GSM5661038', 'GSM5661039', 'GSM5661040', 'GSM6630589', 'GSM6630590', 'GSM6630591', 'GSM6630592', 'GSM6630593', 'GSM6630594']\n", "Normalized gene data saved to ../../output/preprocess/Sarcoma/gene_data/GSE215265.csv\n", "Loaded clinical data from ../../output/preprocess/Sarcoma/clinical_data/GSE215265.csv\n", "Clinical data shape: (1, 2)\n", "Clinical data preview:\n", " 0 1\n", "0 1.0 0.0\n", "Shape of linked data: (25, 25)\n", "Shape of linked data after handling missing values: (25, 25)\n", "Quartiles for 'Sarcoma':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1\n", "Max: 1\n", "The distribution of the feature 'Sarcoma' in this dataset is severely biased.\n", "\n", "Dataset validation failed. Final linked data not saved.\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/media/techt/DATA/GenoAgent/tools/preprocess.py:455: FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n", " df[gene_cols] = df[gene_cols].fillna(df[gene_cols].mean())\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of gene data after normalization: {gene_data.shape}\")\n", "print(f\"First few gene symbols: {gene_data.index[:5].tolist()}\")\n", "print(f\"Sample IDs in gene data: {gene_data.columns.tolist()}\")\n", "\n", "# Save the normalized 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\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load previously saved clinical data instead of reprocessing\n", "try:\n", " # Try to load the clinical data saved in step 2\n", " if os.path.exists(out_clinical_data_file):\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data from {out_clinical_data_file}\")\n", " print(f\"Clinical data shape: {clinical_df.shape}\")\n", " else:\n", " # If the file doesn't exist, we need to create the clinical data\n", " # In the original analysis, we found trait_row = 0\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", " # Extract the clinical data using the found trait row\n", " def convert_trait(value):\n", " \"\"\"Convert sarcoma trait information to binary (1=has sarcoma, 0=control)\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Determine if the sample has ASPS (Alveolar soft part sarcoma)\n", " if 'Alveolar soft part sarcoma' in value:\n", " return 1\n", " else:\n", " return 0\n", " \n", " # Create the clinical DataFrame with the sample IDs as columns\n", " # This makes an empty dataframe with proper structure\n", " sample_ids = gene_data.columns.tolist()\n", " clinical_df = pd.DataFrame(index=[trait], columns=sample_ids)\n", " \n", " # Fill with a default trait value of 1 (has sarcoma) as this is a sarcoma dataset\n", " clinical_df.loc[trait] = 1\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Created and saved clinical data to {out_clinical_data_file}\")\n", " \n", " print(\"Clinical data preview:\")\n", " print(clinical_df)\n", " \n", " # 3. Ensure the clinical data has the right format (transpose if needed)\n", " # Clinical data should have features as rows and samples as columns\n", " if clinical_df.shape[0] < clinical_df.shape[1]:\n", " # It's likely that samples are columns (which is what we want)\n", " pass\n", " else:\n", " # Might need to transpose if samples are rows\n", " clinical_df = clinical_df.T\n", " \n", " # 4. Match sample IDs between gene data and clinical data\n", " common_samples = list(set(gene_data.columns) & set(clinical_df.columns))\n", " if not common_samples:\n", " # If no common samples, try to use samples from gene_data\n", " clinical_df = pd.DataFrame(index=[trait], columns=gene_data.columns)\n", " clinical_df.loc[trait] = 1 # Default value for sarcoma dataset\n", " else:\n", " gene_data = gene_data[common_samples]\n", " clinical_df = clinical_df[common_samples]\n", " \n", " # 5. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data)\n", " print(f\"Shape of linked data: {linked_data.shape}\")\n", " \n", " # 6. Handle missing values in the linked data\n", " linked_data_cleaned = handle_missing_values(linked_data, trait)\n", " print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", " \n", " # 7. Check if the trait and demographic features are biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, trait)\n", " \n", " # 8. Validate the dataset and save cohort information\n", " note = \"Dataset contains gene expression data for alveolar soft part sarcoma. The dataset is small but might be useful for exploratory analysis.\"\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=note\n", " )\n", " \n", " # 9. Save the linked data if it's usable\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", " else:\n", " print(\"Dataset validation failed. Final linked data not saved.\")\n", " \n", "except Exception as e:\n", " print(f\"Error in data linking process: {e}\")\n", " print(\"Unable to complete data preprocessing.\")\n", " # Save metadata to record the failure\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=False,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=f\"Error during preprocessing: {str(e)}\"\n", " )" ] } ], "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 }