Liu-Hy's picture
Add files using upload-large-folder tool
1f52ac2 verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Mesothelioma"
cohort = "GSE163720"
# Input paths
in_trait_dir = "../DATA/GEO/Mesothelioma"
in_cohort_dir = "../DATA/GEO/Mesothelioma/GSE163720"
# Output paths
out_data_file = "./output/preprocess/3/Mesothelioma/GSE163720.csv"
out_gene_data_file = "./output/preprocess/3/Mesothelioma/gene_data/GSE163720.csv"
out_clinical_data_file = "./output/preprocess/3/Mesothelioma/clinical_data/GSE163720.csv"
json_path = "./output/preprocess/3/Mesothelioma/cohort_info.json"
# Get file paths
soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)
# Get background info and clinical data
background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)
print("Background Information:")
print(background_info)
print("\nSample Characteristics:")
# Get dictionary of unique values per row
unique_values_dict = get_unique_values_by_row(clinical_data)
for row, values in unique_values_dict.items():
print(f"\n{row}:")
print(values)
# 1. Gene Expression Data Availability
# From background info, this is a microarray study of gene expression, particularly RERG
is_gene_available = True
# 2.1 Data Availability
# Trait (mesothelioma) is constant for all samples so not available
trait_row = None
# Age is not available in sample characteristics
age_row = None
# Gender data available in row 2
gender_row = 2
# 2.2 Data Type Conversion Functions
def convert_trait(x):
return None # Not used since trait_row is None
def convert_age(x):
return None # Not used since age_row is None
def convert_gender(x):
if not isinstance(x, str):
return None
val = x.split(': ')[-1].strip().upper()
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=False # trait_row is None
)
# 4. Clinical Feature Extraction
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 the extracted clinical features
preview = preview_df(clinical_df)
print("Preview of clinical features:")
print(preview)
# Save clinical data
clinical_df.to_csv(out_clinical_data_file)
# Get gene expression data from matrix file
genetic_data = get_genetic_data(matrix_file_path)
# Examine data structure
print("Data structure and head:")
print(genetic_data.head())
print("\nShape:", genetic_data.shape)
print("\nFirst 20 row IDs (gene/probe identifiers):")
print(list(genetic_data.index)[:20])
# Get a few column names to verify sample IDs
print("\nFirst 5 column names:")
print(list(genetic_data.columns)[:5])
# The IDs start with "7892" which appear to be probe identifiers rather than gene symbols
# Common in microarray data, these would need to be mapped to human gene symbols
requires_gene_mapping = True
# Extract gene annotation data
gene_annotation = get_gene_annotation(soft_file_path)
# Display column names and preview data
print("Column names:")
print(gene_annotation.columns)
print("\nPreview of gene annotation data:")
print(preview_df(gene_annotation))
# 1. Based on observation, the probe IDs in the expression data match 'ID' in the annotation,
# and gene symbols are contained in 'gene_assignment'
prob_col = 'ID'
gene_col = 'gene_assignment'
# 2. Get gene mapping dataframe from the annotation
mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)
# 3. Apply mapping to convert probe level data to gene level expression data
gene_data = apply_gene_mapping(genetic_data, mapping_df)
# Preview results
print("Mapping summary:")
print("Number of probes in mapping:", len(mapping_df))
print("\nResulting gene expression data shape:", gene_data.shape)
print("\nFirst 5 genes and their expression values:")
print(gene_data.head())
# 1. Normalize gene symbols
normalized_genetic_data = normalize_gene_symbols_in_index(genetic_data)
normalized_genetic_data.to_csv(out_gene_data_file)
# Since clinical data is not usable (constant trait), create empty clinical data with Gender only
clinical_df = pd.DataFrame({'Gender': [0 if x == 'Sex: F' else 1 for x in clinical_data.iloc[2]]},
index=clinical_data.columns[1:])
# 2. Link clinical and genetic data
linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_genetic_data)
# 3. Handle missing values systematically
linked_data = handle_missing_values(linked_data, 'Gender')
# 4. Check for bias in demographic features
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, 'Gender')
# 5. Final validation and information saving
note = "Dataset contains only tumor samples without a control group, making it unsuitable for associational studies."
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=True,
is_trait_available=False, # Constant trait (all tumor samples)
is_biased=True, # Dataset is biased by design
df=linked_data,
note=note
)
# 6. Skip saving linked data since dataset is not usable (is_usable will be False)
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
linked_data.to_csv(out_data_file)
# 1. Normalize gene symbols using gene expression data from previous step
normalized_genetic_data = normalize_gene_symbols_in_index(genetic_data)
normalized_genetic_data.to_csv(out_gene_data_file)
# Create clinical data with only Gender available
clinical_df = pd.DataFrame({'Gender': [0 if x == 'Sex: F' else 1 for x in clinical_data.iloc[2]]},
index=clinical_data.columns[1:])
# 2. Link clinical and genetic data
linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_genetic_data)
# 3. Handle missing values systematically
linked_data = handle_missing_values(linked_data, 'Gender')
# 4. Check for bias in demographic features
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, 'Gender')
# 5. Final validation and information saving
note = "Dataset contains only tumor samples without a control group, making it unsuitable for associational studies."
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=True,
is_trait_available=False, # No trait data available
is_biased=True, # Dataset is biased by design
df=linked_data,
note=note
)
# 6. Skip saving linked data since dataset is not usable
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
linked_data.to_csv(out_data_file)
# Get gene expression data from matrix file
genetic_data = get_genetic_data(matrix_file_path)
# Examine data structure
print("Data structure and head:")
print(genetic_data.head())
print("\nShape:", genetic_data.shape)
print("\nFirst 20 row IDs (gene/probe identifiers):")
print(list(genetic_data.index)[:20])
# Get a few column names to verify sample IDs
print("\nFirst 5 column names:")
print(list(genetic_data.columns)[:5])
# Load gene annotation data
gene_annotation = get_gene_annotation(soft_file_path)
# Get gene expression data
genetic_data = get_genetic_data(matrix_file_path)
# 1. Based on observation, the probe IDs in the expression data match 'ID' in the annotation,
# and gene symbols are contained in 'gene_assignment'
prob_col = 'ID'
gene_col = 'gene_assignment'
# 2. Get gene mapping dataframe from the annotation
mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)
# 3. Apply mapping to convert probe level data to gene level expression data
gene_data = apply_gene_mapping(genetic_data, mapping_df)
# Preview results
print("Mapping summary:")
print("Number of probes in mapping:", len(mapping_df))
print("\nResulting gene expression data shape:", gene_data.shape)
print("\nFirst 5 genes and their expression values:")
print(gene_data.head())
# Convert probe-level to gene-level data
gene_data = apply_gene_mapping(genetic_data, mapping_df)
# 1. Normalize gene symbols
genetic_data = normalize_gene_symbols_in_index(gene_data)
genetic_data.to_csv(out_gene_data_file)
# Create clinical data with Gender only
clinical_df = pd.DataFrame({'Gender': [0 if x == 'Sex: F' else 1 for x in clinical_data.iloc[2]]},
index=clinical_data.columns[1:])
# 2. Link clinical and genetic data
linked_data = geo_link_clinical_genetic_data(clinical_df, genetic_data)
# 3. Handle missing values systematically
linked_data = handle_missing_values(linked_data, 'Gender')
# 4. Check for bias in demographic features
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, 'Gender')
# 5. Final validation and information saving
note = "Dataset contains only tumor samples without a control group, making it unsuitable for associational studies."
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=True,
is_trait_available=False, # No trait data available
is_biased=True, # Dataset is biased by design
df=linked_data,
note=note
)
# 6. Skip saving linked data since dataset is not usable
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
linked_data.to_csv(out_data_file)
# Get gene expression data from matrix file
genetic_data = get_genetic_data(matrix_file_path)
# Examine data structure
print("Data structure and head:")
print(genetic_data.head())
print("\nShape:", genetic_data.shape)
print("\nFirst 20 row IDs (gene/probe identifiers):")
print(list(genetic_data.index)[:20])
# Get a few column names to verify sample IDs
print("\nFirst 5 column names:")
print(list(genetic_data.columns)[:5])
# 1. Normalize gene symbols
genetic_data = normalize_gene_symbols_in_index(gene_data)
genetic_data.to_csv(out_gene_data_file)
# 2. Link clinical and genetic data
linked_data = geo_link_clinical_genetic_data(clinical_features, genetic_data)
# 3. Handle missing values systematically
linked_data = handle_missing_values(linked_data, trait)
# 4. Check for bias in trait and demographic features
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Final validation and information saving
note = "Dataset contains only tumor samples without a control group, making it unsuitable for associational studies."
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, # Force biased=True since all samples are tumor samples
df=linked_data,
note=note
)
# 6. Save linked data only if usable (which won't happen since is_biased=True)
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
linked_data.to_csv(out_data_file)