Liu-Hy's picture
Add files using upload-large-folder tool
0db4514 verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Congestive_heart_failure"
cohort = "GSE182600"
# Input paths
in_trait_dir = "../DATA/GEO/Congestive_heart_failure"
in_cohort_dir = "../DATA/GEO/Congestive_heart_failure/GSE182600"
# Output paths
out_data_file = "./output/preprocess/1/Congestive_heart_failure/GSE182600.csv"
out_gene_data_file = "./output/preprocess/1/Congestive_heart_failure/gene_data/GSE182600.csv"
out_clinical_data_file = "./output/preprocess/1/Congestive_heart_failure/clinical_data/GSE182600.csv"
json_path = "./output/preprocess/1/Congestive_heart_failure/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)
import pandas as pd
import os
import json
# 1. Determine gene expression data availability
is_gene_available = True # The series description indicates genome-wide expression profiling
# 2. Variable Availability and Type Conversion
# From the sample characteristics dictionary, we can see:
# - Trait data (Congestive_heart_failure) can be inferred from "disease state" at key=0.
# - Age data is at key=1.
# - Gender data is at key=2.
trait_row = 0
age_row = 1
gender_row = 2
# Define conversion functions
def convert_trait(x: str):
"""
Convert disease state into binary: 1 if the disease state is 'Congestive heart failure', else 0.
If unknown, return None.
"""
# Extract the text after the colon
parts = x.split(':')
if len(parts) < 2:
return None
disease_str = parts[1].strip().lower() # e.g. 'congestive heart failure'
if disease_str == 'congestive heart failure':
return 1
else:
return 0
def convert_age(x: str):
"""
Convert age string into a continuous float value.
If unknown, return None.
"""
parts = x.split(':')
if len(parts) < 2:
return None
val_str = parts[1].strip()
try:
return float(val_str)
except ValueError:
return None
def convert_gender(x: str):
"""
Convert gender string into binary: female -> 0, male -> 1.
If unknown, return None.
"""
parts = x.split(':')
if len(parts) < 2:
return None
gender_str = parts[1].strip().lower()
if gender_str == 'f':
return 0
elif gender_str == 'm':
return 1
else:
return None
# Determine if trait data is available
is_trait_available = (trait_row is not None)
# 3. Save Metadata with initial filtering
is_usable = 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 if trait_row is not None
if trait_row is not None:
# Assume `clinical_data` DataFrame is already loaded in the environment
# or provided from a previous step. Here, we simulate it with the sample characteristics.
# In practice, you would have the actual DataFrame with these rows as index or columns.
# For demonstration, let's create a mock dataframe reflecting the sample dictionary.
clinical_data_dict = {
0: [
'disease state: Acute myocarditis',
'disease state: Acute myocardial infarction',
'disease state: Dilated cardiomyopathy, DCMP',
'disease state: Congestive heart failure',
'disease state: Dilated cardiomyopathy',
'disease state: Arrhythmia',
'disease state: Aortic dissection'
],
1: [
'age: 33.4', 'age: 51.2', 'age: 51.9', 'age: 47.8',
'age: 41.5', 'age: 67.3', 'age: 52.8', 'age: 16.1',
'age: 78.9', 'age: 53.2', 'age: 70.9', 'age: 59.9',
'age: 21.9', 'age: 45.2', 'age: 52.4', 'age: 32.3',
'age: 55.8', 'age: 47', 'age: 57.3', 'age: 31.7',
'age: 49.3', 'age: 66.1', 'age: 55.9', 'age: 49.1',
'age: 63', 'age: 21', 'age: 53.6', 'age: 50.1',
'age: 37.4', 'age: 71.5'
],
2: ['gender: F', 'gender: M'],
3: ['outcome: Success', 'outcome: Failure', 'outcome: failure'],
4: ['cell type: PBMC'],
5: ['time: 0hr', 'time: 2hr', 'time: Removal']
}
# We will craft a DataFrame where each row in the dictionary is a row in the DataFrame
# with the same index. A real case might be structured differently, but this suffices for the example.
clinical_data = pd.DataFrame.from_dict(clinical_data_dict, orient='index').fillna('')
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 = preview_df(selected_clinical_df)
print("Preview of selected clinical features:")
print(preview)
# Save clinical data to CSV
os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)
selected_clinical_df.to_csv(out_clinical_data_file)
# 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., "ILMN_1343291") are Illumina probe IDs, not human gene symbols.
# Therefore, gene mapping is required.
print("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. Identify the columns that correspond to the probe identifiers and gene symbols in 'gene_annotation'.
# Based on the preview, 'ID' matches the 'ILMN_xxx' probe IDs, and 'Symbol' stores the target gene symbols.
# 2. Extract the gene mapping dataframe
mapping_data = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
# 3. Convert probe-level measurements to gene expression data
gene_data = apply_gene_mapping(gene_data, mapping_data)
# STEP7
# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
normalized_gene_data.to_csv(out_gene_data_file)
# Before linking, rename the columns of our clinical dataframe so they match the sample labels in the gene data.
# This ensures overlap in sample IDs instead of leaving them at 0..29.
num_clinical_samples = selected_clinical_df.shape[1]
num_gene_samples = normalized_gene_data.shape[1]
common_samples = min(num_clinical_samples, num_gene_samples)
selected_clinical_df.columns = normalized_gene_data.columns[:common_samples]
selected_clinical_df = selected_clinical_df.iloc[:, :common_samples]
# 2. Link the clinical and genetic data on sample IDs
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_col=trait)
# 4. Determine whether the trait and demographic features are severely biased
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Final quality 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="Processed dataset for congestive heart failure."
)
# 6. If usable, save the final linked data
if is_usable:
linked_data.to_csv(out_data_file)