File size: 5,134 Bytes
6c23825
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3

import argparse
import os
import subprocess
import shlex
from tqdm import tqdm
import multiprocessing
import shutil  # MODIFICATION: Import shutil for directory cleanup

def process_pdb_file(pdb_file, input_dir, output_dir, target_db, tmp_dir, show_compare=False):
    pdb_path = os.path.join(input_dir, pdb_file)
    base_name = os.path.splitext(pdb_file)[0]

    # --- MODIFICATION START: Solve Race Condition ---
    # Create a unique temporary directory for this specific job
    # to avoid conflicts when running in parallel.
    # We use the PDB base name as a unique identifier for the sub-directory.
    job_tmp_dir = os.path.join(tmp_dir, base_name)
    os.makedirs(job_tmp_dir, exist_ok=True)

    if show_compare:
        output_extension = ".html"  # Set extension to .html if show_compare is true
        format_option = "--format-mode 3"
    else:
        output_extension = ".txt"  # Default extension is .txt
        format_option = (
            "--format-output query,target,prob,alntmscore,lddt,fident,alnlen,"
            "mismatch,gapopen,qstart,qend,tstart,tend,evalue,bits"
        )
    
    # Construct the final output path with the correct extension
    output_path = os.path.join(output_dir, f"{base_name}{output_extension}")
    # --- MODIFICATION END ---

    safe_pdb_path = shlex.quote(pdb_path)
    # MODIFICATION: Use the new output_path variable
    safe_output_path = shlex.quote(output_path)
    safe_target_db = shlex.quote(target_db)
    # MODIFICATION: Use the unique job-specific temp directory
    safe_job_tmp_dir = shlex.quote(job_tmp_dir)

    # The format_option is now defined above, so the old if/else is removed
    
    foldseek_cmd = (
        f"foldseek easy-search "
        # MODIFICATION: Use the new safe_output_path and safe_job_tmp_dir variables
        f"{safe_pdb_path} {safe_target_db} {safe_output_path} {safe_job_tmp_dir} "
        f"{format_option}"
    )

    try:
        result = subprocess.run(
            foldseek_cmd,
            shell=True,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True
        )
    except subprocess.CalledProcessError as e:
        # MODIFICATION: Clean up even on failure
        shutil.rmtree(job_tmp_dir)
        return f"Warning: Failed to process {pdb_file}: {e.stderr}"
    
    # --- MODIFICATION START: Clean up the unique temp directory ---
    # After the process is successfully finished, remove its unique temp dir
    try:
        shutil.rmtree(job_tmp_dir)
    except OSError as e:
        # Log a warning if cleanup fails, but don't crash
        return f"Warning: Successfully processed {pdb_file} but failed to clean up temp dir {job_tmp_dir}: {e}"
    # --- MODIFICATION END ---

    return f"Successfully processed {pdb_file}"


def main():
    parser = argparse.ArgumentParser(description='Batch processing of Foldseek structure alignment')
    parser.add_argument('-i', '--input', required=True, help='Input directory containing PDB files')
    parser.add_argument('-o', '--output', required=True, help='Output directory for TXT/HTML results') # MODIFICATION: Updated help text
    parser.add_argument('-t', '--target', required=True, help='Target database for Foldseek search')
    parser.add_argument('-T', '--tmp', default='tmp', help='Temporary directory for intermediate files')
    parser.add_argument('-w', '--workers', type=int, default=4, help='Number of worker processes')
    parser.add_argument("--show_compare", action="store_true", help="If set, will output .html files using '--format-mode 3'") # MODIFICATION: Updated help text
    
    args = parser.parse_args()
    
    os.makedirs(args.output, exist_ok=True)
    os.makedirs(args.tmp, exist_ok=True)
    
    pdb_files = [f for f in os.listdir(args.input) if f.endswith('.pdb')]
    
    if not pdb_files:
        print(f"Error: No PDB files found in directory '{args.input}'")
        return

    # MODIFICATION: Use a list to store results for better error logging
    results = []
    
    with tqdm(total=len(pdb_files), desc="Progress") as pbar:
        def update_progress(result):
            # MODIFICATION: Store the result message and update the bar
            results.append(result)
            pbar.update(1)

        with multiprocessing.Pool(processes=args.workers) as pool:
            for pdb_file in pdb_files:
                pool.apply_async(
                    process_pdb_file,
                    (pdb_file, args.input, args.output, args.target, args.tmp, args.show_compare),
                    callback=update_progress,
                    error_callback=lambda e: pbar.update(1) # MODIFICATION: Ensure bar updates on critical error
                )
            pool.close()
            pool.join()
    
    print(f"\nProcessing completed! Results saved to: {args.output}")

    # MODIFICATION: Log any warnings at the end
    warnings = [r for r in results if r.startswith("Warning:")]
    if warnings:
        print("\n--- Warnings ---")
        for w in warnings:
            print(w)


if __name__ == '__main__':
    main()