Liu-Hy's picture
Add files using upload-large-folder tool
13fd1a3 verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "COVID-19"
cohort = "GSE275334"
# Input paths
in_trait_dir = "../DATA/GEO/COVID-19"
in_cohort_dir = "../DATA/GEO/COVID-19/GSE275334"
# Output paths
out_data_file = "./output/preprocess/3/COVID-19/GSE275334.csv"
out_gene_data_file = "./output/preprocess/3/COVID-19/gene_data/GSE275334.csv"
out_clinical_data_file = "./output/preprocess/3/COVID-19/clinical_data/GSE275334.csv"
json_path = "./output/preprocess/3/COVID-19/cohort_info.json"
# Get file paths for SOFT and matrix files
soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)
# Get background info and clinical data from the matrix file
background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)
# Create dictionary of unique values for each feature
unique_values_dict = get_unique_values_by_row(clinical_data)
# Print the information
print("Dataset Background Information:")
print(background_info)
print("\nSample Characteristics:")
for feature, values in unique_values_dict.items():
print(f"\n{feature}:")
print(values)
# 1. Gene Expression Data Availability
# Yes, contains NanoString gene expression data from immune exhaustion panel
is_gene_available = True
# 2. Variable Availability and Keys
trait_row = 3 # 'disease' field contains trait data
age_row = 1 # 'age (years)' field contains age data
gender_row = 2 # 'Sex' field contains gender data
# 2.2 Data Type Conversion Functions
def convert_trait(value: str) -> int:
"""Convert COVID-19 status to binary. Long COVID=1, others=0"""
if pd.isna(value) or ':' not in value:
return None
value = value.split(':')[1].strip().lower()
if 'long covid' in value:
return 1
elif value in ['healthy control', 'me/cfs']:
return 0
return None
def convert_age(value: str) -> float:
"""Convert age to float"""
if pd.isna(value) or ':' not in value:
return None
try:
return float(value.split(':')[1].strip())
except:
return None
def convert_gender(value: str) -> int:
"""Convert gender to binary. Female=0, Male=1"""
if pd.isna(value) or ':' not in value:
return None
value = value.split(':')[1].strip().lower()
if value == 'female':
return 0
elif value == 'male':
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. Extract Clinical Features
if trait_row is not None:
clinical_features = 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 features
print("Preview of clinical features:")
print(preview_df(clinical_features))
# Save to CSV
clinical_features.to_csv(out_clinical_data_file)
# Extract genetic data matrix
genetic_data = get_genetic_data(matrix_file_path)
# Print first few rows with column names to examine data structure
print("Data preview:")
print("\nColumn names:")
print(list(genetic_data.columns)[:5])
print("\nFirst 5 rows:")
print(genetic_data.head())
print("\nShape:", genetic_data.shape)
# Verify this is gene expression data and check identifiers
is_gene_available = True
# Save updated metadata
validate_and_save_cohort_info(
is_final=False,
cohort=cohort,
info_path=json_path,
is_gene_available=is_gene_available,
is_trait_available=(trait_row is not None)
)
# Save gene expression data
genetic_data.to_csv(out_gene_data_file)
requires_gene_mapping = False
# 1. Normalize gene symbols and save gene data
normalized_gene_data = normalize_gene_symbols_in_index(genetic_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
clinical_features = pd.read_csv(out_clinical_data_file, index_col=0).T
linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)
# Verify data integrity
print("Linked data shape:", linked_data.shape)
print("\nAvailable columns:")
print(list(linked_data.columns)[:10])
print("\nSample preview:")
print(linked_data.head())
# 3. Handle missing values
linked_data = handle_missing_values(linked_data, trait)
# 4. Judge bias in features and remove biased ones
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Final validation and save metadata
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=True,
is_biased=trait_biased,
df=linked_data,
note="NanoString gene expression data comparing long COVID cases with healthy controls and ME/CFS."
)
# 6. Save linked data if usable
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
linked_data.to_csv(out_data_file)
# Since data already contains proper gene symbols, skip mapping and use original genetic data
gene_data = genetic_data
print("Gene mapping skipped - data already contains proper gene symbols")
print(f"Shape of gene expression data: {gene_data.shape}")
print("\nFirst few gene symbols:")
print(list(gene_data.index)[:10])
# Extract gene annotation data
gene_metadata = get_gene_annotation(soft_file_path)
# Preview column names and first few values
preview = preview_df(gene_metadata)
print("\nGene annotation columns and sample values:")
print(preview)
# Extract gene annotation data
gene_metadata = get_gene_annotation(soft_file_path)
# Print column names and first few rows for verification
print("Gene annotation data preview:")
print("Columns:", list(gene_metadata.columns))
print("\nFirst few rows:")
print(gene_metadata.head())
# Get mapping between gene IDs and gene symbols (ID maps to itself since already symbols)
mapping_df = get_gene_mapping(gene_metadata, "ID", "ID")
# Convert index to string type
gene_data = genetic_data.copy()
gene_data.index = gene_data.index.astype(str)
print("\nFirst 10 gene symbols in expression data:")
print(list(gene_data.index)[:10])
print("\nShape of gene expression data:")
print(gene_data.shape)
# 1. Normalize gene symbols and save gene data
normalized_gene_data = normalize_gene_symbols_in_index(genetic_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
clinical_features = pd.read_csv(out_clinical_data_file, index_col=0).T
linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)
# 3. Handle missing values
linked_data = handle_missing_values(linked_data, trait)
# 4. Judge bias in features and remove biased ones
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Final validation and save metadata
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=True,
is_biased=trait_biased,
df=linked_data,
note="NanoString gene expression data comparing long COVID cases with healthy controls and ME/CFS."
)
# 6. Save linked data if usable
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
linked_data.to_csv(out_data_file)
print("Missing critical input. Please provide:")
print("1. Output of previous step containing sample characteristics dictionary")
print("2. Background information about the dataset")
# Get file paths for SOFT and matrix files
soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)
# Get background info and clinical data from the matrix file
background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)
# Create dictionary of unique values for each feature
unique_values_dict = get_unique_values_by_row(clinical_data)
# Print the information
print("Dataset Background Information:")
print(background_info)
print("\nSample Characteristics:")
for feature, values in unique_values_dict.items():
print(f"\n{feature}:")
print(values)
# 1. Gene Expression Data Availability
# Yes, this dataset contains gene expression data according to the background info
is_gene_available = True
# 2.1 Data Availability
trait_row = 3 # 'disease' row contains trait info
age_row = 1 # age is available
gender_row = 2 # gender info is in 'Sex' field
# 2.2 Data Type Conversion Functions
def convert_trait(x):
"""Convert trait values to binary (0 for control, 1 for case)"""
if not x or ':' not in x:
return None
value = x.split(':')[1].strip()
if value == 'Healthy control':
return 0
elif value in ['Long COVID', 'ME/CFS']:
return 1
return None
def convert_age(x):
"""Convert age values to continuous numeric"""
if not x or ':' not in x:
return None
try:
return float(x.split(':')[1].strip())
except:
return None
def convert_gender(x):
"""Convert gender values to binary (0 for female, 1 for male)"""
if not x or ':' not in x:
return None
value = x.split(':')[1].strip()
if value == 'Female':
return 0
elif value == 'Male':
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=trait_row is not None)
# 4. Clinical Feature Extraction
selected_clinical = 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 features
preview_result = preview_df(selected_clinical)
print("Preview of extracted clinical features:")
print(preview_result)
# Save clinical data
selected_clinical.to_csv(out_clinical_data_file)
# Extract genetic data matrix
genetic_data = get_genetic_data(matrix_file_path)
# Print first few rows with column names to examine data structure
print("Data preview:")
print("\nColumn names:")
print(list(genetic_data.columns)[:5])
print("\nFirst 5 rows:")
print(genetic_data.head())
print("\nShape:", genetic_data.shape)
# Verify this is gene expression data and check identifiers
is_gene_available = True
# Save updated metadata
validate_and_save_cohort_info(
is_final=False,
cohort=cohort,
info_path=json_path,
is_gene_available=is_gene_available,
is_trait_available=(trait_row is not None)
)
# Save gene expression data
genetic_data.to_csv(out_gene_data_file)
# Based on gene identifiers like ACACA, ACADVL, ACAT2 - these appear to be standard human gene symbols
# No mapping required as they are already in the correct format
requires_gene_mapping = False
# 1. Normalize gene symbols and save gene data
normalized_gene_data = normalize_gene_symbols_in_index(genetic_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
clinical_features = pd.read_csv(out_clinical_data_file, index_col=0).T
linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)
# Rename trait column to match the trait variable
linked_data = linked_data.rename(columns={'COVID-19': trait})
# 3. Handle missing values
linked_data = handle_missing_values(linked_data, trait)
# 4. Judge bias in features and remove biased ones
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Final validation and save metadata
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=True,
is_biased=trait_biased,
df=linked_data,
note="NanoString gene expression data comparing long COVID cases with healthy controls and ME/CFS patients."
)
# 6. Save linked data if usable
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
linked_data.to_csv(out_data_file)
clinical_data = pd.read_csv("../DATA/GEO/COVID-19/GSE275334/sample_characteristics.csv", index_col=0) # Load data from previous step
sample_info = preview_df(clinical_data)
print(sample_info)
# Based on log2 expression data seen in previous step
is_gene_available = True
# Based on sample characteristics review
trait_row = 9 # critical status
age_row = 5 # age row
gender_row = 6 # gender row
def convert_trait(x):
if x is None:
return None
x = str(x).lower().split(':')[-1].strip()
if 'critical' in x:
return 1
elif 'non-critical' in x:
return 0
return None
def convert_age(x):
if x is None:
return None
try:
age = float(str(x).split(':')[-1].strip())
return age
except:
return None
def convert_gender(x):
if x is None:
return None
x = str(x).lower().split(':')[-1].strip()
if 'female' in x or 'f' in x:
return 0
elif 'male' in x or 'm' in x:
return 1
return None
# 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=(trait_row is not None)
)
# Extract clinical features since trait data is available
clinical_features = 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 extracted features
print("\nExtracted clinical features:")
print(preview_df(clinical_features))
# Save clinical data
clinical_features.to_csv(out_clinical_data_file)