Liu-Hy's picture
Add files using upload-large-folder tool
b5650f0 verified
raw
history blame
7.59 kB
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Crohns_Disease"
cohort = "GSE186582"
# Input paths
in_trait_dir = "../DATA/GEO/Crohns_Disease"
in_cohort_dir = "../DATA/GEO/Crohns_Disease/GSE186582"
# Output paths
out_data_file = "./output/preprocess/1/Crohns_Disease/GSE186582.csv"
out_gene_data_file = "./output/preprocess/1/Crohns_Disease/gene_data/GSE186582.csv"
out_clinical_data_file = "./output/preprocess/1/Crohns_Disease/clinical_data/GSE186582.csv"
json_path = "./output/preprocess/1/Crohns_Disease/cohort_info.json"
# STEP1
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 1. Determine whether the dataset likely contains gene expression data
is_gene_available = True # Based on the microarray-based gene expression description
# Step 2. Identify data availability and define conversion functions
# 2.1 Identify the sample characteristics rows
# The dictionary indicates:
# 0 -> location: {M6, M0I, M0M, Ctrl}
# 1 -> gender: {Female, Male}
# 2 -> smoking: {Yes, No, Ctrl}
# 3 -> postoperative anti tnf treatment: {No, Yes, Ctrl}
# 4 -> rutgeerts: {0, i2b, 1, Ctrl, i2a, i3, i4}
# 5 -> rutgeertrec: {Rem, Rec, Ctrl}
# We will use row 0 to encode Crohn's disease presence (1) vs control (0).
# Gender data is in row 1. No age information is found.
trait_row = 0 # "location: M6 / M0I / M0M" => CD, "location: Ctrl" => control
age_row = None # No age information found
gender_row = 1 # "gender: Female / Male"
# 2.1 Determine trait data availability
# We have a row for the trait, so it is available
is_trait_available = (trait_row is not None)
# 2.2 Define data type conversion functions
def convert_trait(x: str) -> int:
"""
Convert the location string into a binary indicator of Crohn's disease: 1 for CD, 0 for control.
"""
# Parse the portion after the colon
parts = x.split(":")
if len(parts) < 2:
return None
value = parts[1].strip() # e.g. M6, M0I, M0M, or Ctrl
if value == "Ctrl":
return 0
else:
return 1
# Since there's no age row, we don't define convert_age (we will pass None)
def convert_gender(x: str) -> int:
"""
Convert the gender string into a binary indicator: 0 for female, 1 for male.
"""
# Parse the portion after the colon
parts = x.split(":")
if len(parts) < 2:
return None
value = parts[1].strip() # e.g. Female or Male
if value.lower() == "female":
return 0
elif value.lower() == "male":
return 1
else:
return None
# Step 3. Save metadata (initial filtering)
# If either gene or trait is unavailable, the dataset is filtered out at this stage.
# Otherwise, we continue preprocessing. is_final=False means we perform only initial filtering.
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. If trait data is available, extract clinical features
if trait_row is not None:
# Assume 'clinical_data' is the DataFrame we obtained for sample characteristics
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=None,
gender_row=gender_row,
convert_gender=convert_gender
)
# Observe the output
previewed = preview_df(selected_clinical_df)
print("Preview of selected clinical data:", previewed)
# Save to CSV
selected_clinical_df.to_csv(out_clinical_data_file, index=False)
# STEP3
# 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])
# These identifiers (e.g., "1053_at", "1552256_a_at") appear to be Affymetrix microarray probe set IDs.
# They do not represent human gene symbols. Therefore, we need to map them to gene symbols.
requires_gene_mapping = True
# STEP5
# 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: Gene Identifier Mapping
# 1. From the preview of the gene annotation dataframe, we see that "ID" matches the probe identifiers
# (e.g. "1053_at"), and "Gene Symbol" contains the actual gene symbols.
probe_column = "ID"
symbol_column = "Gene Symbol"
# 2. Build the gene mapping dataframe using our predefined library function
mapping_df = get_gene_mapping(
annotation=gene_annotation,
prob_col=probe_column,
gene_col=symbol_column
)
# 3. Convert probe-level measurements (gene_data) into gene-level expression data
gene_data = apply_gene_mapping(
expression_df=gene_data,
mapping_df=mapping_df
)
# Print a summary of the resulting gene expression data
print("Converted gene expression data shape:", gene_data.shape)
print("Head of the gene expression data:\n", gene_data.head())
import os
import pandas as pd
# 1) Normalize gene symbols in the obtained gene expression data
normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
normalized_gene_data.to_csv(out_gene_data_file)
# 2) Read the clinical DataFrame in a way that preserves the feature names as the row index
# and sample IDs as columns. Since we saved it with index=False previously, the first column
# in the CSV is now an unnamed index column, which we can use for the DF index.
selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
# 3) Link the clinical and genetic data
linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
# 4) Handle missing values in the linked data
linked_data = handle_missing_values(linked_data, trait)
# 5) Check for biased features (including the trait)
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 6) Final validation and saving metadata
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=trait_biased,
df=linked_data,
note="Data from GSE186582, trait is Crohn's disease."
)
# 7) If the dataset is usable, save the linked data
if is_usable:
linked_data.to_csv(out_data_file)