| | |
| | from tools.preprocess import * |
| |
|
| | |
| | trait = "Bladder_Cancer" |
| |
|
| | |
| | tcga_root_dir = "../DATA/TCGA" |
| |
|
| | |
| | out_data_file = "./output/z1/preprocess/Bladder_Cancer/TCGA.csv" |
| | out_gene_data_file = "./output/z1/preprocess/Bladder_Cancer/gene_data/TCGA.csv" |
| | out_clinical_data_file = "./output/z1/preprocess/Bladder_Cancer/clinical_data/TCGA.csv" |
| | json_path = "./output/z1/preprocess/Bladder_Cancer/cohort_info.json" |
| |
|
| |
|
| | |
| | import os |
| |
|
| | |
| | subdirs = [d for d in os.listdir(tcga_root_dir) if os.path.isdir(os.path.join(tcga_root_dir, d))] |
| | candidates = [d for d in subdirs if 'bladder' in d.lower()] |
| |
|
| | selected_dir = None |
| | if candidates: |
| | |
| | blca_candidates = [d for d in candidates if 'blca' in d.lower()] |
| | selected_dir = blca_candidates[0] if blca_candidates else candidates[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 |
| | ) |
| | else: |
| | tcga_cohort_dir = os.path.join(tcga_root_dir, selected_dir) |
| |
|
| | |
| | clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(tcga_cohort_dir) |
| |
|
| | |
| | clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False) |
| | genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False) |
| |
|
| | |
| | print(list(clinical_df.columns)) |
| |
|
| | |
| | import re |
| |
|
| | |
| | if 'clinical_df' in globals(): |
| | available_cols = list(clinical_df.columns) |
| | else: |
| | available_cols = [] |
| |
|
| | lower_cols = {c: c.lower() for c in available_cols} |
| |
|
| | age_pattern = re.compile(r'(^|_)age($|_)') |
| | gender_pattern = re.compile(r'(^|_)(gender|sex)($|_)') |
| |
|
| | candidate_age_cols = [] |
| | for c in available_cols: |
| | lc = lower_cols[c] |
| | if 'stage' in lc: |
| | continue |
| | if age_pattern.search(lc) or ('birth' in lc): |
| | candidate_age_cols.append(c) |
| |
|
| | candidate_gender_cols = [c for c in available_cols if gender_pattern.search(lower_cols[c])] |
| |
|
| | |
| | print(f"candidate_age_cols = {candidate_age_cols}") |
| | print(f"candidate_gender_cols = {candidate_gender_cols}") |
| |
|
| | |
| | if 'clinical_df' in globals() and candidate_age_cols: |
| | age_preview = preview_df(clinical_df[candidate_age_cols], n=5) |
| | print(age_preview) |
| |
|
| | if 'clinical_df' in globals() and candidate_gender_cols: |
| | gender_preview = preview_df(clinical_df[candidate_gender_cols], n=5) |
| | print(gender_preview) |
| |
|
| | |
| | |
| |
|
| | |
| | if 'age_values_dict' not in globals(): |
| | age_values_dict = { |
| | 'age_at_initial_pathologic_diagnosis': [63, 66, 69, 59, 83], |
| | 'age_began_smoking_in_years': [20.0, 15.0, float('nan'), float('nan'), 30.0], |
| | 'days_to_birth': [-23323.0, -24428.0, -25259.0, -21848.0, -30520.0], |
| | } |
| | if 'gender_values_dict' not in globals(): |
| | gender_values_dict = { |
| | 'gender': ['MALE', 'MALE', 'MALE', 'FEMALE', 'MALE'] |
| | } |
| |
|
| | |
| | if 'candidate_age_cols' not in globals(): |
| | candidate_age_cols = ['age_at_initial_pathologic_diagnosis', 'age_began_smoking_in_years', 'days_to_birth'] |
| | if 'candidate_gender_cols' not in globals(): |
| | candidate_gender_cols = ['gender'] |
| |
|
| | |
| | age_col = None |
| | gender_col = None |
| |
|
| | |
| | preferred_age_order = [ |
| | 'age_at_initial_pathologic_diagnosis', |
| | 'age_at_diagnosis', |
| | 'age' |
| | ] |
| | for c in preferred_age_order: |
| | if c in candidate_age_cols: |
| | age_col = c |
| | break |
| | |
| | if age_col is None and 'days_to_birth' in candidate_age_cols: |
| | |
| | pass |
| |
|
| | |
| | preferred_gender_order = ['gender', 'sex'] |
| | for c in preferred_gender_order: |
| | if c in candidate_gender_cols: |
| | gender_col = c |
| | break |
| |
|
| | |
| | if 'clinical_df' in globals(): |
| | if age_col is not None and age_col not in clinical_df.columns: |
| | age_col = None |
| | if gender_col is not None and gender_col not in clinical_df.columns: |
| | gender_col = None |
| |
|
| | |
| | def preview_values(col_name, values_dict): |
| | if 'clinical_df' in globals() and col_name is not None and col_name in clinical_df.columns: |
| | return clinical_df[col_name].head(5).tolist() |
| | return values_dict.get(col_name, None) if col_name is not None else None |
| |
|
| | age_preview = preview_values(age_col, age_values_dict) |
| | gender_preview = preview_values(gender_col, gender_values_dict) |
| |
|
| | |
| | print("Selected age_col:", age_col) |
| | print("age_col first 5 values:", age_preview) |
| | print("Selected gender_col:", gender_col) |
| | print("gender_col first 5 values:", gender_preview) |
| |
|
| | |
| | import os |
| | import json |
| |
|
| | |
| | def _to_builtin(obj): |
| | |
| | if obj is None or isinstance(obj, (bool, int, float, str)): |
| | return obj |
| | |
| | if isinstance(obj, dict): |
| | return {str(_to_builtin(k)): _to_builtin(v) for k, v in obj.items()} |
| | if isinstance(obj, (list, tuple, set)): |
| | return [_to_builtin(v) for v in obj] |
| | |
| | try: |
| | |
| | if hasattr(obj, 'item'): |
| | return _to_builtin(obj.item()) |
| | except Exception: |
| | pass |
| | |
| | try: |
| | return json.loads(json.dumps(obj)) |
| | except Exception: |
| | return str(obj) |
| |
|
| | def validate_and_save_cohort_info_safe(is_final: bool, cohort: str, info_path: str, is_gene_available: bool, |
| | is_trait_available: bool, is_biased: Optional[bool] = None, |
| | df: Optional[pd.DataFrame] = None, note: str = '') -> bool: |
| | """ |
| | Wrapper around validate_and_save_cohort_info that sanitizes values to avoid JSON serialization errors. |
| | Mirrors the original function's logic. |
| | """ |
| | is_usable = False |
| | if not is_final: |
| | if is_gene_available and is_trait_available: |
| | return is_usable |
| | else: |
| | new_record = {"is_usable": False, |
| | "is_gene_available": is_gene_available, |
| | "is_trait_available": is_trait_available, |
| | "is_available": False, |
| | "is_biased": None, |
| | "has_age": None, |
| | "has_gender": None, |
| | "sample_size": None, |
| | "note": None} |
| | else: |
| | if (df is None) or (is_biased is None): |
| | raise ValueError("For final data validation, 'df' and 'is_biased' must be provided.") |
| | if len(df) <= 0 or len(df.columns) <= 4: |
| | print(f"Abnormality detected in the cohort: {cohort}. Preprocessing failed.") |
| | is_gene_available = False |
| | if len(df) <= 0: |
| | is_trait_available = False |
| | is_available = bool(is_gene_available and is_trait_available) |
| | is_usable = bool(is_available and (is_biased is False)) |
| | new_record = {"is_usable": is_usable, |
| | "is_gene_available": bool(is_gene_available), |
| | "is_trait_available": bool(is_trait_available), |
| | "is_available": is_available, |
| | "is_biased": (bool(is_biased) if is_available else None), |
| | "has_age": ("Age" in df.columns if is_available else None), |
| | "has_gender": ("Gender" in df.columns if is_available else None), |
| | "sample_size": (int(len(df)) if is_available else None), |
| | "note": note} |
| |
|
| | trait_directory = os.path.dirname(info_path) |
| | os.makedirs(trait_directory, exist_ok=True) |
| | if not os.path.exists(info_path): |
| | with open(info_path, 'w') as file: |
| | json.dump({}, file) |
| | print(f"A new JSON file was created at: {info_path}") |
| |
|
| | with open(info_path, "r") as file: |
| | try: |
| | records = json.load(file) |
| | except json.JSONDecodeError: |
| | records = {} |
| | records[cohort] = new_record |
| |
|
| | |
| | records_sanitized = _to_builtin(records) |
| |
|
| | temp_path = info_path + ".tmp" |
| | try: |
| | with open(temp_path, 'w') as file: |
| | json.dump(records_sanitized, file) |
| | os.replace(temp_path, info_path) |
| | except Exception as e: |
| | print(f"An error occurred: {e}") |
| | if os.path.exists(temp_path): |
| | os.remove(temp_path) |
| | raise |
| |
|
| | return is_usable |
| |
|
| |
|
| | |
| | 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 |
| | ) |
| |
|
| | |
| | os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True) |
| | selected_clinical_df.to_csv(out_clinical_data_file) |
| |
|
| | |
| | blca_samples = selected_clinical_df.index.intersection(genetic_df.columns) |
| | genetic_sub = genetic_df.loc[:, blca_samples] |
| |
|
| | gene_norm = normalize_gene_symbols_in_index(genetic_sub) |
| |
|
| | os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True) |
| | gene_norm.to_csv(out_gene_data_file) |
| |
|
| | |
| | linked_data = selected_clinical_df.join(gene_norm.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) |
| |
|
| | |
| | covariate_cols = [trait, 'Age', 'Gender'] |
| | gene_cols_in_processed = [c for c in processed_df.columns if c not in covariate_cols] |
| | is_gene_available = len(gene_cols_in_processed) > 0 |
| | is_trait_available = (trait in processed_df.columns) and processed_df[trait].notna().any() |
| |
|
| | note = "INFO: Cohort TCGA_BLCA; trait=Tumor(1) vs Normal(0) by TCGA sample type (01-09 vs 10-19). Gene symbols normalized via NCBI synonyms; duplicates averaged." |
| |
|
| | is_usable = validate_and_save_cohort_info_safe( |
| | is_final=True, |
| | cohort="TCGA", |
| | info_path=json_path, |
| | is_gene_available=is_gene_available, |
| | is_trait_available=is_trait_available, |
| | is_biased=trait_biased, |
| | 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) |