-
Notifications
You must be signed in to change notification settings - Fork 0
/
analyzer.py
executable file
·583 lines (519 loc) · 23.1 KB
/
analyzer.py
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# Name: GenomeSuite Analyzer
# Author: Richard Casey
# Date: 09-02-2024 (DD-MM-YYYY)
# Purpose: Human genome structural variant caller.
# Version: v.1.3.0
# Notes: In production mode, this application requires Nvidia GPU's (H100, A100, V100).
# Standard library imports
import argparse
import os
import subprocess
import sys
# Third-party imports
import boto3
from botocore.exceptions import ClientError
from botocore.exceptions import NoCredentialsError
from botocore.exceptions import PartialCredentialsError
# Local application/library specific imports
from utilities.fileUtil import clear_files
from utilities.loggerUtil import logger
def run_command(command: str) -> None:
"""Run a shell command and print the output."""
try:
result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
logger.info(f"{result.stdout}")
logger.info(f"{result.stderr}")
except subprocess.CalledProcessError as e:
logger.error(f"ERROR: run_command failed with error: {e}")
logger.error(f"STDOUT: {e.stdout}")
logger.error(f"STDERR: {e.stderr}")
sys.exit(1)
def set_environment_variables(sample_name: str) -> None:
"""Set environment variables."""
try:
# check which server is hosting the code
home_dir = os.path.expanduser("~") # get home directory
if home_dir == '/home/seqcenter':
os.environ['BASE_DIR'] = '/home/seqcenter/analyzer' # for development ubuntu
elif home_dir == '/home/ubuntu':
os.environ['BASE_DIR'] = '/home/ubuntu/analyzer' # for production ubuntu on AWS
else:
logger.error("ERROR: unknown home directory setting")
sys.exit(1)
except ValueError as e:
logger.error(f"Error: an unexpected error occured{e}")
sys.exit(1)
# MAIN DIRS
os.environ['INPUT_DIR'] = f"{os.environ['BASE_DIR']}/data/INPUTS"
os.environ['OUTPUT_DIR'] = f"{os.environ['BASE_DIR']}/data/OUTPUTS"
# POD5
os.environ['POD5_FILES_DIR'] = f"{os.environ['INPUT_DIR']}/POD5_FILES"
# FAST5
os.environ['FAST5_FILES_DIR'] = f"{os.environ['INPUT_DIR']}/FAST5_FILES"
# BAM
os.environ['BAM_FILES_DIR'] = f"{os.environ['INPUT_DIR']}/BAM_FILES"
os.environ['BAM_FILE'] = f"{os.environ['INPUT_DIR']}/BAM_FILES/{sample_name}.bam"
os.environ['BAM_SORTED_FILE'] = f"{os.environ['INPUT_DIR']}/BAM_FILES/{sample_name}.sorted.bam"
os.environ['BAM_SORTED_INDEX_FILE'] = f"{os.environ['INPUT_DIR']}/BAM_FILES/{sample_name}.sorted.bam.bai"
# REFERENCE
os.environ['REF_FILES_DIR'] = f"{os.environ['INPUT_DIR']}/REF_FILES"
os.environ['REF_FILE'] = f"{os.environ['INPUT_DIR']}/REF_FILES/GCA_009914755.4_T2T-CHM13v2.0_genomic.fna.gz"
# MODELS
os.environ['DORADO_MODELS'] = f"{os.environ['BASE_DIR']}/dorado_models"
# ANALYZER
os.environ['ANALYZER_FILES_DIR'] = f"{os.environ['OUTPUT_DIR']}/analyzer_output"
os.environ['ANALYZER_VCF_FILE'] = f"{os.environ['ANALYZER_FILES_DIR']}/{sample_name}.vcf.gz"
# THREADS
os.environ['THREADS'] = '14'
def check_s3_bucket_exists(bucket_name: str) -> bool:
"""Check if the specified S3 bucket exists."""
s3 = boto3.client('s3')
try:
s3.head_bucket(Bucket=bucket_name)
return True
except ClientError as e:
if e.response['Error']['Code'] == '404':
return False
else:
raise
except NoCredentialsError:
logger.error("ERROR: AWS credentials not found.")
sys.exit(1)
except PartialCredentialsError:
logger.error("ERROR: Incomplete AWS credentials.")
sys.exit(1)
def check_s3_subdirectory_exists(bucket_name: str, subdirectory: str) -> bool:
"""Check if the specified subdirectory exists in the S3 bucket."""
s3 = boto3.client('s3')
try:
result = s3.list_objects_v2(Bucket=bucket_name, Prefix=subdirectory, MaxKeys=1)
if 'Contents' in result:
return True
else:
return False
except ClientError as e:
logger.error(f"ERROR: Subdirectory '{subdirectory}' does not exist in bucket '{bucket_name}': {e}")
sys.exit(1)
def dorado_models():
"""List of available dorado models"""
models = [
"[email protected]_5mCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mC_5hmC@v1",
"[email protected]_5mCG_5hmCG@v1",
"[email protected]_6mA@v1",
"[email protected]_6mA@v2",
"[email protected]_4mC_5mC@v1",
"[email protected]_5mC_5hmC@v1",
"[email protected]_5mCG_5hmCG@v1",
"[email protected]_6mA@v1",
"[email protected]_5mCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mC_5hmC@v1",
"[email protected]_5mCG_5hmCG@v2",
"[email protected]_5mC@v2",
"[email protected]_6mA@v2",
"[email protected]_6mA@v3",
"[email protected]_5mC_5hmC@v1",
"[email protected]_5mCG_5hmCG@v1",
"[email protected]_6mA@v1",
"[email protected]_6mA@v2",
"[email protected]_4mC_5mC@v1",
"[email protected]_5mC_5hmC@v1",
"[email protected]_5mCG_5hmCG@v1",
"[email protected]_6mA@v1",
"[email protected]_5mCG_5hmCG@v0",
"[email protected]_5mCG_5hmCG@v0",
"[email protected]_5mCG_5hmCG@v0",
"rna002_70bps_fast@v3",
"rna002_70bps_hac@v3",
"[email protected]_m6A@v1",
"[email protected]_pseU@v1",
"[email protected]_m6A_DRACH@v1",
"[email protected]_m6A@v1",
"[email protected]_pseU@v1",
]
return models
def print_dorado_models():
"""Print the list of available dorado models"""
models = dorado_models()
print("Available dorado model names:")
for model in models:
print(model)
def copy_pod5_sample_files_S3_to_EC2(bucket_name: str, sample_name: str) -> None:
"""Copy pod5 sample files from S3 to EC2.
Parameters:
--recursive : Copy files recursively. This is a required parameter.
"""
command = (
f"aws s3 cp s3://{bucket_name}/pod5/ "
f"{os.environ['POD5_FILES_DIR']} "
"--recursive"
)
run_command(command)
def copy_fast5_sample_files_S3_to_EC2(bucket_name: str, sample_name: str) -> None:
"""Copy fast5 sample files from S3 to EC2.
Parameters:
--recursive : Copy files recursively. This is a required parameter.
"""
command = (
f"aws s3 cp s3://{bucket_name}/fast5/ "
f"{os.environ['FAST5_FILES_DIR']} "
"--recursive"
)
run_command(command)
def copy_bam_file_S3_to_EC2(bucket_name: str, sample_name: str) -> None:
"""Copy bam file from S3 to EC2.
Parameters:
--recursive : Copy files recursively. This is a required parameter.
"""
command = (
f"aws s3 cp s3://{bucket_name}/bam/ "
f"{os.environ['BAM_FILES_DIR']}"
)
run_command(command)
def convert_fast5_to_pod5(sample_name: str) -> None:
"""Convert FAST5 file to POD5 file.
In pod5 output directory, the default output filename is output.pod5. Rename this file using the "-s" parameter.
Parameters:
-o : POD5 output directory.
-t : Number of threads.
sample_name : The name to use for renaming the output.pod5 file.
"""
command = (
"pod5 convert fast5 "
f" {os.environ['FAST5_FILES_DIR']} "
f"-o {os.environ['POD5_FILES_DIR']} "
f"-t {os.environ['THREADS']}"
)
run_command(command)
# Rename output.pod5 file using the "-s" parameter
try:
original_file = os.path.join(os.environ['POD5_FILES_DIR'], "output.pod5")
new_file = os.path.join(os.environ['POD5_FILES_DIR'], f"{sample_name}.pod5")
os.rename(original_file, new_file)
logger.info(f"Renamed {original_file} to {new_file}")
except Exception as e:
logger.error(f"ERROR: Failed to rename output.pod5 to {sample_name}.pod5: {e}")
sys.exit(1)
def get_gpu_architecture() -> str:
"""Determine if a Nvidia GPU with architecture Volta, Ampere or Hopper is available"""
try:
# Use nvidia-smi to get GPU info
result = subprocess.run(['nvidia-smi', '--query-gpu=name', '--format=csv,noheader'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode != 0:
return None # No Nvidia GPU detected
gpu_name: str = result.stdout.strip()
# Check for architectures of interest
if any(arch in gpu_name for arch in ['Volta', 'Ampere', 'Hopper']):
return 'cuda'
else:
return 'cpu'
except FileNotFoundError:
return 'cpu' # nvidia-smi not found, so assume no GPU is present
def convert_pod5_to_bam(modelname: str) -> None:
"""Convert POD5 file to BAM file using dorado basecaller.
Note: In production mode, set "-x" to "cuda:all" so it uses Nvidia GPU's (H100, A100, V100).
Parameters:
-x : use cpu only or use gpu's. device string in format "cuda:0,...,N", "cuda:all", "metal", "cpu", etc.., [default: "cuda:all"]
"""
# Determine whether to use CPU or GPU (GPU architecture must be Volta, Ampere or Hopper)
gpu_arch = get_gpu_architecture()
# Construct appropriate dorado command for CPU or GPU
if gpu_arch == 'cuda':
command = (
"dorado basecaller "
"-x cuda:all "
f"--reference {os.environ['REF_FILE']} "
f" {os.environ['DORADO_MODELS']}/{modelname} "
f" {os.environ['POD5_FILES_DIR']} > " # this parameter is either a single file name or a directory name (confusing)
f" {os.environ['BAM_FILE']}"
)
else:
command = (
"dorado basecaller "
"-x cpu "
f"--reference {os.environ['REF_FILE']} "
f" {os.environ['DORADO_MODELS']}/{modelname} "
f" {os.environ['POD5_FILES_DIR']} > " # this parameter is either a single file name or a directory name (confusing)
f" {os.environ['BAM_FILE']}"
)
run_command(command)
def create_bam_index_file() -> None:
"""Create bam index file."""
command = (
"samtools index "
f"-@ {os.environ['THREADS']} "
f" {os.environ['BAM_FILE']}"
)
run_command(command)
def sort_bam_file() -> None:
"""Sort bam file."""
command = (
"samtools sort "
f"--threads {os.environ['THREADS']} "
f" {os.environ['BAM_FILE']} "
f"-o {os.environ['BAM_SORTED_FILE']}"
)
run_command(command)
def create_sorted_bam_index_file() -> None:
"""Create sorted bam index file."""
command = (
"samtools index "
f"-@ {os.environ['THREADS']} "
f" {os.environ['BAM_SORTED_FILE']}"
)
run_command(command)
def run_analyzer() -> None:
"""
Perform sturctural variant calling.
Parameters:
-i : Input sorted BAM file.
-v : Output analyzer VCF file
-t : Number of threads.
--allow-overwrite : Overwrite existing output files
"""
command = (
"sniffles "
f"-i {os.environ['BAM_SORTED_FILE']} "
f"-v {os.environ['ANALYZER_VCF_FILE']} "
f"-t {os.environ['THREADS']} "
f"--allow-overwrite"
)
run_command(command)
def copy_bam_files_to_s3(bucket_name: str, sample_name: str) -> None:
"""Copy BAM files to the specified S3 bucket."""
try:
output_dir = os.environ['BAM_FILES_DIR']
bam_files = [
f"{output_dir}/{sample_name}.bam",
f"{output_dir}/{sample_name}.sorted.bam",
f"{output_dir}/{sample_name}.sorted.bam.bai"
]
for bam_file in bam_files:
command = f"aws s3 cp {bam_file} s3://{bucket_name}/bam/"
run_command(command)
except Exception as e:
logger.error(f"ERROR: Failed to copy BAM files to S3: {e}")
sys.exit(1)
def copy_vcf_file_to_s3(bucket_name: str, sample_name: str) -> None:
"""Copy the VCF file to the specified S3 bucket."""
try:
output_dir = os.environ['ANALYZER_FILES_DIR']
vcf_file = f"{output_dir}/{sample_name}.vcf.gz"
command = f"aws s3 cp {vcf_file} s3://{bucket_name}/reports/"
run_command(command)
except Exception as e:
logger.error(f"ERROR: Failed to copy VCF file to S3: {e}")
sys.exit(1)
# main entry point
if __name__ == "__main__":
try:
# set S3 bucket name, sample name, file type and model name
parser = argparse.ArgumentParser()
parser.add_argument("-b", "--bucketname", help="Enter a bucket name for this run.")
parser.add_argument("-s", "--samplename", help="Enter a sample name for this run.")
parser.add_argument('-f', '--filetype', help='Specify the type of input file: POD5, FAST5 or BAM', choices=['pod5', 'fast5', 'bam'])
parser.add_argument('-m', '--modelname', help="Specify the model name to use or omit to see available models. If not specified, default model will be used.", nargs='?')
# Parse arguments
args, unknown = parser.parse_known_args()
# Check if only `-m` is provided
if args.modelname is None and not args.bucketname and not args.samplename and not args.filetype:
print_dorado_models()
sys.exit(0)
# If other required arguments are missing, show an error
if not args.bucketname or not args.samplename or not args.filetype:
logger.error("ERROR: the following arguments are required: -b/--bucketname, -s/--samplename, -f/--filetype")
sys.exit(1)
# Use default dorado model if one is not provided on command line
modelname = args.modelname if args.modelname else "[email protected]"
# Validate user supplied dorado model name against the list in dorado_models
if modelname not in dorado_models():
logger.error(f"ERROR: Model name '{modelname}' not found in the list of available models. Check your spelling for the model name.")
print_dorado_models()
sys.exit(1)
# Start the run
logger.info("Start Analyzer...")
# set env vars
try:
logger.info("Set environment variables...")
set_environment_variables(args.samplename)
except Exception as e:
logger.error(f"ERROR: Could not set environment variables {e}")
sys.exit(1)
# delete all files in subdirectories to set initial state for application
try:
logger.info("Clear files...")
clear_files()
except Exception as e:
logger.error(f"ERROR: Failed to clear files: {e}")
# Check if S3 bucket exists
try:
logger.info("Check if AWS S3 bucket exists...")
if not check_s3_bucket_exists(args.bucketname):
logger.error(f"ERROR: AWS S3 bucket '{args.bucketname}' does not exist.")
sys.exit(1)
except NoCredentialsError:
logger.error("ERROR: AWS credentials not found.")
sys.exit(1)
except PartialCredentialsError:
logger.error("ERROR: Incomplete AWS credentials.")
sys.exit(1)
except Exception as e:
logger.error(f"ERROR: An error occurred while checking the AWS S3 bucket: {e}")
sys.exit(1)
# check if subdirectories exist
try:
logger.info("Check if AWS S3 bucket subdirectories exist...")
subdirectories = ['pod5', 'fast5', 'bam', 'reports']
for subdir in subdirectories:
if not check_s3_subdirectory_exists(args.bucketname, subdir):
logger.error(f"ERROR: Subdirectory '{subdir}' does not exist in bucket '{args.bucketname}'.")
sys.exit(1)
except ClientError as e:
logger.error(f"ERROR: An error occurred while checking subdirectories in the bucket '{args.bucketname}': {e}")
sys.exit(1)
except Exception as e:
logger.error(f"ERROR: An unexpected error occurred while checking subdirectories: {e}")
sys.exit(1)
# 1. copy pod5 or fast5 sample files or bam file from S3 seqcenter-samples bucket to EC2 POD5, FAST5 or BAM directory
if args.filetype == "pod5":
try:
logger.info("Copy POD5 sample files from S3 to EC2...")
copy_pod5_sample_files_S3_to_EC2(args.bucketname, args.samplename)
except Exception as e:
logger.error(f"ERROR: Failed to copy POD5 sample files from S3 to EC2: {e}")
sys.exit(1)
elif args.filetype == "fast5":
try:
logger.info("Copy FAST5 sample files from S3 to EC2...")
copy_fast5_sample_files_S3_to_EC2(args.bucketname, args.samplename)
except Exception as e:
logger.error(f"ERROR: Failed to copy FAST5 sample files from S3 to EC2: {e}")
sys.exit(1)
elif args.filetype == "bam":
try:
logger.info("Copy BAM file from S3 to EC2...")
copy_bam_file_S3_to_EC2(args.bucketname, args.samplename)
except Exception as e:
logger.error(f"ERROR: Failed to copy BAM file from S3 to EC2: {e}")
sys.exit(1)
# 2. convert fast5 file to pod5 file
if args.filetype == "fast5":
try:
logger.info("Convert fast5 to pod5...")
convert_fast5_to_pod5(args.samplename)
except Exception as e:
logger.error(f"ERROR: Failed to convert fast5 to pod5: {e}")
sys.exit(1)
# 3. convert pod5 file to bam file
# skip this step if input file is BAM
if args.filetype in ["pod5", "fast5"]:
try:
logger.info("Convert pod5 to bam...")
convert_pod5_to_bam(modelname)
except Exception as e:
logger.error(f"ERROR: Failed to convert pod5 to bam: {e}")
sys.exit(1)
# 4. sort bam file
try:
logger.info("Sort bam file...")
sort_bam_file()
except Exception as e:
logger.error(f"ERROR: Failed to sort bam file: {e}")
sys.exit(1)
# 5. create sorted bam index file
try:
logger.info("Create sorted bam index file...")
create_sorted_bam_index_file()
except Exception as e:
logger.error(f"ERROR: Failed to create sorted bam index file: {e}")
sys.exit(1)
# 6. perform structural variant calling
try:
logger.info("Perform structural variant calling...")
run_analyzer()
except Exception as e:
logger.error(f"ERROR: Failed to perform structural variant calling: {e}")
sys.exit(1)
# 7. copy BAM files to S3 bucket
try:
logger.info("Copy BAM files to S3 bucket...")
copy_bam_files_to_s3(args.bucketname, args.samplename)
except Exception as e:
logger.error(f"ERROR: Failed to copy BAM files to S3 bucket: {e}")
sys.exit(1)
# 8. copy VCF files to S3 bucket
try:
logger.info("Copy VCF file to S3 bucket...")
copy_vcf_file_to_s3(args.bucketname, args.samplename)
except Exception as e:
logger.error(f"ERROR: Failed to copy VCF file to S3 bucket: {e}")
sys.exit(1)
# End the run
logger.info("Finish Analyzer...")
except Exception as e:
logger.error(f"ERROR: an error occurred in main: {e}")
sys.exit(1)