File size: 8,609 Bytes
1a37a63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Path Configuration
from tools.preprocess import *

# Processing context
trait = "Osteoarthritis"
cohort = "GSE98460"

# Input paths
in_trait_dir = "../DATA/GEO/Osteoarthritis"
in_cohort_dir = "../DATA/GEO/Osteoarthritis/GSE98460"

# Output paths
out_data_file = "./output/preprocess/3/Osteoarthritis/GSE98460.csv"
out_gene_data_file = "./output/preprocess/3/Osteoarthritis/gene_data/GSE98460.csv"
out_clinical_data_file = "./output/preprocess/3/Osteoarthritis/clinical_data/GSE98460.csv"
json_path = "./output/preprocess/3/Osteoarthritis/cohort_info.json"

# Get file paths
soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)

# Get background info and clinical data
background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)
print("Background Information:")
print(background_info)
print("\nSample Characteristics:")

# Get dictionary of unique values per row 
unique_values_dict = get_unique_values_by_row(clinical_data)
for row, values in unique_values_dict.items():
    print(f"\n{row}:")
    print(values)
# 1. Gene Expression Data Availability
is_gene_available = True  # RNA microarray data indicated in background info

# 2. Variable Availability and Data Type
# Trait (OA) - can be inferred from diagnosis field
trait_row = 1
def convert_trait(x):
    if not x or ':' not in x:
        return None
    value = x.split(':')[1].strip().lower()
    if 'osteoarthritis' in value or 'oa' in value:
        return 1
    return 0

# Age - available in field 2
age_row = 2  
def convert_age(x):
    if not x or ':' not in x:
        return None
    try:
        return float(x.split(':')[1].strip().split()[0])
    except:
        return None

# Gender - available in field 3
gender_row = 3
def convert_gender(x):
    if not x or ':' not in x:
        return None
    value = x.split(':')[1].strip().lower()
    if 'female' in value:
        return 0
    elif 'male' in value:
        return 1
    return None

# 3. Save metadata
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. Extract clinical features
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
    )
    print("Preview of selected clinical features:")
    print(preview_df(selected_clinical))
    selected_clinical.to_csv(out_clinical_data_file)
# Get gene expression data from matrix file
genetic_data = get_genetic_data(matrix_file_path)

# Examine data structure
print("Data structure and head:")
print(genetic_data.head())

print("\nShape:", genetic_data.shape)

print("\nFirst 20 row IDs (gene/probe identifiers):")
print(list(genetic_data.index)[:20])

# Get a few column names to verify sample IDs
print("\nFirst 5 column names:")
print(list(genetic_data.columns)[:5])
# Examining gene identifiers
# The IDs look like custom platform probe IDs (e.g. 16650001, 16650003)
# These are not standard human gene symbols (which would be like BRCA1, TP53, etc.)
# We will need to map these probe IDs to gene symbols

requires_gene_mapping = True
# Look at more content in SOFT file to find gene annotation section
with gzip.open(soft_file_path, 'rt') as f:
    platform_found = False
    table_start = False
    first_row = None
    gene_rows = []
    
    for line in f:
        if '!Platform_table_begin' in line:
            table_start = True
            continue
        elif '!Platform_table_end' in line:
            break
        elif table_start:
            if first_row is None:
                first_row = line.strip()
            else:
                gene_rows.append(line.strip())

# Create dataframe from the platform table data
import io
header = first_row.split('\t')
gene_data = '\n'.join(gene_rows)
gene_annotation = pd.read_csv(io.StringIO(gene_data), sep='\t', names=header)

print("Column names:")
print(gene_annotation.columns)

print("\nPreview of gene annotation data:")
print(preview_df(gene_annotation))
# First examine more content in SOFT file to locate gene symbol information
with gzip.open(soft_file_path, 'rt') as f:
    found_table = False
    header = None
    first_five_rows = []
    for line in f:
        if '!Platform_title' in line:
            print("Platform title:", line.strip())
        elif '!Platform_organism' in line:
            print("Platform organism:", line.strip())
        elif '!Platform_table_begin' in line:
            found_table = True
            continue
        elif found_table:
            if header is None:
                header = line.strip()
                print("\nPlatform table header:")
                print(header)
            elif len(first_five_rows) < 5:
                first_five_rows.append(line.strip())
            else:
                break

print("\nFirst few rows:")
for row in first_five_rows:
    print(row)

# Now try using tabs as delimiter to see full column structure
print("\nSplitting first row by tabs to check all fields:")
if first_five_rows:
    print(first_five_rows[0].split('\t'))

# Based on examination results, extract complete platform data
platform_data = pd.read_csv(gzip.open(soft_file_path, 'rt'), 
                          sep='\t',
                          skiprows=lambda x: x == 0 or not found_table,
                          comment='!')

print("\nFull column names found:")
print(platform_data.columns.tolist())

print("\nPreview of complete annotation data:")
print(preview_df(platform_data))
# Extract gene annotation using library function
gene_annotation = get_gene_annotation(soft_file_path)

# Print available columns to identify correct names
print("Available columns:", gene_annotation.columns.tolist())

# First examine the column names 
probe_data = gene_annotation.head()
print("\nFirst few rows:")
print(preview_df(probe_data))

# Create mapping after seeing actual column names
mapping_df = get_gene_mapping(gene_annotation, 
                            prob_col='ID', 
                            gene_col='Gene Title')  

# Convert probe-level measurements to gene expression data
gene_data = apply_gene_mapping(genetic_data, mapping_df)

print("\nPreview of gene expression data after mapping:")
print(preview_df(gene_data))
# Load clinical data
selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)

# Normalize gene symbols and save gene expression data
genetic_data = normalize_gene_symbols_in_index(genetic_data) 
genetic_data.to_csv(out_gene_data_file)

# Link clinical and genetic data using library function
linked_data = geo_link_clinical_genetic_data(selected_clinical_df, genetic_data)

# Handle missing values systematically  
linked_data = handle_missing_values(linked_data, trait)

# Check for bias in trait and demographic features
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)

# Final validation and information saving
note = "This dataset contains cartilage tissue samples from OA patients, with gene expression data and demographic information."
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=linked_data,
    note=note
)

# Save linked data only if usable
if is_usable:
    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
    linked_data.to_csv(out_data_file)
# First examine platform information in SOFT file
print("Examining platform information in SOFT file...")
with gzip.open(soft_file_path, 'rt') as f:
    platform_lines = []
    capture = False
    for line in f:
        if line.startswith(('!Platform_title', '!Platform_organism', '!Platform_technology')):
            print(line.strip())
        elif '!platform_table_begin' in line.lower():
            capture = True
            continue
        elif '!platform_table_end' in line.lower():
            break
        elif capture:
            platform_lines.append(line.strip())

# Now extract complete annotation with pandas
print("\nExtracting complete platform annotation...")
platform_df = pd.read_csv(io.StringIO('\n'.join(platform_lines)), sep='\t')

print("\nFound columns:")
print(platform_df.columns.tolist())

print("\nPreview of annotation data:")
print(preview_df(platform_df))