# Path Configuration from tools.preprocess import * # Processing context trait = "Asthma" cohort = "GSE123086" # Input paths in_trait_dir = "../DATA/GEO/Asthma" in_cohort_dir = "../DATA/GEO/Asthma/GSE123086" # Output paths 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" # 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 # 1) Gene expression data availability (Agilent microarray gene expression per background) is_gene_available = True # 2) Variable availability and conversion functions # Decide rows based on the Sample Characteristics Dictionary in the prompt: # - trait_row: primary diagnosis -> row 1 # - gender_row: contains 'Sex:' (row 2 has Sex plus some diagnosis2; handle non-sex values in converter) # - age_row: rows 3/4 show ages; choose row 3 (handle non-age values in converter) trait_row = 1 gender_row = 2 age_row = 3 # Conversion helpers 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): # Binary: 1 for trait present (Asthma), 0 for all others (including healthy controls and other diseases) v = _after_colon(x).strip().lower() if not v: return None # Match trait name robustly # We only consider "primary diagnosis" row, but keep a generic check if "asthma" in v: return 1 # If it's clearly a known non-trait value (e.g., healthy control or other diseases), map to 0 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): # Continuous: extract numeric age in years; invalid entries -> None v = _after_colon(x) # Some cells in row 3 may contain "Sex: ..." -> return None 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): # Binary: female->0, male->1; unknown -> None v = _after_colon(x).strip().lower() if v in ["female", "f"]: return 0 if v in ["male", "m"]: return 1 return None # 3) Save metadata using 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 trait_row 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, n=5) print(preview) # Save clinical features os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True) selected_clinical_df.to_csv(out_clinical_data_file) # 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 print("requires_gene_mapping = True") # 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 import re import pandas as pd # Preserve original probe-/ID-level expression 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) # 1) Choose ID column from annotation that best matches expression IDs (should be "ID") 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 # Prefer explicit 'ID' if reasonable 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' # 2) Use ENTREZ_GENE_ID as the gene identifier since symbol columns are absent 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)") # 3) Build a clean, 1:1 mapping from ID -> Entrez (numeric-only), avoiding token explosion 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]) # Keep only IDs present in expression annotation_for_map = annotation_for_map[annotation_for_map[best_id_col].isin(expr_df.index)] # Extract pure numeric Entrez IDs; drop rows without a valid numeric Entrez 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']) # Reduce to necessary columns and remove duplicates 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']) # 4) Map expression to Entrez gene IDs (1:1 in this dataset) and aggregate 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() # 5) Sanity check gene count to catch mapping explosions 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.") # Step 7: Data Normalization and Linking import os # 1. Normalize gene data only if index appears to be gene symbols; otherwise keep Entrez IDs idx = gene_data.index.astype(str) digit_ratio = idx.str.fullmatch(r'\d+').mean() # proportion of purely numeric IDs note = "" if digit_ratio < 0.5: # Likely gene symbols: normalize using synonym information normalized_gene_data = normalize_gene_symbols_in_index(gene_data) note = "INFO: Gene symbols detected; normalized using synonym dictionary." else: # Likely Entrez IDs: skip normalization normalized_gene_data = gene_data.copy() note = "INFO: Gene matrix indexed by Entrez Gene IDs; gene symbol normalization skipped." # Ensure output directory exists and save 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 the clinical and genetic data 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. Determine bias and remove biased demographic features is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait) # 5. Final validation and save cohort info is_usable = validate_and_save_cohort_info( True, cohort, json_path, True, True, is_trait_biased, unbiased_linked_data, note=note ) # 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)