Liu-Hy's picture
Add files using upload-large-folder tool
dc810d0 verified
raw
history blame
9.42 kB
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Schizophrenia"
cohort = "GSE145554"
# Input paths
in_trait_dir = "../DATA/GEO/Schizophrenia"
in_cohort_dir = "../DATA/GEO/Schizophrenia/GSE145554"
# Output paths
out_data_file = "./output/preprocess/1/Schizophrenia/GSE145554.csv"
out_gene_data_file = "./output/preprocess/1/Schizophrenia/gene_data/GSE145554.csv"
out_clinical_data_file = "./output/preprocess/1/Schizophrenia/clinical_data/GSE145554.csv"
json_path = "./output/preprocess/1/Schizophrenia/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)
# 1. Determine if this dataset likely contains gene expression data
is_gene_available = True # Based on the background info, it uses microarray mRNA
# 2.1 Identify data availability for 'trait', 'age', 'gender'
# From the sample characteristics dictionary:
# 0 => ['disease state: schizophrenia', 'disease state: control']
# 1 => ['Sex: Male', 'Sex: Female']
# 3 => ['age: 63', 'age: 90', ...]
trait_row = 0
age_row = 3
gender_row = 1
# 2.2 Define data conversion functions
def _parse_after_colon(value: str) -> str:
"""Helper to parse the substring after the first colon."""
parts = value.split(':', 1)
if len(parts) == 2:
return parts[1].strip()
return parts[0].strip()
def convert_trait(x):
val = _parse_after_colon(x)
val_lower = val.lower()
if 'schizophrenia' in val_lower:
return 1
elif 'control' in val_lower:
return 0
return None
def convert_age(x):
val = _parse_after_colon(x)
try:
return float(val)
except ValueError:
return None
def convert_gender(x):
val = _parse_after_colon(x).lower()
if 'male' in val:
return 1
elif 'female' in val:
return 0
return None
# 3. Initial filtering and metadata saving
is_trait_available = (trait_row is not None)
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 available
if trait_row is not None:
selected_clinical_df = geo_select_clinical_features(
clinical_df=clinical_data, # assume 'clinical_data' is already loaded
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 and save
preview_dict = preview_df(selected_clinical_df)
selected_clinical_df.to_csv(out_clinical_data_file, index=False)
# STEP3
import gzip
import pandas as pd
try:
# 1. Attempt to extract gene expression data using the library function
gene_data = get_genetic_data(matrix_file)
except KeyError:
# Fallback: the expected "ID_REF" column may be absent, so manually parse the file
# and rename the first column to "ID".
marker = "!series_matrix_table_begin"
skip_rows = None
# Determine how many rows to skip before the matrix data begins
with gzip.open(matrix_file, 'rt') as f:
for i, line in enumerate(f):
if marker in line:
skip_rows = i + 1
break
else:
raise ValueError(f"Marker '{marker}' not found in the file.")
# Read the data from the determined position
gene_data = pd.read_csv(
matrix_file,
compression='gzip',
skiprows=skip_rows,
comment='!',
delimiter='\t',
on_bad_lines='skip'
)
# If a different column name is used instead of 'ID_REF', rename appropriately
if 'ID_REF' in gene_data.columns:
gene_data.rename(columns={'ID_REF': 'ID'}, inplace=True)
else:
first_col = gene_data.columns[0]
gene_data.rename(columns={first_col: 'ID'}, inplace=True)
gene_data['ID'] = gene_data['ID'].astype(str)
gene_data.set_index('ID', inplace=True)
# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
print(gene_data.index[:20])
# Based on biological knowledge, the identifiers (e.g., '7892501') are numeric and do not match standard human gene symbols.
# Therefore, they require additional mapping to human gene symbols.
print("requires_gene_mapping = True")
# STEP5
# 1 & 2. Only extract and preview gene annotation data if the SOFT file exists, otherwise skip.
if soft_file is None:
print("No SOFT file found. Skipping gene annotation extraction.")
gene_annotation = pd.DataFrame()
else:
try:
# Attempt to extract gene annotation with the default method
gene_annotation = get_gene_annotation(soft_file)
except UnicodeDecodeError:
# Fallback if UTF-8 decoding fails: read with a more lenient encoding and pass the content as a string
import gzip
with gzip.open(soft_file, 'rt', encoding='latin-1', errors='replace') as f:
content = f.read()
gene_annotation = filter_content_by_prefix(
content,
prefixes_a=['^','!','#'],
unselect=True,
source_type='string',
return_df_a=True
)[0]
print("Gene annotation preview:")
print(preview_df(gene_annotation))
# STEP: Gene Identifier Mapping
# 1. Decide which column in the gene annotation matches the probe IDs in our expression data
# and which column stores the gene symbols. From the preview, the annotation "ID" column
# clearly matches the numeric identifiers in the expression data, and "gene_assignment"
# has gene symbol information.
probe_col = 'ID'
gene_symbol_col = 'gene_assignment'
# 2. Create a gene mapping dataframe
mapping_df = get_gene_mapping(annotation=gene_annotation,
prob_col=probe_col,
gene_col=gene_symbol_col)
# 3. Apply the mapping to convert probe-level data to gene-level data
gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
# (Optional) Inspect the resulting gene_data
print("Mapped gene_data shape:", gene_data.shape)
print("Sample of mapped gene symbols:", gene_data.index[:20].tolist())
import os
import pandas as pd
# STEP 7: Data Normalization and Linking
# First, check if the clinical CSV file exists. If it does not, we cannot proceed with trait-based linking.
if not os.path.exists(out_clinical_data_file):
# No trait data file => dataset is not usable for trait analysis
df_null = pd.DataFrame()
is_biased = True # Arbitrary boolean to satisfy function requirement
validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=True,
is_trait_available=False,
is_biased=is_biased,
df=df_null,
note="No trait data file found; dataset not usable for trait analysis."
)
else:
# 1. Normalize the mapped gene expression data using known gene symbol synonyms, then save.
normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
normalized_gene_data.to_csv(out_gene_data_file)
# 2. Load the previously extracted clinical CSV.
selected_clinical_df = pd.read_csv(out_clinical_data_file)
# If we had a single-row trait, rename row 0 to the trait name (example usage).
selected_clinical_df = selected_clinical_df.rename(index={0: trait})
# Combine these as our final clinical data; in this dataset, we only have trait info (if any).
combined_clinical_df = selected_clinical_df
# Link the clinical and genetic data by matching sample IDs in columns.
linked_data = geo_link_clinical_genetic_data(combined_clinical_df, normalized_gene_data)
# 3. Handle missing values in the linked data (drop incomplete rows/columns, then impute).
processed_data = handle_missing_values(linked_data, trait)
# 4. Check trait bias and remove any biased demographic features (if any).
trait_biased, processed_data = judge_and_remove_biased_features(processed_data, trait)
# 5. Final validation and metadata saving.
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=processed_data,
note="Completed trait-based preprocessing."
)
# 6. If final dataset is usable, save. Otherwise, skip.
if is_usable:
processed_data.to_csv(out_data_file)