Update stage1_generate_profiles.py
Browse files- stage1_generate_profiles.py +40 -40
stage1_generate_profiles.py
CHANGED
|
@@ -111,15 +111,15 @@ def load_new_sequences(settings_obj, paths):
|
|
| 111 |
all_records = []
|
| 112 |
|
| 113 |
if settings_obj.useTestData:
|
| 114 |
-
print("\n@
|
| 115 |
else:
|
| 116 |
-
print("\n@
|
| 117 |
|
| 118 |
target_extensions = {'.fasta', '.fa', '.fna', '.seq', '.fas'}
|
| 119 |
fasta_files = [f for f in fasta_dir.rglob('*') if f.is_file() and f.suffix.lower() in target_extensions]
|
| 120 |
|
| 121 |
if not fasta_files:
|
| 122 |
-
print(f"
|
| 123 |
return pd.DataFrame()
|
| 124 |
|
| 125 |
for file_path in fasta_files:
|
|
@@ -140,7 +140,7 @@ def load_new_sequences(settings_obj, paths):
|
|
| 140 |
all_records.append({'Title': header, 'Sequence': sequence})
|
| 141 |
|
| 142 |
df = pd.DataFrame(all_records)
|
| 143 |
-
print(f"✅
|
| 144 |
return df
|
| 145 |
|
| 146 |
|
|
@@ -173,7 +173,7 @@ def get_sequence_files(folder_path):
|
|
| 173 |
target_extensions = ('.seq', '.fasta', '.fas')
|
| 174 |
result_files = []
|
| 175 |
if not os.path.exists(folder_path):
|
| 176 |
-
print(f"
|
| 177 |
return result_files
|
| 178 |
for filename in os.listdir(folder_path):
|
| 179 |
if filename.lower().endswith(target_extensions):
|
|
@@ -183,7 +183,7 @@ def get_sequence_files(folder_path):
|
|
| 183 |
|
| 184 |
def save_target_seqs_in_chunks(df, settings_obj, output_dir, chunk_size=300):
|
| 185 |
"""Target 시퀀스들을 300개씩 나누어 FASTA 파일로 저장합니다."""
|
| 186 |
-
print("\n@
|
| 187 |
|
| 188 |
output_path = Path(output_dir)
|
| 189 |
output_path.mkdir(parents=True, exist_ok=True)
|
|
@@ -208,7 +208,7 @@ def save_target_seqs_in_chunks(df, settings_obj, output_dir, chunk_size=300):
|
|
| 208 |
sequence_col = 'sequence' if settings_obj.newSeq_fromDB else 'Sequence'
|
| 209 |
f.write(f"{header}\n{row[sequence_col]}\n")
|
| 210 |
|
| 211 |
-
print(f"✅
|
| 212 |
|
| 213 |
|
| 214 |
# =============================================================================
|
|
@@ -218,31 +218,31 @@ def run_mafft_alignment(ref_dir, target_dir, output_dir):
|
|
| 218 |
"""Reference-Guided Alignment 방식.
|
| 219 |
1. Reference 정렬(한 번만) 2. Reference의 gap 정보 저장
|
| 220 |
3. 각 Target을 Reference와 1:1 정렬하여 Reference와 aligned된 부분만 추출"""
|
| 221 |
-
print("\n@
|
| 222 |
|
| 223 |
ref_path = Path(ref_dir)
|
| 224 |
target_path = Path(target_dir)
|
| 225 |
output_path = Path(output_dir)
|
| 226 |
output_path.mkdir(parents=True, exist_ok=True)
|
| 227 |
|
| 228 |
-
print("🔬 Step 1/3:
|
| 229 |
ref_files = sorted(ref_path.glob('ref*.seq'))
|
| 230 |
if len(ref_files) == 0:
|
| 231 |
-
print(f"⚠️
|
| 232 |
return
|
| 233 |
if len(ref_files) > 1:
|
| 234 |
-
print(f"⚠️
|
| 235 |
for f in ref_files:
|
| 236 |
print(f" - {f.relative_to(ref_path)}")
|
| 237 |
ref_file = ref_files[0]
|
| 238 |
-
print(f"📌 Reference
|
| 239 |
|
| 240 |
-
print("🔬 Step 2/3:
|
| 241 |
target_files = sorted(list(target_path.rglob('*.seq')))
|
| 242 |
if not target_files:
|
| 243 |
-
print(f"⚠️ '{target_dir}'
|
| 244 |
return
|
| 245 |
-
print(f"📂 {len(target_files)}
|
| 246 |
|
| 247 |
ref_records_all = []
|
| 248 |
with open(ref_file, 'r') as f:
|
|
@@ -263,9 +263,9 @@ def run_mafft_alignment(ref_dir, target_dir, output_dir):
|
|
| 263 |
|
| 264 |
first_ref_header, first_ref_seq = ref_records_all[0]
|
| 265 |
first_ref_content = f"{first_ref_header}\n{first_ref_seq}\n"
|
| 266 |
-
print(f"📌
|
| 267 |
|
| 268 |
-
print("🔬 Step 3/3:
|
| 269 |
successful = 0
|
| 270 |
failed = 0
|
| 271 |
|
|
@@ -319,10 +319,10 @@ def run_mafft_alignment(ref_dir, target_dir, output_dir):
|
|
| 319 |
if parse_and_write(result.stdout, output_file_path):
|
| 320 |
successful += 1
|
| 321 |
else:
|
| 322 |
-
print(f"\n⚠️ '{target_file.name}':
|
| 323 |
failed += 1
|
| 324 |
except subprocess.TimeoutExpired:
|
| 325 |
-
print(f"\n⏱️ '{target_file.name}'
|
| 326 |
try:
|
| 327 |
retry_result = subprocess.run(
|
| 328 |
['mafft', '--auto', '--thread', '-1', '-'],
|
|
@@ -330,30 +330,30 @@ def run_mafft_alignment(ref_dir, target_dir, output_dir):
|
|
| 330 |
capture_output=True, text=True, check=True, timeout=3600
|
| 331 |
)
|
| 332 |
if parse_and_write(retry_result.stdout, output_file_path):
|
| 333 |
-
print(f" ✅
|
| 334 |
successful += 1
|
| 335 |
else:
|
| 336 |
-
print(f" ❌
|
| 337 |
failed += 1
|
| 338 |
except Exception as retry_e:
|
| 339 |
-
print(f" ❌
|
| 340 |
failed += 1
|
| 341 |
except subprocess.CalledProcessError as e:
|
| 342 |
-
print(f"\n⚠️ '{target_file.name}'
|
| 343 |
failed += 1
|
| 344 |
except Exception as e:
|
| 345 |
-
print(f"\n⚠️ '{target_file.name}'
|
| 346 |
failed += 1
|
| 347 |
|
| 348 |
-
print("\n🎉
|
| 349 |
-
print(f"✅
|
| 350 |
-
print(f"❌
|
| 351 |
-
print(f"📁
|
| 352 |
|
| 353 |
|
| 354 |
def prepare_simphet_files(msa_dir, simphet_ref_dir, simphet_input_dir):
|
| 355 |
"""MSA 결과를 파싱하여 Simphet-DivN용 REF 및 INPUT 파일들을 생성합니다."""
|
| 356 |
-
print("\n@
|
| 357 |
msa_path = Path(msa_dir)
|
| 358 |
ref_path = Path(simphet_ref_dir)
|
| 359 |
input_path = Path(simphet_input_dir)
|
|
@@ -398,12 +398,12 @@ def prepare_simphet_files(msa_dir, simphet_ref_dir, simphet_input_dir):
|
|
| 398 |
seq_rna = r['sequence'].upper().replace('T', 'U')
|
| 399 |
f.write(f"{r['header']}\n{seq_rna}\n")
|
| 400 |
|
| 401 |
-
print(f"✅
|
| 402 |
|
| 403 |
|
| 404 |
def run_simphet_analysis(simphet_ref_dir, simphet_input_dir, output_dir, n):
|
| 405 |
"""Simphet-DivN 분석을 수행하고, 각 target 서열에 대한 변이 분석 결과를 CSV로 저장합니다."""
|
| 406 |
-
print("\n@ Simphet-DivN
|
| 407 |
ref_path = Path(simphet_ref_dir)
|
| 408 |
input_path = Path(simphet_input_dir)
|
| 409 |
output_path = Path(output_dir)
|
|
@@ -487,12 +487,12 @@ def run_simphet_analysis(simphet_ref_dir, simphet_input_dir, output_dir, n):
|
|
| 487 |
output_csv_path = subfolder_path / f"{sanitized_header}.csv"
|
| 488 |
df.to_csv(output_csv_path, index=False)
|
| 489 |
|
| 490 |
-
print(f"✅
|
| 491 |
|
| 492 |
|
| 493 |
def select_and_rename_unknowns(output_dir, unknown_dir, settings_obj, seed=42):
|
| 494 |
"""분석된 CSV 파일들을 규칙에 따라 샘플링하고, 표준화된 이름으로 변경하여 복사합니다."""
|
| 495 |
-
print("\n@
|
| 496 |
output_path = Path(output_dir)
|
| 497 |
unknown_path = Path(unknown_dir)
|
| 498 |
unknown_path.mkdir(parents=True, exist_ok=True)
|
|
@@ -547,9 +547,9 @@ def select_and_rename_unknowns(output_dir, unknown_dir, settings_obj, seed=42):
|
|
| 547 |
copy2(src, unknown_path / new_name)
|
| 548 |
copied.append(new_name)
|
| 549 |
|
| 550 |
-
print(f"✅ {len(copied)}
|
| 551 |
if skipped:
|
| 552 |
-
print(f"ℹ️ {len(skipped)}
|
| 553 |
|
| 554 |
|
| 555 |
# =============================================================================
|
|
@@ -562,13 +562,13 @@ def main():
|
|
| 562 |
|
| 563 |
df = load_new_sequences(s, paths)
|
| 564 |
if df.empty:
|
| 565 |
-
print("
|
| 566 |
return
|
| 567 |
|
| 568 |
-
print("\n---
|
| 569 |
print(df.head())
|
| 570 |
if 'country' in df.columns:
|
| 571 |
-
print("\n---
|
| 572 |
print(df['country'].unique())
|
| 573 |
print("-" * 28)
|
| 574 |
|
|
@@ -583,9 +583,9 @@ def main():
|
|
| 583 |
prepare_simphet_files(msa_dir=paths['msa_out_path'], simphet_ref_dir=paths['simphet_ref_path'], simphet_input_dir=paths['simphet_input_path'])
|
| 584 |
run_simphet_analysis(simphet_ref_dir=paths['simphet_ref_path'], simphet_input_dir=paths['simphet_input_path'], output_dir=stage1_output_dir, n=s.n)
|
| 585 |
# select_and_rename_unknowns(output_dir=stage1_output_dir, unknown_dir=paths['unknown_out'], settings_obj=s)
|
| 586 |
-
print("\n🎉
|
| 587 |
except Exception as e:
|
| 588 |
-
print(f"❌
|
| 589 |
|
| 590 |
|
| 591 |
if __name__ == '__main__':
|
|
|
|
| 111 |
all_records = []
|
| 112 |
|
| 113 |
if settings_obj.useTestData:
|
| 114 |
+
print("\n@ Loading target sequences from the test data folder...")
|
| 115 |
else:
|
| 116 |
+
print("\n@ Loading target sequences from the user data folder...")
|
| 117 |
|
| 118 |
target_extensions = {'.fasta', '.fa', '.fna', '.seq', '.fas'}
|
| 119 |
fasta_files = [f for f in fasta_dir.rglob('*') if f.is_file() and f.suffix.lower() in target_extensions]
|
| 120 |
|
| 121 |
if not fasta_files:
|
| 122 |
+
print(f"No FASTA files were found in '{fasta_dir}'.")
|
| 123 |
return pd.DataFrame()
|
| 124 |
|
| 125 |
for file_path in fasta_files:
|
|
|
|
| 140 |
all_records.append({'Title': header, 'Sequence': sequence})
|
| 141 |
|
| 142 |
df = pd.DataFrame(all_records)
|
| 143 |
+
print(f"✅ Loaded a total of {len(df)} sequences from FASTA files.")
|
| 144 |
return df
|
| 145 |
|
| 146 |
|
|
|
|
| 173 |
target_extensions = ('.seq', '.fasta', '.fas')
|
| 174 |
result_files = []
|
| 175 |
if not os.path.exists(folder_path):
|
| 176 |
+
print(f"Warning: The folder '{folder_path}' does not exist.")
|
| 177 |
return result_files
|
| 178 |
for filename in os.listdir(folder_path):
|
| 179 |
if filename.lower().endswith(target_extensions):
|
|
|
|
| 183 |
|
| 184 |
def save_target_seqs_in_chunks(df, settings_obj, output_dir, chunk_size=300):
|
| 185 |
"""Target 시퀀스들을 300개씩 나누어 FASTA 파일로 저장합니다."""
|
| 186 |
+
print("\n@ Saving target sequences as chunked FASTA files...")
|
| 187 |
|
| 188 |
output_path = Path(output_dir)
|
| 189 |
output_path.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 208 |
sequence_col = 'sequence' if settings_obj.newSeq_fromDB else 'Sequence'
|
| 209 |
f.write(f"{header}\n{row[sequence_col]}\n")
|
| 210 |
|
| 211 |
+
print(f"✅ Saved a total of {total_chunks} target FASTA files to '{output_dir}'.")
|
| 212 |
|
| 213 |
|
| 214 |
# =============================================================================
|
|
|
|
| 218 |
"""Reference-Guided Alignment 방식.
|
| 219 |
1. Reference 정렬(한 번만) 2. Reference의 gap 정보 저장
|
| 220 |
3. 각 Target을 Reference와 1:1 정렬하여 Reference와 aligned된 부분만 추출"""
|
| 221 |
+
print("\n@ Starting reference-guided MAFFT alignment...")
|
| 222 |
|
| 223 |
ref_path = Path(ref_dir)
|
| 224 |
target_path = Path(target_dir)
|
| 225 |
output_path = Path(output_dir)
|
| 226 |
output_path.mkdir(parents=True, exist_ok=True)
|
| 227 |
|
| 228 |
+
print("🔬 Step 1/3: Checking the reference file...")
|
| 229 |
ref_files = sorted(ref_path.glob('ref*.seq'))
|
| 230 |
if len(ref_files) == 0:
|
| 231 |
+
print(f"⚠️ No .seq file starting with 'ref' was found in '{ref_dir}'.")
|
| 232 |
return
|
| 233 |
if len(ref_files) > 1:
|
| 234 |
+
print(f"⚠️ Found {len(ref_files)} reference files. Only the first file will be used.")
|
| 235 |
for f in ref_files:
|
| 236 |
print(f" - {f.relative_to(ref_path)}")
|
| 237 |
ref_file = ref_files[0]
|
| 238 |
+
print(f"📌 Reference file: {ref_file.relative_to(ref_path)}")
|
| 239 |
|
| 240 |
+
print("🔬 Step 2/3: Collecting target files...")
|
| 241 |
target_files = sorted(list(target_path.rglob('*.seq')))
|
| 242 |
if not target_files:
|
| 243 |
+
print(f"⚠️ No .seq files were found in '{target_dir}' or its subdirectories.")
|
| 244 |
return
|
| 245 |
+
print(f"📂 Found {len(target_files)} target files")
|
| 246 |
|
| 247 |
ref_records_all = []
|
| 248 |
with open(ref_file, 'r') as f:
|
|
|
|
| 263 |
|
| 264 |
first_ref_header, first_ref_seq = ref_records_all[0]
|
| 265 |
first_ref_content = f"{first_ref_header}\n{first_ref_seq}\n"
|
| 266 |
+
print(f"📌 Alignment reference: {first_ref_header}")
|
| 267 |
|
| 268 |
+
print("🔬 Step 3/3: Aligning target files...")
|
| 269 |
successful = 0
|
| 270 |
failed = 0
|
| 271 |
|
|
|
|
| 319 |
if parse_and_write(result.stdout, output_file_path):
|
| 320 |
successful += 1
|
| 321 |
else:
|
| 322 |
+
print(f"\n⚠️ '{target_file.name}': Failed to parse alignment results")
|
| 323 |
failed += 1
|
| 324 |
except subprocess.TimeoutExpired:
|
| 325 |
+
print(f"\n⏱️ '{target_file.name}' timed out → retrying with --auto mode...")
|
| 326 |
try:
|
| 327 |
retry_result = subprocess.run(
|
| 328 |
['mafft', '--auto', '--thread', '-1', '-'],
|
|
|
|
| 330 |
capture_output=True, text=True, check=True, timeout=3600
|
| 331 |
)
|
| 332 |
if parse_and_write(retry_result.stdout, output_file_path):
|
| 333 |
+
print(f" ✅ Retry succeeded: '{target_file.name}'")
|
| 334 |
successful += 1
|
| 335 |
else:
|
| 336 |
+
print(f" ❌ Failed to parse results after retry: '{target_file.name}'")
|
| 337 |
failed += 1
|
| 338 |
except Exception as retry_e:
|
| 339 |
+
print(f" ❌ Retry also failed: '{target_file.name}' → {str(retry_e)[:80]}")
|
| 340 |
failed += 1
|
| 341 |
except subprocess.CalledProcessError as e:
|
| 342 |
+
print(f"\n⚠️ Alignment failed for '{target_file.name}': {e.stderr[:100]}")
|
| 343 |
failed += 1
|
| 344 |
except Exception as e:
|
| 345 |
+
print(f"\n⚠️ Error while processing '{target_file.name}': {str(e)[:100]}")
|
| 346 |
failed += 1
|
| 347 |
|
| 348 |
+
print("\n🎉 Alignment completed!")
|
| 349 |
+
print(f"✅ Successful: {successful} files")
|
| 350 |
+
print(f"❌ Failed: {failed} files")
|
| 351 |
+
print(f"📁 Output directory: {output_path.resolve()}")
|
| 352 |
|
| 353 |
|
| 354 |
def prepare_simphet_files(msa_dir, simphet_ref_dir, simphet_input_dir):
|
| 355 |
"""MSA 결과를 파싱하여 Simphet-DivN용 REF 및 INPUT 파일들을 생성합니다."""
|
| 356 |
+
print("\n@ Preparing input files for Simphet-DivN analysis...")
|
| 357 |
msa_path = Path(msa_dir)
|
| 358 |
ref_path = Path(simphet_ref_dir)
|
| 359 |
input_path = Path(simphet_input_dir)
|
|
|
|
| 398 |
seq_rna = r['sequence'].upper().replace('T', 'U')
|
| 399 |
f.write(f"{r['header']}\n{seq_rna}\n")
|
| 400 |
|
| 401 |
+
print(f"✅ Created {len(list(ref_path.glob('*')))} REF files and {len(list(input_path.glob('*')))} INPUT files.")
|
| 402 |
|
| 403 |
|
| 404 |
def run_simphet_analysis(simphet_ref_dir, simphet_input_dir, output_dir, n):
|
| 405 |
"""Simphet-DivN 분석을 수행하고, 각 target 서열에 대한 변이 분석 결과를 CSV로 저장합니다."""
|
| 406 |
+
print("\n@ Starting Simphet-DivN mutation analysis...")
|
| 407 |
ref_path = Path(simphet_ref_dir)
|
| 408 |
input_path = Path(simphet_input_dir)
|
| 409 |
output_path = Path(output_dir)
|
|
|
|
| 487 |
output_csv_path = subfolder_path / f"{sanitized_header}.csv"
|
| 488 |
df.to_csv(output_csv_path, index=False)
|
| 489 |
|
| 490 |
+
print(f"✅ Mutation analysis CSV files have been saved. 📁 Output directory: {output_path}")
|
| 491 |
|
| 492 |
|
| 493 |
def select_and_rename_unknowns(output_dir, unknown_dir, settings_obj, seed=42):
|
| 494 |
"""분석된 CSV 파일들을 규칙에 따라 샘플링하고, 표준화된 이름으로 변경하여 복사합니다."""
|
| 495 |
+
print("\n@ Starting final result sampling and file renaming...")
|
| 496 |
output_path = Path(output_dir)
|
| 497 |
unknown_path = Path(unknown_dir)
|
| 498 |
unknown_path.mkdir(parents=True, exist_ok=True)
|
|
|
|
| 547 |
copy2(src, unknown_path / new_name)
|
| 548 |
copied.append(new_name)
|
| 549 |
|
| 550 |
+
print(f"✅ Copied {len(copied)} files. 📁 Output directory: {unknown_path.resolve()}")
|
| 551 |
if skipped:
|
| 552 |
+
print(f"ℹ️ Skipped {len(skipped)} files because the number of countries exceeded 10.")
|
| 553 |
|
| 554 |
|
| 555 |
# =============================================================================
|
|
|
|
| 562 |
|
| 563 |
df = load_new_sequences(s, paths)
|
| 564 |
if df.empty:
|
| 565 |
+
print("No data to process. Exiting the program.")
|
| 566 |
return
|
| 567 |
|
| 568 |
+
print("\n--- Loaded data sample ---")
|
| 569 |
print(df.head())
|
| 570 |
if 'country' in df.columns:
|
| 571 |
+
print("\n--- Countries represented in the newly collected sequences ---")
|
| 572 |
print(df['country'].unique())
|
| 573 |
print("-" * 28)
|
| 574 |
|
|
|
|
| 583 |
prepare_simphet_files(msa_dir=paths['msa_out_path'], simphet_ref_dir=paths['simphet_ref_path'], simphet_input_dir=paths['simphet_input_path'])
|
| 584 |
run_simphet_analysis(simphet_ref_dir=paths['simphet_ref_path'], simphet_input_dir=paths['simphet_input_path'], output_dir=stage1_output_dir, n=s.n)
|
| 585 |
# select_and_rename_unknowns(output_dir=stage1_output_dir, unknown_dir=paths['unknown_out'], settings_obj=s)
|
| 586 |
+
print("\n🎉 All analysis pipeline steps completed successfully.")
|
| 587 |
except Exception as e:
|
| 588 |
+
print(f"❌ An error occurred while running the analysis pipeline: {e}")
|
| 589 |
|
| 590 |
|
| 591 |
if __name__ == '__main__':
|