File size: 14,020 Bytes
6b8ee1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# Path Configuration
from tools.preprocess import *

# Processing context
trait = "Depression"
cohort = "GSE201332"

# Input paths
in_trait_dir = "../DATA/GEO/Depression"
in_cohort_dir = "../DATA/GEO/Depression/GSE201332"

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


# Step 1: Initial Data Loading
from tools.preprocess import *
# 1. Identify the paths to the SOFT file and the matrix file
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)

# 2. Read the matrix file to obtain background information and sample characteristics data
background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)

# 3. Obtain the sample characteristics dictionary from the clinical dataframe
sample_characteristics_dict = get_unique_values_by_row(clinical_data)

# 4. Explicitly print out all the background information and the sample characteristics dictionary
print("Background Information:")
print(background_info)
print("Sample Characteristics Dictionary:")
print(sample_characteristics_dict)

# Step 2: Dataset Analysis and Clinical Feature Extraction
import re
import os

# 1) Gene Expression Data Availability
is_gene_available = True  # "Transcriptional profiling" of whole blood for DEGs indicates mRNA expression data.

# 2) Variable Availability and Converters
trait_row = 1   # 'subject status: heathy controls' vs 'subject status: MDD patients'
age_row = 3     # 'age: 43y', etc.
gender_row = 2  # 'gender: male' / 'gender: female'

def _after_colon(val):
    if val is None:
        return None
    s = str(val).strip()
    if ':' in s:
        s = s.split(':', 1)[1].strip()
    return s

def convert_trait(val):
    s = _after_colon(val)
    if s is None or s == '':
        return None
    s_low = s.lower()
    # Map MDD/depression to 1, controls/healthy to 0
    if any(k in s_low for k in ['mdd', 'depress']):
        return 1
    if any(k in s_low for k in ['control', 'healthy', 'normal', 'hc']):
        return 0
    return None

def convert_age(val):
    s = _after_colon(val)
    if s is None or s == '':
        return None
    m = re.search(r'(\d+(\.\d+)?)', s)
    if m:
        num = float(m.group(1))
        return num
    return None

def convert_gender(val):
    s = _after_colon(val)
    if s is None or s == '':
        return None
    s_low = s.lower()
    if s_low in ['male', 'm']:
        return 1
    if s_low in ['female', 'f']:
        return 0
    return None

# 3) Save Metadata (initial filtering)
is_trait_available = trait_row is not None
_ = validate_and_save_cohort_info(
    is_final=False,
    cohort=cohort,
    info_path=json_path,
    is_gene_available=is_gene_available,
    is_trait_available=is_trait_available
)

# 4) Clinical Feature Extraction (only if clinical data is available)
if trait_row is not None:
    selected_clinical_df = geo_select_clinical_features(
        clinical_df=clinical_data,
        trait=trait,
        trait_row=trait_row,
        convert_trait=convert_trait,
        age_row=age_row,
        convert_age=convert_age,
        gender_row=gender_row,
        convert_gender=convert_gender
    )
    preview = preview_df(selected_clinical_df)
    print(preview)
    os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
    selected_clinical_df.to_csv(out_clinical_data_file, index=True)

# Step 3: Gene Data Extraction
# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
gene_data = get_genetic_data(matrix_file)

# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
print(gene_data.index[:20])

# Step 4: Gene Identifier Review
# The observed identifiers are numeric (e.g., '1', '2', ...), consistent with Entrez Gene IDs, not human gene symbols.
requires_gene_mapping = True
print(f"requires_gene_mapping = {requires_gene_mapping}")

# Step 5: Gene Annotation
# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
gene_annotation = get_gene_annotation(soft_file)

# 2. Use the 'preview_df' function from the library to preview the data and print out the results.
print("Gene annotation preview:")
print(preview_df(gene_annotation))

# Step 6: Gene Identifier Mapping
# Determine the probe ID column and candidate gene symbol columns
probe_col = 'ID' if 'ID' in gene_annotation.columns else None
if probe_col is None:
    raise ValueError("Probe ID column 'ID' was not found in the gene annotation dataframe.")

# Candidate columns that may contain gene symbols or descriptions from which symbols can be extracted
candidate_gene_cols = [
    'GENE_SYMBOL', 'Gene Symbol', 'Symbol', 'SYMBOL', 'Gene', 'GENE',
    'GENE_NAME', 'Gene Name', 'GENE_TITLE', 'GENE TITLE', 'GENE_SYMBOLS',
    'DESCRIPTION', 'DEFINITION', 'Product', 'PRODUCT', 'RefSeq', 'REFSEQ',
    'ENTREZ_GENE_ID', 'ENTREZID', 'GB_ACC', 'SEQ_ACC', 'ORF', 'ACCNUM',
    'SPOT_ID', 'NAME', 'SEQUENCE', 'CHROMOSOMAL_LOCATION'
]
present_gene_cols = [c for c in candidate_gene_cols if c in gene_annotation.columns]

if not present_gene_cols:
    # Fallback: try any non-ID textual columns
    present_gene_cols = [c for c in gene_annotation.columns if c != probe_col]

# Score candidate columns by how many rows yield at least one human gene symbol
best_col = None
best_count = -1
for c in present_gene_cols:
    try:
        tmp_map = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=c)
    except Exception:
        continue
    if tmp_map.empty:
        continue
    # Restrict to probes present in the expression data
    tmp_map = tmp_map[tmp_map['ID'].isin(gene_data.index)]
    if tmp_map.empty:
        continue
    # Count rows with at least one extracted human gene symbol
    count_nonempty = tmp_map['Gene'].apply(extract_human_gene_symbols).apply(lambda x: len(x) if isinstance(x, list) else 0).gt(0).sum()
    if count_nonempty > best_count:
        best_count = count_nonempty
        best_col = c

if best_col is None or best_count <= 0:
    # As a last resort, use 'NAME' if available, otherwise raise an error
    if 'NAME' in gene_annotation.columns:
        best_col = 'NAME'
    else:
        raise ValueError("Could not identify a suitable annotation column containing gene symbols.")

# Build final mapping using the selected column
mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=best_col)

# Convert probe-level data to gene-level expression using the mapping
gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)

# Step 7: Data Normalization and Linking
import os

# 1. Normalize gene symbols and save
normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
normalized_gene_data.to_csv(out_gene_data_file)

# 2. Link clinical and genetic data (fix variable name)
linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)

# 3. Handle missing values
linked_data = handle_missing_values(linked_data, trait)

# 4. Bias assessment and removal of biased demographics
is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)

# 5. Final validation and metadata
is_usable = validate_and_save_cohort_info(
    True,
    cohort,
    json_path,
    True,
    True,
    is_trait_biased,
    unbiased_linked_data,
    note="INFO: Probes mapped to symbols via annotation; symbols normalized using NCBI synonyms."
)

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

# Step 8: Gene Identifier Mapping
import json
import re

# Reload raw expression data to ensure probe IDs
raw_expression_df = get_genetic_data(matrix_file)

# 1) Identify identifier column in annotation
probe_col = 'ID' if 'ID' in gene_annotation.columns else None
if probe_col is None:
    raise ValueError("Probe ID column 'ID' was not found in the gene annotation dataframe.")

# Probes present in expression data
expr_probe_ids = set(raw_expression_df.index.astype(str))

# Exclude known control probes if CONTROL_TYPE is present
if 'CONTROL_TYPE' in gene_annotation.columns:
    control_flags = gene_annotation['CONTROL_TYPE'].astype(str).str.lower()
    non_control_mask = ~control_flags.isin(['pos', 'neg', 'control', 'empty', 'ignore'])
    non_control_ids = set(gene_annotation.loc[non_control_mask, probe_col].astype(str))
else:
    non_control_ids = set(gene_annotation[probe_col].astype(str))

valid_probe_ids = expr_probe_ids.intersection(non_control_ids)

# 2) Select the best annotation column containing gene symbols/descriptors
candidate_gene_cols = [
    'GENE_SYMBOL', 'Gene Symbol', 'Symbol', 'SYMBOL', 'Gene', 'GENE',
    'GENE_NAME', 'Gene Name', 'GENE_TITLE', 'GENE TITLE', 'GENE_SYMBOLS',
    'DESCRIPTION', 'DEFINITION', 'Product', 'PRODUCT', 'RefSeq', 'REFSEQ',
    'ENTREZ_GENE_ID', 'ENTREZID', 'GB_ACC', 'SEQ_ACC', 'ORF', 'ACCNUM',
    'NAME', 'SEQUENCE', 'SPOT_ID', 'CHROMOSOMAL_LOCATION'
]
present_gene_cols = [c for c in candidate_gene_cols if c in gene_annotation.columns]
if not present_gene_cols:
    present_gene_cols = [c for c in gene_annotation.columns if c != probe_col]

# Load synonym dictionary to score columns
with open("./metadata/gene_synonym.json", "r") as f:
    synonym_dict = json.load(f)
synonym_keys = set(synonym_dict.keys())

# Token exclusion patterns (spike-ins, controls, generic RNA placeholders)
exclude_exact = {"GE_BRIGHTCORNER", "DARKCORNER", "EMPTY", "CONTROL", "NEG", "POS"}
exclude_regex = [
    re.compile(r'^ERCC[\w-]*$', re.IGNORECASE),
    re.compile(r'^RNA\d+$', re.IGNORECASE),
    re.compile(r'^RNA\d+-\d+$', re.IGNORECASE),
    re.compile(r'^NEG[\w-]*$', re.IGNORECASE),
    re.compile(r'^POS[\w-]*$', re.IGNORECASE),
]

def filter_tokens(tokens):
    kept = []
    for t in tokens:
        if not isinstance(t, str):
            continue
        u = t.upper()
        if u in exclude_exact:
            continue
        if any(rx.match(u) for rx in exclude_regex):
            continue
        # Only keep tokens recognized by synonym dictionary
        if u in synonym_keys:
            kept.append(u)
    return kept

def score_column(col_name):
    tmp_map = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=col_name)
    if tmp_map.empty:
        return 0, set()
    tmp_map = tmp_map[tmp_map['ID'].astype(str).isin(valid_probe_ids)]
    if tmp_map.empty:
        return 0, set()
    extracted = tmp_map['Gene'].apply(extract_human_gene_symbols)
    # Filter symbols
    filtered_lists = extracted.apply(filter_tokens)
    # Count unique recognized symbols
    uniq_syms = set(sym for lst in filtered_lists if isinstance(lst, list) for sym in lst)
    return len(uniq_syms), uniq_syms

# First pass: score all present columns
scores = {}
uniq_syms_by_col = {}
for c in present_gene_cols:
    cnt, uniq = score_column(c)
    scores[c] = cnt
    uniq_syms_by_col[c] = uniq

# Choose the best column by recognized count
best_col = max(scores, key=lambda k: scores[k]) if scores else None
best_count = scores.get(best_col, 0) if best_col is not None else 0

# Enforce fallback strategy if no recognized symbols
if best_count <= 0:
    for fallback in ['NAME', 'SEQUENCE']:
        if fallback in gene_annotation.columns:
            cnt, uniq = score_column(fallback)
            if cnt > 0:
                best_col = fallback
                best_count = cnt
                uniq_syms_by_col[best_col] = uniq
                break

# As a safety, avoid SPOT_ID unless it yields recognized symbols
if (best_col is None) or (best_count <= 0) or (best_col == 'SPOT_ID' and best_count <= 0):
    raise ValueError("Could not identify an annotation column that yields recognized human gene symbols.")

print(f"Selected identifier column: {probe_col}")
print(f"Selected gene annotation column: {best_col} (recognized_symbols={best_count})")

# 3) Build mapping and apply to convert probes -> genes, with explicit filtering
mapping_df_raw = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=best_col)
mapping_df_raw = mapping_df_raw[mapping_df_raw['ID'].astype(str).isin(valid_probe_ids)].copy()

# Extract and filter tokens per row
extracted = mapping_df_raw['Gene'].apply(extract_human_gene_symbols)
filtered_tokens = extracted.apply(filter_tokens)

# Keep rows that have at least one recognized, non-excluded symbol
keep_mask = filtered_tokens.apply(lambda lst: isinstance(lst, list) and len(lst) > 0)
mapping_df_filtered = mapping_df_raw.loc[keep_mask, ['ID']].copy()
# Join tokens back to a single string so that apply_gene_mapping can re-extract correctly
mapping_df_filtered['Gene'] = filtered_tokens.loc[keep_mask].apply(lambda lst: ';'.join(lst))

print(f"Mapping dataframe shape after filtering: {mapping_df_filtered.shape}")

# Show a small sample of recognized symbols we will map
recognized_syms_sample = sorted(list(set(sym for lst in filtered_tokens.loc[keep_mask] for sym in lst)))[:15]
print(f"Sample of recognized symbols to be mapped: {recognized_syms_sample}")

if mapping_df_filtered.empty:
    raise ValueError("Derived mapping_df is empty after filtering; cannot map probes to gene symbols.")

gene_data = apply_gene_mapping(expression_df=raw_expression_df, mapping_df=mapping_df_filtered)

print(f"Gene-level expression shape: {gene_data.shape}")
print(f"First 10 genes mapped: {list(gene_data.index[:10])}")
if gene_data.empty:
    raise ValueError("Resulting gene_data is empty after applying mapping.")