Download output/preprocess/Cervical_Cancer/code/TCGA.py from Liu-Hy/GenoTEX: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/datasets/Liu-Hy/GenoTEX/resolve/main/output/preprocess/Cervical_Cancer/code/TCGA.py
- Command line
-
hf download hf://datasets/Liu-Hy/GenoTEX/output/preprocess/Cervical_Cancer/code/TCGA.py
-
curl -L -o TCGA.py https://huggingface.co/datasets/Liu-Hy/GenoTEX/resolve/main/output/preprocess/Cervical_Cancer/code/TCGA.py
14.1 kB
| # Path Configuration | |
| from tools.preprocess import * | |
| # Processing context | |
| trait = "Cervical_Cancer" | |
| # Input paths | |
| tcga_root_dir = "../DATA/TCGA" | |
| # Output paths | |
| out_data_file = "./output/z2/preprocess/Cervical_Cancer/TCGA.csv" | |
| out_gene_data_file = "./output/z2/preprocess/Cervical_Cancer/gene_data/TCGA.csv" | |
| out_clinical_data_file = "./output/z2/preprocess/Cervical_Cancer/clinical_data/TCGA.csv" | |
| json_path = "./output/z2/preprocess/Cervical_Cancer/cohort_info.json" | |
| # Step 1: Initial Data Loading | |
| import os | |
| import re | |
| import pandas as pd | |
| # 1) Select the most relevant TCGA cohort directory for the trait | |
| all_entries = os.listdir(tcga_root_dir) | |
| subdirs = [d for d in all_entries if os.path.isdir(os.path.join(tcga_root_dir, d))] | |
| # Prefer names containing "cervic" or "cesc" | |
| pattern = re.compile(r'(cervic|cesc)', re.IGNORECASE) | |
| matches = [d for d in subdirs if pattern.search(d)] | |
| selected_cohort_dir = None | |
| if matches: | |
| # Prefer the most specific match containing "cervical" first, else pick the first match | |
| cervical_matches = [d for d in matches if re.search(r'cervical', d, re.IGNORECASE)] | |
| selected = cervical_matches[0] if cervical_matches else matches[0] | |
| selected_cohort_dir = os.path.join(tcga_root_dir, selected) | |
| if selected_cohort_dir is None: | |
| # No suitable directory found; record and skip | |
| validate_and_save_cohort_info( | |
| is_final=False, | |
| cohort="TCGA", | |
| info_path=json_path, | |
| is_gene_available=False, | |
| is_trait_available=False | |
| ) | |
| tcga_skip_trait = True | |
| else: | |
| tcga_skip_trait = False | |
| # 2) Identify clinical and genetic file paths | |
| clinical_file_path = None | |
| genetic_file_path = None | |
| if not tcga_skip_trait: | |
| try: | |
| clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(selected_cohort_dir) | |
| except Exception: | |
| # Fallback manual search if helper fails | |
| files = os.listdir(selected_cohort_dir) | |
| clinical_candidates = [f for f in files if 'clinicalmatrix' in f.lower()] | |
| genetic_candidates = [f for f in files if 'pancan' in f.lower()] | |
| if clinical_candidates and genetic_candidates: | |
| clinical_file_path = os.path.join(selected_cohort_dir, clinical_candidates[0]) | |
| genetic_file_path = os.path.join(selected_cohort_dir, genetic_candidates[0]) | |
| else: | |
| validate_and_save_cohort_info( | |
| is_final=False, | |
| cohort="TCGA", | |
| info_path=json_path, | |
| is_gene_available=bool(genetic_candidates), | |
| is_trait_available=bool(clinical_candidates) | |
| ) | |
| tcga_skip_trait = True | |
| # 3) Load both files as DataFrames | |
| tcga_clinical_df = None | |
| tcga_genetic_df = None | |
| if not tcga_skip_trait: | |
| tcga_clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False) | |
| tcga_genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False) | |
| # 4) Print the column names of the clinical data | |
| print(list(tcga_clinical_df.columns)) | |
| # Step 2: Find Candidate Demographic Features | |
| import os | |
| import re | |
| import pandas as pd | |
| # The list of column names from the previous step | |
| previous_columns = ['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'additional_treatment_completion_success_outcome', 'adjuvant_rad_therapy_prior_admin', 'age_at_initial_pathologic_diagnosis', 'age_began_smoking_in_years', 'agent_total_dose_count', 'assessment_timepoint_category', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'birth_control_pill_history_usage_category', 'brachytherapy_administered_status', 'brachytherapy_first_reference_point_administered_total_dose', 'brachytherapy_method_other_specify_text', 'brachytherapy_method_type', 'cervical_carcinoma_corpus_uteri_involvement_indicator', 'cervical_carcinoma_pelvic_extension_text', 'cervical_neoplasm_pathologic_margin_involved_text', 'cervical_neoplasm_pathologic_margin_involved_type', 'chemotherapy_negation_radiation_therapy_concurrent_adminstrd_txt', 'chemotherapy_negation_radiation_therapy_concurrnt_nt_dmnstrd_rsn', 'chemotherapy_regimen_type', 'clinical_stage', 'concurrent_chemotherapy_dose', 'days_to_birth', 'days_to_brachytherapy_begin_occurrence', 'days_to_brachytherapy_end_occurrence', 'days_to_chemotherapy_end', 'days_to_chemotherapy_start', 'days_to_collection', 'days_to_death', 'days_to_diagnostic_computed_tomography_performed', 'days_to_diagnostic_mri_performed', 'days_to_fdg_or_ct_pet_performed', '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_performance_status_assessment', 'days_to_radiation_therapy_end', 'days_to_radiation_therapy_start', 'death_cause_text', 'diagnostic_ct_result_outcome', 'diagnostic_mri_result_outcome', 'dose_frequency_text', 'eastern_cancer_oncology_group', 'ectopic_pregnancy_count', 'external_beam_radiation_therapy_administered_status', 'external_beam_radiation_therapy_administrd_prrtc_rgn_lymph_nd_ds', 'fdg_or_ct_pet_performed_outcome', 'female_breast_feeding_or_pregnancy_status_indicator', 'followup_case_report_form_submission_reason', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_of_neoadjuvant_treatment', 'human_papillomavirus_laboratory_procedure_performed_name', 'human_papillomavirus_laboratory_procedure_performed_text', 'human_papillomavirus_other_type_text', 'human_papillomavirus_type', 'hysterectomy_performed_text', 'hysterectomy_performed_type', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'init_pathology_dx_method_other', 'initial_pathologic_diagnosis_method', 'initial_weight', 'is_ffpe', 'keratinizing_squamous_cell_carcinoma_present_indicator', 'lost_follow_up', 'lymph_node_examined_count', 'lymph_node_location_positive_pathology_name', 'lymph_node_location_positive_pathology_text', 'lymphovascular_invasion_indicator', 'menopause_status', 'neoplasm_histologic_grade', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_post_initial_therapy_diagnosis_method_text', 'new_neoplasm_event_post_initial_therapy_diagnosis_method_type', 'new_neoplasm_event_type', 'new_neoplasm_occurrence_anatomic_site_text', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'number_of_lymphnodes_positive_by_he', 'number_of_lymphnodes_positive_by_ihc', 'number_of_successful_pregnancies_which_resultd_n_t_lst_1_lv_brth', 'number_pack_years_smoked', 'oct_embedded', 'oligonucleotide_primer_pair_laboratory_procedure_performed_name', 'other_chemotherapy_agent_administration_specify', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathology_report_file_name', 'patient_death_reason', 'patient_history_immune_system_and_related_disorders_name', 'patient_history_immune_system_and_related_disorders_text', 'patient_id', 'patient_pregnancy_spontaneous_abortion_count', 'patient_pregnancy_therapeutic_abortion_count', 'performance_status_scale_timing', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'pregnancy_stillbirth_count', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'radiation_therapy', 'radiation_therapy_not_administered_reason', 'radiation_therapy_not_administered_specify', 'radiation_type_notes', 'residual_disease_post_new_tumor_event_margin_status', 'rt_administered_type', 'rt_pelvis_administered_total_dose', 'sample_type', 'sample_type_id', 'standardized_uptake_value_cervix_uteri_assessment_measurement', 'stopped_smoking_year', 'system_version', 'targeted_molecular_therapy', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'tobacco_smoking_history', 'total_number_of_pregnancies', 'tumor_response_cdus_type', 'tumor_tissue_site', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_CESC_miRNA_HiSeq', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_data/public/TCGA/CESC/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_CESC_PDMRNAseq', '_GENOMIC_ID_TCGA_CESC_RPPA', '_GENOMIC_ID_TCGA_CESC_hMethyl450', '_GENOMIC_ID_TCGA_CESC_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_CESC_mutation', '_GENOMIC_ID_TCGA_CESC_mutation_broad_gene', '_GENOMIC_ID_TCGA_CESC_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_CESC_mutation_curated_wustl_gene', '_GENOMIC_ID_TCGA_CESC_exp_HiSeqV2', '_GENOMIC_ID_TCGA_CESC_gistic2', '_GENOMIC_ID_TCGA_CESC_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_CESC_gistic2thd'] | |
| # Refined patterns for age and gender | |
| age_pattern = re.compile(r'(^|[_\W])age([_\W]|$)') | |
| birth_pattern = re.compile(r'(^|[_\W])(days_to_birth|year_of_birth|date_of_birth|birth_year)([_\W]|$)') | |
| gender_pattern = re.compile(r'(^|[_\W])gender([_\W]|$)|(^|[_\W])sex([_\W]|$)') | |
| candidate_age_cols = [] | |
| candidate_gender_cols = [] | |
| for col in previous_columns: | |
| low = col.lower() | |
| if (age_pattern.search(low) or birth_pattern.search(low)) and ('birth_control' not in low and 'stillbirth' not in low): | |
| candidate_age_cols.append(col) | |
| if gender_pattern.search(low): | |
| candidate_gender_cols.append(col) | |
| # Print the required lists in the specified format | |
| print(f"candidate_age_cols = {candidate_age_cols}") | |
| print(f"candidate_gender_cols = {candidate_gender_cols}") | |
| # Load clinical data and preview candidate columns if available | |
| clinical_df = None | |
| try: | |
| cohort_dir = None | |
| for entry in os.scandir(tcga_root_dir): | |
| if entry.is_dir() and 'CESC' in entry.name.upper(): | |
| cohort_dir = entry.path | |
| break | |
| if cohort_dir is None: | |
| for root, dirs, _ in os.walk(tcga_root_dir): | |
| for d in dirs: | |
| if 'CESC' in d.upper(): | |
| cohort_dir = os.path.join(root, d) | |
| break | |
| if cohort_dir is not None: | |
| break | |
| if cohort_dir is not None: | |
| clinical_file_path, _ = tcga_get_relevant_filepaths(cohort_dir) | |
| clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, dtype=str) | |
| except Exception: | |
| clinical_df = None | |
| # Extract and preview | |
| age_preview = {} | |
| gender_preview = {} | |
| if isinstance(clinical_df, pd.DataFrame): | |
| age_cols_existing = [c for c in candidate_age_cols if c in clinical_df.columns] | |
| gender_cols_existing = [c for c in candidate_gender_cols if c in clinical_df.columns] | |
| if age_cols_existing: | |
| age_preview = preview_df(clinical_df[age_cols_existing]) | |
| if gender_cols_existing: | |
| gender_preview = preview_df(clinical_df[gender_cols_existing]) | |
| print("age_preview =", age_preview) | |
| print("gender_preview =", gender_preview) | |
| # Step 3: Select Demographic Features | |
| # Select columns based on preview and typical TCGA conventions | |
| age_col = 'age_at_initial_pathologic_diagnosis' if 'age_at_initial_pathologic_diagnosis' in candidate_age_cols else None | |
| gender_col = 'gender' if 'gender' in candidate_gender_cols else None | |
| # Explicitly print chosen columns and their previews | |
| print("Selected age_col:", age_col) | |
| print("Preview of selected age_col:", age_preview.get(age_col) if age_col else None) | |
| print("Selected gender_col:", gender_col) | |
| print("Preview of selected gender_col:", gender_preview.get(gender_col) if gender_col else None) | |
| # Step 4: Feature Engineering and Validation | |
| import os | |
| import pandas as pd | |
| # 1) Extract and standardize clinical features (trait, Age, Gender) | |
| selected_clinical_df = tcga_select_clinical_features( | |
| clinical_df=tcga_clinical_df, | |
| trait=trait, | |
| age_col=age_col, | |
| gender_col=gender_col | |
| ) | |
| # 2) Normalize gene symbols and save normalized gene data | |
| def _looks_like_sample_ids(idx): | |
| try: | |
| return any(str(i).startswith('TCGA-') for i in list(idx)[:10]) | |
| except Exception: | |
| return any(str(i).startswith('TCGA-') for i in idx) | |
| gene_df = tcga_genetic_df | |
| # Ensure genes are in index for normalization | |
| if _looks_like_sample_ids(gene_df.index): | |
| gene_df = gene_df.T | |
| normalized_gene_df = normalize_gene_symbols_in_index(gene_df) | |
| # Optional post-check to ensure samples are columns | |
| if not _looks_like_sample_ids(normalized_gene_df.columns) and _looks_like_sample_ids(normalized_gene_df.index): | |
| normalized_gene_df = normalized_gene_df.T | |
| # Save normalized gene data | |
| os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True) | |
| normalized_gene_df.to_csv(out_gene_data_file) | |
| # 3) Link clinical and genetic data on intersecting sample IDs | |
| common_samples = selected_clinical_df.index.intersection(normalized_gene_df.columns) | |
| linked_clinical = selected_clinical_df.loc[common_samples] | |
| linked_gene = normalized_gene_df[common_samples].T # samples x genes | |
| linked_data = pd.concat([linked_clinical, linked_gene], axis=1) | |
| # 4) Handle missing values | |
| linked_data = handle_missing_values(linked_data, trait_col=trait) | |
| # 5) Determine severe bias; remove biased demographics | |
| trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait=trait) | |
| # 6) Final validation and save cohort info | |
| covariate_cols = [trait, 'Age', 'Gender'] | |
| gene_cols_after = [c for c in linked_data.columns if c not in covariate_cols] | |
| is_gene_available = bool(len(gene_cols_after) > 0) | |
| is_trait_available = bool((trait in linked_data.columns) and bool(linked_data[trait].notna().any())) | |
| note_parts = [ | |
| f"INFO: Cohort TCGA CESC. Samples linked: {len(linked_data)}.", | |
| f"INFO: Gene features retained: {len(gene_cols_after)}.", | |
| f"INFO: Age included: {'Age' in linked_data.columns}.", | |
| f"INFO: Gender included: {'Gender' in linked_data.columns}.", | |
| ] | |
| note = " ".join(note_parts) | |
| is_usable = validate_and_save_cohort_info( | |
| is_final=True, | |
| cohort="TCGA", | |
| info_path=json_path, | |
| is_gene_available=is_gene_available, | |
| is_trait_available=is_trait_available, | |
| is_biased=bool(trait_biased), | |
| df=linked_data, | |
| note=note | |
| ) | |
| # 7) Save linked data only if usable | |
| if is_usable: | |
| os.makedirs(os.path.dirname(out_data_file), exist_ok=True) | |
| linked_data.to_csv(out_data_file) |