# Path Configuration from tools.preprocess import * # Processing context trait = "Allergies" cohort = "GSE203196" # Input paths in_trait_dir = "../DATA/GEO/Allergies" in_cohort_dir = "../DATA/GEO/Allergies/GSE203196" # Output paths out_data_file = "./output/z1/preprocess/Allergies/GSE203196.csv" out_gene_data_file = "./output/z1/preprocess/Allergies/gene_data/GSE203196.csv" out_clinical_data_file = "./output/z1/preprocess/Allergies/clinical_data/GSE203196.csv" json_path = "./output/z1/preprocess/Allergies/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 os # Step 1: Determine gene availability is_gene_available = True # Affymetrix transcriptomic studies imply gene expression microarray data is available. # Step 2: Determine variable availability based on provided sample characteristics dictionary trait_row = 4 # 'allergy: severe/mild/control' age_row = 3 # 'age: ' gender_row = 1 # 'gender: F/M' # Step 2.2: Define conversion functions def _extract_value(x): if x is None: return None s = str(x).strip() if ":" in s: s = s.split(":", 1)[1].strip() return s if s != "" else None def convert_trait(x): v = _extract_value(x) if v is None: return None v_low = v.lower() # Binary allergic status: control -> 0; mild/severe -> 1 if v_low in {"control", "ctrl", "healthy", "non-allergy", "non allergy", "nonallergy"}: return 0 if v_low in {"allergy", "allergic", "mild", "severe"}: return 1 # Heuristic: unknown strings containing 'control' or 'allerg' if "control" in v_low: return 0 if "allerg" in v_low: return 1 return None def convert_age(x): v = _extract_value(x) if v is None: return None # Keep only digits and possible decimal point import re m = re.search(r"[-+]?\d+(\.\d+)?", v) if not m: return None try: return float(m.group()) except Exception: return None def convert_gender(x): v = _extract_value(x) if v is None: return None v_low = v.lower() if v_low in {"f", "female", "woman", "women"}: return 0 if v_low in {"m", "male", "man", "men"}: return 1 return None # Step 3: Initial validation and save metadata 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 ) # Step 4: Clinical feature extraction (only if trait 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) # Save clinical features 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 import os import re import pandas as pd def infer_requires_mapping_from_ids(ids): if not ids: return True n = len(ids) ids = [str(x) for x in ids] numeric_only = sum(s.isdigit() for s in ids) / n has_vendor_prefix = sum(bool(re.match(r'^(ILMN_|A_|AFFX|ENS[A-Z]*|NM_|NR_|XM_|XR_)', s)) for s in ids) / n many_underscores = sum('_' in s for s in ids) / n # Heuristic: if majority are numeric-only or vendor/platform-style, mapping is required if (numeric_only > 0.5) or (has_vendor_prefix > 0.3) or (many_underscores > 0.5): return True # Otherwise, check if they resemble HGNC symbols (alphanumeric, mostly uppercase, few special chars) def looks_like_symbol(s): if s.isdigit(): return False if len(s) > 25: return False # Allowed chars: letters, digits, hyphen, dot if not re.match(r'^[A-Za-z0-9\.\-]+$', s): return False # Must contain at least one letter if not re.search(r'[A-Za-z]', s): return False return True symbol_like = sum(looks_like_symbol(s) for s in ids) / n return symbol_like < 0.5 gene_ids_sample = ['16657436', '16657440', '16657445', '16657447', '16657450', '16657469', '16657473', '16657476', '16657480', '16657485', '16657489', '16657492', '16657502', '16657506', '16657509', '16657514', '16657527', '16657529', '16657534', '16657554'] ids_to_check = None if os.path.exists(out_gene_data_file): try: df_gene = pd.read_csv(out_gene_data_file, index_col=0) ids_to_check = df_gene.index.astype(str).tolist() except Exception: ids_to_check = gene_ids_sample else: ids_to_check = gene_ids_sample requires_gene_mapping = infer_requires_mapping_from_ids(ids_to_check) print(f"requires_gene_mapping = {str(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 # Ensure required dataframes exist from previous steps try: gene_annotation except NameError: gene_annotation = get_gene_annotation(soft_file) try: probe_data = gene_data except NameError: probe_data = get_genetic_data(matrix_file) # 1-2. Decide columns: probe IDs in annotation match expression IDs ('ID'); gene symbols info in 'gene_assignment' probe_col = 'ID' gene_col = 'gene_assignment' mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=gene_col) # 3. Apply mapping to convert probe-level to gene-level expression; result named gene_data gene_data = apply_gene_mapping(probe_data, mapping_df) # Step 7: Data Normalization and Linking import os import pandas as pd # Ensure clinical features are available in current session if 'selected_clinical_df' not in locals(): if os.path.exists(out_clinical_data_file): selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0) else: # Fallback: re-extract if necessary (should not happen under normal pipeline) selected_clinical_df = geo_select_clinical_features( clinical_df=clinical_data, trait=trait, trait_row=4, convert_trait=convert_trait, age_row=3, convert_age=convert_age, gender_row=1, convert_gender=convert_gender ) # Ensure gene_data (gene-level from mapping) is available if 'gene_data' not in locals(): # Recompute from raw files if needed try: gene_annotation except NameError: gene_annotation = get_gene_annotation(soft_file) try: mapping_df except NameError: mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='gene_assignment') try: probe_data except NameError: probe_data = get_genetic_data(matrix_file) gene_data = apply_gene_mapping(probe_data, mapping_df) # 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 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) # Derive availability flags based on actual data is_gene_available = normalized_gene_data.shape[0] > 0 and normalized_gene_data.shape[1] > 0 is_trait_available = (trait in selected_clinical_df.index) and (not selected_clinical_df.loc[trait].isna().all()) # Optional note: dataset contains multiple cell types which may be a confounder if not modeled note = "INFO: Samples span multiple cell types (CD14+, CD3+, platelets); consider including cell type as a covariate in downstream analyses." # 5. Final validation and metadata saving is_usable = validate_and_save_cohort_info( is_final=True, cohort=cohort, info_path=json_path, is_gene_available=is_gene_available, is_trait_available=is_trait_available, is_biased=is_trait_biased, df=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)