| |
| from tools.preprocess import * |
|
|
| |
| trait = "Adrenocortical_Cancer" |
|
|
| |
| tcga_root_dir = "../DATA/TCGA" |
|
|
| |
| out_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/TCGA.csv" |
| out_gene_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/gene_data/TCGA.csv" |
| out_clinical_data_file = "./output/z1/preprocess/Adrenocortical_Cancer/clinical_data/TCGA.csv" |
| json_path = "./output/z1/preprocess/Adrenocortical_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))] |
| target_keywords = ['adrenocortical', '(acc)'] |
| matches = [] |
| for d in subdirs: |
| name = d.lower() |
| score = 0 |
| if 'adrenocortical' in name: |
| score += 2 |
| if '(acc)' in name or '_acc' in name: |
| score += 1 |
| if score > 0: |
| matches.append((score, d)) |
|
|
| selected_dir = None |
| if matches: |
| |
| matches.sort(key=lambda x: (-x[0], x[1])) |
| selected_dir = matches[0][1] |
|
|
| |
| 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 |
| ) |
| else: |
| cohort_dir = os.path.join(tcga_root_dir, selected_dir) |
| |
| try: |
| clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir) |
| except Exception: |
| |
| validate_and_save_cohort_info( |
| is_final=False, |
| cohort="TCGA", |
| info_path=json_path, |
| is_gene_available=False, |
| is_trait_available=False |
| ) |
| else: |
| |
| clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, compression='infer', low_memory=False) |
| genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, compression='infer', low_memory=False) |
| |
| print(clinical_df.columns.tolist()) |
|
|
| |
| import os |
| import pandas as pd |
|
|
| |
| if 'clinical_df' not in globals(): |
| |
| acc_dir = os.path.join(tcga_root_dir, 'ACC') |
| if not os.path.isdir(acc_dir): |
| subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))] |
| acc_candidates = [d for d in subdirs if 'ACC' in d.upper()] |
| acc_dir = os.path.join(tcga_root_dir, acc_candidates[0]) if acc_candidates else None |
|
|
| if acc_dir: |
| try: |
| clinical_file_path, _ = tcga_get_relevant_filepaths(acc_dir) |
| clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, dtype=str) |
| except Exception: |
| clinical_df = None |
| else: |
| clinical_df = None |
|
|
| available_cols = list(clinical_df.columns) if isinstance(clinical_df, pd.DataFrame) else [] |
|
|
| def is_age_col(col: str) -> bool: |
| c = col.lower() |
| if 'stage' in c: |
| return False |
| if c.startswith('age') or 'age_' in c or '_age' in c or 'age at' in c: |
| return True |
| if 'days_to_birth' in c or 'birth' in c: |
| return True |
| return False |
|
|
| def is_gender_col(col: str) -> bool: |
| c = col.lower().strip() |
| if c in {'gender', 'sex'}: |
| return True |
| if c.startswith('gender') or c.endswith('_gender'): |
| return True |
| |
| if c == 'sex': |
| return True |
| return False |
|
|
| candidate_age_cols = [c for c in available_cols if is_age_col(c)] |
| candidate_gender_cols = [c for c in available_cols if is_gender_col(c)] |
|
|
| print(f"candidate_age_cols = {candidate_age_cols}") |
| print(f"candidate_gender_cols = {candidate_gender_cols}") |
|
|
| |
| selected_cols = [c for c in (candidate_age_cols + candidate_gender_cols) if c in available_cols] |
| if isinstance(clinical_df, pd.DataFrame) and len(selected_cols) > 0: |
| preview_dict = preview_df(clinical_df[selected_cols], n=5) |
| print(preview_dict) |
| else: |
| print({}) |
|
|
| |
| import math |
|
|
| |
| def _is_valid_preview(values, min_non_missing=3): |
| if not isinstance(values, (list, tuple)) or len(values) == 0: |
| return False |
| def _is_missing(v): |
| if v is None: |
| return True |
| if isinstance(v, float) and math.isnan(v): |
| return True |
| if isinstance(v, str) and v.strip() == "": |
| return True |
| return False |
| non_missing = sum(0 if _is_missing(v) else 1 for v in values) |
| return non_missing >= min_non_missing |
|
|
| |
| age_values_dict = {} |
| gender_values_dict = {} |
|
|
| |
| _possible_age_dict_names = ["age_values_dict", "age_preview_dict", "age_dict"] |
| _possible_gender_dict_names = ["gender_values_dict", "gender_preview_dict", "gender_dict"] |
|
|
| |
| for _name in _possible_age_dict_names: |
| try: |
| _val = eval(_name) |
| if isinstance(_val, dict): |
| age_values_dict = _val |
| break |
| except NameError: |
| pass |
|
|
| for _name in _possible_gender_dict_names: |
| try: |
| _val = eval(_name) |
| if isinstance(_val, dict): |
| gender_values_dict = _val |
| break |
| except NameError: |
| pass |
|
|
| |
| if (not age_values_dict or not gender_values_dict): |
| |
| try: |
| |
| age_keys = set(candidate_age_cols) if 'candidate_age_cols' in globals() else set() |
| gender_keys = set(candidate_gender_cols) if 'candidate_gender_cols' in globals() else set() |
| |
| for _var, _obj in list(globals().items()): |
| if isinstance(_obj, dict): |
| if not age_values_dict and age_keys and any(k in _obj for k in age_keys): |
| age_values_dict = {k: _obj[k] for k in age_keys if k in _obj} |
| if not gender_values_dict and gender_keys and any(k in _obj for k in gender_keys): |
| gender_values_dict = {k: _obj[k] for k in gender_keys if k in _obj} |
| if age_values_dict and gender_values_dict: |
| break |
| except Exception: |
| pass |
|
|
| |
| age_col = None |
| gender_col = None |
|
|
| |
| if isinstance(candidate_age_cols, (list, tuple)) and len(candidate_age_cols) > 0 and isinstance(age_values_dict, dict): |
| |
| valid_age_candidates = [c for c in candidate_age_cols if c in age_values_dict and _is_valid_preview(age_values_dict.get(c, []))] |
| |
| if 'age_at_initial_pathologic_diagnosis' in valid_age_candidates: |
| age_col = 'age_at_initial_pathologic_diagnosis' |
| elif 'days_to_birth' in valid_age_candidates: |
| age_col = 'days_to_birth' |
| elif valid_age_candidates: |
| age_col = valid_age_candidates[0] |
|
|
| |
| if isinstance(candidate_gender_cols, (list, tuple)) and len(candidate_gender_cols) > 0 and isinstance(gender_values_dict, dict): |
| valid_gender_candidates = [c for c in candidate_gender_cols if c in gender_values_dict and _is_valid_preview(gender_values_dict.get(c, []))] |
| if 'gender' in valid_gender_candidates: |
| gender_col = 'gender' |
| elif valid_gender_candidates: |
| gender_col = valid_gender_candidates[0] |
|
|
| |
| if not isinstance(age_values_dict, dict) or len(age_values_dict) == 0: |
| age_col = None |
| if not isinstance(gender_values_dict, dict) or len(gender_values_dict) == 0: |
| gender_col = None |
|
|
| |
| print(f"Selected age_col: {age_col}") |
| if age_col is not None and isinstance(age_values_dict, dict) and age_col in age_values_dict: |
| print(f"age_col first5 values: {age_values_dict[age_col]}") |
| else: |
| print("age_col first5 values: None") |
|
|
| print(f"Selected gender_col: {gender_col}") |
| if gender_col is not None and isinstance(gender_values_dict, dict) and gender_col in gender_values_dict: |
| print(f"gender_col first5 values: {gender_values_dict[gender_col]}") |
| else: |
| print("gender_col first5 values: None") |
|
|
| |
| import os |
| import pandas as pd |
|
|
| |
| if 'clinical_df' not in globals() or 'genetic_df' not in globals(): |
| |
| subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))] |
| acc_dir = None |
| for d in subdirs: |
| if 'adrenocortical_cancer_(acc)' in d.lower() or d.upper().endswith('(ACC)') or d.upper() == 'ACC': |
| acc_dir = os.path.join(tcga_root_dir, d) |
| break |
| if acc_dir is None: |
| |
| acc_candidates = [d for d in subdirs if 'ACC' in d.upper()] |
| acc_dir = os.path.join(tcga_root_dir, acc_candidates[0]) if acc_candidates else None |
|
|
| if acc_dir: |
| clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(acc_dir) |
| clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, compression='infer', low_memory=False) |
| genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, compression='infer', low_memory=False) |
| else: |
| raise RuntimeError("ACC cohort directory not found; cannot proceed.") |
|
|
| |
| age_col = age_col if 'age_col' in globals() else None |
| gender_col = gender_col if 'gender_col' in globals() else None |
|
|
| |
| selected_clinical_df = tcga_select_clinical_features( |
| clinical_df=clinical_df, |
| trait=trait, |
| age_col=age_col, |
| gender_col=gender_col |
| ) |
|
|
| |
| normalized_gene_df = normalize_gene_symbols_in_index(genetic_df.copy()) |
| normalized_gene_df = normalized_gene_df.apply(pd.to_numeric, errors='coerce') |
|
|
| |
| os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True) |
| normalized_gene_df.to_csv(out_gene_data_file) |
|
|
| |
| expr_t = normalized_gene_df.T |
| linked_data = selected_clinical_df.join(expr_t, how='inner') |
|
|
| |
| processed_df = handle_missing_values(linked_data, trait_col=trait) |
|
|
| |
| trait_biased, processed_df = judge_and_remove_biased_features(processed_df, trait) |
|
|
| |
| |
| processed_df_safe = processed_df.copy() |
| processed_df_safe.index = processed_df_safe.index.astype(str) |
| processed_df_safe.columns = [str(c) for c in list(processed_df_safe.columns)] |
|
|
| covariate_cols = [trait, 'Age', 'Gender'] |
| gene_cols_in_processed = [c for c in processed_df_safe.columns if c not in covariate_cols] |
| is_gene_available = bool(len(gene_cols_in_processed) > 0) |
| is_trait_available = bool((trait in processed_df_safe.columns) and processed_df_safe[trait].notna().any()) |
|
|
| note_parts = [ |
| "INFO: TCGA ACC cohort processed; gene symbols normalized via NCBI synonyms.", |
| ] |
| if age_col or gender_col: |
| note_parts.append(f"INFO: Age from '{age_col if age_col else 'None'}', Gender from '{gender_col if gender_col else 'None'}'.") |
| if trait_biased: |
| note_parts.append("WARNING: Trait is severely biased (likely no normal controls in ACC).") |
| note = " ".join(note_parts) |
|
|
| |
| is_usable = False |
| try: |
| 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=processed_df_safe, |
| note=note |
| ) |
| except TypeError as e: |
| |
| processed_df_safe2 = processed_df_safe.copy() |
| processed_df_safe2.index = [str(x) for x in processed_df_safe2.index.tolist()] |
| processed_df_safe2.columns = [str(x) for x in processed_df_safe2.columns.tolist()] |
| try: |
| is_usable = validate_and_save_cohort_info( |
| is_final=True, |
| cohort="TCGA", |
| info_path=json_path, |
| is_gene_available=bool(is_gene_available), |
| is_trait_available=bool(is_trait_available), |
| is_biased=bool(trait_biased), |
| df=processed_df_safe2, |
| note=note |
| ) |
| except Exception as e2: |
| |
| is_usable = False |
|
|
| |
| if is_usable: |
| os.makedirs(os.path.dirname(out_data_file), exist_ok=True) |
| processed_df_safe.to_csv(out_data_file) |