{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "39840d3c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:48:41.521101Z", "iopub.status.busy": "2025-03-25T03:48:41.520909Z", "iopub.status.idle": "2025-03-25T03:48:41.682322Z", "shell.execute_reply": "2025-03-25T03:48:41.681967Z" } }, "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 = \"Retinoblastoma\"\n", "cohort = \"GSE208143\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Retinoblastoma\"\n", "in_cohort_dir = \"../../input/GEO/Retinoblastoma/GSE208143\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Retinoblastoma/GSE208143.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Retinoblastoma/gene_data/GSE208143.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Retinoblastoma/clinical_data/GSE208143.csv\"\n", "json_path = \"../../output/preprocess/Retinoblastoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "e9026335", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "22466f0f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:48:41.683851Z", "iopub.status.busy": "2025-03-25T03:48:41.683696Z", "iopub.status.idle": "2025-03-25T03:48:41.821708Z", "shell.execute_reply": "2025-03-25T03:48:41.821368Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the cohort directory:\n", "['GSE208143_family.soft.gz', 'GSE208143_series_matrix.txt.gz']\n", "Identified SOFT files: ['GSE208143_family.soft.gz']\n", "Identified matrix files: ['GSE208143_series_matrix.txt.gz']\n", "\n", "Background Information:\n", "!Series_title\t\"mRNA expression profile from retinoblastoma tumors and pediatric controls\"\n", "!Series_summary\t\"To discover differentially expressed mRNA's in Rb tumors compared to pediatric retina\"\n", "!Series_overall_design\t\"Nine enucleated human retinoblastoma tumors and two pediatric retina controls used for the study. Total RNA was isolated from 9 Rb tumors and 2 control pediatric retina samples using Agilent Absolutely RNA miRNA kit. Twenty-five nanograms of RNA from Rb tumors and control pediatric retina samples were labeled with Cy3 dye using an Agilent Low Input Quick Amp Labeling Kit\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Tumor', 'tissue: Pediatric Retina'], 1: ['gender: Male', 'gender: Female']}\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": "97f17860", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "bd897d68", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:48:41.822959Z", "iopub.status.busy": "2025-03-25T03:48:41.822851Z", "iopub.status.idle": "2025-03-25T03:48:41.831437Z", "shell.execute_reply": "2025-03-25T03:48:41.831119Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features:\n", "{'Feature_0': [1.0, nan], 'Feature_1': [nan, 1.0]}\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# This dataset is looking at mRNA expression profiles in retinoblastoma tumors vs controls\n", "# The dataset mentions \"Total RNA was isolated\", \"mRNA expression profile\"\n", "# indicating that it contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Retinoblastoma):\n", "# From the sample characteristics, key 0 has 'tissue: Tumor' and 'tissue: Pediatric Retina'\n", "# which indicates Retinoblastoma status (Tumor vs Control)\n", "trait_row = 0\n", "\n", "# For gender:\n", "# From the sample characteristics, key 1 has 'gender: Male' and 'gender: Female'\n", "gender_row = 1\n", "\n", "# For age:\n", "# There is no age information in the sample characteristics dictionary\n", "age_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "# Convert tissue type to binary (Tumor = 1, Control = 0)\n", "def convert_trait(value):\n", " if isinstance(value, str):\n", " value = value.lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'tumor' in value:\n", " return 1\n", " elif 'retina' in value or 'control' in value:\n", " return 0\n", " return None\n", "\n", "# Convert gender to binary (Male = 1, Female = 0)\n", "def convert_gender(value):\n", " if isinstance(value, str):\n", " value = value.lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'male' in value:\n", " return 1\n", " elif 'female' in value:\n", " return 0\n", " return None\n", "\n", "# Age conversion function (not used in this dataset)\n", "def convert_age(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial 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", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " try:\n", " # Import necessary function\n", " from tools.preprocess import get_feature_data\n", " \n", " # The sample characteristics dictionary from the previous output\n", " sample_characteristics_dict = {0: ['tissue: Tumor', 'tissue: Pediatric Retina'], \n", " 1: ['gender: Male', 'gender: Female']}\n", " \n", " # Create DataFrame from the sample characteristics\n", " sample_ids = [f\"Sample_{i+1}\" for i in range(len(sample_characteristics_dict[0]))]\n", " clinical_data = pd.DataFrame(index=sample_ids)\n", " \n", " # Add each feature as a column\n", " for row_idx, values in sample_characteristics_dict.items():\n", " feature_name = f\"Feature_{row_idx}\"\n", " clinical_data[feature_name] = values\n", " \n", " # Extract clinical features\n", " clinical_features = 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(clinical_features)\n", " print(\"Preview of clinical features:\")\n", " print(preview)\n", " \n", " # Save the clinical features to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file, index=False)\n", " except Exception as e:\n", " print(f\"Error in clinical feature extraction: {e}\")\n", " print(\"Unable to extract clinical features. Skipping this step.\")\n" ] }, { "cell_type": "markdown", "id": "4bbaf1e8", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "a406e680", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:48:41.832593Z", "iopub.status.busy": "2025-03-25T03:48:41.832489Z", "iopub.status.idle": "2025-03-25T03:48:42.028757Z", "shell.execute_reply": "2025-03-25T03:48:42.028377Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "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", "\n", "Gene expression data shape: (50521, 33)\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": "0d2198a2", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "fbc27b5a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:48:42.030260Z", "iopub.status.busy": "2025-03-25T03:48:42.030064Z", "iopub.status.idle": "2025-03-25T03:48:42.032208Z", "shell.execute_reply": "2025-03-25T03:48:42.031899Z" } }, "outputs": [], "source": [ "# Examine the identifiers in the gene expression data\n", "# The identifiers starting with \"A_19_P\" appear to be Agilent microarray probe IDs\n", "# and not standard human gene symbols\n", "\n", "# These are probe identifiers from an Agilent microarray platform\n", "# They need to be mapped to human gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "725bc653", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "0b30da9c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:48:42.033399Z", "iopub.status.busy": "2025-03-25T03:48:42.033294Z", "iopub.status.idle": "2025-03-25T03:48:45.149726Z", "shell.execute_reply": "2025-03-25T03:48:45.149204Z" } }, "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", "try:\n", " # Use the correct variable name from previous steps\n", " gene_annotation = get_gene_annotation(soft_file_path)\n", " \n", " # 2. Preview the gene annotation dataframe\n", " print(\"Gene annotation preview:\")\n", " print(preview_df(gene_annotation))\n", " \n", "except UnicodeDecodeError as e:\n", " print(f\"Unicode decoding error: {e}\")\n", " print(\"Trying alternative approach...\")\n", " \n", " # Read the file with Latin-1 encoding which is more permissive\n", " import gzip\n", " import pandas as pd\n", " \n", " # Manually read the file line by line with error handling\n", " data_lines = []\n", " with gzip.open(soft_file_path, 'rb') as f:\n", " for line in f:\n", " # Skip lines starting with prefixes we want to filter out\n", " line_str = line.decode('latin-1')\n", " if not line_str.startswith('^') and not line_str.startswith('!') and not line_str.startswith('#'):\n", " data_lines.append(line_str)\n", " \n", " # Create dataframe from collected lines\n", " if data_lines:\n", " gene_data_str = '\\n'.join(data_lines)\n", " gene_annotation = pd.read_csv(pd.io.common.StringIO(gene_data_str), sep='\\t', low_memory=False)\n", " print(\"Gene annotation preview (alternative method):\")\n", " print(preview_df(gene_annotation))\n", " else:\n", " print(\"No valid gene annotation data found after filtering.\")\n", " gene_annotation = pd.DataFrame()\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene annotation data: {e}\")\n", " gene_annotation = pd.DataFrame()\n" ] }, { "cell_type": "markdown", "id": "edd2666b", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "832610b7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:48:45.151322Z", "iopub.status.busy": "2025-03-25T03:48:45.151199Z", "iopub.status.idle": "2025-03-25T03:48:45.784726Z", "shell.execute_reply": "2025-03-25T03:48:45.784271Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (46204, 2)\n", "First few mapping entries:\n", " ID Gene\n", "2 A_23_P117082 HEBP1\n", "3 A_33_P3246448 KCNE4\n", "4 A_33_P3318220 BPIFA3\n", "5 A_33_P3236322 LOC100129869\n", "6 A_33_P3319925 IRG1\n", "\n", "After mapping, gene expression data shape: (20330, 33)\n", "First few gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT',\n", " 'A4GNT', 'AA06'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "After normalization, gene expression data shape: (19825, 33)\n", "First few normalized gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A2MP1', 'A4GALT', 'A4GNT',\n", " 'AA06', 'AAA1'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Retinoblastoma/gene_data/GSE208143.csv\n" ] } ], "source": [ "# 1. Identify the relevant columns for mapping\n", "# From the gene annotation preview, we can see:\n", "# - 'ID' contains the probe identifiers like A_23_P117082 which match gene_data's index\n", "# - 'GENE_SYMBOL' contains the human gene symbols like HEBP1\n", "\n", "# 2. Get a gene mapping dataframe using the library function which ensures proper column naming\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"First few mapping entries:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# We'll use the library function to handle the many-to-many mapping scenario\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"\\nAfter mapping, gene expression data shape: {gene_data.shape}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Let's also normalize gene symbols to ensure consistency across datasets\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"\\nAfter normalization, gene expression data shape: {gene_data.shape}\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save gene expression data to file\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": "e2de45aa", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "653690ed", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:48:45.786171Z", "iopub.status.busy": "2025-03-25T03:48:45.786051Z", "iopub.status.idle": "2025-03-25T03:48:57.910101Z", "shell.execute_reply": "2025-03-25T03:48:57.909477Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape: (50521, 33)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (19825, 33)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Retinoblastoma/gene_data/GSE208143.csv\n", "Clinical features shape: (2, 33)\n", "Clinical features preview:\n", "{'GSM6338046': [1.0, 1.0], 'GSM6338047': [1.0, 1.0], 'GSM6338048': [1.0, 1.0], 'GSM6338049': [1.0, 1.0], 'GSM6338050': [1.0, 1.0], 'GSM6338051': [1.0, 1.0], 'GSM6338052': [1.0, 1.0], 'GSM6338053': [1.0, 1.0], 'GSM6338054': [1.0, 1.0], 'GSM6338055': [1.0, 1.0], 'GSM6338056': [1.0, 1.0], 'GSM6338057': [1.0, 1.0], 'GSM6338058': [1.0, 1.0], 'GSM6338059': [1.0, 1.0], 'GSM6338060': [1.0, 1.0], 'GSM6338061': [1.0, 1.0], 'GSM6338062': [1.0, 1.0], 'GSM6338063': [1.0, 1.0], 'GSM6338064': [1.0, 1.0], 'GSM6338065': [1.0, 1.0], 'GSM6338066': [1.0, 1.0], 'GSM6338067': [1.0, 1.0], 'GSM6338068': [1.0, 1.0], 'GSM6338069': [1.0, 1.0], 'GSM6338070': [1.0, 1.0], 'GSM6338071': [1.0, 1.0], 'GSM6338072': [1.0, 1.0], 'GSM6338073': [0.0, 1.0], 'GSM6338074': [0.0, 1.0], 'GSM6338075': [0.0, 1.0], 'GSM6338076': [0.0, 1.0], 'GSM6338077': [0.0, 1.0], 'GSM6338078': [0.0, 1.0]}\n", "Clinical features saved to ../../output/preprocess/Retinoblastoma/clinical_data/GSE208143.csv\n", "Linked data shape: (33, 19827)\n", "Linked data preview (first 5 rows, first 5 columns):\n", " Retinoblastoma Gender A1BG A1BG-AS1 A1CF\n", "GSM6338046 1.0 1.0 -2.752950 0.010037 -0.380270\n", "GSM6338047 1.0 1.0 -3.516410 -2.643171 -0.536300\n", "GSM6338048 1.0 1.0 -2.694007 -1.735662 -0.864301\n", "GSM6338049 1.0 1.0 -5.203022 -2.575239 -4.128648\n", "GSM6338050 1.0 1.0 -4.843595 -2.322952 -4.238761\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, linked data shape: (33, 19827)\n", "For the feature 'Retinoblastoma', the least common label is '0.0' with 6 occurrences. This represents 18.18% of the dataset.\n", "The distribution of the feature 'Retinoblastoma' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 33 occurrences. This represents 100.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "A new JSON file was created at: ../../output/preprocess/Retinoblastoma/cohort_info.json\n", "Data quality check result: Usable\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Retinoblastoma/GSE208143.csv\n" ] } ], "source": [ "# 1. Re-extract and normalize gene data\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Re-extract gene expression data\n", "gene_data = get_genetic_data(matrix_file_path)\n", "print(f\"Gene expression data shape: {gene_data.shape}\")\n", "\n", "# Re-extract gene annotation\n", "gene_annotation = get_gene_annotation(soft_file_path)\n", "\n", "# Get gene mapping and apply it\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Normalize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\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", "# Get clinical data\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\n", " if isinstance(value, str):\n", " value = value.lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'tumor' in value:\n", " return 1\n", " elif 'retina' in value or 'control' in value:\n", " return 0\n", " return None\n", "\n", "def convert_gender(value):\n", " if isinstance(value, str):\n", " value = value.lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'male' in value:\n", " return 1\n", " elif 'female' in value:\n", " return 0\n", " return None\n", "\n", "# Extract clinical features\n", "clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=0, # As identified in Step 2\n", " convert_trait=convert_trait,\n", " gender_row=1,\n", " convert_gender=convert_gender\n", ")\n", "\n", "print(f\"Clinical features shape: {clinical_features.shape}\")\n", "print(\"Clinical features preview:\")\n", "print(preview_df(clinical_features))\n", "\n", "# Save the clinical features\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", "# 2. 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", "# 3. Handle missing values\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"After handling missing values, linked data shape: {linked_data.shape}\")\n", "\n", "# 4. Determine if trait and demographic features are biased\n", "is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. Validate and save cohort information\n", "note = \"Dataset contains gene expression data from retinoblastoma tumors and pediatric retina controls.\"\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, # We have trait data (tumor vs control)\n", " is_biased=is_trait_biased, \n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 6. Save linked data if usable\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n", "if is_usable:\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 quality check failed. The dataset is not suitable for association studies.\")" ] } ], "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 }