| |
| from tools.preprocess import * |
|
|
| |
| trait = "Asthma" |
| cohort = "GSE123086" |
|
|
| |
| in_trait_dir = "../DATA/GEO/Asthma" |
| in_cohort_dir = "../DATA/GEO/Asthma/GSE123086" |
|
|
| |
| out_data_file = "./output/z1/preprocess/Asthma/GSE123086.csv" |
| out_gene_data_file = "./output/z1/preprocess/Asthma/gene_data/GSE123086.csv" |
| out_clinical_data_file = "./output/z1/preprocess/Asthma/clinical_data/GSE123086.csv" |
| json_path = "./output/z1/preprocess/Asthma/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 |
|
|
| |
| is_gene_available = True |
|
|
| |
|
|
| |
| |
| |
| |
| trait_row = 1 |
| gender_row = 2 |
| age_row = 3 |
|
|
| |
| def _after_colon(x: str) -> str: |
| if x is None: |
| return "" |
| parts = str(x).split(":", 1) |
| return parts[1].strip() if len(parts) > 1 else str(x).strip() |
|
|
| def convert_trait(x): |
| |
| v = _after_colon(x).strip().lower() |
| if not v: |
| return None |
| |
| |
| if "asthma" in v: |
| return 1 |
| |
| non_trait_keywords = [ |
| "healthy_control", "obesity", "seasonal_allergic_rhinitis", "psoriasis", |
| "crohn", "influenza", "ulcerative_colitis", "atherosclerosis", |
| "breast_cancer", "type_1_diabetes", "chronic_lymphocytic_leukemia", |
| "atopic_eczema", "acute_tonsillitis" |
| ] |
| if any(k in v for k in non_trait_keywords): |
| return 0 |
| return None |
|
|
| def convert_age(x): |
| |
| v = _after_colon(x) |
| |
| m = re.search(r"(-?\d+(?:\.\d+)?)", v) |
| if not m: |
| return None |
| try: |
| age_val = float(m.group(1)) |
| if 0 <= age_val <= 120: |
| return age_val |
| return None |
| except Exception: |
| return None |
|
|
| def convert_gender(x): |
| |
| v = _after_colon(x).strip().lower() |
| if v in ["female", "f"]: |
| return 0 |
| if v in ["male", "m"]: |
| return 1 |
| 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, n=5) |
| print(preview) |
| |
| os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True) |
| selected_clinical_df.to_csv(out_clinical_data_file) |
|
|
| |
| |
| gene_data = get_genetic_data(matrix_file) |
|
|
| |
| print(gene_data.index[:20]) |
|
|
| |
| print("requires_gene_mapping = True") |
|
|
| |
| |
| gene_annotation = get_gene_annotation(soft_file) |
|
|
| |
| print("Gene annotation preview:") |
| print(preview_df(gene_annotation)) |
|
|
| |
| import re |
| import pandas as pd |
|
|
| |
| expr_df = gene_data.copy() |
|
|
| def normalize_id_series(s: pd.Series) -> pd.Series: |
| s = s.astype(str).str.strip() |
| return s.str.replace(r'\.0$', '', regex=True) |
|
|
| |
| expr_ids = set(expr_df.index.astype(str).str.strip()) |
| best_id_col = None |
| best_overlap = -1 |
| for col in gene_annotation.columns: |
| cand = normalize_id_series(gene_annotation[col]) |
| overlap = cand.isin(expr_ids).sum() |
| if overlap > best_overlap: |
| best_overlap = overlap |
| best_id_col = col |
|
|
| |
| if 'ID' in gene_annotation.columns: |
| cand = normalize_id_series(gene_annotation['ID']) |
| overlap = cand.isin(expr_ids).sum() |
| if overlap >= best_overlap * 0.95: |
| best_id_col = 'ID' |
|
|
| |
| if 'ENTREZ_GENE_ID' not in gene_annotation.columns: |
| raise ValueError("ENTREZ_GENE_ID column not found in annotation; cannot proceed with Entrez mapping.") |
|
|
| print(f"Chosen ID column: {best_id_col}") |
| print("Chosen Gene column: ENTREZ_GENE_ID (Entrez IDs)") |
|
|
| |
| annotation_for_map = gene_annotation.loc[:, [best_id_col, 'ENTREZ_GENE_ID']].copy() |
| annotation_for_map[best_id_col] = normalize_id_series(annotation_for_map[best_id_col]) |
|
|
| |
| annotation_for_map = annotation_for_map[annotation_for_map[best_id_col].isin(expr_df.index)] |
|
|
| |
| def extract_numeric_entrez(x): |
| if pd.isna(x): |
| return None |
| m = re.search(r'\d+', str(x)) |
| return m.group(0) if m else None |
|
|
| annotation_for_map['Gene'] = annotation_for_map['ENTREZ_GENE_ID'].apply(extract_numeric_entrez) |
| annotation_for_map = annotation_for_map.dropna(subset=['Gene']) |
|
|
| |
| mapping_df = annotation_for_map.loc[:, [best_id_col, 'Gene']].rename(columns={best_id_col: 'ID'}) |
| mapping_df['ID'] = mapping_df['ID'].astype(str).str.strip() |
| mapping_df['Gene'] = mapping_df['Gene'].astype(str).str.strip() |
| mapping_df = mapping_df.drop_duplicates(subset=['ID', 'Gene']) |
|
|
| |
| mapped = mapping_df.set_index('ID').join(expr_df, how='inner') |
| expr_cols = [c for c in mapped.columns if c != 'Gene'] |
| gene_data = mapped.groupby('Gene')[expr_cols].sum() |
|
|
| |
| n_genes = gene_data.shape[0] |
| n_samples = gene_data.shape[1] |
| print(f"Gene-level data shape: {gene_data.shape} (genes x samples)") |
| if n_genes < 5000 or n_genes > 80000: |
| raise ValueError(f"Implausible gene count after mapping: {n_genes}. Check mapping logic and annotation parsing.") |
|
|
| |
| import os |
|
|
| |
| idx = gene_data.index.astype(str) |
| digit_ratio = idx.str.fullmatch(r'\d+').mean() |
| note = "" |
|
|
| if digit_ratio < 0.5: |
| |
| normalized_gene_data = normalize_gene_symbols_in_index(gene_data) |
| note = "INFO: Gene symbols detected; normalized using synonym dictionary." |
| else: |
| |
| normalized_gene_data = gene_data.copy() |
| note = "INFO: Gene matrix indexed by Entrez Gene IDs; gene symbol normalization skipped." |
|
|
| |
| 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=note |
| ) |
|
|
| |
| if is_usable: |
| os.makedirs(os.path.dirname(out_data_file), exist_ok=True) |
| unbiased_linked_data.to_csv(out_data_file) |