# Path Configuration from tools.preprocess import * # Processing context trait = "Anxiety_disorder" cohort = "GSE60190" # Input paths in_trait_dir = "../DATA/GEO/Anxiety_disorder" in_cohort_dir = "../DATA/GEO/Anxiety_disorder/GSE60190" # Output paths out_data_file = "./output/preprocess/3/Anxiety_disorder/GSE60190.csv" out_gene_data_file = "./output/preprocess/3/Anxiety_disorder/gene_data/GSE60190.csv" out_clinical_data_file = "./output/preprocess/3/Anxiety_disorder/clinical_data/GSE60190.csv" json_path = "./output/preprocess/3/Anxiety_disorder/cohort_info.json" # Get file paths soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir) # Extract background info and clinical data background_info, clinical_data = get_background_and_clinical_data(matrix_file) # Get unique values per clinical feature sample_characteristics = get_unique_values_by_row(clinical_data) # Print background info print("Dataset Background Information:") print(f"{background_info}\n") # Print sample characteristics print("Sample Characteristics:") for feature, values in sample_characteristics.items(): print(f"Feature: {feature}") print(f"Values: {values}\n") ```python # 1. Gene Expression Data Availability # Based on Series_summary, this dataset uses Illumina HumanHT-12 v3 microarray for gene expression measurement is_gene_available = True # 2.1 Data Availability & 2.2 Data Type Conversion # trait (anxiety) can be inferred from dx field trait_row = 3 def convert_trait(value): if not isinstance(value, str): return None val = value.split(": ")[-1] # Anxiety disorder can be comorbid with OCD, so consider OCD cases as anxiety cases if val in ["OCD", "Tics"]: return 1 elif val == "Control": return 0 return None # age is available age_row = 5 def convert_age(value): if not isinstance(value, str): return None try: return float(value.split(": ")[-1]) except: return None # gender is available gender_row = 7 def convert_gender(value): if not isinstance(value, str): return None val = value.split(": ")[-1] if val == "F": return 0 elif val == "M": return 1 return None # 3. Save Metadata validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, is_gene_available=is_gene_available, is_trait_available=True) # 4. Clinical Feature Extraction sample_characteristics = { '0': ['rin: 7.4', 'rin: 8.6', 'rin: 7.8', 'rin: 8.2', 'rin: 8.5', 'rin: 8.3', 'rin: 8.1', 'rin: 8.8', 'rin: 8.7', 'rin: 7.5', 'rin: 9', 'rin: 7.1', 'rin: 7.2', 'rin: 7.7', 'rin: 8.9', 'rin: 6.7', 'rin: 6', 'rin: 8.4', 'rin: 7.3', 'rin: 8', 'rin: 9.1', 'rin: 7.9', 'rin: 9.7', 'rin: 9.2', 'rin: 6.5', 'rin: 7', 'rin: 7.6', 'rin: 6.6', 'rin: 5.4', 'rin: 5.6'], '1': ['ocd: ED', 'ocd: Control', 'ocd: OCD'], '2': ['rinmatched: 1', 'rinmatched: 0'], '3': ['dx: Bipolar', 'dx: Control', 'dx: MDD', 'dx: Tics', 'dx: OCD', 'dx: ED'], '4': ['ph: 6.18', 'ph: 6.59', 'ph: 6.37', 'ph: 6.6', 'ph: 6.38', 'ph: 6.02', 'ph: 6.87', 'ph: 6.95', 'ph: 6.82', 'ph: 6.27', 'ph: 6.53', 'ph: 6.55', 'ph: 6', 'ph: 6.13', 'ph: 6.08', 'ph: 6.29', 'ph: 6.98', 'ph: 5.91', 'ph: 6.06', 'ph: 6.9', 'ph: 6.83', 'ph: 6.36', 'ph: 6.84', 'ph: 6.74', 'ph: 6.28', 'ph: 6.49', 'ph: 6.7', 'ph: 6.63', 'ph: 6.48', 'ph: 6.62'], '5': ['age: 50.421917', 'age: 27.49863', 'age: 30.627397', 'age: 61.167123', 'age: 32.69589', 'age: 39.213698', 'age: 58.605479', 'age: 49.2', 'age: 41.041095', 'age: 51.750684', 'age: 50.89863', 'age: 26.745205', 'age: 29.104109', 'age: 39.301369', 'age: 48.978082', 'age: 57.884931', 'age: 28.364383', 'age: 24.041095', 'age: 19.268493', 'age: 27.230136', 'age: 46.605479', 'age: 23.443835', 'age: 51.038356', 'age: 39.663013', 'age: 46.109589', 'age: 77.989041', 'age: 46.967123', 'age: 63.241095', 'age: 62.306849', 'age: 83.641095'], '6': ['pmi: 27', 'pmi: 19.5', 'pmi: 71.5', 'pmi: 22.5', 'pmi: 64', 'pmi: 28', 'pmi: 18', 'pmi: 29', 'pmi: 49', 'pmi: 13', 'pmi: 26.5', 'pmi: 16.5', 'pmi: 35', 'pmi: 19', 'pmi: 20.5', 'pmi: 9.5', 'pmi: 65.5', 'pmi: 68', 'pmi: 17.5', 'pmi: 44', 'pmi: 34', 'pmi: 21.5', 'pmi: 67.5', 'pmi: 26', 'pmi: 46.5', 'pmi: 33.5', 'pmi: 24.5', 'pmi: 30.5', 'pmi: 29.5', 'pmi: 51.5'], '7': ['Sex: F', 'Sex: M'], '8': ['race: CAUC'], '9': ['batch1: 16', 'batch1: 18', 'batch1: 19', 'batch1: 20', 'batch1: 21', 'batch1: 9', 'batch1: 10', 'batch1: 12', 'batch1: 14', 'batch1: 23', 'batch1: 24', 'batch1: 25', 'batch1: 26', 'batch1: 27', 'batch1: 29', 'batch1: 33', 'batch1: 32', 'batch1: 31', 'batch1: 36', 'batch1: 37', 'batch1: 38', 'batch1: 39', 'batch1: 40', 'batch1: 41', 'batch1: 42', 'batch1: 44', 'batch1: 45', 'batch1: 48', 'batch1: 53', 'batch1: 59'] } clinical_data = pd.DataFrame(sample_characteristics) selected_clinical_df = geo_select_clinical_features(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_ print("Step 3 cannot be implemented without the output from the previous step that contains:") print("1. Sample characteristics dictionary") print("2. Background information about the dataset") print("3. Preview of the clinical data") print("\nPlease provide this information to proceed with proper data analysis.") # Get file paths soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir) # Extract gene expression data from matrix file gene_data = get_genetic_data(matrix_file) # Print first 20 row IDs and shape of data to help debug print("Shape of gene expression data:", gene_data.shape) print("\nFirst few rows of data:") print(gene_data.head()) print("\nFirst 20 gene/probe identifiers:") print(gene_data.index[:20]) # Inspect a snippet of raw file to verify identifier format import gzip with gzip.open(matrix_file, 'rt', encoding='utf-8') as f: lines = [] for i, line in enumerate(f): if "!series_matrix_table_begin" in line: # Get the next 5 lines after the marker for _ in range(5): lines.append(next(f).strip()) break print("\nFirst few lines after matrix marker in raw file:") for line in lines: print(line) # The IDs start with "ILMN_" which indicates these are Illumina probe IDs # These need to be mapped to official human gene symbols requires_gene_mapping = True # Extract gene annotation from SOFT file gene_annotation = get_gene_annotation(soft_file) # Preview annotation dataframe structure print("Gene Annotation Preview:") print("Column names:", gene_annotation.columns.tolist()) print("\nFirst few rows as dictionary:") print(preview_df(gene_annotation)) # 1. Identify mapping columns: # 'ID' in annotation matches the probe IDs like 'ILMN_1343291' in gene expression data # 'Symbol' contains the gene symbols we want to map to # 2. Extract mapping between probe IDs and gene symbols mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol') # 3. Convert probe measurements to gene expression data gene_data = apply_gene_mapping(gene_data, mapping_df) # Inspect the result print("Mapped gene expression data shape:", gene_data.shape) print("\nFirst few rows of mapped data:") print(gene_data.head()) print("\nFirst 20 mapped gene symbols:") print(gene_data.index[:20]) # Re-run gene mapping to restore gene_data mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol') gene_data = apply_gene_mapping(expression_df, mapping_df) # 1. Normalize gene symbols gene_data = normalize_gene_symbols_in_index(gene_data) # Save normalized gene data os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True) gene_data.to_csv(out_gene_data_file) # Get clinical features from sample characteristics trait_row = 3 # From 'dx' field def convert_trait(value): if not isinstance(value, str): return None val = value.split(": ")[-1] # Anxiety disorder can be comorbid with OCD, so consider OCD cases as anxiety cases if val in ["OCD", "Tics"]: return 1 elif val == "Control": return 0 return None age_row = 5 def convert_age(value): if not isinstance(value, str): return None try: return float(value.split(": ")[-1]) except: return None gender_row = 7 def convert_gender(value): if not isinstance(value, str): return None val = value.split(": ")[-1] if val == "F": return 0 elif val == "M": return 1 return None # Extract clinical features and save clinical_df = geo_select_clinical_features(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) # Save clinical data os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True) clinical_df.to_csv(out_clinical_data_file) # 2. Link clinical and genetic data linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data) # 3. Handle missing values linked_data = handle_missing_values(linked_data, trait) # 4. Determine if features are biased is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait) # 5. Validate and save cohort info is_usable = validate_and_save_cohort_info( is_final=True, cohort=cohort, info_path=json_path, is_gene_available=True, is_trait_available=True, is_biased=is_trait_biased, df=linked_data, note="Gene expression data successfully mapped and linked with clinical features" ) # 6. Save linked data only if usable AND trait is not biased if is_usable and not is_trait_biased: os.makedirs(os.path.dirname(out_data_file), exist_ok=True) linked_data.to_csv(out_data_file) # Get file paths soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir) # Extract gene annotation from SOFT file gene_annotation = get_gene_annotation(soft_file) # Preview annotation dataframe structure print("Gene Annotation Preview:") print("Column names:", gene_annotation.columns.tolist()) print("\nFirst few rows as dictionary:") print(preview_df(gene_annotation)) # Get file paths soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir) # Get genetic data and map to genes gene_data = get_genetic_data(matrix_file) mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol') gene_data = apply_gene_mapping(gene_data, mapping_df) # 1. Normalize gene symbols and save os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True) gene_data = normalize_gene_symbols_in_index(gene_data) gene_data.to_csv(out_gene_data_file) # 2. Link clinical and genetic data try: clinical_data = pd.read_csv(out_clinical_data_file, index_col=0) linked_data = geo_link_clinical_genetic_data(clinical_data, gene_data) # 3. Handle missing values linked_data = handle_missing_values(linked_data, trait) # 4. Determine if features are biased is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait) # 5. Validate and save cohort info is_usable = validate_and_save_cohort_info( is_final=True, cohort=cohort, info_path=json_path, is_gene_available=True, is_trait_available=True, is_biased=is_trait_biased, df=linked_data, note="Gene expression data successfully mapped and linked with clinical features" ) # 6. Save linked data if usable if is_usable and not is_trait_biased: os.makedirs(os.path.dirname(out_data_file), exist_ok=True) linked_data.to_csv(out_data_file) except Exception as e: print(f"Error in data linking and processing: {str(e)}") is_usable = validate_and_save_cohort_info( is_final=True, cohort=cohort, info_path=json_path, is_gene_available=True, is_trait_available=True, is_biased=True, df=pd.DataFrame(), note=f"Data processing failed: {str(e)}" ) # Get file paths soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir) # Extract gene expression data from matrix file gene_data = get_genetic_data(matrix_file) # Print first 20 row IDs and shape of data to help debug print("Shape of gene expression data:", gene_data.shape) print("\nFirst few rows of data:") print(gene_data.head()) print("\nFirst 20 gene/probe identifiers:") print(gene_data.index[:20]) # Inspect a snippet of raw file to verify identifier format import gzip with gzip.open(matrix_file, 'rt', encoding='utf-8') as f: lines = [] for i, line in enumerate(f): if "!series_matrix_table_begin" in line: # Get the next 5 lines after the marker for _ in range(5): lines.append(next(f).strip()) break print("\nFirst few lines after matrix marker in raw file:") for line in lines: print(line) # Get file paths soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir) # Extract background info and clinical data background_info, clinical_data = get_background_and_clinical_data(matrix_file) # Get unique values per clinical feature sample_characteristics = get_unique_values_by_row(clinical_data) # Print background info print("Dataset Background Information:") print(f"{background_info}\n") # Print sample characteristics print("Sample Characteristics:") for feature, values in sample_characteristics.items(): print(f"Feature: {feature}") print(f"Values: {values}\n") # 1. Gene Expression Data Availability # Yes, based on the background info showing Illumina HumanHT-12 microarray data is_gene_available = True # 2.1 Data Availability & 2.2 Data Type Conversion # Trait: Available in feature 1 'ocd' with values like 'ED', 'Control', 'OCD' trait_row = 1 def convert_trait(value): # Since we're looking for anxiety disorder, OCD patients are the cases if not value or ':' not in value: return None val = value.split(':')[1].strip() if val == 'OCD': return 1 elif val == 'Control': return 0 return None # Other values like 'ED' are not relevant # Age: Available in feature 5 age_row = 5 def convert_age(value): if not value or ':' not in value: return None try: return float(value.split(':')[1].strip()) except: return None # Gender: Available in feature 7 'Sex' gender_row = 7 def convert_gender(value): if not value or ':' not in value: return None val = value.split(':')[1].strip() if val == 'F': return 0 elif val == 'M': return 1 return None # 3. 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) # 4. Clinical Feature Extraction selected_clinical = geo_select_clinical_features(clinical_data, trait, trait_row, convert_trait, age_row, convert_age, gender_row, convert_gender) print("Preview of selected clinical features:") print(preview_df(selected_clinical)) selected_clinical.to_csv(out_clinical_data_file) # 1. Normalize gene symbols gene_data = normalize_gene_symbols_in_index(gene_data) # Save normalized gene data gene_data.to_csv(out_gene_data_file) # 2. Link clinical and genetic data try: clinical_data = pd.read_csv(out_clinical_data_file, index_col=0) linked_data = geo_link_clinical_genetic_data(clinical_data, gene_data) # 3. Handle missing values linked_data = handle_missing_values(linked_data, trait) # 4. Determine if features are biased is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait) # 5. Validate and save cohort info is_usable = validate_and_save_cohort_info( is_final=True, cohort=cohort, info_path=json_path, is_gene_available=True, is_trait_available=True, is_biased=is_trait_biased, df=linked_data, note="Gene expression data successfully mapped and linked with clinical features" ) # 6. Save linked data only if usable AND trait is not biased if is_usable and not is_trait_biased: linked_data.to_csv(out_data_file) except Exception as e: print(f"Error in data linking and processing: {str(e)}") is_usable = validate_and_save_cohort_info( is_final=True, cohort=cohort, info_path=json_path, is_gene_available=True, is_trait_available=True, is_biased=True, df=pd.DataFrame(), note=f"Data processing failed: {str(e)}" )