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

# Processing context
trait = "Melanoma"
cohort = "GSE144296"

# Input paths
in_trait_dir = "../DATA/GEO/Melanoma"
in_cohort_dir = "../DATA/GEO/Melanoma/GSE144296"

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

# Get file paths for SOFT and matrix files
soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)

# Get background info and clinical data from the matrix file
background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)

# Create dictionary of unique values for each feature
unique_values_dict = get_unique_values_by_row(clinical_data)

# Print the information
print("Dataset Background Information:")
print(background_info)
print("\nSample Characteristics:")
for feature, values in unique_values_dict.items():
    print(f"\n{feature}:")
    print(values)
# 1. Gene Expression Data Availability
# Based on background info mentioning mRNA sequencing and gene expression analysis
is_gene_available = True

# 2.1 Data Availability
# Trait (melanoma vs non-melanoma) can be inferred from cell type field (row 1)
trait_row = 1
# Age not available in data
age_row = None  
# Gender not available in data
gender_row = None

# 2.2 Data Type Conversion Functions
def convert_trait(x):
    """Convert cell type to binary melanoma indicator"""
    if not isinstance(x, str):
        return None
    x = x.lower().split(': ')[-1]
    if 'melanoma' in x:
        return 1
    elif 'colorectal' in x:
        return 0
    return None

def convert_age(x):
    """Placeholder for age conversion"""
    return None

def convert_gender(x):
    """Placeholder for gender conversion"""
    return None

# 3. Save metadata for initial filtering
validate_and_save_cohort_info(
    is_final=False,
    cohort=cohort,
    info_path=json_path,
    is_gene_available=is_gene_available,
    is_trait_available=trait_row is not None
)

# 4. Clinical Feature Extraction
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 processed clinical data
    preview_df(selected_clinical)
    
    # Save clinical features
    selected_clinical.to_csv(out_clinical_data_file)
# Extract genetic data matrix with case-insensitive marker 
genetic_data = get_genetic_data(matrix_file_path, marker="!series_matrix_table_begin".lower())

# Verify data was loaded
if len(genetic_data.index) == 0:
    # Try alternative marker format
    genetic_data = get_genetic_data(matrix_file_path, marker="!Series_Matrix_Table_Begin")
    
if len(genetic_data.index) == 0:
    print("Warning: No data was extracted from the matrix file. Please check the matrix file formatting.")
    is_gene_available = False
else:
    print("First 20 row IDs:")
    print(list(genetic_data.index)[:20])
    is_gene_available = True

# Save updated metadata 
validate_and_save_cohort_info(
    is_final=False,
    cohort=cohort,
    info_path=json_path,
    is_gene_available=is_gene_available,
    is_trait_available=(trait_row is not None)
)

if is_gene_available:
    genetic_data.to_csv(out_gene_data_file)
# Examine file content before filtering
with gzip.open(soft_file_path, 'rt') as f:
    print("\nSample of unfiltered SOFT file content (first 20 lines):")
    for i, line in enumerate(f):
        if i < 20:  # Print more lines to better understand the structure
            print(line.strip())
        elif i == 20:
            print("...")
            break

# Try reading the matrix file for gene annotations since the SOFT file seems to lack them
with gzip.open(matrix_file_path, 'rt') as f:
    print("\nSample of matrix file content (first 20 lines):")
    for i, line in enumerate(f):
        if i < 20:
            print(line.strip())
        elif i == 20:
            print("...")
            break

# Since we can see the file content now, update the gene metadata extraction
probe_info_found = False
with gzip.open(matrix_file_path, 'rt') as f:
    lines = []
    for line in f:
        if line.startswith('!Platform_organism'):
            probe_info_found = True
            lines.append(line)
        elif probe_info_found and line.startswith('!'):
            lines.append(line)
        elif probe_info_found and not any(line.startswith(p) for p in ['!', '#', '^']):
            break
    gene_metadata_text = '\n'.join(lines)
    
print("\nExtracted probe/gene information:")
print(gene_metadata_text)
# Try reading gene expression data using the library function
genetic_data = get_genetic_data(matrix_file_path)

# Convert index to string type
genetic_data.index = genetic_data.index.astype(str)

# Print sample identifiers for verification
print("\nSample identifiers from genetic data:")
print(list(genetic_data.index)[:5])

# Extract gene mapping info
try:
    with gzip.open(matrix_file_path, 'rt') as f:
        for line in f:
            if '!series_matrix_table_begin' in line.lower():
                # Found start of expression data
                break
            if line.startswith('!Sample_platform_id'):
                # Save the platform ID if we find it
                platform_line = line.strip()

    # For RNA-seq data, create a 1:1 mapping using the original gene identifiers
    ids = genetic_data.index.tolist()
    annotation_df = pd.DataFrame({
        'ID': ids,
        'Gene': ids  # Use same IDs as gene symbols for now
    })

    print("\nSample rows from annotation mapping:")
    print(annotation_df.head())

    # Apply gene mapping using library function 
    gene_data = apply_gene_mapping(genetic_data, annotation_df)

    # Convert gene indices to string before normalization
    gene_data.index = gene_data.index.astype(str)

    # Normalize gene symbols
    gene_data = normalize_gene_symbols_in_index(gene_data)

    print("\nFinal gene data shape:", gene_data.shape)
    print("Sample gene names after normalization:")
    print(list(gene_data.index)[:5])

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

except Exception as e:
    print(f"Error during gene mapping: {str(e)}")
    # Save genetic data without mapping if error occurs
    genetic_data.to_csv(out_gene_data_file)
# Read the entire file first to find the exact line numbers of begin/end markers
with gzip.open(matrix_file_path, 'rt') as f:
    lines = f.readlines()
    
start_idx = None
end_idx = None
for i, line in enumerate(lines):
    if '!series_matrix_table_begin' in line.lower():
        start_idx = i + 1  # Skip the marker line
    elif '!series_matrix_table_end' in line.lower():
        end_idx = i
        break

genetic_data = None
if start_idx and end_idx:
    # Read only the data section
    genetic_data = pd.read_csv(io.StringIO(''.join(lines[start_idx:end_idx])), 
                              sep='\t', index_col=0)

# Print results
if genetic_data is not None and len(genetic_data) > 0:
    print("\nFirst 20 row IDs:")
    print(list(genetic_data.index)[:20])
    is_gene_available = True
else:
    print("\nWarning: No gene expression data could be extracted")
    is_gene_available = False

# Save updated metadata
validate_and_save_cohort_info(
    is_final=False,
    cohort=cohort,
    info_path=json_path, 
    is_gene_available=is_gene_available,
    is_trait_available=(trait_row is not None)
)

if is_gene_available:
    genetic_data.to_csv(out_gene_data_file)