File size: 16,516 Bytes
9fe78b4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "4bcb1c5b",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:48:24.322981Z",
"iopub.status.busy": "2025-03-25T03:48:24.322755Z",
"iopub.status.idle": "2025-03-25T03:48:24.508611Z",
"shell.execute_reply": "2025-03-25T03:48:24.508134Z"
}
},
"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 = \"Red_Hair\"\n",
"\n",
"# Input paths\n",
"tcga_root_dir = \"../../input/TCGA\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Red_Hair/TCGA.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Red_Hair/gene_data/TCGA.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Red_Hair/clinical_data/TCGA.csv\"\n",
"json_path = \"../../output/preprocess/Red_Hair/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "980a80c4",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "5ee2fc6c",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:48:24.510137Z",
"iopub.status.busy": "2025-03-25T03:48:24.509982Z",
"iopub.status.idle": "2025-03-25T03:48:25.684368Z",
"shell.execute_reply": "2025-03-25T03:48:25.684015Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Found matching directories: ['TCGA_Melanoma_(SKCM)', 'TCGA_Ocular_melanomas_(UVM)']\n",
"Selected directory: TCGA_Melanoma_(SKCM)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Clinical data columns:\n",
"['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'breslow_depth_value', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'days_to_submitted_specimen_dx', 'distant_metastasis_anatomic_site', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'height', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'interferon_90_day_prior_excision_admin_indicator', 'is_ffpe', 'lactate_dehydrogenase_result', 'lost_follow_up', 'malignant_neoplasm_mitotic_count_rate', 'melanoma_clark_level_value', 'melanoma_origin_skin_anatomic_site', 'melanoma_ulceration_indicator', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_non_melanoma_event_histologic_type_text', 'new_primary_melanoma_anatomic_site', 'new_tumor_dx_prior_submitted_specimen_dx', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'new_tumor_metastasis_anatomic_site', 'new_tumor_metastasis_anatomic_site_other_text', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'primary_anatomic_site_count', 'primary_melanoma_at_diagnosis_count', 'primary_neoplasm_melanoma_dx', 'primary_tumor_multiple_present_ind', 'prior_systemic_therapy_type', 'radiation_therapy', 'sample_type', 'sample_type_id', 'subsequent_primary_melanoma_during_followup', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tissue_type', 'tumor_descriptor', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_SKCM_exp_HiSeqV2', '_GENOMIC_ID_TCGA_SKCM_hMethyl450', '_GENOMIC_ID_TCGA_SKCM_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_SKCM_miRNA_HiSeq', '_GENOMIC_ID_TCGA_SKCM_gistic2thd', '_GENOMIC_ID_data/public/TCGA/SKCM/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_SKCM_RPPA', '_GENOMIC_ID_TCGA_SKCM_mutation_bcm_gene', '_GENOMIC_ID_TCGA_SKCM_mutation_broad_gene', '_GENOMIC_ID_TCGA_SKCM_gistic2', '_GENOMIC_ID_TCGA_SKCM_mutation', '_GENOMIC_ID_TCGA_SKCM_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_SKCM_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_SKCM_PDMRNAseq', '_GENOMIC_ID_TCGA_SKCM_exp_HiSeqV2_percentile']\n"
]
}
],
"source": [
"# Step 1: Search for directories related to Red Hair\n",
"import os\n",
"\n",
"# List all directories in TCGA root directory\n",
"tcga_dirs = os.listdir(tcga_root_dir)\n",
"\n",
"# Red hair is associated with melanoma risk, so look for melanoma or skin cancer datasets\n",
"matching_dirs = [dir_name for dir_name in tcga_dirs \n",
" if any(term in dir_name.lower() for term in \n",
" [\"melanoma\", \"skin cancer\", \"skin\", \"skcm\"])]\n",
"\n",
"if not matching_dirs:\n",
" print(f\"No matching directory found for trait: {trait}\")\n",
" \n",
" # Record that this trait is not available and exit\n",
" validate_and_save_cohort_info(\n",
" is_final=False,\n",
" cohort=\"TCGA\",\n",
" info_path=json_path,\n",
" is_gene_available=False,\n",
" is_trait_available=False\n",
" )\n",
" print(f\"Task marked as completed. {trait} is not directly represented in the TCGA dataset.\")\n",
"else:\n",
" # If we found matching directories\n",
" print(f\"Found matching directories: {matching_dirs}\")\n",
" \n",
" # Select the most specific directory for melanoma (which may have red hair data)\n",
" if \"TCGA_Melanoma_(SKCM)\" in matching_dirs:\n",
" selected_dir = \"TCGA_Melanoma_(SKCM)\" # Choose the most specific match\n",
" else:\n",
" selected_dir = matching_dirs[0] # Default to first match if specific one not found\n",
" \n",
" print(f\"Selected directory: {selected_dir}\")\n",
" cohort_dir = os.path.join(tcga_root_dir, selected_dir)\n",
" \n",
" # Step 2: Get file paths for clinical and genetic data\n",
" clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
" \n",
" # Step 3: Load the files\n",
" clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
" genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n",
" \n",
" # Step 4: Print column names of clinical data\n",
" print(\"Clinical data columns:\")\n",
" print(clinical_df.columns.tolist())\n"
]
},
{
"cell_type": "markdown",
"id": "1b7156cd",
"metadata": {},
"source": [
"### Step 2: Find Candidate Demographic Features"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "4ce443f7",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:48:25.685713Z",
"iopub.status.busy": "2025-03-25T03:48:25.685600Z",
"iopub.status.idle": "2025-03-25T03:48:25.695704Z",
"shell.execute_reply": "2025-03-25T03:48:25.695377Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Age columns preview:\n",
"{'age_at_initial_pathologic_diagnosis': [71.0, 82.0, 82.0, 46.0, 74.0], 'days_to_birth': [-26176.0, -30286.0, -30163.0, -17025.0, -27124.0], 'year_of_initial_pathologic_diagnosis': [2012.0, 2009.0, 2013.0, 2010.0, 2010.0]}\n",
"\n",
"Gender columns preview:\n",
"{'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'FEMALE']}\n"
]
}
],
"source": [
"# 1. Identify candidate demographic columns\n",
"candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'days_to_birth', 'year_of_initial_pathologic_diagnosis']\n",
"candidate_gender_cols = ['gender']\n",
"\n",
"# 2. Load the clinical data to preview\n",
"cohort_dir = os.path.join(tcga_root_dir, 'TCGA_Melanoma_(SKCM)')\n",
"clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir)\n",
"clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
"\n",
"# Extract the candidate columns for preview\n",
"age_preview = {}\n",
"for col in candidate_age_cols:\n",
" if col in clinical_df.columns:\n",
" age_preview[col] = clinical_df[col].head(5).tolist()\n",
"\n",
"gender_preview = {}\n",
"for col in candidate_gender_cols:\n",
" if col in clinical_df.columns:\n",
" gender_preview[col] = clinical_df[col].head(5).tolist()\n",
"\n",
"print(\"Age columns preview:\")\n",
"print(age_preview)\n",
"print(\"\\nGender columns preview:\")\n",
"print(gender_preview)\n"
]
},
{
"cell_type": "markdown",
"id": "d6b9284b",
"metadata": {},
"source": [
"### Step 3: Select Demographic Features"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "cf4c8b5b",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:48:25.696925Z",
"iopub.status.busy": "2025-03-25T03:48:25.696817Z",
"iopub.status.idle": "2025-03-25T03:48:25.699402Z",
"shell.execute_reply": "2025-03-25T03:48:25.699102Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Selected age column: age_at_initial_pathologic_diagnosis\n",
"Selected gender column: gender\n"
]
}
],
"source": [
"# Analyze the available demographic information\n",
"\n",
"# Check age columns\n",
"# We have 3 potential age columns:\n",
"# 1. age_at_initial_pathologic_diagnosis - direct age values\n",
"# 2. days_to_birth - negative days (can be converted to years by dividing by -365)\n",
"# 3. year_of_initial_pathologic_diagnosis - not useful for age calculation without additional info\n",
"\n",
"# Check gender columns\n",
"# We have only one gender column: 'gender'\n",
"\n",
"# Select the most appropriate columns\n",
"age_col = 'age_at_initial_pathologic_diagnosis' # Direct age values are most useful\n",
"gender_col = 'gender' # Only option available\n",
"\n",
"# Print chosen columns\n",
"print(f\"Selected age column: {age_col}\")\n",
"print(f\"Selected gender column: {gender_col}\")\n"
]
},
{
"cell_type": "markdown",
"id": "80b05aff",
"metadata": {},
"source": [
"### Step 4: Feature Engineering and Validation"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "2554f72e",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T03:48:25.700432Z",
"iopub.status.busy": "2025-03-25T03:48:25.700327Z",
"iopub.status.idle": "2025-03-25T03:48:39.476972Z",
"shell.execute_reply": "2025-03-25T03:48:39.476439Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Saved clinical data with 481 samples\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"After normalization: 19848 genes remaining\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Saved normalized gene expression data\n",
"Linked data shape: (474, 19851) (samples x features)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"After handling missing values, data shape: (474, 19851)\n",
"For the feature 'Red_Hair', the least common label is '0' with 1 occurrences. This represents 0.21% of the dataset.\n",
"The distribution of the feature 'Red_Hair' in this dataset is severely biased.\n",
"\n",
"Quartiles for 'Age':\n",
" 25%: 48.0\n",
" 50% (Median): 58.0\n",
" 75%: 70.75\n",
"Min: 15.0\n",
"Max: 90.0\n",
"The distribution of the feature 'Age' in this dataset is fine.\n",
"\n",
"For the feature 'Gender', the least common label is '0.0' with 180 occurrences. This represents 37.97% of the dataset.\n",
"The distribution of the feature 'Gender' in this dataset is fine.\n",
"\n",
"Dataset was determined to be unusable and was not saved.\n"
]
}
],
"source": [
"# Step 1: Extract and standardize clinical features\n",
"# Use the Melanoma directory identified in Step 1\n",
"selected_dir = \"TCGA_Melanoma_(SKCM)\"\n",
"cohort_dir = os.path.join(tcga_root_dir, selected_dir)\n",
"\n",
"# Get the file paths for clinical and genetic data\n",
"clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)\n",
"\n",
"# Load the data\n",
"clinical_df = pd.read_csv(clinical_file_path, sep='\\t', index_col=0)\n",
"genetic_df = pd.read_csv(genetic_file_path, sep='\\t', index_col=0)\n",
"\n",
"# Extract standardized clinical features using the provided trait variable\n",
"clinical_features = tcga_select_clinical_features(\n",
" clinical_df, \n",
" trait=trait, # Using the provided trait variable\n",
" age_col=age_col, \n",
" gender_col=gender_col\n",
")\n",
"\n",
"# Save the clinical data to out_clinical_data_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\"Saved clinical data with {len(clinical_features)} samples\")\n",
"\n",
"# Step 2: Normalize gene symbols in gene expression data\n",
"# Transpose to get genes as rows\n",
"gene_df = genetic_df\n",
"\n",
"# Normalize gene symbols using NCBI Gene database synonyms\n",
"normalized_gene_df = normalize_gene_symbols_in_index(gene_df)\n",
"print(f\"After normalization: {len(normalized_gene_df)} genes remaining\")\n",
"\n",
"# Save the normalized gene expression data\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"normalized_gene_df.to_csv(out_gene_data_file)\n",
"print(f\"Saved normalized gene expression data\")\n",
"\n",
"# Step 3: Link clinical and genetic data\n",
"# Merge clinical features with genetic expression data\n",
"linked_data = clinical_features.join(normalized_gene_df.T, how='inner')\n",
"print(f\"Linked data shape: {linked_data.shape} (samples x features)\")\n",
"\n",
"# Step 4: Handle missing values\n",
"cleaned_data = handle_missing_values(linked_data, trait_col=trait)\n",
"print(f\"After handling missing values, data shape: {cleaned_data.shape}\")\n",
"\n",
"# Step 5: Determine if trait or demographics are severely biased\n",
"trait_biased, cleaned_data = judge_and_remove_biased_features(cleaned_data, trait=trait)\n",
"\n",
"# Step 6: Validate data quality and save cohort information\n",
"note = \"The dataset contains gene expression data along with clinical information for melanoma patients from TCGA, which is relevant for studying Red_Hair trait due to its association with melanoma risk.\"\n",
"is_usable = validate_and_save_cohort_info(\n",
" is_final=True,\n",
" cohort=\"TCGA\",\n",
" info_path=json_path,\n",
" is_gene_available=True,\n",
" is_trait_available=True,\n",
" is_biased=trait_biased,\n",
" df=cleaned_data,\n",
" note=note\n",
")\n",
"\n",
"# Step 7: Save the linked data if usable\n",
"if is_usable:\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" cleaned_data.to_csv(out_data_file)\n",
" print(f\"Saved usable linked data to {out_data_file}\")\n",
"else:\n",
" print(\"Dataset 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
}
|