File size: 13,394 Bytes
7c88557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Path Configuration
from tools.preprocess import *

# Processing context
trait = "Colon_and_Rectal_Cancer"

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

# Output paths
out_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/TCGA.csv"
out_gene_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/gene_data/TCGA.csv"
out_clinical_data_file = "./output/z2/preprocess/Colon_and_Rectal_Cancer/clinical_data/TCGA.csv"
json_path = "./output/z2/preprocess/Colon_and_Rectal_Cancer/cohort_info.json"


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

# 1) Select the most appropriate TCGA cohort directory for Colon and Rectal Cancer
subdirs = os.listdir(tcga_root_dir)
preferred_patterns = [
    "TCGA_Colon_and_Rectal_Cancer_(COADREAD)",
    "COADREAD",
    "Colon_and_Rectal_Cancer",
]
selected_dir = None
for pat in preferred_patterns:
    candidates = [d for d in subdirs if pat.lower() in d.lower()]
    if candidates:
        # If multiple options exist, choose the most specific match (first by our preference order)
        selected_dir = sorted(candidates, key=len)[0]
        break

if selected_dir is None:
    # No suitable directory found -> mark as completed and skip
    validate_and_save_cohort_info(
        is_final=False,
        cohort="TCGA_Colon_and_Rectal_Cancer_NotFound",
        info_path=json_path,
        is_gene_available=False,
        is_trait_available=False
    )
else:
    cohort_dir = os.path.join(tcga_root_dir, selected_dir)

    # 2) Identify clinical and genetic file paths
    clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)

    # 3) Load both files as DataFrames
    clinical_df = pd.read_csv(clinical_file_path, sep='\t', index_col=0, low_memory=False, compression='infer')
    genetic_df = pd.read_csv(genetic_file_path, sep='\t', index_col=0, low_memory=False, compression='infer')

    # 4) Print the column names of the clinical data
    print(list(clinical_df.columns))

# Step 2: Find Candidate Demographic Features
# Use available clinical_df columns if present; otherwise fall back to the provided list
provided_columns = ['AWG_MLH1_silencing', 'AWG_cancer_type_Oct62011', 'CDE_ID_3226963', 'CIMP', 'MSI_updated_Oct62011', '_INTEGRATION', '_PANCAN_CNA_PANCAN_K8', '_PANCAN_Cluster_Cluster_PANCAN', '_PANCAN_DNAMethyl_COADREAD', '_PANCAN_DNAMethyl_PANCAN', '_PANCAN_RPPA_PANCAN_K8', '_PANCAN_UNC_RNAseq_PANCAN_K16', '_PANCAN_miRNA_PANCAN', '_PANCAN_mutation_PANCAN', '_PATIENT', '_cohort', '_primary_disease', '_primary_site', 'additional_pharmaceutical_therapy', 'additional_radiation_therapy', 'age_at_initial_pathologic_diagnosis', 'anatomic_neoplasm_subdivision', 'bcr_followup_barcode', 'bcr_patient_barcode', 'bcr_sample_barcode', 'braf_gene_analysis_performed', 'braf_gene_analysis_result', 'circumferential_resection_margin', 'colon_polyps_present', 'days_to_birth', 'days_to_collection', 'days_to_death', 'days_to_initial_pathologic_diagnosis', 'days_to_last_followup', 'days_to_new_tumor_event_additional_surgery_procedure', 'days_to_new_tumor_event_after_initial_treatment', 'disease_code', 'followup_case_report_form_submission_reason', 'followup_treatment_success', 'form_completion_date', 'gender', 'height', 'histological_type', 'history_of_colon_polyps', 'history_of_neoadjuvant_treatment', 'hypermutation', 'icd_10', 'icd_o_3_histology', 'icd_o_3_site', 'informed_consent_verified', 'initial_weight', 'intermediate_dimension', 'is_ffpe', 'kras_gene_analysis_performed', 'kras_mutation_codon', 'kras_mutation_found', 'longest_dimension', 'loss_expression_of_mismatch_repair_proteins_by_ihc', 'loss_expression_of_mismatch_repair_proteins_by_ihc_result', 'lost_follow_up', 'lymph_node_examined_count', 'lymphatic_invasion', 'microsatellite_instability', 'new_neoplasm_event_type', 'new_tumor_event_additional_surgery_procedure', 'new_tumor_event_after_initial_treatment', 'non_nodal_tumor_deposits', 'non_silent_mutation', 'non_silent_rate_per_Mb', 'number_of_abnormal_loci', 'number_of_first_degree_relatives_with_cancer_diagnosis', 'number_of_loci_tested', 'number_of_lymphnodes_positive_by_he', 'number_of_lymphnodes_positive_by_ihc', 'oct_embedded', 'pathologic_M', 'pathologic_N', 'pathologic_T', 'pathologic_stage', 'pathology_report_file_name', 'patient_id', 'perineural_invasion_present', 'person_neoplasm_cancer_status', 'postoperative_rx_tx', 'preoperative_pretreatment_cea_level', 'primary_lymph_node_presentation_assessment', 'primary_therapy_outcome_success', 'project_code', 'radiation_therapy', 'residual_disease_post_new_tumor_event_margin_status', 'residual_tumor', 'sample_type', 'sample_type_id', 'shortest_dimension', 'silent_mutation', 'silent_rate_per_Mb', 'site_of_additional_surgery_new_tumor_event_mets', 'synchronous_colon_cancer_present', 'system_version', 'tissue_prospective_collection_indicator', 'tissue_retrospective_collection_indicator', 'tissue_source_site', 'total_mutation', 'tumor_tissue_site', 'venous_invasion', 'vial_number', 'vital_status', 'weight', 'year_of_initial_pathologic_diagnosis', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2_exon', '_GENOMIC_ID_TCGA_COADREAD_PDMRNAseq', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2_PANCAN', '_GENOMIC_ID_TCGA_COADREAD_hMethyl450', '_GENOMIC_ID_TCGA_COADREAD_gistic2thd', '_GENOMIC_ID_TCGA_COADREAD_hMethyl27', '_GENOMIC_ID_TCGA_COADREAD_G4502A_07_3', '_GENOMIC_ID_TCGA_COADREAD_PDMarrayCNV', '_GENOMIC_ID_TCGA_COADREAD_exp_HiSeqV2', '_GENOMIC_ID_TCGA_COADREAD_PDMarray', '_GENOMIC_ID_TCGA_COADREAD_gistic2', '_GENOMIC_ID_TCGA_COADREAD_mutation', '_GENOMIC_ID_TCGA_COADREAD_RPPA_RBN', '_GENOMIC_ID_TCGA_COADREAD_PDMRNAseqCNV']

all_columns = list(clinical_df.columns) if 'clinical_df' in globals() else provided_columns

# Identify candidate columns with careful patterns to avoid false positives like "pathologic_stage"
candidate_age_cols = []
candidate_gender_cols = []

for col in all_columns:
    col_l = col.lower()
    # Age candidates
    if (
        col_l == 'age' or
        col_l.startswith('age_') or
        'age_at' in col_l or
        col_l.endswith('_age') or
        col_l in {'days_to_birth', 'years_to_birth', 'year_of_birth', 'dob'}
    ):
        candidate_age_cols.append(col)
    # Gender candidates (avoid partial matches like "seq")
    if (
        col_l in {'gender', 'sex'} or
        col_l.endswith('_gender') or
        col_l.endswith('_sex') or
        col_l.startswith('gender_') or
        col_l.startswith('sex_')
    ):
        candidate_gender_cols.append(col)

# Print required lists in strict format
print(f"candidate_age_cols = {candidate_age_cols}")
print(f"candidate_gender_cols = {candidate_gender_cols}")

# Preview extracted data if clinical_df is available
if 'clinical_df' in globals():
    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:
        print(preview_df(clinical_df[age_cols_present], n=5))
    if gender_cols_present:
        print(preview_df(clinical_df[gender_cols_present], n=5))

# Step 3: Select Demographic Features
import pandas as pd
import numpy as np

# Defaults
age_col = None
gender_col = None

# Heuristics thresholds
min_non_missing_ratio = 0.6

# Helper to check if a variable exists
def var_exists(name):
    return name in globals() or name in locals()

# Select age column
if var_exists('candidate_age_cols'):
    if 'clinical_df' in globals() or 'clinical_df' in locals():
        df = clinical_df
        best_score = -np.inf
        best_col = None
        for col in candidate_age_cols:
            if col in df.columns:
                s = pd.to_numeric(df[col], errors='coerce')
                non_missing_ratio = s.notna().mean()

                # Plausible human age range in years
                plausible_ratio = ((s >= 0) & (s <= 120)).mean(skipna=True)

                # Small bonus if column name suggests age in years
                name_bonus = 0.1 if 'age' in col.lower() and 'birth' not in col.lower() else 0.0

                score = plausible_ratio * 1.0 + non_missing_ratio * 0.2 + name_bonus

                if non_missing_ratio >= min_non_missing_ratio and score > best_score:
                    best_score = score
                    best_col = col

        age_col = best_col
    else:
        # Fallback to commonly correct choice if DataFrame not available
        age_col = 'age_at_initial_pathologic_diagnosis' if 'age_at_initial_pathologic_diagnosis' in candidate_age_cols else None

# Select gender column
if var_exists('candidate_gender_cols'):
    if 'clinical_df' in globals() or 'clinical_df' in locals():
        df = clinical_df
        best_score = -np.inf
        best_col = None

        allowed = {'male', 'female', 'm', 'f'}
        for col in candidate_gender_cols:
            if col in df.columns:
                s = df[col].astype(str).str.strip().str.lower()
                non_missing_ratio = df[col].notna().mean()
                in_allowed = s.isin(allowed)
                allowed_ratio = in_allowed.mean()

                # Score prioritizes valid gender values and completeness
                score = allowed_ratio * 1.0 + non_missing_ratio * 0.2

                if non_missing_ratio >= min_non_missing_ratio and score > best_score:
                    best_score = score
                    best_col = col

        gender_col = best_col
    else:
        gender_col = 'gender' if 'gender' in candidate_gender_cols else None

# Print selected columns and a brief preview if available
print("Selected age_col:", age_col)
if age_col is not None and ('clinical_df' in globals() or 'clinical_df' in locals()):
    print("age_col preview (first 5):", clinical_df[age_col].head(5).tolist())

print("Selected gender_col:", gender_col)
if gender_col is not None and ('clinical_df' in globals() or 'clinical_df' in locals()):
    print("gender_col preview (first 5):", clinical_df[gender_col].head(5).tolist())

# Step 4: Feature Engineering and Validation
import os
import pandas as pd
import numpy as np

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

# 2) Prepare genetic data with genes as index, samples as columns
def _tcga_prop_tcga_prefix(labels):
    if len(labels) == 0:
        return 0.0
    return np.mean([isinstance(x, str) and x.startswith('TCGA') for x in labels])

# Detect orientation: are TCGA sample IDs in index or columns?
p_idx = _tcga_prop_tcga_prefix(genetic_df.index.tolist())
p_col = _tcga_prop_tcga_prefix(genetic_df.columns.tolist())

if p_idx >= 0.5 and p_idx > p_col:
    # Index are samples; transpose to get genes as index
    gene_df_raw = genetic_df.T
else:
    gene_df_raw = genetic_df

# Ensure numeric and drop all-nan rows/cols safely
gene_df_raw = gene_df_raw.apply(pd.to_numeric, errors='coerce')
gene_df_raw = gene_df_raw.dropna(axis=0, how='all').dropna(axis=1, how='all')

# Normalize gene symbols using NCBI synonyms and aggregate duplicates
normalized_gene_df = normalize_gene_symbols_in_index(gene_df_raw)

# Save normalized gene expression 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
# Harmonize sample identifiers to first 15 chars (e.g., TCGA-XX-XXXX-01)
def _to_sample15(s):
    return str(s)[:15] if isinstance(s, str) else s

E = normalized_gene_df.T.copy()  # samples x genes
E.index = E.index.map(_to_sample15)
E = E[~E.index.duplicated(keep='first')]

clinical_harmonized = selected_clinical_df.copy()
clinical_harmonized.index = clinical_harmonized.index.map(_to_sample15)
clinical_harmonized = clinical_harmonized[~clinical_harmonized.index.duplicated(keep='first')]

linked_data = clinical_harmonized.join(E, how='inner')

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

# 5) Determine bias in trait and demographics; remove biased demographics
is_biased, debiased_df = judge_and_remove_biased_features(processed_df, trait=trait)
is_biased = bool(is_biased)  # ensure Python-native bool

# 6) Final quality validation and save cohort metadata
cohort_name = selected_dir if 'selected_dir' in globals() else "TCGA_Colon_and_Rectal_Cancer_(COADREAD)"
is_gene_available = bool((normalized_gene_df.shape[0] > 0) and (normalized_gene_df.shape[1] > 0))
is_trait_available = bool((trait in debiased_df.columns) and bool(debiased_df[trait].notna().any()))

note = (
    f"INFO: Linked clinical and gene expression data for {cohort_name}. "
    f"Normalized genes: {normalized_gene_df.shape[0]}; samples in gene data: {normalized_gene_df.shape[1]}. "
    f"Linked samples after harmonization: {linked_data.shape[0]}; final samples after QC: {debiased_df.shape[0]}; "
    f"final features: {debiased_df.shape[1]}."
)

is_usable = validate_and_save_cohort_info(
    is_final=True,
    cohort=str(cohort_name),
    info_path=json_path,
    is_gene_available=is_gene_available,
    is_trait_available=is_trait_available,
    is_biased=is_biased,
    df=debiased_df,
    note=note
)

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