Liu-Hy's picture
Add files using upload-large-folder tool
56598a1 verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Bladder_Cancer"
# Input paths
tcga_root_dir = "../DATA/TCGA"
# Output paths
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"
# Step 1: Initial Data Loading
import os
# Step 1: Select the most appropriate TCGA cohort directory for Bladder Cancer
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:
# Prefer directory explicitly containing BLCA code
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:
# No suitable directory found; record and exit early
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)
# Step 2: Identify clinical and genetic data file paths
clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(tcga_cohort_dir)
# Step 3: Load both files as DataFrames
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)
# Step 4: Print the column names of the clinical data
print(list(clinical_df.columns))
# Step 2: Find Candidate Demographic Features
import re
# Identify candidate columns for age and gender from available clinical data columns
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 # exclude false positives like 'pathologic_stage'
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])]
# Strictly required output format for candidate lists
print(f"candidate_age_cols = {candidate_age_cols}")
print(f"candidate_gender_cols = {candidate_gender_cols}")
# Preview extracted candidate columns if available
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)
# Step 3: Select Demographic Features
# Select age and gender columns based on candidate lists and previewed values
# Fallback previews from the previous step (only set if not already available)
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']
}
# Ensure candidate lists are available (use previous step's output if missing)
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']
# Selection logic
age_col = None
gender_col = None
# Prefer direct age at diagnosis over smoking age or days_to_birth
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 none of the preferred are present but days_to_birth exists, we could process it later; for now, we still prefer None over unsuitable columns
if age_col is None and 'days_to_birth' in candidate_age_cols:
# Keep None here since days_to_birth requires transformation; we will only use if absolutely necessary
pass
# Prefer 'gender' or 'sex'
preferred_gender_order = ['gender', 'sex']
for c in preferred_gender_order:
if c in candidate_gender_cols:
gender_col = c
break
# Validate against clinical_df if available
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
# Prepare previews for printing
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)
# Explicitly print out chosen columns and their previews
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)
# Step 4: Feature Engineering and Validation
import os
import json
# Helper: sanitize objects to be JSON-serializable
def _to_builtin(obj):
# Fast path for already serializable basic types
if obj is None or isinstance(obj, (bool, int, float, str)):
return obj
# Containers
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]
# Pandas / numpy scalars
try:
# numpy/pandas scalars often have .item()
if hasattr(obj, 'item'):
return _to_builtin(obj.item())
except Exception:
pass
# Pandas timestamps/timedeltas or other objects: convert to string
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
# Sanitize before dump
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
# 1) Extract and standardize clinical features (trait, Age, Gender)
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
)
# Save standardized clinical data for inspection
os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
selected_clinical_df.to_csv(out_clinical_data_file)
# 2) Normalize gene symbols and save gene data (subset to BLCA samples present in clinical data)
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)
# 3) Link clinical and genetic data on sample IDs
linked_data = selected_clinical_df.join(gene_norm.T, how='inner')
# 4) Handle missing values systematically
processed_df = handle_missing_values(linked_data, trait_col=trait)
# 5) Determine bias in trait and demographics; drop biased demographics
trait_biased, processed_df = judge_and_remove_biased_features(processed_df, trait)
# 6) Final quality validation and save cohort info (use safe wrapper to avoid JSON serialization issues)
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
)
# 7) Save linked data only if usable
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
processed_df.to_csv(out_data_file)