Liu-Hy's picture
Add files using upload-large-folder tool
72233eb verified
Raw
History Blame Contribute Delete
14.1 kB
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Adrenocortical_Cancer"
# Input paths
tcga_root_dir = "../DATA/TCGA"
# Output paths
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"
# Step 1: Initial Data Loading
import os
import pandas as pd
# Identify the most relevant TCGA cohort directory for the current trait
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)'] # prioritize exact trait and abbreviation
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:
# Choose the highest score; if tie, the first one encountered
matches.sort(key=lambda x: (-x[0], x[1]))
selected_dir = matches[0][1]
# If no suitable directory is found, mark as completed for this trait and stop further processing
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)
# Identify clinical and genetic file paths
try:
clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
except Exception:
# If file identification fails, mark as unavailable
validate_and_save_cohort_info(
is_final=False,
cohort="TCGA",
info_path=json_path,
is_gene_available=False,
is_trait_available=False
)
else:
# Load clinical and genetic data
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 column names
print(clinical_df.columns.tolist())
# Step 2: Find Candidate Demographic Features
import os
import pandas as pd
# Try to use existing clinical_df; otherwise, attempt to load from TCGA ACC cohort
if 'clinical_df' not in globals():
# Heuristic to locate ACC cohort directory
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: # avoid false positive from 'stage'
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
# Avoid false positive from strings containing 'sex' (e.g., 'excess')
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}")
# Preview extracted data if clinical_df is available and there are candidate columns
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({})
# Step 3: Select Demographic Features
import math
# Helper to check if a small list of preview values is usable (not mostly missing)
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
# Try to locate the preview dictionaries created in prior steps
age_values_dict = {}
gender_values_dict = {}
# Known possible variable names
_possible_age_dict_names = ["age_values_dict", "age_preview_dict", "age_dict"]
_possible_gender_dict_names = ["gender_values_dict", "gender_preview_dict", "gender_dict"]
# Pull from known names if available
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 separate dicts not found, try to derive them from any combined dict present in the environment
if (not age_values_dict or not gender_values_dict):
# Search for a dict with keys covering candidate columns
try:
# Collect candidate keys for age and gender
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()
# Scan global namespace for any dict that might contain these keys
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
# Initialize selections
age_col = None
gender_col = None
# Select age column with preference and validity checks
if isinstance(candidate_age_cols, (list, tuple)) and len(candidate_age_cols) > 0 and isinstance(age_values_dict, dict):
# Filter to candidates that exist in the preview dict and look valid
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, []))]
# Apply preference: age_at_initial_pathologic_diagnosis > days_to_birth > first valid
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]
# Select gender column with validity checks
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 preview dicts are empty, set to None explicitly per instruction
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
# Explicitly print out selected columns and their first 5 values (if available)
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")
# Step 4: Feature Engineering and Validation
import os
import pandas as pd
# Ensure clinical_df and genetic_df are available (fallback to reload if needed)
if 'clinical_df' not in globals() or 'genetic_df' not in globals():
# Locate ACC cohort directory
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:
# Worst-case, pick any directory containing ACC
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.")
# Use selected demographic columns from previous step; default to None if missing
age_col = age_col if 'age_col' in globals() else None
gender_col = gender_col if 'gender_col' in globals() else None
# 1) Extract and standardize clinical features (Trait, optional Age and Gender)
selected_clinical_df = tcga_select_clinical_features(
clinical_df=clinical_df,
trait=trait,
age_col=age_col,
gender_col=gender_col
)
# 2) Normalize gene symbols and save normalized gene expression
normalized_gene_df = normalize_gene_symbols_in_index(genetic_df.copy())
normalized_gene_df = normalized_gene_df.apply(pd.to_numeric, errors='coerce')
# 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 sample IDs
expr_t = normalized_gene_df.T # samples x genes
linked_data = selected_clinical_df.join(expr_t, how='inner')
# 4) Handle missing values systematically
processed_df = handle_missing_values(linked_data, trait_col=trait)
# 5) Determine bias in trait and demographic features; remove biased demographics
trait_biased, processed_df = judge_and_remove_biased_features(processed_df, trait)
# 6) Final validation and save cohort info
# Sanitize DataFrame to avoid potential non-JSON-serializable types from pandas index/columns
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)
# Attempt validation; if serialization fails, retry after deeper sanitization
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:
# Deep sanitize: ensure Python-native types in a minimal copy of df metadata
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:
# If still failing, do not raise to keep pipeline running; mark unusable in a minimal way
is_usable = False
# 7) Save linked data only if usable
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
processed_df_safe.to_csv(out_data_file)