File size: 7,732 Bytes
a0b62f5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Arrhythmia"
cohort = "GSE53622"
# Input paths
in_trait_dir = "../DATA/GEO/Arrhythmia"
in_cohort_dir = "../DATA/GEO/Arrhythmia/GSE53622"
# Output paths
out_data_file = "./output/preprocess/3/Arrhythmia/GSE53622.csv"
out_gene_data_file = "./output/preprocess/3/Arrhythmia/gene_data/GSE53622.csv"
out_clinical_data_file = "./output/preprocess/3/Arrhythmia/clinical_data/GSE53622.csv"
json_path = "./output/preprocess/3/Arrhythmia/cohort_info.json"
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Extract background info and clinical data
background_info, clinical_data = get_background_and_clinical_data(matrix_file)
# Get unique values per clinical feature
sample_characteristics = get_unique_values_by_row(clinical_data)
# Print background info
print("Dataset Background Information:")
print(f"{background_info}\n")
# Print sample characteristics
print("Sample Characteristics:")
for feature, values in sample_characteristics.items():
print(f"Feature: {feature}")
print(f"Values: {values}\n")
# Step 1: Gene expression data availability
# Based on the series title and summary, this is a lncRNA microarray study
# lncRNA is a type of gene expression data, so it is suitable
is_gene_available = True
# Step 2.1: Identify data rows
trait_row = 10 # Arrhythmia data in row 10
age_row = 1 # Age data in row 1
gender_row = 2 # Gender data in row 2
# Step 2.2: Define conversion functions
def convert_trait(x):
# Convert arrhythmia values to binary (no:0, yes:1)
if not isinstance(x, str):
return None
value = x.split(': ')[-1].lower()
if value == 'no':
return 0
elif value == 'yes':
return 1
return None
def convert_age(x):
# Convert age to float
if not isinstance(x, str):
return None
try:
return float(x.split(': ')[-1])
except:
return None
def convert_gender(x):
# Convert gender to binary (female:0, male:1)
if not isinstance(x, str):
return None
value = x.split(': ')[-1].lower()
if value == 'female':
return 0
elif value == 'male':
return 1
return None
# Step 3: Save metadata for initial filtering
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)
# Step 4: Extract clinical features since trait data is available
if trait_row is not None:
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
print("Preview of extracted clinical features:")
print(preview_df(selected_clinical))
# Save to file
selected_clinical.to_csv(out_clinical_data_file)
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Extract gene expression data from matrix file
gene_data = get_genetic_data(matrix_file)
# Print first 20 row IDs and shape of data to help debug
print("Shape of gene expression data:", gene_data.shape)
print("\nFirst few rows of data:")
print(gene_data.head())
print("\nFirst 20 gene/probe identifiers:")
print(gene_data.index[:20])
# Inspect a snippet of raw file to verify identifier format
import gzip
with gzip.open(matrix_file, 'rt', encoding='utf-8') as f:
lines = []
for i, line in enumerate(f):
if "!series_matrix_table_begin" in line:
# Get the next 5 lines after the marker
for _ in range(5):
lines.append(next(f).strip())
break
print("\nFirst few lines after matrix marker in raw file:")
for line in lines:
print(line)
# Based on the gene identifiers showing simple numeric values (1,2,24,25,26 etc)
# and the very high number of rows (71584), these appear to be probe IDs from a
# microarray platform rather than direct gene symbols. They will need to be mapped
# to standard gene symbols.
requires_gene_mapping = True
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Extract gene annotation from SOFT file by filtering out lines with prefixes
gene_annotation = get_gene_annotation(soft_file)
# Print platform information and key columns
print("Platform Information:")
with gzip.open(soft_file, 'rt') as f:
for line in f:
if '!Platform_title' in line or '!Platform_geo_accession' in line:
print(line.strip())
# Download and read platform annotation file from GEO
import urllib.request
import io
# Download GPL18109 platform annotation
platform_url = "https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?mode=raw&is_datatable=true&acc=GPL18109&id=18415&db=GeoDb_blob118"
response = urllib.request.urlopen(platform_url)
platform_data = response.read().decode('utf-8')
# Read into dataframe
platform_df = pd.read_csv(io.StringIO(platform_data), sep='\t', comment='#')
print("\nPlatform Annotation Preview:")
print("Column names:", platform_df.columns.tolist())
print("\nFirst few rows as dictionary:")
print(preview_df(platform_df))
# Store platform dataframe as our gene annotation
gene_annotation = platform_df
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Read SOFT file content
with gzip.open(soft_file, 'rt') as f:
platform_content = f.read()
# Extract the platform table section
table_start = platform_content.find("!platform_table_begin")
table_end = platform_content.find("!platform_table_end")
platform_table = platform_content[table_start:table_end]
# Read platform annotation into dataframe
gene_annotation = pd.read_csv(io.StringIO(platform_table), sep='\t', skiprows=1)
# Print column names to identify mapping columns
print("Available columns:", gene_annotation.columns.tolist())
print("\nSample rows:")
print(gene_annotation.head())
# Get mapping between probe IDs and gene symbols
mapping_df = get_gene_mapping(gene_annotation, prob_col='ID_REF', gene_col='GENE')
# Apply mapping to convert probe data to gene expression data
gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
# Print shape and preview to verify conversion worked
print("\nShape of mapped gene expression data:", gene_data.shape)
print("\nFirst few rows after mapping:")
print(gene_data.head())
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Extract gene annotation from SOFT file
gene_annotation = get_gene_annotation(soft_file)
# Print annotation info
print("Looking for gene annotation in file:", soft_file)
print("\nGene Annotation Preview:")
print("Number of rows:", len(gene_annotation))
print("Column names:", gene_annotation.columns.tolist())
# The platform appears to lack complete annotation in the SOFT file
# This is GPL18109 platform which requires special handling
print("\nNOTE: This dataset uses GPL18109 platform (Agilent-038314 CBC Homo sapiens lncRNA + mRNA microarray)")
print("The complete gene mapping information is not available in the SOFT file.")
print("Manual annotation retrieval from GEO is required for this platform.")
# Since automated annotation retrieval failed, we should stop here and inform about manual annotation need
raise ValueError("Gene mapping information not found in SOFT file. Manual annotation retrieval required for GPL18109.") |