{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "c02f8562", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:35:04.781498Z", "iopub.status.busy": "2025-03-25T08:35:04.781398Z", "iopub.status.idle": "2025-03-25T08:35:04.943708Z", "shell.execute_reply": "2025-03-25T08:35:04.943369Z" } }, "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 = \"Cystic_Fibrosis\"\n", "cohort = \"GSE129168\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Cystic_Fibrosis\"\n", "in_cohort_dir = \"../../input/GEO/Cystic_Fibrosis/GSE129168\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Cystic_Fibrosis/GSE129168.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Cystic_Fibrosis/gene_data/GSE129168.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE129168.csv\"\n", "json_path = \"../../output/preprocess/Cystic_Fibrosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "dfcf5971", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "4f3f951a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:35:04.945154Z", "iopub.status.busy": "2025-03-25T08:35:04.945013Z", "iopub.status.idle": "2025-03-25T08:35:05.005716Z", "shell.execute_reply": "2025-03-25T08:35:05.005420Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"High-throughput screening for modulators of CFTR activity applying an organotypic functional assay based on genetically engineered Cystic Fibrosis disease-specific iPSCs\"\n", "!Series_summary\t\"Organotypic culture systems from disease-specific induced pluripotent stem cells (iPSCs) exhibit obvious advantages compared to immortalized cell lines and primary cell cultures but implementation of iPSC-based high throughput (HT) assays is still technically challenging. Here we demonstrate the development and conduction of an organotypic HT Cl-/I- exchange assay using Cystic Fibrosis (CF) disease-specific iPSCs. The introduction of a halide sensitive YFP variant enabled automated quantitative measurement of Cystic Fibrosis Transmembrane Conductance Regulator (CFTR) function in iPSC-derived intestinal epithelia. CFTR function was partially rescued by treatment with VX-770 and VX-809, and seamless gene correction of the p.Phe508del mutation resulted in full restoration of CFTR function. The identification of a series of validated primary hits that improve the function of p.Phe508del CFTR from a library of ~ 42.500 chemical compounds demonstrates that the advantages of complex iPSC-derived culture systems for disease modelling can also be utilized for drug screening at a true HT format.\"\n", "!Series_overall_design\t\"For detailed analysis of the differentiated hiPSC cell populations on day 15 of differentiation 32 samples in total were analyzed. Three independent donor lines were utilized (donor 1 and 6 CFTR WT, donor 2 (p.Phe508del)) and one isogenic gene corrected control line (donor 2 gene corrected-CFTR WT.) Samples from undifferentiated and differentiated cells represent biological replicates (n=3). As controls RNA from adult intestine, liver and colon was. Tissue samples are represented as technical replicates.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['donor line: donor 2', 'donor line: donor 2 gene corrected', 'donor line: donor 6', 'donor line: donor 1', 'tissue: small intestine', 'tissue: colon', 'tissue: liver'], 1: ['cell type: pluripotent stem cell', 'developmental stage: adult'], 2: ['genotype: CFiPS (p.Phe508del)', 'genotype: CFiPS (p.Phe508del) gene corrected', 'genotype: iPS CFTR WT', 'genotype: CFTR WT'], 3: ['treatment: untreated/undifferentiated', 'treatment: day 15 of differentiation', nan]}\n" ] } ], "source": [ "from tools.preprocess import *\n", "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Read the matrix file to obtain background information and sample characteristics data\n", "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n", "print(\"Background Information:\")\n", "print(background_info)\n", "print(\"Sample Characteristics Dictionary:\")\n", "print(sample_characteristics_dict)\n" ] }, { "cell_type": "markdown", "id": "fb80c221", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "cc17f829", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:35:05.006916Z", "iopub.status.busy": "2025-03-25T08:35:05.006688Z", "iopub.status.idle": "2025-03-25T08:35:05.011063Z", "shell.execute_reply": "2025-03-25T08:35:05.010778Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data file not found at ../../input/GEO/Cystic_Fibrosis/GSE129168/clinical_data.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# This dataset contains gene expression data as it relates to CFTR function analysis\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Cystic Fibrosis): \n", "# We can infer this from row 2 which contains genotype information about CFTR mutations\n", "trait_row = 2\n", "\n", "# For age: Age is not explicitly provided and cannot be reliably inferred\n", "age_row = None\n", "\n", "# For gender: Gender is not specified in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert CFTR genotype to binary trait value for Cystic Fibrosis\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # CFTR p.Phe508del mutation indicates CF\n", " if 'p.Phe508del' in value and 'gene corrected' not in value:\n", " return 1 # Has CF\n", " else:\n", " return 0 # Does not have CF (CFTR WT or gene corrected)\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function since age data is not available\"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function since gender data is not available\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering on usability\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Read the clinical data file\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.csv\")\n", " if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_csv(clinical_data_path)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the dataframe\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical features dataframe\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(f\"Clinical data file not found at {clinical_data_path}\")\n" ] }, { "cell_type": "markdown", "id": "2b30c678", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "c6ab63f3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:35:05.012077Z", "iopub.status.busy": "2025-03-25T08:35:05.011971Z", "iopub.status.idle": "2025-03-25T08:35:05.080214Z", "shell.execute_reply": "2025-03-25T08:35:05.079885Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 73\n", "Header line: \"ID_REF\"\t\"GSM3701915\"\t\"GSM3701916\"\t\"GSM3701917\"\t\"GSM3701918\"\t\"GSM3701919\"\t\"GSM3701920\"\t\"GSM3701921\"\t\"GSM3701922\"\t\"GSM3701923\"\t\"GSM3701924\"\t\"GSM3701925\"\t\"GSM3701926\"\t\"GSM3701927\"\t\"GSM3701928\"\t\"GSM3701929\"\t\"GSM3701930\"\t\"GSM3701931\"\t\"GSM3701932\"\t\"GSM3701933\"\t\"GSM3701934\"\t\"GSM3701935\"\t\"GSM3701936\"\t\"GSM3701937\"\t\"GSM3701938\"\t\"GSM3701939\"\t\"GSM3701940\"\t\"GSM3701941\"\t\"GSM3701942\"\t\"GSM3701943\"\t\"GSM3701944\"\t\"GSM3701945\"\t\"GSM3701946\"\n", "First data line: \"A_23_P100001\"\t1884\t1647\t1959\t3268\t3346\t3801\t1817\t1418\t1572\t3890\t3638\t4027\t2250\t1820\t7073\t8081\t7426\t2005\t2163\t2350\t5476\t4873\t4716\t2374\t2490\t2381\t1399\t1333\t1287\t818\t984\t901\n", "Index(['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074',\n", " 'A_23_P100127', 'A_23_P100141', 'A_23_P100189', 'A_23_P100196',\n", " 'A_23_P100203', 'A_23_P100220', 'A_23_P100240', 'A_23_P10025',\n", " 'A_23_P100292', 'A_23_P100315', 'A_23_P100326', 'A_23_P100344',\n", " 'A_23_P100355', 'A_23_P100386', 'A_23_P100392', 'A_23_P100420'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "e010ed08", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "e53445f2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:35:05.081483Z", "iopub.status.busy": "2025-03-25T08:35:05.081379Z", "iopub.status.idle": "2025-03-25T08:35:05.083189Z", "shell.execute_reply": "2025-03-25T08:35:05.082914Z" } }, "outputs": [], "source": [ "# Based on the output, the gene identifiers in this dataset appear to be Agilent microarray probe IDs \n", "# (format A_23_Pxxxxxx), not human gene symbols. These identifiers need to be mapped to gene symbols\n", "# for proper analysis.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "c657ad9e", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "0aa49076", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:35:05.084298Z", "iopub.status.busy": "2025-03-25T08:35:05.084203Z", "iopub.status.idle": "2025-03-25T08:35:06.854120Z", "shell.execute_reply": "2025-03-25T08:35:06.853735Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_014848', 'NM_194272', 'NM_020371', 'NM_170589'], 'GB_ACC': ['NM_207446', 'NM_014848', 'NM_194272', 'NM_020371', 'NM_170589'], 'LOCUSLINK_ID': [400451.0, 9899.0, 348093.0, 57099.0, 57082.0], 'GENE_SYMBOL': ['FAM174B', 'SV2B', 'RBPMS2', 'AVEN', 'KNL1'], 'GENE_NAME': ['family with sequence similarity 174 member B', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein, mRNA processing factor 2', 'apoptosis and caspase activation inhibitor', 'kinetochore scaffold 1'], 'UNIGENE_ID': ['Hs.27373', 'Hs.21754', 'Hs.436518', 'Hs.555966', 'Hs.181855'], 'ENSEMBL_ID': ['ENST00000553393', nan, nan, 'ENST00000306730', 'ENST00000527044'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000553393|ens|ENST00000327355|ref|XR_931815', 'ref|NM_014848|ref|NM_001323039|ref|NM_001323032|ref|NM_001323037', 'ref|NM_194272|ref|NR_138350|ref|NR_138363|ref|NR_138364', 'ref|NM_020371|ens|ENST00000306730|ref|XM_011521819|ref|XM_011521818', 'ref|NM_170589|ref|NM_144508|ens|ENST00000527044|ens|ENST00000533001'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680', 'chr15:40917525-40917584'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14', 'hs|15q15.1'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174 member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein, mRNA processing factor 2 (RBPMS2), transcript variant 1, mRNA [NM_194272]', 'Homo sapiens apoptosis and caspase activation inhibitor (AVEN), mRNA [NM_020371]', 'Homo sapiens kinetochore scaffold 1 (KNL1), transcript variant 1, mRNA [NM_170589]'], 'GO_ID': ['GO:0016021(integral component of membrane)', 'GO:0001669(acrosomal vesicle)|GO:0005515(protein binding)|GO:0005886(plasma membrane)|GO:0006836(neurotransmitter transport)|GO:0007268(chemical synaptic transmission)|GO:0008021(synaptic vesicle)|GO:0016020(membrane)|GO:0016021(integral component of membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0043005(neuron projection)|GO:0055085(transmembrane transport)', 'GO:0000398(mRNA splicing, via spliceosome)|GO:0003729(mRNA binding)|GO:0005515(protein binding)|GO:0005737(cytoplasm)|GO:0030514(negative regulation of BMP signaling pathway)|GO:0035614(snRNA stem-loop binding)|GO:0042803(protein homodimerization activity)|GO:0048557(embryonic digestive tract morphogenesis)|GO:0048661(positive regulation of smooth muscle cell proliferation)|GO:0051151(negative regulation of smooth muscle cell differentiation)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0006915(apoptotic process)|GO:0012505(endomembrane system)|GO:0016020(membrane)|GO:0043066(negative regulation of apoptotic process)', 'GO:0000777(condensed chromosome kinetochore)|GO:0001669(acrosomal vesicle)|GO:0001675(acrosome assembly)|GO:0005515(protein binding)|GO:0005634(nucleus)|GO:0005654(nucleoplasm)|GO:0005829(cytosol)|GO:0008608(attachment of spindle microtubules to kinetochore)|GO:0010923(negative regulation of phosphatase activity)|GO:0016604(nuclear body)|GO:0034080(CENP-A containing nucleosome assembly)|GO:0034501(protein localization to kinetochore)|GO:0051301(cell division)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA', 'CGGTCTCTAGCAAAGATTCAGGCATTGGATCTGTTGCAGGTAAACTGAACCTAAGTCCTT']}\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": "8c51b3c5", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "36ec5cbe", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:35:06.855429Z", "iopub.status.busy": "2025-03-25T08:35:06.855313Z", "iopub.status.idle": "2025-03-25T08:35:06.982482Z", "shell.execute_reply": "2025-03-25T08:35:06.982015Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using probe IDs from column 'ID' and gene symbols from 'GENE_SYMBOL'\n", "First few probe IDs: ['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127']\n", "First few gene symbols: ['FAM174B', 'SV2B', 'RBPMS2', 'AVEN', 'KNL1']\n", "Created mapping dataframe with shape: (30331, 2)\n", "Mapping preview: {'ID': ['A_23_P100001', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100127'], 'Gene': ['FAM174B', 'SV2B', 'RBPMS2', 'AVEN', 'KNL1']}\n", "Generated gene expression data with shape: (20520, 32)\n", "First 5 gene symbols in the gene expression data: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-1']\n" ] } ], "source": [ "# 1. Identify the columns in gene annotation for mapping\n", "probe_column = 'ID' # This is the probe identifier column that matches the gene expression index\n", "gene_symbol_column = 'GENE_SYMBOL' # This is the column with the gene symbols we want to map to\n", "\n", "# Print relevant information for validation\n", "print(f\"Using probe IDs from column '{probe_column}' and gene symbols from '{gene_symbol_column}'\")\n", "print(f\"First few probe IDs: {gene_annotation[probe_column][:5].tolist()}\")\n", "print(f\"First few gene symbols: {gene_annotation[gene_symbol_column][:5].tolist()}\")\n", "\n", "# 2. Create a mapping dataframe with these two columns\n", "mapping_df = get_gene_mapping(gene_annotation, probe_column, gene_symbol_column)\n", "print(f\"Created mapping dataframe with shape: {mapping_df.shape}\")\n", "print(f\"Mapping preview: {preview_df(mapping_df)}\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# This function handles the many-to-many mapping and proper distribution of expression values\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Generated gene expression data with shape: {gene_data.shape}\")\n", "print(f\"First 5 gene symbols in the gene expression data: {gene_data.index[:5].tolist()}\")\n" ] }, { "cell_type": "markdown", "id": "0718db00", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "42f5a015", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:35:06.983916Z", "iopub.status.busy": "2025-03-25T08:35:06.983807Z", "iopub.status.idle": "2025-03-25T08:35:15.368133Z", "shell.execute_reply": "2025-03-25T08:35:15.367780Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (20134, 32)" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "First few genes with their expression values after normalization:\n", " GSM3701915 GSM3701916 GSM3701917 GSM3701918 GSM3701919 \\\n", "Gene \n", "A1BG 4010.0 4608.0 3222.0 865.0 889.0 \n", "A1BG-AS1 197.0 166.0 205.0 122.0 101.0 \n", "A1CF 7.0 8.0 7.0 5318.0 5750.0 \n", "A2M 11.0 10.0 255.0 1018.0 1230.0 \n", "A2M-AS1 224.0 215.0 218.0 222.0 265.0 \n", "\n", " GSM3701920 GSM3701921 GSM3701922 GSM3701923 GSM3701924 ... \\\n", "Gene ... \n", "A1BG 810.0 5707.0 4568.0 3420.0 841.0 ... \n", "A1BG-AS1 155.0 147.0 179.0 178.0 163.0 ... \n", "A1CF 5530.0 6.0 6.0 7.0 5716.0 ... \n", "A2M 1378.0 5.0 10.0 83.0 1544.0 ... \n", "A2M-AS1 288.0 174.0 227.0 208.0 216.0 ... \n", "\n", " GSM3701937 GSM3701938 GSM3701939 GSM3701940 GSM3701941 \\\n", "Gene \n", "A1BG 795.0 1465.0 1499.0 1616.0 1044.0 \n", "A1BG-AS1 162.0 172.0 199.0 175.0 121.0 \n", "A1CF 4115.0 2257.0 2270.0 2159.0 2176.0 \n", "A2M 17876.0 70912.0 75801.0 69552.0 56138.0 \n", "A2M-AS1 237.0 738.0 807.0 834.0 419.0 \n", "\n", " GSM3701942 GSM3701943 GSM3701944 GSM3701945 GSM3701946 \n", "Gene \n", "A1BG 990.0 953.0 200616.0 205414.0 203146.0 \n", "A1BG-AS1 120.0 119.0 41.0 37.0 44.0 \n", "A1CF 2090.0 2057.0 26980.0 27768.0 27456.0 \n", "A2M 52852.0 49948.0 151045.0 157701.0 150048.0 \n", "A2M-AS1 395.0 391.0 1355.0 1466.0 1380.0 \n", "\n", "[5 rows x 32 columns]\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Cystic_Fibrosis/gene_data/GSE129168.csv\n", "Raw clinical data shape: (4, 33)\n", "Clinical features:\n", " GSM3701915 GSM3701916 GSM3701917 GSM3701918 GSM3701919 \\\n", "Cystic_Fibrosis 1.0 1.0 1.0 1.0 1.0 \n", "\n", " GSM3701920 GSM3701921 GSM3701922 GSM3701923 GSM3701924 \\\n", "Cystic_Fibrosis 1.0 0.0 0.0 0.0 0.0 \n", "\n", " ... GSM3701937 GSM3701938 GSM3701939 GSM3701940 \\\n", "Cystic_Fibrosis ... 0.0 0.0 0.0 0.0 \n", "\n", " GSM3701941 GSM3701942 GSM3701943 GSM3701944 GSM3701945 \\\n", "Cystic_Fibrosis 0.0 0.0 0.0 0.0 0.0 \n", "\n", " GSM3701946 \n", "Cystic_Fibrosis 0.0 \n", "\n", "[1 rows x 32 columns]\n", "Clinical features saved to ../../output/preprocess/Cystic_Fibrosis/clinical_data/GSE129168.csv\n", "Linked data shape: (32, 20135)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Cystic_Fibrosis A1BG A1BG-AS1 A1CF A2M\n", "GSM3701915 1.0 4010.0 197.0 7.0 11.0\n", "GSM3701916 1.0 4608.0 166.0 8.0 10.0\n", "GSM3701917 1.0 3222.0 205.0 7.0 255.0\n", "GSM3701918 1.0 865.0 122.0 5318.0 1018.0\n", "GSM3701919 1.0 889.0 101.0 5750.0 1230.0\n", "Missing values before handling:\n", " Trait (Cystic_Fibrosis) missing: 0 out of 32\n", " Genes with >20% missing: 0\n", " Samples with >5% missing genes: 0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (32, 20135)\n", "For the feature 'Cystic_Fibrosis', the least common label is '1.0' with 6 occurrences. This represents 18.75% of the dataset.\n", "The distribution of the feature 'Cystic_Fibrosis' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Cystic_Fibrosis/GSE129168.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(\"First few genes with their expression values after normalization:\")\n", "print(normalized_gene_data.head())\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Extract clinical features directly from the matrix file\n", "try:\n", " # Get the file paths for the matrix file to extract clinical data\n", " _, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Get raw clinical data from the matrix file\n", " _, clinical_raw = get_background_and_clinical_data(matrix_file)\n", " \n", " # Verify clinical data structure\n", " print(\"Raw clinical data shape:\", clinical_raw.shape)\n", " \n", " # Extract clinical features using the defined conversion functions\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_raw,\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", " print(\"Clinical features:\")\n", " print(clinical_features)\n", " \n", " # Save clinical features to file\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n", " \n", " # 3. Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(\"Linked data preview (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # 4. Handle missing values\n", " print(\"Missing values before handling:\")\n", " print(f\" Trait ({trait}) missing: {linked_data[trait].isna().sum()} out of {len(linked_data)}\")\n", " if 'Age' in linked_data.columns:\n", " print(f\" Age missing: {linked_data['Age'].isna().sum()} out of {len(linked_data)}\")\n", " if 'Gender' in linked_data.columns:\n", " print(f\" Gender missing: {linked_data['Gender'].isna().sum()} out of {len(linked_data)}\")\n", " print(f\" Genes with >20% missing: {sum(linked_data.iloc[:, 1:].isna().mean() > 0.2)}\")\n", " print(f\" Samples with >5% missing genes: {sum(linked_data.iloc[:, 1:].isna().mean(axis=1) > 0.05)}\")\n", " \n", " cleaned_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {cleaned_data.shape}\")\n", " \n", " # 5. Evaluate bias in trait and demographic features\n", " is_trait_biased = False\n", " if len(cleaned_data) > 0:\n", " trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait)\n", " is_trait_biased = trait_biased\n", " else:\n", " print(\"No data remains after handling missing values.\")\n", " is_trait_biased = True\n", " \n", " # 6. Final validation and save\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=cleaned_data,\n", " note=\"Dataset contains gene expression data comparing CFTR WT vs CFTR mutant (p.Phe508del) samples.\"\n", " )\n", " \n", " # 7. Save if usable\n", " if is_usable and len(cleaned_data) > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " cleaned_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data was determined to be unusable or empty and was not saved\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing data: {e}\")\n", " # Handle the error case by still recording cohort info\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, # Mark as not available due to processing issues\n", " is_biased=True, \n", " df=pd.DataFrame(), # Empty dataframe\n", " note=f\"Error processing data: {str(e)}\"\n", " )\n", " print(\"Data was determined to be unusable and was not saved\")" ] } ], "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 }