-
Notifications
You must be signed in to change notification settings - Fork 89
/
CRISPRessoShared.py
1812 lines (1561 loc) · 91.5 KB
/
CRISPRessoShared.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
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
'''
CRISPResso2 - Kendell Clement and Luca Pinello 2020
Software pipeline for the analysis of genome editing outcomes from deep sequencing data
(c) 2020 The General Hospital Corporation. All Rights Reserved.
'''
import argparse
import datetime
import errno
import gzip
import json
import numpy as np
import os
import pandas as pd
import re
import string
import shutil
import signal
import subprocess as sb
import unicodedata
import logging
from CRISPResso2 import CRISPResso2Align
from CRISPResso2 import CRISPRessoCOREResources
__version__ = "2.2.14"
###EXCEPTIONS############################
class FlashException(Exception):
pass
class TrimmomaticException(Exception):
pass
class NoReadsAlignedException(Exception):
pass
class AlignmentException(Exception):
pass
class SgRNASequenceException(Exception):
pass
class NTException(Exception):
pass
class ExonSequenceException(Exception):
pass
class DuplicateSequenceIdException(Exception):
pass
class NoReadsAfterQualityFilteringException(Exception):
pass
class BadParameterException(Exception):
pass
class AutoException(Exception):
pass
class OutputFolderIncompleteException(Exception):
pass
class InstallationException(Exception):
pass
class InputFileFormatException(Exception):
pass
#########################################
class StatusFormatter(logging.Formatter):
def format(self, record):
record.percent_complete = ''
if record.args and 'percent_complete' in record.args:
record.percent_complete = '{0:.2f}% '.format(record.args['percent_complete'])
self.last_percent_complete = record.percent_complete
elif hasattr(self, 'last_percent_complete'): # if we don't have a percent complete, use the last one
record.percent_complete = self.last_percent_complete
return super().format(record)
class StatusHandler(logging.FileHandler):
def __init__(self, filename):
super().__init__(filename, 'w')
self.setFormatter(StatusFormatter('%(percent_complete)s%(message)s'))
def emit(self, record):
"""Overwrite the existing file and write the new log."""
if self.stream is None: # log file is empty
self.stream = self._open()
else: # log file is not empty, overwrite
self.stream.seek(0)
logging.StreamHandler.emit(self, record)
self.stream.truncate()
class LogStreamHandler(logging.StreamHandler):
def __init__(self, stream=None):
super().__init__(stream)
self.setFormatter(logging.Formatter(
'%(levelname)-5s @ %(asctime)s:\n\t %(message)s \n',
datefmt='%a, %d %b %Y %H:%M:%S',
))
self.setLevel(logging.INFO)
def set_console_log_level(logger, level, debug=False):
for handler in logger.handlers:
if isinstance(handler, LogStreamHandler):
if level == 4 or debug:
handler.setLevel(logging.DEBUG)
elif level == 3:
handler.setLevel(logging.INFO)
elif level == 2:
handler.setLevel(logging.WARNING)
elif level == 1:
handler.setLevel(logging.ERROR)
break
def getCRISPRessoArgParser(parser_title="CRISPResso Parameters", required_params=[], suppress_params=[]):
parser = argparse.ArgumentParser(description=parser_title, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
parser.add_argument('-r1', '--fastq_r1', type=str, help='First fastq file', default='',
required='fastq_r1' in required_params)
parser.add_argument('-r2', '--fastq_r2', type=str, help='Second fastq file for paired end reads', default='')
parser.add_argument('-a', '--amplicon_seq', type=str,
help='Amplicon Sequence (can be comma-separated list of multiple sequences)',
required='amplicon_seq' in required_params)
parser.add_argument('-an', '--amplicon_name', type=str,
help='Amplicon Name (can be comma-separated list of multiple names, corresponding to amplicon sequences given in --amplicon_seq',
default='Reference')
parser.add_argument('-amas', '--amplicon_min_alignment_score', type=str,
help='Amplicon Minimum Alignment Score; score between 0 and 100; sequences must have at least this homology score with the amplicon to be aligned (can be comma-separated list of multiple scores, corresponding to amplicon sequences given in --amplicon_seq)',
default="")
parser.add_argument('--default_min_aln_score', '--min_identity_score', type=int,
help='Default minimum homology score for a read to align to a reference amplicon', default=60)
parser.add_argument('--expand_ambiguous_alignments',
help='If more than one reference amplicon is given, reads that align to multiple reference amplicons will count equally toward each amplicon. Default behavior is to exclude ambiguous alignments.',
action='store_true')
parser.add_argument('--assign_ambiguous_alignments_to_first_reference',
help='If more than one reference amplicon is given, ambiguous reads that align with the same score to multiple amplicons will be assigned to the first amplicon. Default behavior is to exclude ambiguous alignments.',
action='store_true')
parser.add_argument('-g', '--guide_seq', '--sgRNA',
help="sgRNA sequence, if more than one, please separate by commas. Note that the sgRNA needs to be input as the guide RNA sequence (usually 20 nt) immediately adjacent to but not including the PAM sequence (5' of NGG for SpCas9). If the PAM is found on the opposite strand with respect to the Amplicon Sequence, ensure the sgRNA sequence is also found on the opposite strand. The CRISPResso convention is to depict the expected cleavage position using the value of the parameter '--quantification_window_center' nucleotides from the 3' end of the guide. In addition, the use of alternate nucleases besides SpCas9 is supported. For example, if using the Cpf1 system, enter the sequence (usually 20 nt) immediately 3' of the PAM sequence and explicitly set the '--cleavage_offset' parameter to 1, since the default setting of -3 is suitable only for SpCas9.",
default='')
parser.add_argument('-gn', '--guide_name', help="sgRNA names, if more than one, please separate by commas.",
default='')
parser.add_argument('-fg', '--flexiguide_seq',
help="sgRNA sequence (flexible) (can be comma-separated list of multiple flexiguides). The flexiguide sequence will be aligned to the amplicon sequence(s), as long as the guide sequence has homology as set by --flexiguide_homology.")
parser.add_argument('-fh', '--flexiguide_homology', type=int,
help="flexiguides will yield guides in amplicons with at least this homology to the flexiguide sequence.",
default=80)
parser.add_argument('-fgn', '--flexiguide_name', help="flexiguide name", default='')
parser.add_argument('--discard_guide_positions_overhanging_amplicon_edge',
help="If set, for guides that align to multiple positions, guide positions will be discarded if plotting around those regions would included bp that extend beyond the end of the amplicon. ",
action='store_true')
parser.add_argument('-e', '--expected_hdr_amplicon_seq', help='Amplicon sequence expected after HDR', default='')
parser.add_argument('-c', '--coding_seq',
help='Subsequence/s of the amplicon sequence covering one or more coding sequences for frameshift analysis. If more than one (for example, split by intron/s), please separate by commas.',
default='')
# quality filtering options
parser.add_argument('-q', '--min_average_read_quality', type=int,
help='Minimum average quality score (phred33) to keep a read', default=0)
parser.add_argument('-s', '--min_single_bp_quality', type=int,
help='Minimum single bp score (phred33) to keep a read', default=0)
parser.add_argument('--min_bp_quality_or_N', type=int,
help='Bases with a quality score (phred33) less than this value will be set to "N"', default=0)
# output options
parser.add_argument('--file_prefix', help='File prefix for output plots and tables', default='')
parser.add_argument('-n', '--name',
help='Output name of the report (default: the name is obtained from the filename of the fastq file/s used in input)',
default='')
parser.add_argument("--suppress_amplicon_name_truncation",help="If set, amplicon names will not be truncated when creating output filename prefixes. If not set, amplicon names longer than 21 characters will be truncated when creating filename prefixes.",
action='store_true')
parser.add_argument('-o', '--output_folder', help='Output folder to use for the analysis (default: current folder)',
default='')
parser.add_argument('-v', '--verbosity', type=int, help='Verbosity level of output to the console (1-4), 4 is the most verbose', default=3)
## read preprocessing params
parser.add_argument('--split_interleaved_input', '--split_paired_end',
help='Splits a single fastq file containing paired end reads into two files before running CRISPResso',
action='store_true')
parser.add_argument('--trim_sequences', help='Enable the trimming of Illumina adapters with Trimmomatic',
action='store_true')
parser.add_argument('--trimmomatic_command', type=str, help='Command to run trimmomatic', default='trimmomatic')
parser.add_argument('--trimmomatic_options_string', type=str,
help='Override options for Trimmomatic, e.g. "ILLUMINACLIP:/data/NexteraPE-PE.fa:0:90:10:0:true"',
default='')
parser.add_argument('--flash_command', type=str, help='Command to run flash', default='flash')
parser.add_argument('--min_paired_end_reads_overlap', type=int,
help='Parameter for the FLASH read merging step. Minimum required overlap length between two reads to provide a confident overlap. ',
default=10)
parser.add_argument('--max_paired_end_reads_overlap', type=int,
help='Parameter for the FLASH merging step. Maximum overlap length expected in approximately 90%% of read pairs. Please see the FLASH manual for more information.',
default=100)
parser.add_argument('--stringent_flash_merging',
help='Use stringent parameters for flash merging. In the case where flash could merge R1 and R2 reads ambiguously, the expected overlap is calculated as 2*average_read_length - amplicon_length. The flash parameters for --min-overlap and --max-overlap will be set to prefer merged reads with length within 10bp of the expected overlap. These values override the --min_paired_end_reads_overlap or --max_paired_end_reads_overlap CRISPResso parameters.',
action='store_true')
parser.add_argument('--force_merge_pairs', help=argparse.SUPPRESS,
action='store_true') # help=Force-merges R1 and R2 if they cannot be merged using flash (use with caution -- may create non-biological apparent indels at the joining site)
# quantification window params
parser.add_argument('-w', '--quantification_window_size', '--window_around_sgrna', type=str,
help='Defines the size (in bp) of the quantification window extending from the position specified by the "--cleavage_offset" or "--quantification_window_center" parameter in relation to the provided guide RNA sequence(s) (--sgRNA). Mutations within this number of bp from the quantification window center are used in classifying reads as modified or unmodified. A value of 0 disables this window and indels in the entire amplicon are considered. Default is 1, 1bp on each side of the cleavage position for a total length of 2bp. Multiple quantification window sizes (corresponding to each guide specified by --guide_seq) can be specified with a comma-separated list.',
default='1')
parser.add_argument('-wc', '--quantification_window_center', '--cleavage_offset', type=str,
help="Center of quantification window to use within respect to the 3' end of the provided sgRNA sequence. Remember that the sgRNA sequence must be entered without the PAM. For cleaving nucleases, this is the predicted cleavage position. The default is -3 and is suitable for the Cas9 system. For alternate nucleases, other cleavage offsets may be appropriate, for example, if using Cpf1 this parameter would be set to 1. For base editors, this could be set to -17 to only include mutations near the 5' end of the sgRNA. Multiple quantification window centers (corresponding to each guide specified by --guide_seq) can be specified with a comma-separated list.",
default='-3')
# parser.add_argument('--cleavage_offset', type=str, help="Predicted cleavage position for cleaving nucleases with respect to the 3' end of the provided sgRNA sequence. Remember that the sgRNA sequence must be entered without the PAM. The default value of -3 is suitable for the Cas9 system. For alternate nucleases, other cleavage offsets may be appropriate, for example, if using Cpf1 this parameter would be set to 1. To suppress the cleavage offset, enter 'N'.", default=-3)
parser.add_argument('--exclude_bp_from_left', type=int,
help='Exclude bp from the left side of the amplicon sequence for the quantification of the indels',
default=15)
parser.add_argument('--exclude_bp_from_right', type=int,
help='Exclude bp from the right side of the amplicon sequence for the quantification of the indels',
default=15)
parser.add_argument('--use_legacy_insertion_quantification',
help='If set, the legacy insertion quantification method will be used (i.e. with a 1bp quantification window, indels at the cut site and 1bp away from the cut site would be quantified). By default (if this parameter is not set) with a 1bp quantification window, only insertions at the cut site will be quantified.',
action='store_true')
parser.add_argument('--ignore_substitutions',
help='Ignore substitutions events for the quantification and visualization',
action='store_true')
parser.add_argument('--ignore_insertions', help='Ignore insertions events for the quantification and visualization',
action='store_true')
parser.add_argument('--ignore_deletions', help='Ignore deletions events for the quantification and visualization',
action='store_true')
parser.add_argument('--discard_indel_reads',
help='Discard reads with indels in the quantification window from analysis',
action='store_true')
# alignment parameters
parser.add_argument('--needleman_wunsch_gap_open', type=int, help='Gap open option for Needleman-Wunsch alignment',
default=-20)
parser.add_argument('--needleman_wunsch_gap_extend', type=int,
help='Gap extend option for Needleman-Wunsch alignment', default=-2)
parser.add_argument('--needleman_wunsch_gap_incentive', type=int,
help='Gap incentive value for inserting indels at cut sites', default=1)
parser.add_argument('--needleman_wunsch_aln_matrix_loc', type=str,
help='Location of the matrix specifying substitution scores in the NCBI format (see ftp://ftp.ncbi.nih.gov/blast/matrices/)',
default='EDNAFULL')
parser.add_argument('--aln_seed_count', type=int, default=5,
help=argparse.SUPPRESS) # help='Number of seeds to test whether read is forward or reverse',default=5)
parser.add_argument('--aln_seed_len', type=int, default=10,
help=argparse.SUPPRESS) # help='Length of seeds to test whether read is forward or reverse',default=10)
parser.add_argument('--aln_seed_min', type=int, default=2,
help=argparse.SUPPRESS) # help='number of seeds that must match to call the read forward/reverse',default=2)
# plotting parameters
parser.add_argument('--plot_histogram_outliers',
help="If set, all values will be shown on histograms. By default (if unset), histogram ranges are limited to plotting data within the 99 percentile.",
action='store_true')
# allele plot parameters
parser.add_argument('--plot_window_size', '--offset_around_cut_to_plot', type=int,
help='Defines the size of the window extending from the quantification window center to plot. Nucleotides within plot_window_size of the quantification_window_center for each guide are plotted.',
default=20)
parser.add_argument('--min_frequency_alleles_around_cut_to_plot', type=float,
help='Minimum %% reads required to report an allele in the alleles table plot.', default=0.2)
parser.add_argument('--expand_allele_plots_by_quantification',
help='If set, alleles with different modifications in the quantification window (but not necessarily in the plotting window (e.g. for another sgRNA)) are plotted on separate lines, even though they may have the same apparent sequence. To force the allele plot and the allele table to be the same, set this parameter. If unset, all alleles with the same sequence will be collapsed into one row.',
action='store_true')
parser.add_argument('--allele_plot_pcts_only_for_assigned_reference',
help='If set, in the allele plots, the percentages will show the percentage as a percent of reads aligned to the assigned reference. Default behavior is to show percentage as a percent of all reads.',
action='store_true')
parser.add_argument('-qwc', '--quantification_window_coordinates', type=str,
help='Bp positions in the amplicon sequence specifying the quantification window. This parameter overrides values of the "--quantification_window_center", "--cleavage_offset", "--window_around_sgrna" or "--window_around_sgrna" values. Any indels/substitutions outside this window are excluded. Indexes are 0-based, meaning that the first nucleotide is position 0. Ranges are separted by the dash sign (e.g. "start-stop"), and multiple ranges can be separated by the underscore (_). ' +
'A value of 0 disables this filter. (can be comma-separated list of values, corresponding to amplicon sequences given in --amplicon_seq e.g. 5-10,5-10_20-30 would specify the 5th-10th bp in the first reference and the 5th-10th and 20th-30th bp in the second reference)',
default=None)
parser.add_argument('--annotate_wildtype_allele', type=str,
help='Wildtype alleles in the allele table plots will be marked with this string (e.g. **).',
default='')
# output parameters
parser.add_argument('--keep_intermediate', help='Keep all the intermediate files', action='store_true')
parser.add_argument('--dump', help='Dump numpy arrays and pandas dataframes to file for debugging purposes',
action='store_true')
parser.add_argument('--write_detailed_allele_table',
help='If set, a detailed allele table will be written including alignment scores for each read sequence.',
action='store_true')
parser.add_argument('--fastq_output', help='If set, a fastq file with annotations for each read will be produced.',
action='store_true')
parser.add_argument('--bam_output', help='If set, a bam file with alignments for each read will be produced.',
action='store_true')
parser.add_argument('-x', '--bowtie2_index', type=str, help='Basename of Bowtie2 index for the reference genome',
default='')
parser.add_argument('--zip_output', help="If set, the output will be placed in a zip folder.", action='store_true')
# report style parameters
parser.add_argument('--max_rows_alleles_around_cut_to_plot', type=int,
help='Maximum number of rows to report in the alleles table plot.', default=50)
parser.add_argument('--suppress_report', help='Suppress output report', action='store_true')
parser.add_argument('--place_report_in_output_folder',
help='If true, report will be written inside the CRISPResso output folder. By default, the report will be written one directory up from the report output.',
action='store_true')
parser.add_argument('--suppress_plots', help='Suppress output plots', action='store_true')
parser.add_argument('--write_cleaned_report', action='store_true',
help=argparse.SUPPRESS) # trims working directories from output in report (for web access)
# base editor parameters
parser.add_argument('--base_editor_output',
help='Outputs plots and tables to aid in analysis of base editor studies.', action='store_true')
parser.add_argument('--conversion_nuc_from',
help='For base editor plots, this is the nucleotide targeted by the base editor', default='C')
parser.add_argument('--conversion_nuc_to',
help='For base editor plots, this is the nucleotide produced by the base editor', default='T')
# prime editing parameters
parser.add_argument('--prime_editing_pegRNA_spacer_seq', type=str,
help="pegRNA spacer sgRNA sequence used in prime editing. The spacer should not include the PAM sequence. The sequence should be given in the RNA 5'->3' order, so for Cas9, the PAM would be on the right side of the given sequence.",
default='')
parser.add_argument('--prime_editing_pegRNA_extension_seq', type=str,
help="Extension sequence used in prime editing. The sequence should be given in the RNA 5'->3' order, such that the sequence starts with the RT template including the edit, followed by the Primer-binding site (PBS).",
default='')
parser.add_argument('--prime_editing_pegRNA_extension_quantification_window_size', type=int,
help="Quantification window size (in bp) at flap site for measuring modifications anchored at the right side of the extension sequence. Similar to the --quantification_window parameter, the total length of the quantification window will be 2x this parameter. Default: 5bp (10bp total window size)",
default=5)
parser.add_argument('--prime_editing_pegRNA_scaffold_seq', type=str,
help="If given, reads containing any of this scaffold sequence before extension sequence (provided by --prime_editing_extension_seq) will be classified as 'Scaffold-incorporated'. The sequence should be given in the 5'->3' order such that the RT template directly follows this sequence. A common value is 'GGCACCGAGUCGGUGC'.",
default='')
parser.add_argument('--prime_editing_pegRNA_scaffold_min_match_length', type=int,
help="Minimum number of bases matching scaffold sequence for the read to be counted as 'Scaffold-incorporated'. If the scaffold sequence matches the reference sequence at the incorporation site, the minimum number of bases to match will be minimally increased (beyond this parameter) to disambiguate between prime-edited and scaffold-incorporated sequences.",
default=1)
parser.add_argument('--prime_editing_nicking_guide_seq', type=str,
help="Nicking sgRNA sequence used in prime editing. The sgRNA should not include the PAM sequence. The sequence should be given in the RNA 5'->3' order, so for Cas9, the PAM would be on the right side of the sequence",
default='')
parser.add_argument('--prime_editing_override_prime_edited_ref_seq', type=str,
help="If given, this sequence will be used as the prime-edited reference sequence. This may be useful if the prime-edited reference sequence has large indels or the algorithm cannot otherwise infer the correct reference sequence.",
default='')
parser.add_argument('--prime_editing_override_sequence_checks',
help="If set, checks to assert that the prime editing guides and extension sequence are in the proper orientation are not performed. This may be useful if the checks are failing inappropriately, but the user is confident that the sequences are correct.",
action='store_true')
# special running modes
parser.add_argument('--crispresso1_mode', help='Parameter usage as in CRISPResso 1', action='store_true')
parser.add_argument('--dsODN', help='Label reads with the dsODN sequence provided', default='')
parser.add_argument('--auto', help='Infer amplicon sequence from most common reads', action='store_true')
parser.add_argument('--debug', help='Show debug messages', action='store_true')
parser.add_argument('--no_rerun',
help="Don't rerun CRISPResso2 if a run using the same parameters has already been finished.",
action='store_true')
parser.add_argument('-p', '--n_processes', type=str, help='Specify the number of processes to use for analysis.\
Please use with caution since increasing this parameter will significantly increase the memory required to run CRISPResso. Can be set to \'max\'.',
default='1')
# processing of aligned bam files
if 'bam_input' not in suppress_params:
parser.add_argument('--bam_input', type=str, help='Aligned reads for processing in bam format', default='')
if 'bam_chr_loc' not in suppress_params:
parser.add_argument('--bam_chr_loc', type=str,
help='Chromosome location in bam for reads to process. For example: "chr1:50-100" or "chrX".',
default='')
# deprecated params
parser.add_argument('--save_also_png', default=False,
help=argparse.SUPPRESS) # help='Save also .png images in addition to .pdf files') #depreciated -- now pngs are automatically created. Pngs can be suppressed by '--suppress_report'
return parser
def get_crispresso_options():
parser = getCRISPRessoArgParser(parser_title="Temp Params", required_params=[])
crispresso_options = set()
d = parser.__dict__['_option_string_actions']
for key in d.keys():
d2 = d[key].__dict__['dest']
crispresso_options.add(d2)
return crispresso_options
def get_crispresso_options_lookup():
##dict to lookup abbreviated params
# crispresso_options_lookup = {
# 'r1':'fastq_r1',
# 'r2':'fastq_r2',
# 'a':'amplicon_seq',
# 'an':'amplicon_name',
# .....
# }
crispresso_options_lookup = {}
parser = getCRISPRessoArgParser(parser_title="Temp Params", required_params=[])
d = parser.__dict__['_option_string_actions']
for key in d.keys():
d2 = d[key].__dict__['dest']
key_sub = re.sub("^-*", "", key)
if key_sub != d2:
crispresso_options_lookup[key_sub] = d2
return crispresso_options_lookup
def propagate_crispresso_options(cmd, options, params, paramInd=None):
####
# cmd - the command to run
# options - list of options to propagate e.g. crispresso options
# params - arguments given to this program
# paramInd - index in dict - this is the run number in case of multiple runs.
for option in options:
if option:
if option in params:
if paramInd is None:
if type(params) == dict:
val = params[option]
else:
val = getattr(params, option)
else:
val = params.loc[paramInd, option]
if val is None:
pass
elif str(val) == "True":
cmd += ' --%s' % option
elif str(val) == "False":
pass
elif isinstance(val, str):
if val != "":
if re.match(r'-\d+$', val):
cmd += ' --%s %s' % (option, str(val))
elif " " in val or "-" in val:
cmd += ' --%s "%s"' % (option, str(val)) # quotes for options with spaces
else:
cmd += ' --%s %s' % (option, str(val))
elif isinstance(val, bool):
if val:
cmd += ' --%s' % option
else:
cmd += ' --%s %s' % (option, str(val))
return cmd
#######
# Sequence functions
#######
nt_complement = dict({'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N', '_': '_', '-': '-'})
def reverse_complement(seq):
return "".join([nt_complement[c] for c in seq.upper()[-1::-1]])
def reverse(seq):
return "".join(c for c in seq.upper()[-1::-1])
def find_wrong_nt(sequence):
return list(set(sequence.upper()).difference({'A', 'T', 'C', 'G', 'N'}))
def capitalize_sequence(x):
return str(x).upper() if not pd.isnull(x) else x
def slugify(value):
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = re.sub(rb'[\s\'*"/\\\[\]:;|,<>?]', b'_', value).strip()
value = re.sub(rb'_{2,}', b'_', value)
return value.decode('utf-8')
CIGAR_LOOKUP = {
('A', 'A'): 'M', ('A', 'C'): 'M', ('A', 'T'): 'M', ('A', 'G'): 'M', ('A', 'N'): 'M',
('C', 'A'): 'M', ('C', 'C'): 'M', ('C', 'T'): 'M', ('C', 'G'): 'M', ('C', 'N'): 'M',
('T', 'A'): 'M', ('T', 'C'): 'M', ('T', 'T'): 'M', ('T', 'G'): 'M', ('T', 'N'): 'M',
('G', 'A'): 'M', ('G', 'C'): 'M', ('G', 'T'): 'M', ('G', 'G'): 'M', ('G', 'N'): 'M',
('N', 'A'): 'M', ('N', 'C'): 'M', ('N', 'T'): 'M', ('N', 'G'): 'M', ('N', 'N'): 'M',
('A', '-'): 'I', ('T', '-'): 'I', ('C', '-'): 'I', ('G', '-'): 'I', ('N', '-'): 'I',
('-', 'A'): 'D', ('-', 'T'): 'D', ('-', 'C'): 'D', ('-', 'G'): 'D', ('-', 'N'): 'D',
}
cigarUnexplodePattern = re.compile(r'((\w)\2{0,})')
def unexplode_cigar(exploded_cigar_string):
"""Make a CIGAR string from an exploded cigar string.
Exploded cigar: IIMMMMMMM
cigar_els: ['2I','7M']
CIGAR: 2I7M
Parameters
----------
exploded_cigar_string : str
Exploded cigar string, e.g. IIMMMMMMM
Returns
-------
cigar_els : list
List of CIGAR elements
"""
cigar_els = []
for (cigar_str, cigar_char) in re.findall(cigarUnexplodePattern, exploded_cigar_string):
cigar_els.append(str(len(cigar_str)) + cigar_char)
return cigar_els
def get_ref_length_from_cigar(cigar_string):
"""
Given a CIGAR string, return the number of bases consumed from the
reference sequence.
"""
read_consuming_ops = ("M", "D", "N", "=", "X")
result = 0
ops = re.findall(r'(\d+)(\w)', cigar_string)
for c in ops:
length, op = c
if op in read_consuming_ops:
result += int(length)
return result
######
# File functions
######
def clean_filename(filename):
# get a clean name that we can use for a filename
validFilenameChars = "+-_.()%s%s" % (string.ascii_letters, string.digits)
filename = slugify(str(filename).replace(' ', '_'))
cleanedFilename = unicodedata.normalize('NFKD', filename)
return(''.join(c for c in cleanedFilename if c in validFilenameChars))
def check_file(filename):
try:
with open(filename):
pass
except IOError:
files_in_curr_dir = os.listdir('.')
if len(files_in_curr_dir) > 15:
files_in_curr_dir = files_in_curr_dir[0:15]
files_in_curr_dir.append("(Complete listing truncated)")
dir_string = ""
file_dir = os.path.dirname(filename)
if file_dir == "":
dir_string = ""
elif os.path.isdir(file_dir):
files_in_file_dir = os.listdir(file_dir)
if len(files_in_file_dir) > 15:
files_in_file_dir = files_in_file_dir[0:15]
files_in_file_dir.append("(Complete listing truncated)")
dir_string = "\nAvailable files in " + file_dir + ":\n\t" + "\n\t".join(files_in_file_dir)
else:
dir_string = "\nAdditionally, the folder '" + os.path.dirname(filename) + "' does not exist"
raise BadParameterException(
"The specified file '" + filename + "' cannot be opened.\nAvailable files in current directory:\n\t" + "\n\t".join(
files_in_curr_dir) + dir_string)
def force_symlink(src, dst):
if os.path.exists(dst) and os.path.samefile(src, dst):
return
try:
os.symlink(src, dst)
except OSError as exc:
if exc.errno == errno.EEXIST:
os.remove(dst)
os.symlink(src, dst)
elif exc.errno == errno.EPROTO:
# in docker on windows 7, symlinks don't work so well, so we'll just copy the file.
shutil.copyfile(src, dst)
def parse_count_file(fileName):
if os.path.exists(fileName):
with open(fileName) as infile:
lines = infile.readlines()
ampSeq = lines[0].rstrip().split("\t")
ampSeq.pop(0) # get rid of 'Amplicon' at the beginning of line
ampSeq = "".join(ampSeq)
lab_freqs = {}
for i in range(1, len(lines)):
line = lines[i].rstrip()
lab_freq_arr = line.split()
lab = lab_freq_arr.pop(0)
lab_freqs[lab] = lab_freq_arr
return ampSeq, lab_freqs
else:
print("Cannot find output file '%s'" % fileName)
return None, None
def parse_alignment_file(fileName):
if os.path.exists(fileName):
with open(fileName) as infile:
lines = infile.readlines()
ampSeq = lines[0].rstrip().split("\t")
ampSeq.pop(0) # get rid of 'Amplicon' at the beginning of line
ampSeq = "".join(ampSeq)
lab_freqs = {}
for i in range(1, len(lines)):
line = lines[i].rstrip()
lab_freq_arr = line.split()
lab = lab_freq_arr.pop(0)
lab_freqs[lab] = lab_freq_arr
return ampSeq, lab_freqs
else:
print("Cannot find output file '%s'" % fileName)
return None, None
def assert_fastq_format(file_path, max_lines_to_check=100):
"""
Checks to see that the fastq file is in the correct format
Accepts files in gzipped format if they end in .gz.
Raises a InputFileFormatException if the file is not in the correct format.
params:
file_path: path to fastq file
max_lines_to_check: number of lines to check in the file
returns:
True if the file is in the correct format
"""
try:
if file_path.endswith('.gz'):
# Read gzipped file
with gzip.open(file_path, 'rt') as file:
for line_num, line in enumerate(file):
if line_num >= max_lines_to_check:
break
if line_num % 4 == 0:
if not line.startswith('@'):
raise InputFileFormatException('File %s is not in fastq format! Line %d does not start with @ \n%s: %s' % (file_path, line_num, line_num, line))
elif line_num % 4 == 1 or line_num % 4 == 3:
if len(line.strip()) == 0:
raise InputFileFormatException('File %s is not in fastq format! Line %d is empty \n%s: %s' % (file_path, line_num, line_num, line))
elif line_num % 4 == 2:
if not line.startswith('+'):
raise InputFileFormatException('File %s is not in fastq format! Line %d does not start with + \n%s: %s' % (file_path, line_num, line_num, line))
else:
# Read uncompressed file
with open(file_path, 'r') as file:
for line_num, line in enumerate(file):
if line_num >= max_lines_to_check:
break
if line_num % 4 == 0:
if not line.startswith('@'):
raise InputFileFormatException('File %s is not in fastq format! Line %d does not start with @ \n%s: %s' % (file_path, line_num, line_num, line))
elif line_num % 4 == 1 or line_num % 4 == 3:
if len(line.strip()) == 0:
raise InputFileFormatException('File %s is not in fastq format! Line %d is empty \n%s: %s' % (file_path, line_num, line_num, line))
elif line_num % 4 == 2:
if not line.startswith('+'):
raise InputFileFormatException('File %s is not in fastq format! Line %d does not start with + \n%s: %s' % (file_path, line_num, line_num, line))
return True
except UnicodeDecodeError as e:
raise InputFileFormatException('File %s is not in fastq format! Perhaps it is a gzipped file but does not end in .gz?' % (file_path)) from e
except Exception as e:
raise InputFileFormatException('File %s is not in fastq format!' % (file_path)) from e
def check_output_folder(output_folder):
"""
Checks to see that the CRISPResso run has completed, and gathers the amplicon info for that run
returns:
- quantification file = CRISPResso_quantification_of_editing_frequency.txt for this run
- amplicons = a list of amplicons analyzed in this run
- amplicon_info = a dict of attributes found in quantification_file for each amplicon
"""
run_file = os.path.join(output_folder, 'CRISPResso2_info.json')
if not os.path.exists(run_file):
raise OutputFolderIncompleteException(
'The folder %s is not a valid CRISPResso2 output folder. Cannot find summary file %s.' % (
output_folder, run_file))
with open(run_file) as fh:
run_data = json.load(fh)
amplicon_info = {}
amplicons = run_data['results']['ref_names']
quantification_file = os.path.join(output_folder, run_data['running_info']['quant_of_editing_freq_filename'])
if os.path.exists(quantification_file):
with open(quantification_file) as quant_file:
head_line = quant_file.readline()
head_line_els = head_line.split("\t")
for line in quant_file:
line_els = line.split("\t")
amplicon_name = line_els[0]
amplicon_info[amplicon_name] = {}
amplicon_quant_file = os.path.join(output_folder, run_data['results']['refs'][amplicon_name][
'combined_pct_vector_filename'])
if not os.path.exists(amplicon_quant_file):
raise OutputFolderIncompleteException(
'The folder %s is not a valid CRISPResso2 output folder. Cannot find quantification file %s for amplicon %s.' % (
output_folder, amplicon_quant_file, amplicon_name))
amplicon_info[amplicon_name]['quantification_file'] = amplicon_quant_file
amplicon_mod_count_file = os.path.join(output_folder, run_data['results']['refs'][amplicon_name][
'quant_window_mod_count_filename'])
if not os.path.exists(amplicon_mod_count_file):
raise OutputFolderIncompleteException(
'The folder %s is not a valid CRISPResso2 output folder. Cannot find modification count vector file %s for amplicon %s.' % (
output_folder, amplicon_mod_count_file, amplicon_name))
amplicon_info[amplicon_name]['modification_count_file'] = amplicon_mod_count_file
if 'allele_frequency_files' in run_data['results']['refs'][amplicon_name]:
amplicon_info[amplicon_name]['allele_files'] = [os.path.join(output_folder, x) for x in
run_data['results']['refs'][amplicon_name][
'allele_frequency_files']]
else:
amplicon_info[amplicon_name]['allele_files'] = []
for idx, el in enumerate(head_line_els):
amplicon_info[amplicon_name][el] = line_els[idx]
return quantification_file, amplicons, amplicon_info
else:
raise OutputFolderIncompleteException(
"The folder %s is not a valid CRISPResso2 output folder. Cannot find quantification file '%s'." % (
output_folder, quantification_file))
# Thanks https://gist.github.com/simonw/7000493 for this idea
class CRISPRessoJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return {
'_type': 'np.ndarray',
'value': obj.tolist(),
}
if isinstance(obj, np.integer):
return int(obj)
if isinstance(obj, np.floating):
return float(obj)
if isinstance(obj, pd.DataFrame):
return {
'_type': 'pd.DataFrame',
'value': obj.to_json(orient='split'),
}
if isinstance(obj, datetime.datetime):
return {
'_type': 'datetime.datetime',
'value': str(obj),
}
if isinstance(obj, datetime.timedelta):
return {
'_type': 'datetime.timedelta',
'value': {
'days': obj.days,
'seconds': obj.seconds,
'microseconds': obj.microseconds,
},
}
if isinstance(obj, set):
return {
'_type': 'set',
'value': repr(obj),
}
if isinstance(obj, range):
return {
'_type': 'range',
'value': repr(obj),
}
if isinstance(obj, argparse.Namespace):
return {
'_type': 'argparse.Namespace',
'value': vars(obj),
}
return json.JSONEncoder.default(self, obj)
class CRISPRessoJSONDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(
self,
object_hook=self.object_hook,
*args,
**kwargs,
)
def object_hook(self, obj):
if '_type' in obj:
if obj['_type'] == 'np.ndarray':
return np.array(obj['value'])
if obj['_type'] == 'pd.DataFrame':
return pd.read_json(obj['value'], orient='split')
if obj['_type'] == 'datetime.datetime':
return datetime.datetime.fromisoformat(obj['value'])
if obj['_type'] == 'datetime.timedelta':
return datetime.timedelta(
days=obj['value']['days'],
seconds=obj['value']['seconds'],
microseconds=obj['value']['microseconds'],
)
if obj['_type'] == 'set':
return eval(obj['value'])
if obj['_type'] == 'range':
start, end, step = re.match(
r'range\((\d+), (\d+)(?:, (\d+))?\)', obj['value'],
).groups()
if step is not None:
return range(int(start), int(end), int(step))
return range(int(start), int(end))
if obj['_type'] == 'argparse.Namespace':
return argparse.Namespace(**obj['value'])
return obj
def load_crispresso_info(
crispresso_output_folder="",
crispresso_info_file_name='CRISPResso2_info.json',
crispresso_info_file_path=None
):
"""Load the CRISPResso2 info for a CRISPResso run.
If crispresso_info_file_path is given, attempt to read info file at that location
Otherwise, read file at crispresso_output_folder/crispresso_info_file_name
Parameters
----------
crispresso_output_folder : string
Path to CRISPResso folder
crispresso_info_file_name : string
Name of info file in CRISPResso folder
crispresso_info_path: string
Path to info file
Returns
-------
dict
Dict of relevant information for a CRISPResso run
"""
crispresso_info_file = os.path.join(
crispresso_output_folder, crispresso_info_file_name,
)
if crispresso_info_file_path is not None:
crispresso_info_file = crispresso_info_file_path
if not os.path.isfile(crispresso_info_file):
raise Exception('Cannot open CRISPResso info file at ' + crispresso_info_file)
try:
with open(crispresso_info_file) as fh:
crispresso2_info = json.load(fh, cls=CRISPRessoJSONDecoder)
return crispresso2_info
except json.JSONDecodeError as e:
raise Exception('Cannot open CRISPResso info file at ' + crispresso_info_file + "\n" + str(e))
except (AttributeError, EOFError, ImportError, IndexError) as e:
# secondary errors
raise Exception('Cannot open CRISPResso info file at ' + crispresso_info_file + "\n" + str(e))
except Exception as e:
raise Exception('Cannot open CRISPResso info file at ' + crispresso_info_file + "\n" + str(e))
def write_crispresso_info(crispresso_output_file, crispresso2_info):
"""Write info hash to crispresso info output file.
Parameters
----------
crispresso_output_file : string
File path to write info to
crispresso2_info : dict
Dict of relevant run properties
Returns
-------
Nothing
"""
with open(crispresso_output_file, 'w') as fh:
json.dump(crispresso2_info, fh, cls=CRISPRessoJSONEncoder)
def get_command_output(command):
"""
Run a shell command and returns an iter to read the output.
param:
command: shell command to run
returns:
iter to read the output
"""
p = sb.Popen(command,
stdout=sb.PIPE,
stderr=sb.STDOUT, shell=True,
# encoding='utf-8',universal_newlines=True)
universal_newlines=True,
bufsize=-1) # bufsize system default
while True:
retcode = p.poll()
line = p.stdout.readline()
yield line
if retcode is not None:
break
def get_most_frequent_reads(fastq_r1, fastq_r2, number_of_reads_to_consider, flash_command, max_paired_end_reads_overlap, min_paired_end_reads_overlap, split_interleaved_input=False, debug=False):
"""
Get the most frequent amplicon from a fastq file (or after merging a r1 and r2 fastq file).
Note: only works on paired end or single end reads (not interleaved)
input:
fastq_r1: path to fastq r1 (can be gzipped)
fastq_r2: path to fastq r2 (can be gzipped)
number_of_reads_to_consider: number of reads from the top of the file to examine
min_paired_end_reads_overlap: min overlap in bp for flashing (merging) r1 and r2
max_paired_end_reads_overlap: max overlap in bp for flashing (merging) r1 and r2
returns:
list of amplicon strings sorted by order in format:
12345 AATTCCG
124 ATATATA
5 TTATA
"""
if split_interleaved_input:
output_r1 = fastq_r1 + ".tmp.r1.gz"
output_r2 = fastq_r2 + ".tmp.r2.gz"
if fastq_r1.endswith('.gz'):
fastq_handle = gzip.open(fastq_r1, 'rt')
else:
fastq_handle=open(fastq_r1)
try:
o1 = gzip.open(output_r1, 'wt')
o2 = gzip.open(output_r2, 'wt')
lines_read = 1
r1_id = fastq_handle.readline()
r1_seq = fastq_handle.readline()
r1_plus = fastq_handle.readline()
r1_qual = fastq_handle.readline()
r2_id = fastq_handle.readline()
r2_seq = fastq_handle.readline()
r2_plus = fastq_handle.readline()
r2_qual = fastq_handle.readline()
while (r1_id and lines_read <= number_of_reads_to_consider):
o1.write("%s%s%s%s"%(r1_id,r1_seq,r1_plus,r1_qual))
o2.write("%s%s%s%s"%(r2_id,r2_seq,r2_plus,r2_qual))
r1_id = fastq_handle.readline()
r1_seq = fastq_handle.readline()
r1_plus = fastq_handle.readline()
r1_qual = fastq_handle.readline()
r2_id = fastq_handle.readline()
r2_seq = fastq_handle.readline()
r2_plus = fastq_handle.readline()
r2_qual = fastq_handle.readline()
o1.close()
o2.close()
fastq_handle.close()
except:
raise BadParameterException('Error in splitting read pairs from a single file')
fastq_r1 = output_r1
fastq_r2 = output_r2
view_cmd_1 = 'cat'
if fastq_r1.endswith('.gz'):
view_cmd_1 = 'zcat'
file_generation_command = "%s %s | head -n %d " % (view_cmd_1, fastq_r1, number_of_reads_to_consider * 4)
if fastq_r2:
view_cmd_2 = 'cat'
if fastq_r2.endswith('.gz'):
view_cmd_2 = 'zcat'
max_overlap_param = ""
min_overlap_param = ""
if max_paired_end_reads_overlap:
max_overlap_param = "--max-overlap=" + str(max_paired_end_reads_overlap)
if min_paired_end_reads_overlap:
min_overlap_param = "--min-overlap=" + str(min_paired_end_reads_overlap)
file_generation_command = "bash -c 'paste <(%s \"%s\") <(%s \"%s\")' | head -n %d | paste - - - - | awk -v OFS=\"\\n\" -v FS=\"\\t\" '{print($1,$3,$5,$7,$2,$4,$6,$8)}' | %s - --interleaved-input --allow-outies %s %s --to-stdout 2>/dev/null " % (
view_cmd_1, fastq_r1, view_cmd_2, fastq_r2, number_of_reads_to_consider * 4, flash_command, max_overlap_param,
min_overlap_param)
count_frequent_cmd = file_generation_command + " | awk '((NR-2)%4==0){print $1}' | sort | uniq -c | sort -nr "
def default_sigpipe():
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
if (debug):
print('command used: ' + count_frequent_cmd)
piped_commands = count_frequent_cmd.split("|")
pipes = [None] * len(piped_commands)
pipes[0] = sb.Popen(piped_commands[0], stdout=sb.PIPE, preexec_fn=default_sigpipe, shell=True)
for pipe_i in range(1, len(piped_commands)):
pipes[pipe_i] = sb.Popen(piped_commands[pipe_i], stdin=pipes[pipe_i - 1].stdout, stdout=sb.PIPE,
preexec_fn=default_sigpipe, shell=True)
top_unaligned = pipes[-1].communicate()[0]
if pipes[-1].poll() != 0:
raise AutoException('Cannot retrieve most frequent amplicon sequences. Got nonzero return code.')
seq_lines = top_unaligned.decode('utf-8').strip().split("\n")
if len(seq_lines) == 0 or seq_lines == ['']:
raise AutoException('Cannot parse any frequent amplicons sequences.')
if split_interleaved_input:
os.remove(output_r1)
os.remove(output_r2)