File size: 7,690 Bytes
3ee376c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Path Configuration
from tools.preprocess import *

# Processing context
trait = "Breast_Cancer"
cohort = "GSE249377"

# Input paths
in_trait_dir = "../DATA/GEO/Breast_Cancer"
in_cohort_dir = "../DATA/GEO/Breast_Cancer/GSE249377"

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

# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)

# Extract background info and clinical data using specified prefixes
background_info, clinical_data = get_background_and_clinical_data(
    matrix_file,
    prefixes_a=['!Series_title', '!Series_summary', '!Series_overall_design'],
    prefixes_b=['!Sample_geo_accession', '!Sample_characteristics_ch1']
)

# 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
# This is a transcriptomics dataset using MCF7 breast cancer cell line
is_gene_available = True

# 2.1 Variable availability - look at unique values under each feature ID
trait_row = 2  # Treatment status available in Feature 2
age_row = None  # No age information
gender_row = None  # No gender information - cell line data only

# 2.2 Data type conversion functions
def convert_trait(value: str) -> Optional[int]:
    """Convert treatment data to binary: treated (1) vs untreated (0)"""
    if value is None or 'NA' in value:
        return None
    if 'untreated' in value:
        return 0
    if 'exposure' in value:
        return 1
    return None

def convert_age(value: str) -> Optional[float]:
    """Not used since age data unavailable"""
    return None

def convert_gender(value: str) -> Optional[int]:
    """Not used since gender data unavailable"""
    return None

# 3. Save metadata about data availability
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 and save
if trait_row is not None:
    selected_clinical_df = 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
    preview = preview_df(selected_clinical_df)
    print("Preview of extracted clinical features:")
    print(preview)
    
    # Save clinical data
    selected_clinical_df.to_csv(out_clinical_data_file)
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)

# Debug: Print section around matrix begin marker
print("Examining data format:")
with gzip.open(matrix_file, 'rt') as f:
    found = False
    for i, line in enumerate(f):
        if "!series_matrix_table_begin" in line:
            found = True
            print("Found marker at line:", i)
            print("\nHeader line:")
            header = next(f).strip()
            print(header)
            print("\nFirst few data lines:")
            for _ in range(4):  # Print 4 data lines
                print(next(f).strip())
            break
    if not found:
        print("Matrix begin marker not found")

# Now extract gene expression data with better error handling
def get_gene_data_debug(file_path: str, marker: str = "!series_matrix_table_begin") -> pd.DataFrame:
    skip_rows = 0
    with gzip.open(file_path, 'rt') as file:
        for i, line in enumerate(file):
            if marker in line:
                skip_rows = i
                break
    
    # Read the data starting right after the marker line
    genetic_data = pd.read_csv(file_path, compression='gzip', skiprows=skip_rows+1, 
                           sep='\t', index_col=0)
    return genetic_data

gene_data = get_gene_data_debug(matrix_file)

# Print information about loaded data
print("\nShape 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].tolist())
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)

# Extract gene data using library function
gene_data = get_genetic_data(matrix_file)

# Print debug info
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].tolist())
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)

# Try direct read with error handling and verification
try:
    # Use the library function but verify output
    gene_data = get_genetic_data(matrix_file)
    
    # Verify we got data
    if gene_data.empty:
        print("WARNING: No gene expression data loaded!")
    else:
        print(f"\nSuccessfully loaded gene expression data with shape: {gene_data.shape}")
        print("\nFirst 5 rows:")
        print(gene_data.head())
        print("\nFirst 20 gene/probe identifiers:")
        print(gene_data.index[:20].tolist())
        
    # Save gene data
    gene_data.to_csv(out_gene_data_file)

except Exception as e:
    print(f"Error reading gene data: {e}")
    print("\nAttempting to examine file content:")
    with gzip.open(matrix_file, 'rt') as f:
        # Read a bit more after the header
        header = False
        for i, line in enumerate(f):
            if "!series_matrix_table_begin" in line:
                header = True
                print("\nFound data start marker")
                continue
            if header:
                print(f"Line after marker {i}: {line[:100]}...")
                if i > 85:  # Print a few lines after marker
                    break
# First examine if file contains platform/probe information
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
    has_platform = False
    gene_annotation_lines = []
    for i, line in enumerate(f):
        line = line.strip()
        if 'platform' in line.lower():
            print(f"Platform line: {line}")
            has_platform = True
        # Collect lines between !platform_table_begin and !platform_table_end
        if has_platform and "!platform_table_begin" in line:
            next(f)  # Skip header line
            for data_line in f:
                if "!platform_table_end" in data_line:
                    break
                gene_annotation_lines.append(data_line)
            break

# Convert collected lines to dataframe if any found
if gene_annotation_lines:
    # Join lines and create dataframe
    annotation_text = ''.join(gene_annotation_lines)
    gene_metadata = pd.read_csv(io.StringIO(annotation_text), delimiter='\t')
    
    print("\nGene annotation dataframe shape:", gene_metadata.shape)
    print("\nColumn names:", gene_metadata.columns.tolist())
    print("\nFirst few rows:")
    print(gene_metadata.head())
else:
    print("\nNo gene annotation data found in platform section")
    # Create empty dataframe as placeholder
    gene_metadata = pd.DataFrame()