Liu-Hy's picture
Add files using upload-large-folder tool
ff3b0fa verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Epilepsy"
cohort = "GSE199759"
# Input paths
in_trait_dir = "../DATA/GEO/Epilepsy"
in_cohort_dir = "../DATA/GEO/Epilepsy/GSE199759"
# Output paths
out_data_file = "./output/preprocess/3/Epilepsy/GSE199759.csv"
out_gene_data_file = "./output/preprocess/3/Epilepsy/gene_data/GSE199759.csv"
out_clinical_data_file = "./output/preprocess/3/Epilepsy/clinical_data/GSE199759.csv"
json_path = "./output/preprocess/3/Epilepsy/cohort_info.json"
# Get paths to the SOFT and matrix files
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Get background info and clinical data from matrix file
background_info, clinical_data = get_background_and_clinical_data(matrix_file)
# Get unique values for each feature (row) in clinical data
unique_values_dict = get_unique_values_by_row(clinical_data)
# Print background info
print("=== Dataset Background Information ===")
print(background_info)
print("\n=== Sample Characteristics ===")
print(json.dumps(unique_values_dict, indent=2))
# 1. Gene expression data availability
is_gene_available = True # Yes - Series has mRNA data from Agilent LncRNA+mRNA Human Gene Expression Microarray
# 2.1 Row identifiers for clinical variables
# From sample characteristics dict:
# trait - not explicitly given in sample characteristics
# gender - key 1 has gender data
# age - key 2 has age data
trait_row = None # Not in sample characteristics
gender_row = 1
age_row = 2
# 2.2 Data type conversion functions
def convert_trait(value):
# Not used since trait data not in sample characteristics
return None
def convert_gender(value):
# Extract value after colon and convert to binary
if not value or ':' not in value:
return None
gender = value.split(':')[1].strip().lower()
if gender == 'female':
return 0
elif gender == 'male':
return 1
return None
def convert_age(value):
# Extract number from strings like "age: 39y"
if not value or ':' not in value:
return None
try:
age = value.split(':')[1].strip()
return float(age.replace('y', ''))
except:
return None
# 3. Save initial 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. Skip clinical feature extraction since trait_row is None
# Extract gene expression data from matrix file
genetic_df = get_genetic_data(matrix_file)
# Print DataFrame shape and first 20 row IDs
print("DataFrame shape:", genetic_df.shape)
print("\nFirst 20 row IDs:")
print(genetic_df.index[:20])
print("\nPreview of first few rows and columns:")
print(genetic_df.head().iloc[:, :5])
# These identifiers (A_19_P...) are not standard human gene symbols
# They appear to be Agilent probe IDs which need to be mapped to gene symbols
requires_gene_mapping = True
# Extract gene annotation data, focusing on mRNA platform section
from io import StringIO
import gzip
# Read the SOFT file and identify the mRNA platform section
mRNA_annotation = []
in_mRNA_platform = False
with gzip.open(soft_file, 'rt') as f:
for line in f:
# Look for the start of mRNA platform section (should contain "LncRNA+mRNA" in the description)
if "!Platform_title" in line and "LncRNA+mRNA" in line:
in_mRNA_platform = True
# Once in mRNA platform section, collect annotation lines
if in_mRNA_platform and not line.startswith(("^", "!", "#")):
mRNA_annotation.append(line)
# Stop when we hit the next platform section
if in_mRNA_platform and line.startswith("^Platform"):
break
# Convert collected annotation lines to DataFrame
annotation_text = ''.join(mRNA_annotation)
gene_metadata = pd.read_csv(StringIO(annotation_text), sep='\t', low_memory=False)
# Preview the annotation data
print("Column names:")
print(gene_metadata.columns)
print("\nPreview of gene annotation data:")
print(preview_df(gene_metadata))
# Extract gene annotation data using the library function
gene_metadata = get_gene_annotation(soft_file)
# Print detailed information about first few rows to help identify probe and gene columns
print("Column names:")
print(gene_metadata.columns)
print("\nDetailed view of first row:")
print(gene_metadata.iloc[0].to_dict())
print("\nFirst 5 rows of ID and SystematicName columns:")
print(gene_metadata[['ID', 'SystematicName']].head())
# Get mapping between probe IDs and gene symbols
# The ID column matches probe IDs in expression data
# SystematicName column appears to contain gene information
mapping_df = get_gene_mapping(gene_metadata, 'ID', 'SystematicName')
# Apply gene mapping to convert probe-level data to gene-level data
gene_data = apply_gene_mapping(genetic_df, mapping_df)
# Preview the gene data
print("\nGene expression data shape:", gene_data.shape)
print("\nFirst few genes and samples:")
print(gene_data.head().iloc[:, :5])
# Extract gene annotation data, focusing on mRNA platform section
from io import StringIO
import gzip
# Read the SOFT file and identify the mRNA platform section
platform_data = []
in_platform = False
columns_found = False
with gzip.open(soft_file, 'rt') as f:
for line in f:
# Look for the start and end of platform sections
if line.startswith('^PLATFORM'):
# If we find a new platform section, check if previous was mRNA
if in_platform and 'LncRNA+mRNA' in ''.join(platform_data):
break
platform_data = []
in_platform = True
continue
if in_platform:
# Look for lines containing column names with gene information
if "Reporter Name" in line or "Gene Symbol" in line or "Gene Name" in line:
columns_found = True
platform_data.append(line)
# If we didn't find useful columns, try the whole file
if not columns_found:
with gzip.open(soft_file, 'rt') as f:
platform_data = f.readlines()
# Convert platform data to string filtering out prefixes and extracting table data
filtered_lines = []
table_started = False
for line in platform_data:
if table_started:
if not line.startswith(('^', '!', '#')):
filtered_lines.append(line)
elif "Reporter Name\tGene Symbol" in line or "ID\tGene Name" in line:
table_started = True
filtered_lines.append(line)
# Convert filtered lines to DataFrame
gene_metadata = pd.read_csv(StringIO(''.join(filtered_lines)), sep='\t', low_memory=False)
# Preview the annotation data
print("Column names:")
print(gene_metadata.columns)
print("\nPreview of first 5 rows:")
print(gene_metadata.head().to_dict())
# Save the initial filtering info indicating the dataset cannot be used
validate_and_save_cohort_info(
is_final=False, # Changed to False since this is initial filtering
cohort=cohort,
info_path=json_path,
is_gene_available=False, # Although there is gene data, we can't properly map the identifiers
is_trait_available=False # No trait information available in clinical data
)