| | |
| | from tools.preprocess import * |
| |
|
| | |
| | trait = "Depression" |
| | cohort = "GSE201332" |
| |
|
| | |
| | in_trait_dir = "../DATA/GEO/Depression" |
| | in_cohort_dir = "../DATA/GEO/Depression/GSE201332" |
| |
|
| | |
| | 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" |
| |
|
| |
|
| | |
| | from tools.preprocess import * |
| | |
| | soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir) |
| |
|
| | |
| | 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) |
| |
|
| | |
| | sample_characteristics_dict = get_unique_values_by_row(clinical_data) |
| |
|
| | |
| | print("Background Information:") |
| | print(background_info) |
| | print("Sample Characteristics Dictionary:") |
| | print(sample_characteristics_dict) |
| |
|
| | |
| | import re |
| | import os |
| |
|
| | |
| | is_gene_available = True |
| |
|
| | |
| | trait_row = 1 |
| | age_row = 3 |
| | gender_row = 2 |
| |
|
| | 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() |
| | |
| | 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 |
| |
|
| | |
| | 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 |
| | ) |
| |
|
| | |
| | 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) |
| |
|
| | |
| | |
| | gene_data = get_genetic_data(matrix_file) |
| |
|
| | |
| | print(gene_data.index[:20]) |
| |
|
| | |
| | |
| | requires_gene_mapping = True |
| | print(f"requires_gene_mapping = {requires_gene_mapping}") |
| |
|
| | |
| | |
| | gene_annotation = get_gene_annotation(soft_file) |
| |
|
| | |
| | print("Gene annotation preview:") |
| | print(preview_df(gene_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.") |
| |
|
| | |
| | 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: |
| | |
| | present_gene_cols = [c for c in gene_annotation.columns if c != probe_col] |
| |
|
| | |
| | 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 |
| | |
| | tmp_map = tmp_map[tmp_map['ID'].isin(gene_data.index)] |
| | if tmp_map.empty: |
| | continue |
| | |
| | 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: |
| | |
| | if 'NAME' in gene_annotation.columns: |
| | best_col = 'NAME' |
| | else: |
| | raise ValueError("Could not identify a suitable annotation column containing gene symbols.") |
| |
|
| | |
| | mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=best_col) |
| |
|
| | |
| | gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df) |
| |
|
| | |
| | import os |
| |
|
| | |
| | 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) |
| |
|
| | |
| | linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data) |
| |
|
| | |
| | linked_data = handle_missing_values(linked_data, trait) |
| |
|
| | |
| | is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait) |
| |
|
| | |
| | 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." |
| | ) |
| |
|
| | |
| | if is_usable: |
| | os.makedirs(os.path.dirname(out_data_file), exist_ok=True) |
| | unbiased_linked_data.to_csv(out_data_file) |
| |
|
| | |
| | import json |
| | import re |
| |
|
| | |
| | raw_expression_df = get_genetic_data(matrix_file) |
| |
|
| | |
| | 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.") |
| |
|
| | |
| | expr_probe_ids = set(raw_expression_df.index.astype(str)) |
| |
|
| | |
| | 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) |
| |
|
| | |
| | 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] |
| |
|
| | |
| | with open("./metadata/gene_synonym.json", "r") as f: |
| | synonym_dict = json.load(f) |
| | synonym_keys = set(synonym_dict.keys()) |
| |
|
| | |
| | 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 |
| | |
| | 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) |
| | |
| | filtered_lists = extracted.apply(filter_tokens) |
| | |
| | uniq_syms = set(sym for lst in filtered_lists if isinstance(lst, list) for sym in lst) |
| | return len(uniq_syms), uniq_syms |
| |
|
| | |
| | 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 |
| |
|
| | |
| | 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 |
| |
|
| | |
| | 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 |
| |
|
| | |
| | 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})") |
| |
|
| | |
| | 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() |
| |
|
| | |
| | extracted = mapping_df_raw['Gene'].apply(extract_human_gene_symbols) |
| | filtered_tokens = extracted.apply(filter_tokens) |
| |
|
| | |
| | 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() |
| | |
| | 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}") |
| |
|
| | |
| | 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.") |