| |
| from tools.preprocess import * |
|
|
| |
| trait = "Bile_Duct_Cancer" |
|
|
| |
| tcga_root_dir = "../DATA/TCGA" |
|
|
| |
| out_data_file = "./output/z1/preprocess/Bile_Duct_Cancer/TCGA.csv" |
| out_gene_data_file = "./output/z1/preprocess/Bile_Duct_Cancer/gene_data/TCGA.csv" |
| out_clinical_data_file = "./output/z1/preprocess/Bile_Duct_Cancer/clinical_data/TCGA.csv" |
| json_path = "./output/z1/preprocess/Bile_Duct_Cancer/cohort_info.json" |
|
|
|
|
| |
| import os |
| import pandas as pd |
|
|
| |
| subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))] |
| lower_map = {d: d.lower() for d in subdirs} |
|
|
| |
| selected_dir = None |
| exact_key = 'bile_duct_cancer' |
| synonym_keys = ['(chol', 'cholangio'] |
|
|
| |
| candidates_exact = [d for d, dl in lower_map.items() if exact_key in dl] |
| if candidates_exact: |
| |
| selected_dir = sorted(candidates_exact, key=len)[0] |
| else: |
| |
| candidates_syn = [d for d, dl in lower_map.items() if any(k in dl for k in synonym_keys)] |
| if candidates_syn: |
| selected_dir = sorted(candidates_syn, key=len)[0] |
|
|
| if selected_dir is None: |
| |
| validate_and_save_cohort_info( |
| is_final=False, |
| cohort="TCGA", |
| info_path=json_path, |
| is_gene_available=False, |
| is_trait_available=False |
| ) |
| print("No suitable TCGA cohort found for the trait. Skipping.") |
| else: |
| tcga_cohort_dir = os.path.join(tcga_root_dir, selected_dir) |
| |
| tcga_clinical_file, tcga_genetic_file = tcga_get_relevant_filepaths(tcga_cohort_dir) |
|
|
| |
| tcga_clinical_df = pd.read_csv(tcga_clinical_file, sep='\t', index_col=0, low_memory=False, compression='infer') |
| tcga_genetic_df = pd.read_csv(tcga_genetic_file, sep='\t', index_col=0, low_memory=False, compression='infer') |
|
|
| |
| print(list(tcga_clinical_df.columns)) |
|
|
| |
| import os |
| import pandas as pd |
|
|
| |
| column_names = ['_INTEGRATION', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'albumin_result_lower_limit', 'albumin_result_specified_value', 'albumin_result_upper_limit', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'bilirubin_lower_limit', 'bilirubin_upper_limit', 'ca_19_9_level', 'ca_19_9_level_lower', 'ca_19_9_level_upper', 'cancer_first_degree_relative', 'child_pugh_classification_grade', 'cholangitis_tissue_evidence', 'creatinine_lower_level', 'creatinine_upper_limit', 'creatinine_value_in_mg_dl', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_after_initial_treatment', 'eastern_cancer_oncology_group', 'family_cancer_type_txt', 'family_member_relationship_type', 'fetoprotein_outcome_lower_limit', 'fetoprotein_outcome_upper_limit', 'fetoprotein_outcome_value', 'fibrosis_ishak_score', 'form_completion_date', 'gender', 'height', 'hist_hepato_carc_fact', 'hist_hepato_carcinoma_risk', 'histological_type', 'history_of_neoadjuvant_treatment', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'inter_norm_ratio_lower_limit', 'intern_norm_ratio_upper_limit', 'is_ffpe', 'lost_follow_up', 'neoplasm_histologic_grade', 'new_neoplasm_event_occurrence_anatomic_site', 'new_neoplasm_event_type', 'new_tumor_event_ablation_embo_tx', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'new_tumor_event_liver_transplant', 'oct_embedded', 'other_dx', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'perineural_invasion_present', 'person_neoplasm_cancer_status', 'platelet_result_count', 'platelet_result_lower_limit', 'platelet_result_upper_limit', 'post_op_ablation_embolization_tx', 'postoperative_rx_tx', 'prothrombin_time_result_value', 'radiation_therapy', 'relative_family_cancer_history', 'residual_tumor', 'sample_type', 'sample_type_id', 'specimen_collection_method_name', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'total_bilirubin_upper_limit', 'tumor_tissue_site', 'vascular_tumor_cell_type', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_CHOL_mutation_broad_gene', '_GENOMIC_ID_TCGA_CHOL_mutation_bcgsc_gene', '_GENOMIC_ID_TCGA_CHOL_hMethyl450', '_GENOMIC_ID_TCGA_CHOL_exp_HiSeqV2', '_GENOMIC_ID_TCGA_CHOL_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_CHOL_mutation_bcm_gene', '_GENOMIC_ID_TCGA_CHOL_miRNA_HiSeq', '_GENOMIC_ID_TCGA_CHOL_gistic2thd', '_GENOMIC_ID_TCGA_CHOL_gistic2', '_GENOMIC_ID_TCGA_CHOL_PDMRNAseqCNV', '_GENOMIC_ID_TCGA_CHOL_exp_HiSeqV2_exon', '_GENOMIC_ID_data/public/TCGA/CHOL/miRNA_HiSeq_gene', '_GENOMIC_ID_TCGA_CHOL_mutation_ucsc_maf_gene', '_GENOMIC_ID_TCGA_CHOL_PDMRNAseq', '_GENOMIC_ID_TCGA_CHOL_exp_HiSeqV2_percentile', '_GENOMIC_ID_TCGA_CHOL_RPPA'] |
|
|
| |
| candidate_age_cols = [col for col in column_names if col in ['age_at_initial_pathologic_diagnosis', 'days_to_birth']] |
| candidate_gender_cols = [col for col in column_names if col.lower() == 'gender'] |
|
|
| print(f"candidate_age_cols = {candidate_age_cols}") |
| print(f"candidate_gender_cols = {candidate_gender_cols}") |
|
|
| |
| clinical_df = None |
| clinical_file_path = None |
|
|
| |
| try: |
| |
| found = False |
| for root, dirs, files in os.walk(tcga_root_dir): |
| try: |
| cpath, _ = tcga_get_relevant_filepaths(root) |
| if os.path.exists(cpath) and ('chol' in cpath.lower() or 'chol' in root.lower()): |
| clinical_file_path = cpath |
| found = True |
| break |
| except Exception: |
| pass |
| |
| if not found: |
| for root, dirs, files in os.walk(tcga_root_dir): |
| for f in files: |
| fl = f.lower() |
| if 'clinical' in fl and 'matrix' in fl and 'chol' in fl: |
| clinical_file_path = os.path.join(root, f) |
| found = True |
| break |
| if found: |
| break |
|
|
| if clinical_file_path and os.path.exists(clinical_file_path): |
| |
| clinical_df = pd.read_csv(clinical_file_path, sep='\t', header=0, index_col=0, dtype=str) |
| except Exception: |
| clinical_df = None |
|
|
| age_preview = {} |
| gender_preview = {} |
|
|
| if clinical_df is not None: |
| age_cols_present = [c for c in candidate_age_cols if c in clinical_df.columns] |
| gender_cols_present = [c for c in candidate_gender_cols if c in clinical_df.columns] |
|
|
| if age_cols_present: |
| age_preview = preview_df(clinical_df[age_cols_present], n=5) |
| if gender_cols_present: |
| gender_preview = preview_df(clinical_df[gender_cols_present], n=5) |
|
|
| print(age_preview) |
| print(gender_preview) |
|
|
| |
| |
| |
|
|
| |
| def _get_global(name, default=None): |
| return globals()[name] if name in globals() else default |
|
|
| |
| def _find_preview_dict(candidates, preferred_names): |
| for n in preferred_names: |
| d = _get_global(n, None) |
| if isinstance(d, dict): |
| return d |
| |
| best = None |
| best_overlap = 0 |
| for k, v in globals().items(): |
| if isinstance(v, dict) and v: |
| try: |
| overlap = len(set(v.keys()) & set(candidates)) |
| except Exception: |
| overlap = 0 |
| if overlap > best_overlap: |
| best = v |
| best_overlap = overlap |
| return best if best_overlap > 0 else {} |
|
|
| |
| def _parse_int_with_sign(x): |
| if x is None: |
| return None |
| s = str(x).strip() |
| m = re.search(r'-?\d+', s) |
| return int(m.group()) if m else None |
|
|
| def _is_valid_age_column(col, values): |
| if not isinstance(values, list) or len(values) == 0: |
| return False |
| n = len(values) |
| min_valid = max(1, int((0.6 * n) + 0.9999)) |
| lc = col.lower() |
|
|
| if 'days' in lc and 'birth' in lc: |
| parsed = [_parse_int_with_sign(v) for v in values] |
| valid = [p for p in parsed if isinstance(p, int)] |
| if len(valid) < min_valid: |
| return False |
| plausible = [abs(v) / 365.25 for v in valid] |
| plausible_cnt = sum(0 <= yr <= 120 for yr in plausible) |
| return plausible_cnt >= min_valid |
| else: |
| |
| parsed = [tcga_convert_age(v) for v in values] |
| valid = [p for p in parsed if isinstance(p, int)] |
| if len(valid) < min_valid: |
| return False |
| plausible_cnt = sum(0 <= p <= 120 for p in valid) |
| return plausible_cnt >= min_valid |
|
|
| def _is_valid_gender_values(values): |
| if not isinstance(values, list) or len(values) == 0: |
| return False |
| n = len(values) |
| min_valid = max(1, int((0.6 * n) + 0.9999)) |
| mapped = [tcga_convert_gender(v) for v in values] |
| valid = [m for m in mapped if m in (0, 1)] |
| return len(valid) >= min_valid |
|
|
| def select_age_col(candidates, age_preview_dict): |
| if not candidates or not isinstance(age_preview_dict, dict) or not age_preview_dict: |
| return None |
| |
| priority_order = [ |
| "age_at_initial_pathologic_diagnosis", |
| "age_at_diagnosis", |
| "age_at_index", |
| "age" |
| ] |
| ordered = [p for p in priority_order if p in candidates] |
| ordered += [c for c in candidates if c not in ordered] |
|
|
| for c in ordered: |
| if c in age_preview_dict and _is_valid_age_column(c, age_preview_dict[c]): |
| return c |
| |
| for c in candidates: |
| if c.lower() == 'days_to_birth' and c in age_preview_dict and _is_valid_age_column(c, age_preview_dict[c]): |
| return c |
| return None |
|
|
| def select_gender_col(candidates, gender_preview_dict): |
| if not candidates or not isinstance(gender_preview_dict, dict) or not gender_preview_dict: |
| return None |
| priority_order = ["gender", "sex"] |
| ordered = [p for p in priority_order if p in candidates] |
| ordered += [c for c in candidates if c not in ordered] |
|
|
| for c in ordered: |
| if c in gender_preview_dict and _is_valid_gender_values(gender_preview_dict[c]): |
| return c |
| return None |
|
|
| |
| candidate_age_cols = _get_global('candidate_age_cols', []) |
| candidate_gender_cols = _get_global('candidate_gender_cols', []) |
|
|
| |
| age_preview_dict = _find_preview_dict(candidate_age_cols, ['age_preview_dict', 'age_preview']) |
| gender_preview_dict = _find_preview_dict(candidate_gender_cols, ['gender_preview_dict', 'gender_preview']) |
|
|
| |
| age_col = select_age_col(candidate_age_cols, age_preview_dict) |
| gender_col = select_gender_col(candidate_gender_cols, gender_preview_dict) |
|
|
| |
| print(f"Chosen age_col: {age_col}") |
| if age_col is not None and isinstance(age_preview_dict, dict) and age_col in age_preview_dict: |
| print(f"age_col preview values: {age_preview_dict[age_col]}") |
| else: |
| print("age_col preview values: None or not available") |
|
|
| print(f"Chosen gender_col: {gender_col}") |
| if gender_col is not None and isinstance(gender_preview_dict, dict) and gender_col in gender_preview_dict: |
| print(f"gender_col preview values: {gender_preview_dict[gender_col]}") |
| else: |
| print("gender_col preview values: None or not available") |
|
|
| |
| import os |
|
|
| |
| selected_clinical_df = tcga_select_clinical_features( |
| clinical_df=tcga_clinical_df, |
| trait=trait, |
| age_col=age_col, |
| gender_col=gender_col |
| ) |
|
|
| |
| normalized_gene_df = normalize_gene_symbols_in_index(tcga_genetic_df.copy()) |
| os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True) |
| normalized_gene_df.to_csv(out_gene_data_file) |
|
|
| |
| gene_t = normalized_gene_df.T |
| linked_data = selected_clinical_df.join(gene_t, how='inner') |
|
|
| |
| processed_df = handle_missing_values(linked_data.copy(), trait_col=trait) |
|
|
| |
| is_biased, processed_df = judge_and_remove_biased_features(processed_df, trait=trait) |
|
|
| |
| |
| is_gene_available = bool((normalized_gene_df.shape[0] > 0) and (normalized_gene_df.shape[1] > 0)) |
| is_trait_available = bool((trait in selected_clinical_df.columns) and bool(selected_clinical_df[trait].notna().any())) |
| is_biased_bool = bool(is_biased) |
|
|
| note = ( |
| f"INFO: Age column used: {age_col}; Gender column used: {gender_col}. " |
| f"Linked samples (pre-QC): {linked_data.shape[0]}, genes: {linked_data.shape[1] - selected_clinical_df.shape[1]}." |
| ) |
|
|
| 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=is_biased_bool, |
| df=processed_df, |
| note=note |
| ) |
|
|
| |
| if is_usable: |
| os.makedirs(os.path.dirname(out_data_file), exist_ok=True) |
| processed_df.to_csv(out_data_file) |