isahn commited on
Commit
ff55778
·
verified ·
1 Parent(s): 3b8af24

Update stage1_generate_profiles.py

Browse files
Files changed (1) hide show
  1. 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"'{fasta_dir}' 폴더에서 FASTA 파일을 찾을 수 없습니다.")
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"✅ FASTA 파일로부터 총 {len(df)}개의 시퀀스를 로드했습니다.")
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"경고: '{folder_path}' 폴더가 존재하지 않습니다.")
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@ Target 서열을 청크 단위 FASTA 파일로 저장합니다...")
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"✅ 총 {total_chunks}개의 Target FASTA 파일이 '{output_dir}'에 저장되었습니다.")
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@ Reference-Guided MAFFT 정렬을 시작합니다...")
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: Reference 파일 확인 중...")
229
  ref_files = sorted(ref_path.glob('ref*.seq'))
230
  if len(ref_files) == 0:
231
- print(f"⚠️ '{ref_dir}'에서 'ref'로 시작하는 .seq 파일을 찾을 수 없습니다.")
232
  return
233
  if len(ref_files) > 1:
234
- print(f"⚠️ Reference 파일이 {len(ref_files)}개 발견됨. 첫 번째 파일만 사용합니다.")
235
  for f in ref_files:
236
  print(f" - {f.relative_to(ref_path)}")
237
  ref_file = ref_files[0]
238
- print(f"📌 Reference 파일: {ref_file.relative_to(ref_path)}")
239
 
240
- print("🔬 Step 2/3: Target 파일들 수집 중...")
241
  target_files = sorted(list(target_path.rglob('*.seq')))
242
  if not target_files:
243
- print(f"⚠️ '{target_dir}' 및 하위 폴더에서 .seq 파일을 찾을 수 없습니다.")
244
  return
245
- print(f"📂 {len(target_files)}개 Target 파일 발견")
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"📌 정렬 기준 ref: {first_ref_header}")
267
 
268
- print("🔬 Step 3/3: Target 파일들 정렬 중...")
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}' 시간 초과 → --auto 모드로 재시도...")
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" ✅ 재시도 성공: '{target_file.name}'")
334
  successful += 1
335
  else:
336
- print(f" ❌ 재시도 후 파싱 실패: '{target_file.name}'")
337
  failed += 1
338
  except Exception as retry_e:
339
- print(f" ❌ 재시도도 실패: '{target_file.name}' → {str(retry_e)[:80]}")
340
  failed += 1
341
  except subprocess.CalledProcessError as e:
342
- print(f"\n⚠️ '{target_file.name}' 정렬 실패: {e.stderr[:100]}")
343
  failed += 1
344
  except Exception as e:
345
- print(f"\n⚠️ '{target_file.name}' 처리 중 오류: {str(e)[:100]}")
346
  failed += 1
347
 
348
- print("\n🎉 정렬 완료!")
349
- print(f"✅ 성공: {successful}개 파일")
350
- print(f"❌ 실패: {failed}개 파일")
351
- print(f"📁 저장 경로: {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@ Simphet-DivN 분석용 입력 파일을 전처리합니다...")
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"✅ REF 파일 {len(list(ref_path.glob('*')))}개, INPUT 파일 {len(list(input_path.glob('*')))}개 생성 완료.")
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"✅ 변이 분석 CSV 저장 완료. 📁 저장 경로: {output_path}")
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)}개 파일을 복사했습니다. 📁 저장 경로: {unknown_path.resolve()}")
551
  if skipped:
552
- print(f"ℹ️ {len(skipped)}개 파일은 국가 수가 10개를 초과하여 건너뛰었습니다.")
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"❌ 파이프라인 실행 중 오류가 발생했습니다: {e}")
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__':