File size: 14,599 Bytes
56598a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# Path Configuration
from tools.preprocess import *

# Processing context
trait = "Bile_Duct_Cancer"

# Input paths
tcga_root_dir = "../DATA/TCGA"

# Output paths
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"


# Step 1: Initial Data Loading
import os
import pandas as pd

# Find the most appropriate TCGA cohort directory for the trait
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}

# Prioritize exact trait phrase, then synonyms
selected_dir = None
exact_key = 'bile_duct_cancer'
synonym_keys = ['(chol', 'cholangio']  # CHOL code and cholangiocarcinoma keyword

# Exact match
candidates_exact = [d for d, dl in lower_map.items() if exact_key in dl]
if candidates_exact:
    # Choose the most specific (shortest name) if multiple
    selected_dir = sorted(candidates_exact, key=len)[0]
else:
    # Synonym-based match
    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:
    # No suitable cohort found; mark and stop further processing in this step
    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)
    # Identify clinical and genetic file paths
    tcga_clinical_file, tcga_genetic_file = tcga_get_relevant_filepaths(tcga_cohort_dir)

    # Load dataframes
    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 clinical column names for further analysis
    print(list(tcga_clinical_df.columns))

# Step 2: Find Candidate Demographic Features
import os
import pandas as pd

# Column names from the previous step
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']

# Step 1: Identify candidate demographic columns
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}")

# Step 2: Extract candidate columns from clinical data and preview
clinical_df = None
clinical_file_path = None

# Try to locate the CHOL clinical file under tcga_root_dir
try:
    # Prefer directories that contain CHOL
    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
    # Fallback: directly search for clinical files mentioning CHOL
    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):
        # Xena clinicalMatrix is tab-separated; sample IDs as index
        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)

# Step 3: Select Demographic Features
# Robust selection of demographic columns using provided candidate lists and preview dictionaries.
# Incorporates value plausibility checks and handles empty inputs.

# Helper to safely get global variables by name
def _get_global(name, default=None):
    return globals()[name] if name in globals() else default

# Try to find the preview dictionary by known names or by heuristic overlap with candidate columns
def _find_preview_dict(candidates, preferred_names):
    for n in preferred_names:
        d = _get_global(n, None)
        if isinstance(d, dict):
            return d
    # Heuristic scan: choose dict with the largest overlap with candidates
    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 {}

# Parsing helpers
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))  # ceil(0.6*n)
    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:
        # Treat as age in years
        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))  # ceil(0.6*n)
    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: explicit age in years over derived days
    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
    # As a last resort, if days_to_birth is available and valid, use it
    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

# Retrieve candidate lists
candidate_age_cols = _get_global('candidate_age_cols', [])
candidate_gender_cols = _get_global('candidate_gender_cols', [])

# Retrieve preview dicts (try known names, then heuristic)
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'])

# Select columns using both candidates and previews
age_col = select_age_col(candidate_age_cols, age_preview_dict)
gender_col = select_gender_col(candidate_gender_cols, gender_preview_dict)

# Explicitly print chosen columns and their preview values (first 5)
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")

# Step 4: Feature Engineering and Validation
import os

# 1) Extract and standardize clinical features
selected_clinical_df = tcga_select_clinical_features(
    clinical_df=tcga_clinical_df,
    trait=trait,
    age_col=age_col,
    gender_col=gender_col
)

# 2) Normalize gene symbols and save
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)

# 3) Link clinical and genetic data
gene_t = normalized_gene_df.T  # samples as index
linked_data = selected_clinical_df.join(gene_t, how='inner')

# 4) Handle missing values
processed_df = handle_missing_values(linked_data.copy(), trait_col=trait)

# 5) Determine bias and remove biased demographic features if needed
is_biased, processed_df = judge_and_remove_biased_features(processed_df, trait=trait)

# 6) Final validation and save cohort info
# Cast to Python bool to avoid numpy.bool_ JSON serialization issues
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
)

# 7) Save linked data if usable
if is_usable:
    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
    processed_df.to_csv(out_data_file)