Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
5686 lines (4346 loc) · 236 KB
/
Copy pathutils.py
File metadata and controls
5686 lines (4346 loc) · 236 KB
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Lonely, helper functions that are broadly used and don't fit anywhere"""
# The following try/except block is to make sure when git hooks are doing
# their things in anvi'o development environments, we have a means to remind
# developers that they may have not initialized their anvi'o environment
# properly. This didn't have to be in utils.py, but since this module is
# imported from so many other modules, it is kind of an appropriate place
# for this
try:
import os
import sys
import ssl
import json
import yaml
import gzip
import time
import copy
import random
import socket
import shutil
import tarfile
import hashlib
import textwrap
import linecache
import webbrowser
import subprocess
import tracemalloc
import urllib.request
import numpy as np
import pandas as pd
import Bio.PDB as PDB
import itertools as it
from numba import jit
from collections import Counter
import anvio
import anvio.db as db
import anvio.tables as t
import anvio.fastalib as u
import anvio.constants as constants
import anvio.filesnpaths as filesnpaths
from anvio.dbinfo import DBInfo as dbi
from anvio.sequence import Composition
from anvio.version import versions_for_db_types
from anvio.errors import ConfigError, FilesNPathsError
from anvio.terminal import Run, Progress, SuppressAllOutput, get_date, TimeCode, pluralize
except ModuleNotFoundError as e:
# Extract just the module name from "No module named 'modulename'"
module_name = str(e).split("'")[1] if "'" in str(e) else str(e)
print(f"\n\nWARNING\n"
f"\n===========================================================\n"
f"The anvi'o conda environment does not seem to have not been\n"
f"properly initialized since Python complains that it cannot\n"
f"import '{module_name}'. Are you sure you have initialized\n"
f"the anvi'o environment properly?\n\n")
sys.exit(1)
# psutil is causing lots of problems for lots of people :/
with SuppressAllOutput():
try:
import psutil
PSUTIL_OK=True
except:
PSUTIL_OK=False
__copyright__ = "Copyleft 2015-2024, The Anvi'o Project (http://anvio.org/)"
__credits__ = []
__license__ = "GPL 3.0"
__version__ = anvio.__version__
__maintainer__ = "A. Murat Eren"
__email__ = "a.murat.eren@gmail.com"
__status__ = "Development"
# for full output
pd.options.display.max_columns=100
pd.options.display.max_rows=100
# Mock progress object that will not report anything, for general clarity.
progress = Progress()
progress.verbose = False
run = Run()
run.verbose = False
def get_total_memory_usage(keep_raw=False):
"""Get the total memory, including children
Parameters
==========
keep_raw : bool, False
A human readable format is returned, e.g. "1.41 GB". If keep_raw, the raw number is
returned, e.g. 1515601920
"""
if not PSUTIL_OK:
return None
current_process = psutil.Process(os.getpid())
mem = current_process.memory_info().rss
for child in current_process.children(recursive=True):
try:
mem += child.memory_info().rss
except:
pass
return mem if keep_raw else human_readable_file_size(mem)
def display_top_memory_usage(snapshot, key_type='lineno', limit=10):
"""A pretty-print for the tracemalloc memory usage module
Modified from https://docs.python.org/3/library/tracemalloc.html
Examples
========
>>> import tracemalloc
>>> import anvio.utils as utils
>>> tracemalloc.start()
>>> snap = tracemalloc.take_snapshot
>>> utils.display_top_memory_usage(snap)
Top 10 lines
#1: anvio/bamops.py:160: 4671.3 KiB
constants.cigar_consumption,
#2: anvio/bamops.py:96: 2571.6 KiB
self.cigartuples = np.array(read.cigartuples)
#3: python3.6/linecache.py:137: 1100.0 KiB
lines = fp.readlines()
#4: <frozen importlib._bootstrap_external>:487: 961.4 KiB
#5: typing/templates.py:627: 334.3 KiB
return type(base)(name, (base,), dct)
#6: typing/templates.py:923: 315.7 KiB
class Template(cls):
#7: python3.6/_weakrefset.py:84: 225.2 KiB
self.data.add(ref(item, self._remove))
#8: targets/npyimpl.py:411: 143.2 KiB
class _KernelImpl(_Kernel):
#9: _vendor/pyparsing.py:3349: 139.7 KiB
self.errmsg = "Expected " + _ustr(self)
#10: typing/context.py:456: 105.1 KiB
def on_disposal(wr, pop=self._globals.pop):
3212 other: 4611.9 KiB
Total allocated size: 15179.4 KiB
"""
snapshot = snapshot.filter_traces((
tracemalloc.Filter(False, "<frozen importlib._bootstrap>"),
tracemalloc.Filter(False, "<unknown>"),
))
top_stats = snapshot.statistics(key_type)
print("Top %s lines" % limit)
for index, stat in enumerate(top_stats[:limit], 1):
frame = stat.traceback[0]
# replace "/path/to/module/file.py" with "module/file.py"
filename = os.sep.join(frame.filename.split(os.sep)[-2:])
print("#%s: %s:%s: %.1f KiB"
% (index, filename, frame.lineno, stat.size / 1024))
line = linecache.getline(frame.filename, frame.lineno).strip()
if line:
print(' %s' % line)
other = top_stats[limit:]
if other:
size = sum(stat.size for stat in other)
print("%s other: %.1f KiB" % (len(other), size / 1024))
total = sum(stat.size for stat in top_stats)
print("Total allocated size: %.1f KiB" % (total / 1024))
def rev_comp(seq):
return seq.translate(constants.complements)[::-1]
def rev_comp_gene_calls_dict(gene_calls_dict, contig_sequence, preserve_gene_caller_ids=False):
contig_length = len(contig_sequence)
gene_caller_ids = list(gene_calls_dict.keys())
if preserve_gene_caller_ids:
# the caller wants to keep the original gene caller ids rather than resetting them to
# start from 0, so the conversion dict is simply an identity mapping
gene_caller_id_conversion_dict = dict([(g, g) for g in gene_caller_ids])
else:
gene_caller_id_conversion_dict = dict([(gene_caller_ids[-i - 1], i) for i in range(0, len(gene_caller_ids))])
G = lambda g: gene_caller_id_conversion_dict[g]
reverse_complemented_gene_calls = {}
for gene_callers_id in gene_calls_dict:
g = copy.deepcopy(gene_calls_dict[gene_callers_id])
g['start'], g['stop'] = contig_length - g['stop'], contig_length - g['start']
g['direction'] = 'f' if g['direction'] == 'r' else 'r'
reverse_complemented_gene_calls[G(gene_callers_id)] = g
return reverse_complemented_gene_calls, gene_caller_id_conversion_dict
def serialize_args(args, single_dash=False, use_underscore=False, skip_keys=None, translate=None):
cmdline = []
for param, value in args.__dict__.items():
if isinstance(skip_keys, list):
if param in skip_keys:
continue
if translate and param in translate:
param = translate[param]
dash = '-' if single_dash else '--'
if not use_underscore:
param = param.replace('_', '-')
if value is True:
cmdline.append('%s%s' % (dash, param))
elif value is not False and value is not None:
cmdline.append('%s%s' % (dash, param))
cmdline.append(str(value))
return cmdline
def get_predicted_type_of_items_in_a_dict(d, key):
"""Gets a dictionary `d` and a `key` in it, and returns a type function.
It is a bit counter intuitive. dictionary should look like this:
d = {'x': {'key': item, (...)},
'y': {'key': item, (...)},
(...),
}
This is a shitty function, but there was a real need for it, so here we are :/
"""
items = [x.get(key) for x in d.values()]
if not items:
# there is nothing to see here
return None
try:
if(set(items) == set([None])):
# all items is of type None.
return None
except TypeError:
# this means we are working with an unhashable type.
# it is either list or dict. we will go through items
# and return the type of first item that is not None:
for item in items:
if item == None:
continue
else:
return type(item)
# the code should never come to this line since if everything
# was None that would have been captured by the try block and the
# exception would have never been thrown, but here is a final line
# just to be sure we are not moving on with the rest of the code
# if we entered into this block:
return None
# if we are here, it means not all items are None, and they are not of
# unhashable types (so they must be atomic types such as int, float, or str)
not_float = False
for item in items:
try:
float(item or 0)
except ValueError:
not_float = True
break
if not_float:
return str
else:
for item in items:
try:
if int(item or 0) == float(item or 0):
continue
else:
return float
except ValueError:
return float
return int
def human_readable_file_size(nbytes):
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
if nbytes == 0: return '0 B'
i = 0
while nbytes >= 1024 and i < len(suffixes)-1:
nbytes /= 1024.
i += 1
f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
return '%s %s' % (f, suffixes[i])
def human_readable_number(value, decimals=2, suffixes=None):
"""Return a compact string for large numbers (e.g., 12340 -> 12.3K)."""
suffixes = suffixes or ['', 'K', 'M', 'G', 'T', 'P']
try:
num = float(value)
except (TypeError, ValueError):
return str(value)
negative = num < 0
num = abs(num)
if num == 0:
return '0'
i = 0
while num >= 1000 and i < len(suffixes) - 1:
num /= 1000.0
i += 1
fmt = f"{{:.{decimals}f}}".format(num).rstrip('0').rstrip('.')
return f"{'-' if negative else ''}{fmt}{suffixes[i]}"
def get_port_num(port_num = 0, ip='0.0.0.0', run=run):
"""Get a port number for the `ip` address."""
try:
port_num = int(port_num) if port_num else 0
except Exception as e:
raise ConfigError("Not a happy port number :/ %s." % e)
if not port_num:
port_num = get_next_available_port_num(constants.default_port_number)
if not port_num:
raise ConfigError("Anvi'o searched a bunch of port numbers starting from %d, but failed "
"to find an available one for you. Maybe you should specify one :/")
else:
if is_port_in_use(port_num):
raise ConfigError("The port number %d seems to be in use :/" % port_num)
if os.getuid() and port_num < 1024:
run.warning("Using the port number %d requires superuser priviliges, which your user does not "
"seem to have. Since anvi'o does not know anything about your system configuraiton, "
"you are free to go for now. But be prepared for a failed attempt to use this port "
"number to serve stuff." % port_num)
return port_num
def get_next_available_port_num(start=constants.default_port_number, look_upto_next_num_ports=100, ip='0.0.0.0'):
"""Starts from 'start' and incrementally looks for an available port
until 'start + look_upto_next_num_ports', and returns the first
available one."""
for p in range(start, start + look_upto_next_num_ports):
if not is_port_in_use(p, ip):
return p
return None
def is_port_in_use(port, ip='0.0.0.0'):
in_use = False
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip, port))
if result == 0:
in_use = True
sock.close()
return in_use
def get_available_program_names_in_active_environment(prefix=None, contains=None, postfix=None):
"""Find all executable programs in the current environment that match the given criteria.
Parameters
==========
prefix : str, optional
The prefix to search for (e.g., 'anvi-')
contains : str, optional
String that must be contained in the program name (e.g., 'graph')
postfix : str, optional
The postfix/suffix to search for (e.g., '.py', '-dev')
Returns
=======
program_names : set
A set of program names that match all specified criteria
"""
program_names = set()
# Get all directories in PATH
path_dirs = os.environ.get('PATH', '').split(os.pathsep)
for path_dir in path_dirs:
if not path_dir or not os.path.isdir(path_dir):
continue
try:
# List all files in the directory
for item in os.listdir(path_dir):
item_path = os.path.join(path_dir, item)
# Check if it's a file and executable
if os.path.isfile(item_path) and os.access(item_path, os.X_OK):
# Check all specified criteria
matches = True
if prefix is not None:
if not item.lower().startswith(prefix.lower()):
matches = False
if contains is not None and matches:
if contains.lower() not in item.lower():
matches = False
if postfix is not None and matches:
if not item.lower().endswith(postfix.lower()):
matches = False
if matches:
program_names.add(item)
except (PermissionError, OSError):
# Skip directories we can't read
continue
return program_names
def is_program_exists(program, dont_raise=False):
IsExe = lambda p: os.path.isfile(p) and os.access(p, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if IsExe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = os.path.expanduser(path).strip('"')
exe_file = os.path.join(path, program)
if IsExe(exe_file):
return exe_file
if dont_raise:
return False
raise ConfigError("An anvi'o function needs '%s' to be installed on your system, but it doesn't seem to appear "
"in your path :/ If you are certain you have it on your system (for instance you can run it "
"by typing '%s' in your terminal window), you may want to send a detailed bug report. Sorry!"
% (program, program))
def format_cmdline(cmdline):
"""Takes a cmdline for `run_command` or `run_command_STDIN`, and makes it beautiful."""
if not cmdline or (not isinstance(cmdline, str) and not isinstance(cmdline, list)):
raise ConfigError("You made utils::format_cmdline upset. The parameter you sent to run kinda sucks. It should be string "
"or list type. Note that the parameter `shell` for subprocess.call in this `run_command` function "
"is always False, therefore if you send a string type, it will be split into a list prior to being "
"sent to subprocess.")
if isinstance(cmdline, str):
cmdline = [str(x) for x in cmdline.split(' ')]
else:
cmdline = [str(x) for x in cmdline]
return cmdline
def gzip_compress_file(input_file_path, output_file_path=None, keep_original=False):
filesnpaths.is_file_exists(input_file_path)
if not output_file_path:
output_file_path = input_file_path + '.gz'
filesnpaths.is_output_file_writable(output_file_path)
import gzip
with open(input_file_path, 'rb') as f_in, gzip.open(output_file_path, 'wb') as f_out:
f_out.writelines(f_in)
if not keep_original:
os.remove(input_file_path)
def gzip_decompress_file(input_file_path, output_file_path=None, keep_original=True):
filesnpaths.is_file_exists(input_file_path)
if not input_file_path.endswith('.gz'):
raise ConfigError("gzip_decompress_file function is upset because your input file ('%s') does not "
"end with a '.gz' extension :(")
if not output_file_path:
output_file_path = input_file_path[:-3]
filesnpaths.is_output_file_writable(output_file_path)
import gzip
with gzip.open(input_file_path, 'rb') as f_in, open(output_file_path, 'wb') as f_out:
f_out.writelines(f_in)
if not keep_original:
os.remove(input_file_path)
return output_file_path
def tar_extract_file(input_file_path, output_file_path=None, keep_original=True):
filesnpaths.is_file_tar_file(input_file_path)
if not output_file_path:
raise ConfigError("The tar_extract_file function is displeased because an output file path has not been specified. "
"If you are seeing this message, you are probably a developer, so go fix your code please, and "
"everyone will be happy then.")
tf = tarfile.open(input_file_path)
tf.extractall(path = output_file_path)
if not keep_original:
os.remove(input_file_path)
def validate_discov_params(window_length, window_length_as_percentage, min_window_length, alpha, discov_formula, require_window_param=True):
"""Validate distribution of coverage (discov) parameters and raise ConfigError for any invalid combination.
Parameters
==========
window_length : int or None
Fixed window length in bp.
window_length_as_percentage : int or None
Window length as a percentage of the sequence length.
min_window_length : int or None
Minimum window length when using window_length_as_percentage.
alpha : float
Weight of S in the discov score. Must be in [0, 1].
discov_formula : str
Combination formula. Must be 'linear' or 'geometric'.
require_window_param : bool
When True, raise an error if neither window_length nor window_length_as_percentage
is set. Set to False for callers (e.g. anvi-summarize) that supply context-sensitive
defaults when the user omits both flags.
"""
if require_window_param and not window_length and not window_length_as_percentage:
raise ConfigError("In order to compute distribution of coverage (discov), we need you to specify a scheme "
"for setting the window length. Either provide an exact length using --window-length or a "
"percentage value (as an integer) using --window-length-as-percentage.")
if window_length and window_length_as_percentage:
raise ConfigError("Please choose either --window-length or --window-length-as-percentage, not both.")
if (window_length and window_length <= 0) or (window_length_as_percentage and window_length_as_percentage <= 0):
raise ConfigError("A positive window length (or percentage) is required for computing distribution of coverage (discov).")
if window_length_as_percentage and window_length_as_percentage > 100:
raise ConfigError("We cannot work with windows that are longer than 100% of a given sequence. Please change your "
"--window-length-as-percentage value.")
if window_length and min_window_length:
raise ConfigError("The --min-window-length is only relevant when using the --window-length-as-percentage option.")
if min_window_length and min_window_length < 0:
raise ConfigError("The --min-window-length parameter has to be a positive integer.")
if alpha is None:
raise ConfigError("You'd better be a programmer messing with stuff, because it is not supposed to be possible "
"to pass a None value for the discov alpha parameter. Nor is it advisable (because it will "
"throw off the calculation), so we are stopping the show right here.")
if alpha < 0 or alpha > 1:
raise ConfigError("The --alpha parameter for discov should take a value between 0 and 1 (inclusive). Keep in "
"mind that it is going to be used to combine S and E into the spread-evenness score as either "
"C = αS + (1-α)E or C = S^α * E^(1-α). Hopefully that helps explain these restrictions :)")
if discov_formula not in ('linear', 'geometric'):
raise ConfigError(f"The --discov-formula parameter must be either 'linear' or 'geometric', but you provided "
f"'{discov_formula}'. Please fix that and try again.")
class CoverageStats:
"""A class to return coverage stats for an array of nucleotide level coverages.
FIXME: This class should replace `coverage_c` function in bamops to avoid redundancy.
In addition to the classic stats, this class can also compute a distribution of coverage (discov)
score, which can be used to assess presence-absence of the reference sequence in a metagenomic
sample. Discov combines a metric for assessing spread of coverage across the sequence (S), a
metric for assessing the evenness of nonzero coverage depth (E), and detection.
S is the proportion of non-overlapping, equal-sized windows that contain at least some coverage.
If the last window is shorter than 10% of the window length, it's dropped before counting. We
normalize S with the 'expected spread' computed by assuming reads distribute randomly; that is,
S_exp = 1 − e^(−(B + N·w)/G), where B is the total aligned read length, N is number of reads that mapped,
w is the window length, and G is the reference length. Normalized spread is therefore min(1, S / S_exp),
so it will be closer to 1 if reads truly distribute randomly and the observed proportion of covered windows
is as high (or higher) than we expect.
E is a 0-1 evenness score that computes the coefficient of variation (CV) on the nonzero mean coverages
of the same non-overlapping, equal-sized windows used in S. E = 1 / (1 + CV). If fewer than 3 windows have
coverage (which can happen on short or poorly covered sequences), we do not compute CV and E is set to 0
(maximum unevenness).
We combine (normalized) S and E into a 'spread-evenness score'. They can be combined linearly
with a weight α following the formula: C = αS_norm + (1-α)E. Or, they can be combined by
taking a weighted geometric mean following the formula: C = S_norm^α * E^(1-α).
Finally, we compute discov by adding detection on top of the spread-evenness score. The boost
provided by the detection value is modulated so that large values yield a disproportionately larger
boost than small values (since small detection does not necessarily imply absence).
discov = min(1, C + D^2)
Parameters
==========
coverage : array
Nucleotide-level coverages. The only required parameter.
skip_outliers : boolean
Whether or not to compute the self.is_outlier attribute
discov_window_length : int
How long to make the windows for computing S
discov_window_percentage : int
If provided, window length will be computed dynamically as a percentage of the input sequence length
discov_min_window_len : int, None
Specifies the minimum window length when discov_window_percentage is used. If None is passed, it will
be converted to 0
discov_alpha : float
A value in [0,1] that indicates how much to weight S over E in the discov score
discov_formula : string
Can be 'linear' or 'geometric', to choose which formula to use.
num_reads : int, None
Number of reads mapping to the sequence, needed to compute the normalized spread
report_discov : boolean
Whether or not to compute discov and its sub-metrics. All discov-related attributes are None otherwise
"""
def __init__(self, coverage, skip_outliers=False, discov_window_length=10000, discov_window_percentage=None,
discov_min_window_len=500, discov_alpha=0.5,
return_window_info=False, discov_formula='geometric', num_reads=None, report_discov=False):
self.num_reads = num_reads
self.min: float = np.amin(coverage)
self.max: float = np.amax(coverage)
self.median: float = np.median(coverage)
self.mean: float = np.mean(coverage)
self.std: float = np.std(coverage)
self.detection: float = np.sum(coverage > 0) / len(coverage)
if coverage.size < 4:
self.mean_Q2Q3: float = self.mean
else:
sorted_c = np.sort(coverage)
Q = int(coverage.size * 0.25)
Q2Q3 = sorted_c[Q:-Q]
self.mean_Q2Q3: float = np.mean(Q2Q3)
if skip_outliers:
self.is_outlier = None
else:
self.is_outlier = get_list_of_outliers(coverage, median=self.median) # this is an array not a list
self.num_windows = None
self.prop_win_covered = None
self.window_depth_evenness = None
self.spread_expected = None
self.spread_norm = None
self.spread_evenness_score = None
self.discov = None
self.windows = None
if report_discov:
self.compute_discov_stats(coverage, discov_window_length, discov_window_percentage, discov_min_window_len, discov_alpha, discov_formula,
return_window_info)
def compute_discov_stats(self, coverage, discov_window_length, discov_window_percentage, discov_min_window_len, discov_alpha, discov_formula, return_window_info):
"""Computes discov and its sub-metrics (see the class docstring), and sets them as attributes of this object."""
if discov_min_window_len is None:
discov_min_window_len = 0
# divide reference sequence into non-overlapping windows
if discov_window_percentage:
discov_window_length = int(len(coverage) * discov_window_percentage / 100)
if discov_window_length < discov_min_window_len:
discov_window_length = discov_min_window_len
windows = self.get_window_regions(coverage, window_length=discov_window_length)
if len(windows) > 1:
final_window_len = windows[-1][1] - windows[-1][0]
if final_window_len < 0.1*discov_window_length: # don't count the last window if it is too small
windows = windows[:-1]
# compute spread (S) and evenness (E) from the windows
nonzero_window_means = [x[2] for x in windows if x[2] > 0]
self.num_windows = len(windows)
self.prop_win_covered = len(nonzero_window_means) / self.num_windows
cv_of_means = self.compute_CV(nonzero_window_means) if len(nonzero_window_means) >= 3 else None
if cv_of_means is not None:
self.window_depth_evenness = 1 / (1 + cv_of_means)
else:
self.window_depth_evenness = 0.0 # maximum unevenness
# get_window_regions() shrinks the window to the sequence length when the sequence is shorter than
# discov_window_length, so we take the length of the first window as the one actually used for S
actual_window_length = windows[0][1] - windows[0][0]
self.spread_expected = self.expected_spread(B=np.sum(coverage), N=self.num_reads, w=actual_window_length, G=len(coverage))
self.spread_norm = self.normalized_spread(self.prop_win_covered, self.spread_expected)
self.spread_evenness_score = self.compute_spread_evenness_score(S=self.spread_norm, E=self.window_depth_evenness, alpha=discov_alpha, formula=discov_formula)
self.discov = self.compute_discov(C=self.spread_evenness_score, D=self.detection)
if return_window_info:
self.windows = self._get_window_info(coverage, windows)
def get_window_regions(self, coverage, window_length):
"""Given an array of coverage values, divides it into non-overlapping windows of the requested length.
Each region is described as a tuple of (start_position, stop_position, mean_coverage), with start and stop
positions following Python indexing rules to enable slicing. If the array doesn't divide equally by the
window length, the final window will be shorter than the rest. And if the input array is smaller than the
window length, this function will return a single window covering the entire array.
"""
if window_length > len(coverage): # if the input is smaller than the window size, make it one window
window_length = len(coverage)
elif window_length == 0:
raise ConfigError("The get_window_regions() function was requested to make zero-length windows. Impossible!")
windows = []
current_start = 0
current_stop = current_start + window_length
while current_stop <= len(coverage):
region_data = (current_start, current_stop, np.mean(coverage[current_start:current_stop]))
windows.append(region_data)
current_start = current_stop
current_stop = current_start + window_length
# EDGE CASE: final region is incomplete window
if current_stop > len(coverage) and current_start < len(coverage):
final_region = (current_start, len(coverage), np.mean(coverage[current_start:]))
windows.append(final_region)
return windows
def _get_window_info(self, coverage, windows):
"""Return a dict-of-dicts with per-window stats for optional window-level output.
Parameters
==========
coverage : array
Full nucleotide-level coverage array.
windows : list
List of (start, stop, mean_coverage) tuples from get_window_regions().
Returns
=======
window_info : dict
Dict-of-dicts keyed by sequential integer index. Each inner dict has keys:
start, stop, length, has_coverage, mean_coverage,
num_bases_with_coverage.
"""
window_info = {}
for i, (start, stop, mean_cov) in enumerate(windows):
window_info[i] = {'start': start, 'stop': stop, 'length': stop - start,
'has_coverage': int(mean_cov > 0), 'mean_coverage': mean_cov,
'num_bases_with_coverage': int(np.count_nonzero(coverage[start:stop]))}
return window_info
def expected_spread(self, B, N, w, G):
"""Returns the spread expected if reads were placed randomly: S_exp = 1 - e^(-(B + N*w) / G)
B is the sum of aligned lengths (sum of the coverage array), N is the number of reads mapping to the reference,
w is the window length used to compute the observed spread, and G is the reference length.
"""
if N is None:
raise ConfigError("The expected_spread() function needs the number of reads mapping to the sequence (N) "
"to compute the expected spread, but it was not provided. If you are seeing this error, "
"whichever part of anvi'o initialized CoverageStats should have passed the `num_reads` "
"parameter but did not. This is a programmer error, so please let the developers know.")
return 1 - np.exp(-(B + N * w) / G)
def normalized_spread(self, S_obs, S_exp):
"""Returns observed spread relative to the spread expected if reads were placed randomly: min(1, S_obs / S_exp)
Returns None if S_obs is not available, and 0 if there is no coverage (S_exp is then 0).
"""
if S_obs is None:
return None
if S_exp == 0:
return 0.0
return min(1.0, S_obs / S_exp)
def compute_spread_evenness_score(self, S, E, alpha, formula='geometric'):
"""Computes the Spread-Evenness score."""
if formula == 'linear':
return alpha * S + (1-alpha) * E
else: # 'geometric'
return (S ** alpha) * (E ** (1-alpha))
def compute_discov(self, C, D, beta=1, k=2):
"""Adds a detection-dependent bonus to C, capped at 1: F = min(1, C + β·D^k)"""
if C is None or D is None:
return None
return min(1.0, C + beta * D**k)
def compute_CV(self, array):
"""Returns coefficient of variation from an input array. Returns None if array is empty or mean is 0."""
if not len(array):
return None
mean = np.mean(array)
std = np.std(array)
if mean == 0:
return None
return std / mean
class RunInDirectory(object):
""" Run any block of code in a specified directory. Return to original directory
Parameters
==========
run_dir : str or Path-like
The directory the block of code should be run in
"""
def __init__(self, run_dir):
self.run_dir = run_dir
self.cur_dir = os.getcwd()
if not os.path.isdir(self.run_dir):
raise ConfigError("RunInDirectory :: %s is not a directory." % str(self.run_dir))
def __enter__(self):
os.chdir(self.run_dir)
def __exit__(self, exc_type, exc_value, traceback):
os.chdir(self.cur_dir)
def run_command(cmdline, log_file_path, first_line_of_log_is_cmdline=True, remove_log_file_if_exists=True):
""" Uses subprocess.call to run your `cmdline`
Parameters
==========
cmdline : str or list
The command to be run, e.g. "echo hello" or ["echo", "hello"]
log_file_path : str or Path-like
All stdout from the command is sent to this filepath
Raises ConfigError if ret_val < 0, or on OSError. Does NOT raise if program terminated with exit code > 0.
"""
cmdline = format_cmdline(cmdline)
if anvio.DEBUG:
Progress().reset()
Run().info("[DEBUG] `run_command` is running",
' '.join(['%s' % (('"%s"' % str(x)) if ' ' in str(x) else ('%s' % str(x))) for x in cmdline]),
nl_before=1, nl_after=1, mc='red', lc='yellow')
filesnpaths.is_output_file_writable(log_file_path)
if remove_log_file_if_exists and os.path.exists(log_file_path):
os.remove(log_file_path)
try:
if first_line_of_log_is_cmdline:
with open(log_file_path, "a") as log_file: log_file.write('# DATE: %s\n# CMD LINE: %s\n' % (get_date(), ' '.join(cmdline)))
log_file = open(log_file_path, 'a')
ret_val = subprocess.call(cmdline, shell=False, stdout=log_file, stderr=subprocess.STDOUT)
log_file.close()
# This can happen in POSIX due to signal termination (e.g., SIGKILL).
if ret_val < 0:
raise ConfigError("Command failed to run. What command, you say? This: '%s'" % ' '.join(cmdline))
else:
return ret_val
except OSError as e:
raise ConfigError("command was failed for the following reason: '%s' ('%s')" % (e, cmdline))
def start_command(cmdline, log_file_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, first_line_of_log_is_cmdline=True, remove_log_file_if_exists=True):
"""Start a command using subprocess.Popen, returning an object that can be monitored."""
cmdline = format_cmdline(cmdline)
if anvio.DEBUG:
Progress().reset()
Run().info("[DEBUG] `start_command`",
' '.join(['%s' % (('"%s"' % str(x)) if ' ' in str(x) else ('%s' % str(x))) for x in cmdline]),
nl_before=1, nl_after=1, mc='red', lc='yellow')
filesnpaths.is_output_file_writable(log_file_path)
if remove_log_file_if_exists and os.path.exists(log_file_path):
os.remove(log_file_path)
try:
if first_line_of_log_is_cmdline:
with open(log_file_path, 'a') as log_file:
log_file.write(f"# DATE: {get_date()}\n# CMD LINE: {' '.join(cmdline)}\n")
p = subprocess.Popen(cmdline, stdout=stdout, stderr=stderr)
return p
except OSError as e:
raise ConfigError("The command failed for the following reason: '%s' ('%s')" % (e, cmdline))
def run_command_STDIN(cmdline, log_file_path, input_data, first_line_of_log_is_cmdline=True, remove_log_file_if_exists=True):
"""Uses subprocess.Popen and sends data to your `cmdline` through STDIN"""
cmdline = format_cmdline(cmdline)
filesnpaths.is_output_file_writable(log_file_path)
if remove_log_file_if_exists and os.path.exists(log_file_path):
os.remove(log_file_path)
try:
if first_line_of_log_is_cmdline:
with open(log_file_path, "a") as log_file: log_file.write('# DATE: %s\n# CMD LINE: %s\n' % (get_date(), ' '.join(cmdline)))
p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
ret_val = p.communicate(input=input_data.encode('utf-8'))[0]
return ret_val.decode()
except OSError as e:
raise ConfigError("command was failed for the following reason: '%s' ('%s')" % (e, cmdline))
def get_command_output_from_shell(cmd_line):
ret_code = 0
try:
out_bytes = subprocess.check_output(cmd_line.split(), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
out_bytes = e.output.decode("utf-8")
ret_code = e.returncode
return out_bytes, ret_code
def run_command_and_get_output(cmdline, raise_on_error=True, log_file_path=None):
"""Run a command and return its stdout as a string.
This is a modern utility function using subprocess.run() that captures
stdout for parsing while optionally logging stderr to a file. At some point
we will have to migrate all run_command functionality to this style and stop
using the older `subprocess.Popen()` approach.
Parameters
==========
cmdline : str or list
The command to be run, e.g. "echo hello" or ["echo", "hello"]
raise_on_error : bool, True
If True, raises ConfigError when command exits with non-zero status
log_file_path : str or Path-like, None
Optional path to log stderr output. If None, stderr is captured to stdout.
Returns
=======
stdout : str
The stdout from the command as a decoded string
Raises
======
ConfigError
If raise_on_error is True and command returns non-zero exit code
"""
cmdline = format_cmdline(cmdline)
if anvio.DEBUG:
Progress().reset()
Run().info("[DEBUG] `run_command_and_get_output` is running",
' '.join(['%s' % (('"%s"' % str(x)) if ' ' in str(x) else ('%s' % str(x))) for x in cmdline]),
nl_before=1, nl_after=1, mc='red', lc='yellow')
try:
proc = subprocess.run(
cmdline,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
if proc.returncode != 0:
error_msg = f"Command failed (exit {proc.returncode}): {' '.join(cmdline)}"
if proc.stderr:
error_msg += f"\n{proc.stderr.strip()}"
if log_file_path: