File size: 11,947 Bytes
61e25af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# Path Configuration
from tools.preprocess import *

# Processing context
trait = "Obesity"
cohort = "GSE123086"

# Input paths
in_trait_dir = "../DATA/GEO/Obesity"
in_cohort_dir = "../DATA/GEO/Obesity/GSE123086"

# Output paths
out_data_file = "./output/preprocess/3/Obesity/GSE123086.csv"
out_gene_data_file = "./output/preprocess/3/Obesity/gene_data/GSE123086.csv"
out_clinical_data_file = "./output/preprocess/3/Obesity/clinical_data/GSE123086.csv"
json_path = "./output/preprocess/3/Obesity/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")
# 1. Gene Expression Data Availability
# Yes, from series design we can see RNA microarray was used
is_gene_available = True

# 2.1 Data Availability
# Trait data is in Feature 1 under "primary diagnosis"
trait_row = 1

# Age data is spread across Features 3 and 4
age_row = 3

# Gender data is in Feature 2 under "Sex"
gender_row = 2

# 2.2 Data Type Conversion Functions
def convert_trait(x):
    # Extract value after colon and convert to binary
    if pd.isna(x):
        return None
    value = x.split(': ')[1]
    if value == 'OBESITY':
        return 1
    elif value == 'HEALTHY_CONTROL':
        return 0
    return None

def convert_age(x):
    # Extract age value as continuous
    if pd.isna(x):
        return None
    if not x.startswith('age:'):
        return None
    try:
        return float(x.split(': ')[1])
    except:
        return None

def convert_gender(x):
    # Convert gender to binary (female=0, male=1)
    if pd.isna(x):
        return None
    if not x.startswith('Sex:'):
        return None
    value = x.split(': ')[1]
    if value == 'Female':
        return 0
    elif value == 'Male':
        return 1
    return None

# 3. Initial Filtering and 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. Clinical Feature Extraction
if trait_row is not None:
    clinical_features = geo_select_clinical_features(
        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
    )
    print("Preview of extracted clinical features:")
    print(preview_df(clinical_features))
    clinical_features.to_csv(out_clinical_data_file)
# 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)
# Looking at the identifiers - they are numeric values (1,2,3,9,10 etc)
# These appear to be probe/feature IDs rather than gene symbols
# Therefore mapping to gene symbols will be required
requires_gene_mapping = True
# Get file paths using library function
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)

# For SOFT files with platform annotations, we need to get rows not starting with '!'
# but also not containing just numeric IDs and entrez genes
gene_annotation = pd.read_csv(soft_file, compression='gzip', sep='\t', header=None,
                            comment='!', on_bad_lines='skip')

# Find rows with detailed platform annotations (containing gene symbols)
annotation_starts = False
annotation_lines = []
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
    for line in f:
        if "!platform_table_begin" in line:
            annotation_starts = True
            # Get the header line
            header = next(f).strip()
            annotation_lines.append(header)
            continue
        if annotation_starts:
            if "!platform_table_end" in line:
                break
            annotation_lines.append(line.strip())

# Convert annotation lines to dataframe
annotation_content = '\n'.join(annotation_lines)
gene_annotation = pd.read_csv(io.StringIO(annotation_content), sep='\t')

# Preview annotation data
print("Gene annotation shape:", gene_annotation.shape)
print("\nAll column names:")
print(gene_annotation.columns.tolist())

print("\nFirst few rows:") 
print(gene_annotation.head().to_string())

print("\nNumber of non-null values in each column:")
print(gene_annotation.count())

# Print example rows showing ID and gene symbol columns
print("\nSample rows showing the ID and gene symbol mapping:")
symbol_col = [col for col in gene_annotation.columns if 'symbol' in col.lower()][0]
print(gene_annotation[['ID', symbol_col]].head(10))
# Extract complete platform annotation table from SOFT file
platform_lines = []
annotation_starts = False
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
    for line in f:
        if line.startswith('^PLATFORM'):
            platform_lines.append(line)
        elif line.startswith('!Platform_data_row_count'):
            platform_lines.append(line)
        elif line.startswith('!Platform_table_begin'):
            annotation_starts = True
            header = next(f).strip()
            platform_lines.append(header)
            continue
        elif annotation_starts:
            if line.startswith('!Platform_table_end'):
                break
            platform_lines.append(line.strip())

# Parse platform annotation content
platform_content = '\n'.join(platform_lines)
gene_annotation = pd.read_csv(io.StringIO(platform_content), sep='\t', comment='!', skiprows=2)

# Create mapping DataFrame using ID and gene symbol
mapping_df = gene_annotation[['ID', 'GB_ACC']].copy() 
mapping_df = mapping_df.rename(columns={'GB_ACC': 'Gene'})

# Clean gene symbols - split on spaces/semicolons and take first value
mapping_df['Gene'] = mapping_df['Gene'].astype(str).apply(lambda x: x.split(';')[0].split()[0])
mapping_df = mapping_df.dropna()

# Apply gene mapping to convert probe expression to gene expression
gene_data = apply_gene_mapping(gene_data, mapping_df)

# Normalize gene symbols using the provided function
gene_data = normalize_gene_symbols_in_index(gene_data)

# Save gene expression data
gene_data.to_csv(out_gene_data_file)

# Preview the mapped gene data
print("Shape of gene expression data after mapping:", gene_data.shape)
print("\nFirst few mapped genes and their expression values:")
print(gene_data.head())
# Get file paths using library function
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)

# Try to peek at the SOFT file contents first
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
    # Read first few lines to understand file structure
    print("First 20 lines of SOFT file:")
    for i, line in enumerate(f):
        if i < 20:
            print(line.strip())
        else:
            break

    # Reset file pointer
    f.seek(0)
    
    # Look for the platform table section
    print("\nPlatform table header:")
    for line in f:
        if "!Platform_table_begin" in line:
            # Print the next line which should be the header
            print(next(f).strip())
            break

# Now extract annotation data using a simpler method - get lines between table markers
annotation_lines = []
table_started = False
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
    for line in f:
        if "!Platform_table_begin" in line:
            header = next(f).strip()
            annotation_lines.append(header)
            table_started = True
            continue
        if table_started:
            if "!Platform_table_end" in line:
                break
            annotation_lines.append(line.strip())

# Convert to dataframe
annotation_text = '\n'.join(annotation_lines)
gene_annotation = pd.read_csv(io.StringIO(annotation_text), sep='\t')

# Preview annotation data
print("\nAnnotation data shape:", gene_annotation.shape)
print("\nColumn names:")
print(gene_annotation.columns.tolist())
print("\nFirst few rows:")
print(gene_annotation.head())
# 1. Let's examine SOFT file content first to identify correct gene identifier columns
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
    for line in f:
        if '!Platform_table_begin' in line:
            header = next(f).strip()
            print("Platform table header:")
            print(header)
            print("\nFirst few data rows:")
            for i in range(5):
                print(next(f).strip())
            break

# Extract gene metadata using library function
gene_metadata = get_gene_annotation(soft_file)

# Print available columns to identify gene symbol column
print("\nAvailable annotation columns:")
print(gene_metadata.columns.tolist())

print("\nPreview of gene metadata:")
print(gene_metadata.head())

# Get gene expression data
gene_data = get_genetic_data(matrix_file)

# Print shape and preview of expression data before mapping
print("\nShape of gene expression data before mapping:", gene_data.shape)
print("\nPreview of gene expression data before mapping:")
print(gene_data.head())
# Use library function to get gene annotation from SOFT file
gene_metadata = get_gene_annotation(soft_file)

# Create mapping DataFrame using ID and ENTREZ_GENE_ID 
mapping_df = gene_metadata[['ID', 'ENTREZ_GENE_ID']].copy()
mapping_df = mapping_df.rename(columns={'ENTREZ_GENE_ID': 'Gene'})

# Clean and prepare mapping data
mapping_df['ID'] = mapping_df['ID'].astype(str)
mapping_df['Gene'] = mapping_df['Gene'].astype(str)
mapping_df = mapping_df.dropna()

# Apply gene mapping to convert probe expression to gene expression
gene_data = apply_gene_mapping(gene_data, mapping_df)

# Normalize gene symbols
gene_data = normalize_gene_symbols_in_index(gene_data)

# Save processed gene expression data
gene_data.to_csv(out_gene_data_file)

print("\nShape of gene expression data after mapping:", gene_data.shape)
print("\nFirst few mapped genes and their expression values:")
print(gene_data.head())
# Get file paths using library function
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)

# Extract gene annotation from SOFT file and get meaningful data 
gene_annotation = get_gene_annotation(soft_file)

# Preview gene annotation data
print("Gene annotation shape:", gene_annotation.shape)
print("\nGene annotation preview:")
print(preview_df(gene_annotation))

print("\nNumber of non-null values in each column:")
print(gene_annotation.count())

# Print example rows showing the mapping information columns
print("\nSample mapping columns ('ID' and 'GENE_SYMBOL'):")
print("\nFirst 5 rows:")
print(gene_annotation[['ID', 'GENE_SYMBOL']].head().to_string())

print("\nNote: Gene mapping will use:")
print("'ID' column: Probe identifiers") 
print("'GENE_SYMBOL' column: Contains gene symbol information")