{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "c359468d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:02.997294Z", "iopub.status.busy": "2025-03-25T04:10:02.996907Z", "iopub.status.idle": "2025-03-25T04:10:03.176580Z", "shell.execute_reply": "2025-03-25T04:10:03.176236Z" } }, "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 = \"Thyroid_Cancer\"\n", "cohort = \"GSE107754\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Thyroid_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Thyroid_Cancer/GSE107754\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Thyroid_Cancer/GSE107754.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Thyroid_Cancer/gene_data/GSE107754.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Thyroid_Cancer/clinical_data/GSE107754.csv\"\n", "json_path = \"../../output/preprocess/Thyroid_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f79bcae5", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ceab73ac", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:03.178008Z", "iopub.status.busy": "2025-03-25T04:10:03.177856Z", "iopub.status.idle": "2025-03-25T04:10:03.406632Z", "shell.execute_reply": "2025-03-25T04:10:03.406301Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"A novel genomic signature predicting FDG uptake in diverse metastatic tumors\"\n", "!Series_summary\t\"Purpose: Building a universal genomic signature predicting the intensity of FDG uptake in diverse metastatic tumors may allow us to understand better the biological processes underlying this phenomenon and their requirements of glucose uptake.\"\n", "!Series_summary\t\"Methods: A balanced training set (n=71) of metastatic tumors including some of the most frequent histologies, with matched PET/CT quantification measurements and whole human genome gene expression microarrays, was used to build the signature. Selection of microarray features was carried out exclusively on the basis of their strong association with FDG uptake (as measured by SUVmean35) by means of univariate linear regression. A thorough bioinformatics study of these genes was performed and multivariable models were built by fitting several state of the art regression techniques to the training set for comparison.\"\n", "!Series_summary\t\"Results: The 909 probes with the strongest association with the SUVmean35 (comprising 742 identifiable genes and 62 probes not matched to a symbol) were used to build the signature. Partial Least Squares using 3 components (PLS-3) was the best performing model in the training dataset cross-validation (Root Mean Square Error, RMSE=0.443) and was validated further in an independent validation dataset (n=13) obtaining a performance within the 95% CI of that obtained in the training dataset (RMSE=0.645). Significantly overrepresented biological processes correlating with the SUVmean35 were identified beyond glycolysis, such as ribosome biogenesis and DNA replication (correlating with a higher SUVmean35), and cytoskeleton reorganization and autophagy (correlating with a lower SUVmean35), among others.\"\n", "!Series_summary\t\"Conclusions: PLS-3 is a signature predicting accurately the intensity of FDG uptake in diverse metastatic tumors. FDG-PET might help in the design of specific targeted therapies directed to counteract the identified malignant biological processes more likely activated in a tumor as inferred from the SUVmean35 and also from its variations in response to antineoplastic treatments.\"\n", "!Series_overall_design\t\"Whole human genome microarrays from biopsies of human metastatic tumors (71 patients) with matched SUVmean35 measurements, this submission includes the 71 patients of the training set used to build the genomic signature predicting FDG uptake in diverse metastatic tumors. This dataset is complemented with a validation set comprised of 13 patients.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: Male', 'gender: Female'], 1: ['dataset: Validation set', 'dataset: Training set'], 2: ['biopsy location: Lung', 'biopsy location: Lymph node', 'biopsy location: Primary', 'biopsy location: Liver', 'biopsy location: Retroperitoneal implant', 'tissue: Pancreatic cancer', 'tissue: Esophagus cancer', 'tissue: Breast cancer', 'tissue: Colorectal cancer', 'tissue: Ovarian cancer', 'tissue: Head&neck cancer', 'tissue: Lung cancer', 'tissue: Malignant Melanoma', 'tissue: Endometrial cancer', 'tissue: Cervix cancer', 'tissue: Soft tissue sarcoma', 'tissue: Gastric cancer', 'tissue: Unknown primary', 'tissue: Malignant Mesothelioma', 'tissue: Thyroid cancer', 'tissue: Testes cancer', 'tissue: Non Hodgkin lymphoma', 'tissue: Merkel cell carcinoma', 'tissue: Vaginal cancer', 'tissue: Kidney cancer', 'tissue: Cervical cancer', 'tissue: Bile duct cancer', 'tissue: Urothelial cancer'], 3: ['suvmean35: 4.09', 'suvmean35: 8.36', 'suvmean35: 5.18', 'suvmean35: 10.74', 'suvmean35: 8.62', 'suvmean35: 8.02', 'suvmean35: 6.87', 'suvmean35: 4.93', 'suvmean35: 1.96', 'suvmean35: 8.83', 'suvmean35: 3.96', 'suvmean35: 3.38', 'suvmean35: 9.95', 'suvmean35: 5.19', 'suvmean35: 7.22', 'suvmean35: 5.02', 'suvmean35: 4.92', 'suvmean35: 4.99', 'suvmean35: 4.01', 'suvmean35: 2.52', 'suvmean35: 5.52', 'suvmean35: 8.38', 'suvmean35: 3.46', 'suvmean35: 4.07', 'suvmean35: 4.67', 'suvmean35: 7.09', 'suvmean35: 4.83', 'suvmean35: 6.7', 'suvmean35: 3.95', 'suvmean35: 5.03']}\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": "f0bc7b2a", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "2cd2a8e5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:03.407931Z", "iopub.status.busy": "2025-03-25T04:10:03.407811Z", "iopub.status.idle": "2025-03-25T04:10:03.417258Z", "shell.execute_reply": "2025-03-25T04:10:03.416864Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features:\n", "{'Sample_1': [0.0, 1.0], 'Sample_2': [0.0, 0.0]}\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# From the background information, we can see this dataset contains gene expression microarray data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For the trait variable (Thyroid Cancer), we need to check if it's in the sample characteristics\n", "trait_row = 2 # Looking at row 2, we find 'tissue: Thyroid cancer' among other tissue types\n", "\n", "# For age, there's no key in the sample characteristics dictionary that contains age information\n", "age_row = None\n", "\n", "# For gender, we can find it in row 0\n", "gender_row = 0\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(x):\n", " \"\"\"Convert trait data to binary values (0 for non-thyroid cancer, 1 for thyroid cancer)\"\"\"\n", " if isinstance(x, str):\n", " if 'thyroid cancer' in x.lower():\n", " return 1\n", " elif 'tissue:' in x.lower() or 'biopsy location:' in x.lower(): # Any other tissue type is not thyroid cancer\n", " return 0\n", " return None\n", "\n", "def convert_gender(x):\n", " \"\"\"Convert gender data to binary values (0 for female, 1 for male)\"\"\"\n", " if isinstance(x, str):\n", " if ':' in x:\n", " value = x.split(':', 1)[1].strip().lower()\n", " if value == 'female':\n", " return 0\n", " elif value == 'male':\n", " return 1\n", " return None\n", "\n", "# Age conversion function is not needed since age data is not available\n", "convert_age = None\n", "\n", "# 3. Save Metadata\n", "# Set is_trait_available based on whether trait_row is None\n", "is_trait_available = trait_row is not None\n", "\n", "# Use the validate_and_save_cohort_info function for initial filtering\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", " # Create a DataFrame from the sample characteristics\n", " sample_characteristics = {\n", " 0: ['gender: Male', 'gender: Female'],\n", " 1: ['dataset: Validation set', 'dataset: Training set'],\n", " 2: ['biopsy location: Lung', 'biopsy location: Lymph node', 'biopsy location: Primary', 'biopsy location: Liver', \n", " 'biopsy location: Retroperitoneal implant', 'tissue: Pancreatic cancer', 'tissue: Esophagus cancer', \n", " 'tissue: Breast cancer', 'tissue: Colorectal cancer', 'tissue: Ovarian cancer', 'tissue: Head&neck cancer', \n", " 'tissue: Lung cancer', 'tissue: Malignant Melanoma', 'tissue: Endometrial cancer', 'tissue: Cervix cancer', \n", " 'tissue: Soft tissue sarcoma', 'tissue: Gastric cancer', 'tissue: Unknown primary', \n", " 'tissue: Malignant Mesothelioma', 'tissue: Thyroid cancer', 'tissue: Testes cancer', \n", " 'tissue: Non Hodgkin lymphoma', 'tissue: Merkel cell carcinoma', 'tissue: Vaginal cancer', \n", " 'tissue: Kidney cancer', 'tissue: Cervical cancer', 'tissue: Bile duct cancer', 'tissue: Urothelial cancer'],\n", " 3: ['suvmean35: 4.09', 'suvmean35: 8.36', 'suvmean35: 5.18', 'suvmean35: 10.74', 'suvmean35: 8.62', \n", " 'suvmean35: 8.02', 'suvmean35: 6.87', 'suvmean35: 4.93', 'suvmean35: 1.96', 'suvmean35: 8.83', \n", " 'suvmean35: 3.96', 'suvmean35: 3.38', 'suvmean35: 9.95', 'suvmean35: 5.19', 'suvmean35: 7.22', \n", " 'suvmean35: 5.02', 'suvmean35: 4.92', 'suvmean35: 4.99', 'suvmean35: 4.01', 'suvmean35: 2.52', \n", " 'suvmean35: 5.52', 'suvmean35: 8.38', 'suvmean35: 3.46', 'suvmean35: 4.07', 'suvmean35: 4.67', \n", " 'suvmean35: 7.09', 'suvmean35: 4.83', 'suvmean35: 6.7', 'suvmean35: 3.95', 'suvmean35: 5.03']\n", " }\n", " \n", " # Convert the dictionary to a DataFrame format that geo_select_clinical_features expects\n", " # Creating a DataFrame with sample IDs as columns and characteristics types as rows\n", " sample_ids = [f\"Sample_{i+1}\" for i in range(len(sample_characteristics[0]) if 0 in sample_characteristics else 0)]\n", " \n", " # Create empty DataFrame\n", " clinical_data = pd.DataFrame(index=sample_characteristics.keys(), columns=sample_ids)\n", " \n", " # Fill the DataFrame with sample characteristics\n", " # Since we don't have individual mappings, we'll distribute the values across samples\n", " # This is a simplification for demonstration purposes\n", " for row_idx, values in sample_characteristics.items():\n", " for col_idx, value in enumerate(values):\n", " if col_idx < len(sample_ids):\n", " clinical_data.loc[row_idx, sample_ids[col_idx]] = value\n", " \n", " # Extract clinical features using the provided function\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", " 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 processed clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n" ] }, { "cell_type": "markdown", "id": "d8e66b8e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "3680f67a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:03.418729Z", "iopub.status.busy": "2025-03-25T04:10:03.418607Z", "iopub.status.idle": "2025-03-25T04:10:03.825852Z", "shell.execute_reply": "2025-03-25T04:10:03.825523Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Thyroid_Cancer/GSE107754/GSE107754_family.soft.gz\n", "Matrix file: ../../input/GEO/Thyroid_Cancer/GSE107754/GSE107754_series_matrix.txt.gz\n", "Found the matrix table marker in the file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (41000, 84)\n", "First 20 gene/probe identifiers:\n", "['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074', 'A_23_P100092', 'A_23_P100103', 'A_23_P100111', 'A_23_P100127', 'A_23_P100133', 'A_23_P100141', 'A_23_P100156', 'A_23_P100177', 'A_23_P100189', 'A_23_P100196', 'A_23_P100203', 'A_23_P100220', 'A_23_P100240', 'A_23_P10025', 'A_23_P100263']\n" ] } ], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for line in file:\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " break\n", " \n", " if found_marker:\n", " print(\"Found the matrix table marker in the file.\")\n", " else:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " \n", " # Try to extract gene data from the matrix file\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " is_gene_available = False\n", " \n", " # Try to diagnose the file format\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if i < 10: # Print first 10 lines to diagnose\n", " print(f\"Line {i}: {line.strip()[:100]}...\") # Print first 100 chars of each line\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", "\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n" ] }, { "cell_type": "markdown", "id": "5229f03e", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "7a7e8afd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:03.827074Z", "iopub.status.busy": "2025-03-25T04:10:03.826944Z", "iopub.status.idle": "2025-03-25T04:10:03.828940Z", "shell.execute_reply": "2025-03-25T04:10:03.828660Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers\n", "# These identifiers (A_23_P100001, etc.) appear to be Agilent microarray probe IDs rather than\n", "# standard human gene symbols (like BRCA1, TP53, etc.)\n", "# They need to be mapped to standard gene symbols for meaningful analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "cb12b324", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "acd59035", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:03.829929Z", "iopub.status.busy": "2025-03-25T04:10:03.829826Z", "iopub.status.idle": "2025-03-25T04:10:08.996689Z", "shell.execute_reply": "2025-03-25T04:10:08.996349Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'SPOT_ID', 'CONTROL_TYPE', 'REFSEQ', 'GB_ACC', 'GENE', 'GENE_SYMBOL', 'GENE_NAME', 'UNIGENE_ID', 'ENSEMBL_ID', 'TIGR_ID', 'ACCESSION_STRING', 'CHROMOSOMAL_LOCATION', 'CYTOBAND', 'DESCRIPTION', 'GO_ID', 'SEQUENCE']\n", "{'ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'SPOT_ID': ['A_23_P100001', 'A_23_P100011', 'A_23_P100022', 'A_23_P100056', 'A_23_P100074'], 'CONTROL_TYPE': ['FALSE', 'FALSE', 'FALSE', 'FALSE', 'FALSE'], 'REFSEQ': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GB_ACC': ['NM_207446', 'NM_005829', 'NM_014848', 'NM_194272', 'NM_020371'], 'GENE': [400451.0, 10239.0, 9899.0, 348093.0, 57099.0], 'GENE_SYMBOL': ['FAM174B', 'AP3S2', 'SV2B', 'RBPMS2', 'AVEN'], 'GENE_NAME': ['family with sequence similarity 174, member B', 'adaptor-related protein complex 3, sigma 2 subunit', 'synaptic vesicle glycoprotein 2B', 'RNA binding protein with multiple splicing 2', 'apoptosis, caspase activation inhibitor'], 'UNIGENE_ID': ['Hs.27373', 'Hs.632161', 'Hs.21754', 'Hs.436518', 'Hs.555966'], 'ENSEMBL_ID': ['ENST00000557398', nan, 'ENST00000557410', 'ENST00000300069', 'ENST00000306730'], 'TIGR_ID': [nan, nan, nan, nan, nan], 'ACCESSION_STRING': ['ref|NM_207446|ens|ENST00000557398|ens|ENST00000553393|ens|ENST00000327355', 'ref|NM_005829|ref|NM_001199058|ref|NR_023361|ref|NR_037582', 'ref|NM_014848|ref|NM_001167580|ens|ENST00000557410|ens|ENST00000330276', 'ref|NM_194272|ens|ENST00000300069|gb|AK127873|gb|AK124123', 'ref|NM_020371|ens|ENST00000306730|gb|AF283508|gb|BC010488'], 'CHROMOSOMAL_LOCATION': ['chr15:93160848-93160789', 'chr15:90378743-90378684', 'chr15:91838329-91838388', 'chr15:65032375-65032316', 'chr15:34158739-34158680'], 'CYTOBAND': ['hs|15q26.1', 'hs|15q26.1', 'hs|15q26.1', 'hs|15q22.31', 'hs|15q14'], 'DESCRIPTION': ['Homo sapiens family with sequence similarity 174, member B (FAM174B), mRNA [NM_207446]', 'Homo sapiens adaptor-related protein complex 3, sigma 2 subunit (AP3S2), transcript variant 1, mRNA [NM_005829]', 'Homo sapiens synaptic vesicle glycoprotein 2B (SV2B), transcript variant 1, mRNA [NM_014848]', 'Homo sapiens RNA binding protein with multiple splicing 2 (RBPMS2), mRNA [NM_194272]', 'Homo sapiens apoptosis, caspase activation inhibitor (AVEN), mRNA [NM_020371]'], 'GO_ID': ['GO:0016020(membrane)|GO:0016021(integral to membrane)', 'GO:0005794(Golgi apparatus)|GO:0006886(intracellular protein transport)|GO:0008565(protein transporter activity)|GO:0016020(membrane)|GO:0016192(vesicle-mediated transport)|GO:0030117(membrane coat)|GO:0030659(cytoplasmic vesicle membrane)|GO:0031410(cytoplasmic vesicle)', 'GO:0001669(acrosomal vesicle)|GO:0006836(neurotransmitter transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0022857(transmembrane transporter activity)|GO:0030054(cell junction)|GO:0030672(synaptic vesicle membrane)|GO:0031410(cytoplasmic vesicle)|GO:0045202(synapse)', 'GO:0000166(nucleotide binding)|GO:0003676(nucleic acid binding)', 'GO:0005515(protein binding)|GO:0005622(intracellular)|GO:0005624(membrane fraction)|GO:0006915(apoptosis)|GO:0006916(anti-apoptosis)|GO:0012505(endomembrane system)|GO:0016020(membrane)'], 'SEQUENCE': ['ATCTCATGGAAAAGCTGGATTCCTCTGCCTTACGCAGAAACACCCGGGCTCCATCTGCCA', 'TCAAGTATTGGCCTGACATAGAGTCCTTAAGACAAGCAAAGACAAGCAAGGCAAGCACGT', 'ATGTCGGCTGTGGAGGGTTAAAGGGATGAGGCTTTCCTTTGTTTAGCAAATCTGTTCACA', 'CCCTGTCAGATAAGTTTAATGTTTAGTTTGAGGCATGAAGAAGAAAAGGGTTTCCATTCT', 'GACCAGCCAGTTTACAAGCATGTCTCAAGCTAGTGTGTTCCATTATGCTCACAGCAGTAA']}\n", "\n", "Complete sample of a few rows:\n", " ID SPOT_ID CONTROL_TYPE REFSEQ\n", "0 A_23_P100001 A_23_P100001 FALSE NM_207446\n", "1 A_23_P100011 A_23_P100011 FALSE NM_005829\n", "2 A_23_P100022 A_23_P100022 FALSE NM_014848\n", "\n", "Checking for gene information in gene_assignment column:\n", "Sample gene_assignment text: Column not found...\n", "\n", "Error: Could not find 'gene_assignment' column in the annotation data\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Get a more complete view to understand the annotation structure\n", "print(\"\\nComplete sample of a few rows:\")\n", "print(gene_annotation.iloc[:3, :4].to_string()) # Show only first few columns for readability\n", "\n", "# Examine the gene_assignment column which contains gene information\n", "print(\"\\nChecking for gene information in gene_assignment column:\")\n", "sample_text = gene_annotation.loc[0, 'gene_assignment'] if 'gene_assignment' in gene_annotation.columns else \"Column not found\"\n", "print(f\"Sample gene_assignment text: {sample_text[:200]}...\") # Print first 200 chars\n", "\n", "# Extract gene symbols from gene_assignment column\n", "if 'gene_assignment' in gene_annotation.columns:\n", " # Create a new column with extracted gene symbols\n", " gene_annotation['Gene'] = gene_annotation['gene_assignment'].apply(extract_human_gene_symbols)\n", " \n", " # Display a sample of the extracted gene symbols\n", " print(\"\\nSample of extracted gene symbols:\")\n", " sample_df = gene_annotation[['ID', 'Gene']].head(10)\n", " print(sample_df)\n", " \n", " # Check if gene symbols were successfully extracted\n", " empty_genes = gene_annotation['Gene'].apply(lambda x: len(x) == 0).sum()\n", " print(f\"\\nNumber of probes with no gene symbols extracted: {empty_genes} out of {len(gene_annotation)}\")\n", " \n", " # Create the mapping using our new Gene column\n", " mapping_data = gene_annotation[['ID', 'Gene']].copy()\n", " mapping_data = mapping_data[mapping_data['Gene'].apply(len) > 0] # Filter out empty gene lists\n", " \n", " # Print sample of the mapping to confirm\n", " print(\"\\nSample of probe ID to gene symbol mappings:\")\n", " print(mapping_data.head(10))\n", " \n", " # Check the size of the mapping data\n", " print(f\"\\nTotal number of probe-to-gene mappings: {len(mapping_data)}\")\n", "else:\n", " print(\"\\nError: Could not find 'gene_assignment' column in the annotation data\")\n" ] }, { "cell_type": "markdown", "id": "daafecf9", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "a499483e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:08.997911Z", "iopub.status.busy": "2025-03-25T04:10:08.997790Z", "iopub.status.idle": "2025-03-25T04:10:10.305319Z", "shell.execute_reply": "2025-03-25T04:10:10.304820Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created mapping dataframe with 30936 rows\n", "Sample of the mapping dataframe:\n", " ID Gene\n", "0 A_23_P100001 FAM174B\n", "1 A_23_P100011 AP3S2\n", "2 A_23_P100022 SV2B\n", "3 A_23_P100056 RBPMS2\n", "4 A_23_P100074 AVEN\n", "5 A_23_P100092 ZSCAN29\n", "6 A_23_P100103 VPS39\n", "7 A_23_P100111 CHP\n", "8 A_23_P100127 CASC5\n", "9 A_23_P100133 ATMIN\n", "\n", "Gene data shape before mapping: (41000, 84)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after mapping: (18488, 84)\n", "First few gene symbols:\n", "['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAAS', 'AACS']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Thyroid_Cancer/gene_data/GSE107754.csv\n" ] } ], "source": [ "# 1. Identify which columns in gene annotation contain probe IDs and gene symbols\n", "# Based on the gene annotation preview, 'ID' contains probe identifiers that match the gene expression data\n", "# 'GENE_SYMBOL' contains the gene symbols we need to map to\n", "\n", "# 2. Get a gene mapping dataframe with the identifier and gene symbol columns\n", "mapping_df = gene_annotation[['ID', 'GENE_SYMBOL']].copy()\n", "mapping_df = mapping_df.rename(columns={'GENE_SYMBOL': 'Gene'})\n", "mapping_df = mapping_df.dropna(subset=['Gene']) # Remove rows with missing gene symbols\n", "\n", "print(f\"Created mapping dataframe with {len(mapping_df)} rows\")\n", "print(\"Sample of the mapping dataframe:\")\n", "print(mapping_df.head(10))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# First, let's check our input data\n", "print(f\"\\nGene data shape before mapping: {gene_data.shape}\")\n", "\n", "# Apply the mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Check the result\n", "print(f\"Gene data shape after mapping: {gene_data.shape}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Save the processed gene data for future use\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": "dd8ebbfb", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "bfa3cc14", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T04:10:10.306850Z", "iopub.status.busy": "2025-03-25T04:10:10.306723Z", "iopub.status.idle": "2025-03-25T04:10:16.979200Z", "shell.execute_reply": "2025-03-25T04:10:16.978723Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (18488, 84)\n", "Gene data shape after normalization: (18247, 84)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Thyroid_Cancer/gene_data/GSE107754.csv\n", "Sample conversion results:\n", "Sample trait value: 'biopsy location: Lung' -> 0\n", "Sample gender value: 'gender: Male' -> 1\n", "Extracted clinical data shape: (2, 84)\n", "Preview of clinical data (first 5 samples):\n", " GSM2878070 GSM2878071 GSM2878072 GSM2878073 GSM2878074\n", "Thyroid_Cancer 0.0 0.0 0.0 0.0 0.0\n", "Gender 1.0 0.0 1.0 1.0 0.0\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Clinical data saved to ../../output/preprocess/Thyroid_Cancer/clinical_data/GSE107754.csv\n", "Gene data columns (first 5): ['GSM2878070', 'GSM2878071', 'GSM2878072', 'GSM2878073', 'GSM2878074']\n", "Clinical data columns (first 5): ['GSM2878070', 'GSM2878071', 'GSM2878072', 'GSM2878073', 'GSM2878074']\n", "Found 84 common samples between gene and clinical data\n", "Initial linked data shape: (84, 18249)\n", "Preview of linked data (first 5 rows, first 5 columns):\n", " Thyroid_Cancer Gender A1BG A1BG-AS1 A1CF\n", "GSM2878070 0.0 1.0 16.675251 8.138944 15.194191\n", "GSM2878071 0.0 0.0 18.589095 9.361230 15.252929\n", "GSM2878072 0.0 1.0 17.665959 8.513994 16.779446\n", "GSM2878073 0.0 1.0 20.260758 9.269932 19.487898\n", "GSM2878074 0.0 0.0 17.885257 9.537095 15.190126\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (84, 18249)\n", "For the feature 'Thyroid_Cancer', the least common label is '1.0' with 2 occurrences. This represents 2.38% of the dataset.\n", "The distribution of the feature 'Thyroid_Cancer' in this dataset is severely biased.\n", "\n", "For the feature 'Gender', the least common label is '1.0' with 35 occurrences. This represents 41.67% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is fine.\n", "\n", "A new JSON file was created at: ../../output/preprocess/Thyroid_Cancer/cohort_info.json\n", "Data not usable for the trait study - not saving final linked data.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use the gene_data variable from the previous step (don't try to load it from file)\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data\n", "try:\n", " # Load the clinical data from file\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Debug the trait and gender conversion functions\n", " print(\"Sample conversion results:\")\n", " sample_trait = list(clinical_data.iloc[2])[1] # Get a sample from trait row (row 2)\n", " sample_gender = list(clinical_data.iloc[0])[1] # Get a sample from gender row (row 0)\n", " print(f\"Sample trait value: '{sample_trait}' -> {convert_trait(sample_trait)}\")\n", " print(f\"Sample gender value: '{sample_gender}' -> {convert_gender(sample_gender)}\")\n", " \n", " # Extract clinical features with CORRECT indices from Step 2\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=2, # Correct trait row from Step 2\n", " convert_trait=convert_trait,\n", " gender_row=0, # Correct gender row from Step 2\n", " convert_gender=convert_gender,\n", " age_row=None, # Age row is None as per Step 2\n", " convert_age=None\n", " )\n", " \n", " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.iloc[:, :5])\n", " \n", " # Save the properly extracted clinical data\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 data saved to {out_clinical_data_file}\")\n", " \n", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Debug the column names to ensure they match\n", " print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n", " print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n", " \n", " # Check for common sample IDs\n", " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # Debug the trait values before handling missing values\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from thyroid cancer samples with tumor type information.\"\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " # 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", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n", " )\n", "else:\n", " # We can't proceed with linking if either trait or gene data is missing\n", " print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n", " validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=True, # Data is unusable if we're missing components\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=\"Missing essential data components for linking (trait data or gene expression data).\"\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 }