File size: 12,481 Bytes
d818561
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# Path Configuration
from tools.preprocess import *

# Processing context
trait = "Breast_Cancer"

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

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


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

# Step 1: Select the most relevant TCGA cohort directory for Breast Cancer
def select_tcga_cohort(root_dir: str, trait_keywords=None):
    if trait_keywords is None:
        trait_keywords = ['breast', 'brca']

    subdirs = [d for d in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, d))]
    best_dir, best_score = None, -1
    for d in subdirs:
        name = d.lower()
        score = 0
        if 'breast' in name:
            score += 5
        if 'brca' in name:
            score += 3
        if 'tcga_breast_cancer' in name:
            score += 10
        if score > best_score:
            best_score = score
            best_dir = d
    return best_dir, best_score

selected_dir, score = select_tcga_cohort(tcga_root_dir)
if (selected_dir is None) or (score <= 0):
    # No appropriate cohort found; record and stop early for this trait
    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)
    print(f"Selected cohort directory: {selected_dir}")

    # Step 2: Identify clinical and genetic data file paths
    clinical_file_path, genetic_file_path = tcga_get_relevant_filepaths(cohort_dir)
    print(f"Clinical file: {os.path.basename(clinical_file_path)}")
    print(f"Genetic file: {os.path.basename(genetic_file_path)}")

    # Step 3: Load both files as DataFrames
    def read_tcga_file(path: str) -> pd.DataFrame:
        compression = 'gzip' if path.endswith('.gz') else None
        return pd.read_csv(path, sep='\t', index_col=0, low_memory=False, compression=compression)

    clinical_df = read_tcga_file(clinical_file_path)
    genetic_df = read_tcga_file(genetic_file_path)

    # Step 4: Print clinical column names
    print(list(clinical_df.columns))

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

# Determine paths
cohort_dir_name = "TCGA_Breast_Cancer_(BRCA)"
clinical_file_name = "TCGA.BRCA.sampleMap_BRCA_clinicalMatrix"
cohort_dir = os.path.join(tcga_root_dir, cohort_dir_name)
clinical_path = os.path.join(cohort_dir, clinical_file_name)

# Load clinical data
clinical_df = pd.read_csv(clinical_path, sep="\t", index_col=0, dtype=str)

# Identify candidate columns
def is_age_col(col: str) -> bool:
    cl = col.lower()
    if 'days_to_birth' in cl:
        return True
    if 'age_at' in cl:
        return True
    if re.search(r'(^|_)age(_|$)', cl):
        return True
    return False

def is_gender_col(col: str) -> bool:
    cl = col.lower()
    if re.search(r'(^|_)gender(_|$)', cl):
        return True
    if re.search(r'(^|_)sex(_|$)', cl):
        return True
    return False

cols = list(clinical_df.columns)
candidate_age_cols = [c for c in cols if is_age_col(c)]
candidate_gender_cols = [c for c in cols if is_gender_col(c)]

# 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 dictionaries
if candidate_age_cols:
    age_df = clinical_df[candidate_age_cols]
    print(preview_df(age_df, n=5))
if candidate_gender_cols:
    gender_df = clinical_df[candidate_gender_cols]
    print(preview_df(gender_df, n=5))

# Step 3: Select Demographic Features
# Select demographic feature columns based on preview dictionaries if available; fallback to sensible defaults.

age_col = None
gender_col = None

def _safe_get(var_name, default=None):
    # Access a variable by name if it exists in globals()
    return globals().get(var_name, default)

# Attempt to retrieve the preview dictionaries from previous steps
age_preview_dict = _safe_get('age_preview_dict', None)
gender_preview_dict = _safe_get('gender_preview_dict', None)

def is_valid_age_value(v):
    a = tcga_convert_age(v)
    return a is not None and 0 <= a <= 120

def is_valid_gender_value(v):
    g = tcga_convert_gender(v)
    return g is not None and g in (0, 1)

# Determine age_col
if isinstance(age_preview_dict, dict) and isinstance(globals().get('candidate_age_cols', None), list):
    best_col = None
    best_score = -1
    for c in candidate_age_cols:
        vals = age_preview_dict.get(c, [])
        valid_count = sum(1 for v in vals if is_valid_age_value(v))
        # Heuristic tie-breakers: prefer explicit age columns over 'days_to_birth', and avoid 'nature2012' if tied
        score = valid_count
        if 'days_to_birth' in c.lower():
            score -= 0.5
        if 'nature2012' in c.lower():
            score -= 0.1
        if score > best_score:
            best_score = score
            best_col = c
    age_col = best_col if best_score > 0 else None
else:
    # Fallback selection if preview dict not available: prioritize typical age column names
    if 'age_at_initial_pathologic_diagnosis' in globals().get('candidate_age_cols', []):
        age_col = 'age_at_initial_pathologic_diagnosis'
    elif 'Age_at_Initial_Pathologic_Diagnosis_nature2012' in globals().get('candidate_age_cols', []):
        age_col = 'Age_at_Initial_Pathologic_Diagnosis_nature2012'
    elif 'days_to_birth' in globals().get('candidate_age_cols', []):
        age_col = 'days_to_birth'
    else:
        age_col = None

# Determine gender_col
if isinstance(gender_preview_dict, dict) and isinstance(globals().get('candidate_gender_cols', None), list):
    best_col = None
    best_score = -1
    for c in candidate_gender_cols:
        vals = gender_preview_dict.get(c, [])
        valid_count = sum(1 for v in vals if is_valid_gender_value(v))
        # Prefer columns without 'nature2012' if tied
        score = valid_count - (0.1 if 'nature2012' in c.lower() else 0)
        if score > best_score:
            best_score = score
            best_col = c
    gender_col = best_col if best_score > 0 else None
else:
    # Fallback selection if preview dict not available: prefer standard 'gender'
    if 'gender' in globals().get('candidate_gender_cols', []):
        gender_col = 'gender'
    elif 'Gender_nature2012' in globals().get('candidate_gender_cols', []):
        gender_col = 'Gender_nature2012'
    else:
        gender_col = None

# Explicitly print out the information for the chosen columns
print(f"Selected 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"Preview values for age_col ({age_col}): {age_preview_dict[age_col]}")

print(f"Selected 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"Preview values for gender_col ({gender_col}): {gender_preview_dict[gender_col]}")

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

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

# Helper to detect TCGA sample barcode
def _is_tcga_barcode(x: str) -> bool:
    return isinstance(x, str) and x.startswith("TCGA-")

def _fraction_tcga(seq) -> float:
    if len(seq) == 0:
        return 0.0
    cnt = sum(1 for v in seq if _is_tcga_barcode(str(v)))
    return cnt / len(seq)

# 2) Normalize gene symbols in gene expression data
is_gene_available = False
normalized_gene_df = pd.DataFrame()
gene_note = ""

try:
    if isinstance(genetic_df, pd.DataFrame) and len(genetic_df) > 0:
        idx_frac = _fraction_tcga(list(genetic_df.index[:min(len(genetic_df.index), 1000)]))
        col_frac = _fraction_tcga(list(genetic_df.columns[:min(len(genetic_df.columns), 1000)]))

        # Orient to genes as index, samples as columns
        if idx_frac > 0.5 and col_frac <= 0.5:
            oriented = genetic_df.T
            gene_note += "INFO: Genetic data transposed to have genes as index and samples as columns. "
        elif col_frac > 0.5 and idx_frac <= 0.5:
            oriented = genetic_df.copy()
            gene_note += "INFO: Genetic data already oriented with genes as index and samples as columns. "
        else:
            oriented = genetic_df.copy()
            gene_note += "WARNING: Genetic data orientation ambiguous. Proceeded without transposition. "

        # Coerce to numeric
        oriented = oriented.apply(pd.to_numeric, errors='coerce')
        # Keep columns that look like TCGA barcodes to ensure samples are columns
        sample_cols = [c for c in oriented.columns if _is_tcga_barcode(c)]
        if len(sample_cols) == 0:
            gene_note += "ERROR: No sample barcode-like columns detected in genetic data. "
            is_gene_available = False
        else:
            oriented = oriented.loc[:, sample_cols]

            # Normalize gene symbols in index
            normalized_gene_df = normalize_gene_symbols_in_index(oriented)

            # Heuristic checks for availability
            genes_count = normalized_gene_df.shape[0]
            samples_count = normalized_gene_df.shape[1]
            has_values = normalized_gene_df.notna().any().any()
            is_gene_available = (genes_count >= 500) and (samples_count >= 10) and has_values

            # Save normalized gene data if available
            if bool(is_gene_available):
                os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
                normalized_gene_df.to_csv(out_gene_data_file)
            else:
                gene_note += f"ERROR: Insufficient gene expression data after normalization (genes={genes_count}, samples={samples_count}). "
    else:
        gene_note += "ERROR: Genetic dataframe missing or empty. "
except Exception as e:
    gene_note += f"ERROR: Exception during gene processing: {e}. "
    is_gene_available = False
    normalized_gene_df = pd.DataFrame()

# 3) Link clinical and genetic data
if bool(is_gene_available):
    common_samples = selected_clinical_df.index.intersection(normalized_gene_df.columns)
    linked_data = pd.concat(
        [selected_clinical_df.loc[common_samples], normalized_gene_df.loc[:, common_samples].T],
        axis=1
    )
else:
    linked_data = selected_clinical_df.copy()

# 4) Handle missing values
covariate_cols = [trait, "Age", "Gender"]
gene_cols_in_linked = [c for c in linked_data.columns if c not in covariate_cols]
if len(gene_cols_in_linked) > 0:
    linked_data = handle_missing_values(linked_data, trait)
else:
    linked_data = linked_data.dropna(subset=[trait])
    if "Age" in linked_data.columns:
        linked_data["Age"] = pd.to_numeric(linked_data["Age"], errors="coerce")
        linked_data["Age"] = linked_data["Age"].fillna(linked_data["Age"].mean())
    if "Gender" in linked_data.columns:
        mode_result = linked_data["Gender"].mode()
        if len(mode_result) > 0:
            linked_data["Gender"] = linked_data["Gender"].fillna(mode_result[0])
        else:
            linked_data = linked_data.drop(columns=["Gender"])

# 5) Determine biased features and remove biased demographics
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)

# 6) Final validation and save metadata
# Recompute trait availability on the linked dataset to reflect post-processing status
is_trait_available = bool(linked_data[trait].notna().any())
note = gene_note.strip() if gene_note else ""
note = note if note.startswith(("INFO:", "WARNING:", "ERROR:", "DEBUG:")) else (("INFO: " + note) if note else "")

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=linked_data,
    note=note
)

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