{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "0ae586c0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:02:14.650022Z", "iopub.status.busy": "2025-03-25T08:02:14.649795Z", "iopub.status.idle": "2025-03-25T08:02:14.816121Z", "shell.execute_reply": "2025-03-25T08:02:14.815744Z" } }, "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 = \"Endometriosis\"\n", "cohort = \"GSE111974\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Endometriosis\"\n", "in_cohort_dir = \"../../input/GEO/Endometriosis/GSE111974\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Endometriosis/GSE111974.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Endometriosis/gene_data/GSE111974.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Endometriosis/clinical_data/GSE111974.csv\"\n", "json_path = \"../../output/preprocess/Endometriosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ef96dfa9", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ea530a2f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:02:14.817582Z", "iopub.status.busy": "2025-03-25T08:02:14.817439Z", "iopub.status.idle": "2025-03-25T08:02:14.978118Z", "shell.execute_reply": "2025-03-25T08:02:14.977716Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Endometrial Tissue RNA expression in Recurrent Implantation Failure vs. Conrol\"\n", "!Series_summary\t\"We aimed to identify altered biological processes in the endometrium that may be potential markers of receptive endometrium. RNA expression profiling of the endometrium during the window of implantation was performed in patients with Recurrent Implantation Failure (RIF) versus fertile controls.\"\n", "!Series_overall_design\t\"24 patients with RIF treated at the IVF clinic and 24 fertile control patients recruited from the gynecology clinic of Istanbul University School of Medicine during 2014-2015 were involved in this prospective cohort study. RIF was determined as failure of pregnancy in ≥ 3 consecutive IVF cycles with ≥1 transfer(s) of good quality embryo in each cycle. Exclusion criteria for this group were active pelvic infections, undiagnosed vaginal bleeding, uterine anomalies, endometriosis, karyotype anomalies in one or both partners. Fertile control patients had a history of at least one live birth with no associated comorbidities.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Endometrial tissue']}\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": "9b68464c", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "97ffc7fd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:02:14.979567Z", "iopub.status.busy": "2025-03-25T08:02:14.979457Z", "iopub.status.idle": "2025-03-25T08:02:14.986776Z", "shell.execute_reply": "2025-03-25T08:02:14.986482Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A new JSON file was created at: ../../output/preprocess/Endometriosis/cohort_info.json\n" ] }, { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Set gene_expression availability based on data review\n", "# This dataset mentions RNA expression profiling, which indicates gene expression data is available\n", "is_gene_available = True\n", "\n", "# Check clinical data availability (trait, age, gender)\n", "# For trait: The sample characteristics don't show RIF vs Control information\n", "# And the extraction attempt resulted in all NaN values\n", "trait_row = None # No explicit trait information available in the expected format\n", "\n", "# For age: Not mentioned in sample characteristics\n", "age_row = None\n", "\n", "# For gender: All subjects appear to be female by study design (IVF study)\n", "gender_row = None\n", "\n", "# Define conversion functions (needed for the interface but won't be used with None values)\n", "def convert_trait(trait_value):\n", " \"\"\"\n", " Convert trait values to binary (0 for control, 1 for RIF)\n", " \"\"\"\n", " if trait_value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in trait_value:\n", " trait_value = trait_value.split(':', 1)[1].strip()\n", " \n", " trait_value = trait_value.lower()\n", " if 'rif' in trait_value or 'recurrent implantation failure' in trait_value:\n", " return 1\n", " elif 'control' in trait_value or 'fertile' in trait_value:\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(age_value):\n", " \"\"\"\n", " Convert age values to continuous\n", " \"\"\"\n", " if age_value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in age_value:\n", " age_value = age_value.split(':', 1)[1].strip()\n", " \n", " try:\n", " # Try to convert to float, handling various formats\n", " age_value = age_value.replace('years', '').replace('year', '').strip()\n", " return float(age_value)\n", " except (ValueError, AttributeError):\n", " return None\n", "\n", "def convert_gender(gender_value):\n", " \"\"\"\n", " Convert gender values to binary (0 for female, 1 for male)\n", " \"\"\"\n", " if gender_value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in gender_value:\n", " gender_value = gender_value.split(':', 1)[1].strip().lower()\n", " \n", " if 'female' in gender_value or 'f' == gender_value:\n", " return 0\n", " elif 'male' in gender_value or 'm' == gender_value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# Check trait availability based on trait_row\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort information\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", "# Skip clinical feature extraction as trait_row is None\n" ] }, { "cell_type": "markdown", "id": "608e993e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "b374655f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:02:14.987951Z", "iopub.status.busy": "2025-03-25T08:02:14.987844Z", "iopub.status.idle": "2025-03-25T08:02:15.212290Z", "shell.execute_reply": "2025-03-25T08:02:15.211952Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 56\n", "Header line: \"ID_REF\"\t\"GSM3045867\"\t\"GSM3045868\"\t\"GSM3045869\"\t\"GSM3045870\"\t\"GSM3045871\"\t\"GSM3045872\"\t\"GSM3045873\"\t\"GSM3045874\"\t\"GSM3045875\"\t\"GSM3045876\"\t\"GSM3045877\"\t\"GSM3045878\"\t\"GSM3045879\"\t\"GSM3045880\"\t\"GSM3045881\"\t\"GSM3045882\"\t\"GSM3045883\"\t\"GSM3045884\"\t\"GSM3045885\"\t\"GSM3045886\"\t\"GSM3045887\"\t\"GSM3045888\"\t\"GSM3045889\"\t\"GSM3045890\"\t\"GSM3045891\"\t\"GSM3045892\"\t\"GSM3045893\"\t\"GSM3045894\"\t\"GSM3045895\"\t\"GSM3045896\"\t\"GSM3045897\"\t\"GSM3045898\"\t\"GSM3045899\"\t\"GSM3045900\"\t\"GSM3045901\"\t\"GSM3045902\"\t\"GSM3045903\"\t\"GSM3045904\"\t\"GSM3045905\"\t\"GSM3045906\"\t\"GSM3045907\"\t\"GSM3045908\"\t\"GSM3045909\"\t\"GSM3045910\"\t\"GSM3045911\"\t\"GSM3045912\"\t\"GSM3045913\"\t\"GSM3045914\"\n", "First data line: \"A_19_P00315452\"\t8.2941\t9.4957\t9.13\t8.1259\t8.2462\t9.04\t7.7973\t8.5905\t9.2121\t9.0986\t9.6616\t8.5906\t8.1014\t9.2161\t9.364\t8.2461\t8.4084\t9.6027\t7.2648\t7.9788\t8.4856\t8.7482\t9.1229\t9.1373\t8.5388\t7.8161\t7.3634\t7.976\t8.1333\t7.6221\t6.5153\t9.2491\t7.7401\t7.9426\t8.2897\t8.1575\t7.8499\t7.3065\t7.7341\t8.6831\t8.2265\t8.6232\t5.5753\t8.1671\t8.1832\t8.358\t8.4928\t7.4193\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['A_19_P00315452', 'A_19_P00315459', 'A_19_P00315482', 'A_19_P00315492',\n", " 'A_19_P00315493', 'A_19_P00315502', 'A_19_P00315506', 'A_19_P00315518',\n", " 'A_19_P00315519', 'A_19_P00315524', 'A_19_P00315528', 'A_19_P00315529',\n", " 'A_19_P00315538', 'A_19_P00315541', 'A_19_P00315543', 'A_19_P00315550',\n", " 'A_19_P00315551', 'A_19_P00315554', 'A_19_P00315581', 'A_19_P00315583'],\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": "c1d1c44c", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "c68451f6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:02:15.213681Z", "iopub.status.busy": "2025-03-25T08:02:15.213555Z", "iopub.status.idle": "2025-03-25T08:02:15.215519Z", "shell.execute_reply": "2025-03-25T08:02:15.215243Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers from the previous step\n", "# The identifiers like \"A_19_P00315452\" appear to be probe IDs from a microarray platform\n", "# These are not standard human gene symbols and will need to be mapped to proper gene symbols\n", "\n", "# Based on my biomedical knowledge, these \"A_19_P\" identifiers are Agilent microarray probe IDs\n", "# They need to be mapped to standard gene symbols for proper interpretation and analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "27f595c5", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "826bed51", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:02:15.216721Z", "iopub.status.busy": "2025-03-25T08:02:15.216613Z", "iopub.status.idle": "2025-03-25T08:02:18.921856Z", "shell.execute_reply": "2025-03-25T08:02:18.921517Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['GE_BrightCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448', 'A_33_P3318220'], 'CONTROL_TYPE': ['pos', 'pos', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466'], 'GB_ACC': [nan, nan, 'NM_015987', 'NM_080671', 'NM_178466'], 'LOCUSLINK_ID': [nan, nan, 50865.0, 23704.0, 128861.0], 'GENE_SYMBOL': [nan, nan, 'HEBP1', 'KCNE4', 'BPIFA3'], 'GENE_NAME': [nan, nan, 'heme binding protein 1', 'potassium voltage-gated channel, Isk-related family, member 4', 'BPI fold containing family A, member 3'], 'UNIGENE_ID': [nan, nan, 'Hs.642618', 'Hs.348522', 'Hs.360989'], 'ENSEMBL_ID': [nan, nan, 'ENST00000014930', 'ENST00000281830', 'ENST00000375454'], 'ACCESSION_STRING': [nan, nan, 'ref|NM_015987|ens|ENST00000014930|gb|AF117615|gb|BC016277', 'ref|NM_080671|ens|ENST00000281830|tc|THC2655788', 'ref|NM_178466|ens|ENST00000375454|ens|ENST00000471233|tc|THC2478474'], 'CHROMOSOMAL_LOCATION': [nan, nan, 'chr12:13127906-13127847', 'chr2:223920197-223920256', 'chr20:31812208-31812267'], 'CYTOBAND': [nan, nan, 'hs|12p13.1', 'hs|2q36.1', 'hs|20q11.21'], 'DESCRIPTION': [nan, nan, 'Homo sapiens heme binding protein 1 (HEBP1), mRNA [NM_015987]', 'Homo sapiens potassium voltage-gated channel, Isk-related family, member 4 (KCNE4), mRNA [NM_080671]', 'Homo sapiens BPI fold containing family A, member 3 (BPIFA3), transcript variant 1, mRNA [NM_178466]'], 'GO_ID': [nan, nan, 'GO:0005488(binding)|GO:0005576(extracellular region)|GO:0005737(cytoplasm)|GO:0005739(mitochondrion)|GO:0005829(cytosol)|GO:0007623(circadian rhythm)|GO:0020037(heme binding)', 'GO:0005244(voltage-gated ion channel activity)|GO:0005249(voltage-gated potassium channel activity)|GO:0006811(ion transport)|GO:0006813(potassium ion transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0016324(apical plasma membrane)', 'GO:0005576(extracellular region)|GO:0008289(lipid binding)'], 'SEQUENCE': [nan, nan, 'AAGGGGGAAAATGTGATTTGTGCCTGATCTTTCATCTGTGATTCTTATAAGAGCTTTGTC', 'GCAAGTCTCTCTGCACCTATTAAAAAGTGATGTATATACTTCCTTCTTATTCTGTTGAGT', 'CATTCCATAAGGAGTGGTTCTCGGCAAATATCTCACTTGAATTTGACCTTGAATTGAGAC']}\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": "1f87c184", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "c9b5bb66", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:02:18.923675Z", "iopub.status.busy": "2025-03-25T08:02:18.923553Z", "iopub.status.idle": "2025-03-25T08:02:19.163061Z", "shell.execute_reply": "2025-03-25T08:02:19.162654Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data preview after mapping:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT',\n", " 'A4GNT', 'AA06', 'AAA1', 'AAAS', 'AACS', 'AACSP1', 'AADAC', 'AADACL2',\n", " 'AADACL3', 'AADACL4', 'AADAT', 'AAGAB'],\n", " dtype='object', name='Gene')\n", "Shape of gene expression data: (20353, 48)\n" ] } ], "source": [ "# 1. Identify columns for gene identifier mapping\n", "# From the gene annotation preview, we can see:\n", "# - 'ID' column contains identifiers like A_23_P117082, which matches the indices in gene_data\n", "# - 'GENE_SYMBOL' column contains gene symbols like HEBP1, which is what we need\n", "\n", "# 2. Extract the ID and GENE_SYMBOL columns to create mapping dataframe\n", "prob_col = 'ID' # The column containing probe IDs\n", "gene_col = 'GENE_SYMBOL' # The column containing gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Preview the first few rows of the gene expression data after mapping\n", "print(\"Gene expression data preview after mapping:\")\n", "print(gene_data.index[:20]) # Show the first 20 gene symbols\n", "print(f\"Shape of gene expression data: {gene_data.shape}\")\n" ] }, { "cell_type": "markdown", "id": "d7cbfc86", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "1e6b0cd2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:02:19.164273Z", "iopub.status.busy": "2025-03-25T08:02:19.164055Z", "iopub.status.idle": "2025-03-25T08:02:19.782697Z", "shell.execute_reply": "2025-03-25T08:02:19.782272Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Endometriosis/gene_data/GSE111974.csv\n", "Clinical data (empty) saved to ../../output/preprocess/Endometriosis/clinical_data/GSE111974.csv\n", "Data was determined to be unusable due to missing trait information\n" ] } ], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "normalized_gene_data = normalize_gene_symbols_in_index(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", "# Since trait_row is None (as determined in step 2), we use is_final=False for validation\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=False # No trait data available\n", ")\n", "\n", "# Create empty clinical features dataframe since trait_row is None\n", "clinical_features_df = pd.DataFrame()\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_features_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data (empty) saved to {out_clinical_data_file}\")\n", "\n", "# No further processing needed as the dataset is unusable due to lack of trait data\n", "print(\"Data was determined to be unusable due to missing trait information\")" ] } ], "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 }