forked from mengqvist/DNApy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenbank.py
2281 lines (1851 loc) · 90.3 KB
/
genbank.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
#!/usr/bin/env python
#DNApy is a DNA editor written purely in python.
#The program is intended to be an intuitive and fully featured
#editor for molecular and synthetic biology.
#Enjoy!
#
#copyright (C) 2014-2015 Martin Engqvist |
#
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#LICENSE:
#
#DNApy is free software; you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation; either version 3 of the License, or
#(at your option) any later version.
#
#DNApy is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU Library General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software Foundation,
#Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#Get source code at: https://github.com/mengqvist/DNApy
#
#TODO
#fix the line shortening in the header section
#fix file saving
#add single base support to location parsing
#add methods to modify header sections
#match features with mandatory and optional qualifiers
#add a function that checks that everything is ok. I.e. that it conforms to the genbank format.
#make changes to how qualifiers are parsed. For example /qualifier=xyz, the '=' is not always there...
import dna
import copy
import pyperclip
import oligo_localizer
import peptide_localizer
import re
import sys
import wx # for richCopy
import json # for richCopy
import enzyme
#the feature class is not currently used.
#Something I started working on and may or may not continue.
class feature(object):
"""
A feature object class that defines the key, location and qualifiers of a feature and methods to interact with these.
Data structure is as follows:
{key:string #feature key
location:list #list of locations on DNA for feature
qualifiers:list #list of qualifiers attached to the fature
complement:bool #is feature on complement strand or not
join:bool #should feature locations be joined or not
order:bool #are feature locations in a certain order or not
}
"""
def __init__(self, inittype, initlocation, initqualifiers, initcomplement, initjoin, initorder):
self.SetType(inittype) #the type or "key" of the feature
self.SetLocation(initlocation)
self.SetQualifiers(initqualifiers)
self.SetComplement(initcomplement)
self.SetJoin(initjoin)
self.SetOrder(initorder)
def GetType(self):
'''Returns the feature type (its "key")'''
return self.type
def SetType(self, newtype):
'''Sets the feature type (its "key"). Input is a string and must match a feature type as specified by the genbank format.'''
assert type(newtype) == str, 'Error, %s is not a string' % str(newtype)
assert newtype in ["modified_base", "variation", "enhancer", "promoter", "-35_signal", "-10_signal", "CAAT_signal", "TATA_signal", "RBS", "5'UTR", "CDS", "gene", "exon", "intron", "3'UTR", "terminator", "polyA_site", "rep_origin", "primer_bind", "protein_bind", "misc_binding", "mRNA","ncRNA", "prim_transcript", "precursor_RNA", "5'clip", "3'clip", "polyA_signal", "GC_signal", "attenuator", "misc_signal", "sig_peptide", "transit_peptide", "mat_peptide", "STS", "unsure", "conflict", "misc_difference", "old_sequence", "LTR", "repeat_region", "repeat_unit", "satellite", "mRNA", "rRNA", "tRNA", "scRNA", "snRNA", "snoRNA", "misc_RNA", "source", "misc_feature", "misc_binding", "misc_recomb", "misc_structure", "iDNA", "stem_loop", "D-loop", "C_region", "D_segment", "J_segment", "N_region", "S_region", "V_region", "V_segment"], 'Error, %s is not a valid feature type' % newtype
#assert that qualifiers are ok for this one
self.type = newtype
def GetQualifiers(self):
'''Returns a list of qualifiers belonging to the feature.'''
return self.qualifiers
def SetQualifiers(self, newqualifiers):
'''Takes a list of strings and sets which qualifiers belong to the feature'''
assert type(newqualifiers) == list, 'Error, %s is not a list.' % str(newqualifiers)
for entry in newqualifiers:
assert type(entry) == str, 'Error, entry %s in qualifiers is not a string.' % entry
#assert that qualifiers are valid for feature type
def GetLocations(self):
'''Returns a list of locations belonging to the feature.'''
return self.location
def SetLocations(self, newlocations):
'''Takes a list of strings and sets the locations for the feature.'''
assert type(newlocations) == list, 'Error, %s is not a list.' % str(newlocations)
for entry in newlocations:
assert type(entry) == str, 'Error, entry %s in location is not a string.' % entry
self.location = newlocations
def GetOrder(self):
'''Returns a boolean of whether locations are in a certain order or not.'''
return self.order
def SetOrder(self, neworder):
'''Takes a boolean and sets whether locations are in a certain order or not.'''
assert type(neworder) == bool, 'Error, %s is not a boolean.' % str(neworder)
self.order = neworder
def GetJoin(self):
'''Returns a boolian of whether locations should be joined or not.'''
return self.join
def SetJoin(self, newjoin):
'''Takes a boolean and sets whether locations should be joined or not.'''
assert type(newjoin) == bool, 'Error, %s is not a boolean.' % str(newjoin)
self.join = newjoin
def GetComplement(self):
'''Returns a boolian of whether feature is on complement strand or not.'''
return self.complement
def SetComplement(self, newcomplement):
'''Takes a boolean and sets whtehr feature is on complement strand or not.'''
assert type(newcomplement) == bool, 'Error, %s is not a boolean.' % str(newcomplement)
self.complement = newcomplement
class gbobject(object):
"""Class that reads a genbank file (.gb) and has functions to edit its features and DNA sequence"""
def __init__(self, filepath = None):
self.clipboard = {}
self.clipboard['dna'] = ''
self.clipboard['features'] = []
self.featuretypes = ["modified_base", "variation", "enhancer", "promoter", "-35_signal", "-10_signal", "CAAT_signal", "TATA_signal", "RBS", "5'UTR", "CDS", "gene", "exon", "intron", "3'UTR", "terminator", "polyA_site", "rep_origin", "primer_bind", "protein_bind", "misc_binding", "mRNA", "prim_transcript", "precursor_RNA", "5'clip", "3'clip", "polyA_signal", "GC_signal", "attenuator", "misc_signal", "sig_peptide", "transit_peptide", "mat_peptide", "STS", "unsure", "conflict", "misc_difference", "old_sequence", "LTR", "repeat_region", "repeat_unit", "satellite", "mRNA", "rRNA", "tRNA", "scRNA", "snRNA", "snoRNA", "misc_RNA", "source", "misc_feature", "misc_binding", "misc_recomb", "misc_structure", "iDNA", "stem_loop", "D-loop", "C_region", "D_segment", "J_segment", "N_region", "S_region", "V_region", "V_segment"]
self.search_hits = [] # variable for storing a list of search hits
#set up data structure
self.gbfile = {} #this variable stores the whole genbank file
self.gbfile['locus'] = {}
self.gbfile['locus']['name'] = None
self.gbfile['locus']['length'] = None
self.gbfile['locus']['type'] = None
self.gbfile['locus']['topology'] = None
self.gbfile['locus']['division'] = None
self.gbfile['locus']['date'] = None
self.gbfile['definition'] = None
self.gbfile['accession'] = None
self.gbfile['version'] = None
self.gbfile['gi'] = None
self.gbfile['dblink'] = None
self.gbfile['keywords'] = None
self.gbfile['segment'] = None
self.gbfile['source'] = None
self.gbfile['organism'] = None
self.gbfile['references'] = None
self.gbfile['comments'] = None
self.gbfile['dbsource'] = None #not sure this is a valid keyword
self.gbfile['primary'] = None #not sure this is a valid keyword
self.gbfile['features'] = None
self.gbfile['origin'] = None
self.gbfile['contig'] = None
self.gbfile['dna'] = None
self.gbfile['filepath'] = filepath
self.fileName = 'New DNA' #name of the file/plasmid name
## compile regular expressions used for parsing ##
self._re_locus = re.compile(r'''
LOCUS \s+? ([a-zA-Z0-9:=_-]+?) \s+? #match name
([0-9]+?)[ ](?:bp|aa) \s+ #match length
((?:ss-|ds-|ms-)*(?:NA|DNA|RNA|tRNA|rRNA|mRNA|uRNA))* \s+ #match type, zero or one time
(linear|circular)* \s+ #match topology, zero or one time
(PRI|ROD|MAM|VRT|INV|PLN|BCT|VRL|PHG|SYN|UNA|EST|PAT|STS|GSS|HTG|HTC|ENV)* \s+ #match division, zero or one time
([0-9]{2}-(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC){1}-[0-9]{4})* #match date, zero or one time
''', re.VERBOSE)
self._re_version = re.compile(r'''
VERSION \s+ ([-_.a-zA-Z0-9]+)* \s+ #match version, zero or one time
(?:GI:([0-9]+))* #match gi, zero or one time
''', re.VERBOSE)
#for undo/redo
self.file_versions = [] #stores version of the file
self.file_version_index = 0 #stores at which index the current file is
if filepath == None:
pass
else:
platform = sys.platform
if platform == 'win32':
filepath = filepath.replace('\\', '/')
self.opengb(filepath)
# enzymes
self.restrictionEnzymes = enzyme.initRestriction(self)
###############################
def opengb(self, filepath):
'''
Function opens a genbank file.
'''
assert type(filepath) == str or type(filepath) == unicode , "Error opening genbank file. Filepath is not a string: %s" % str(filepath)
self.fileName = filepath.split('/')[-1] #update the fileName variable
#open it and read line by line (very memory efficient)
with open(filepath) as infile:
self.readgb(infile)
def readgb(self, infile):
"""
Method takes a genbank file and parses it into a manageable data structure.
"""
line_list = [] #for collecting the dna
for line in infile:
line = line.replace('\r', '') #important for removing linux \r newline character
# print('line: ',line)
if re.match('^[ \t\n]+$', line) or line == '': #get rid of blank lines
pass
elif line[0] == ' ' and line[0:10] != ' 1 ': #a line that starts with a space is a continuation of the previous line (and belongs to the previous keyword). I have to have a special case ' 1 ' for where the DNA sequence starts.
line_list.append(line)
elif (line[0] != ' ' or line[0:10] == ' 1 ') and len(line_list) == 0: #a line that does not start with a space marks a new keyword
line_list.append(line)
elif (line[0] != ' ' or line[0:10] == ' 1 ') and len(line_list) > 0: #a line that does not start with a space marks a new keyword
self.parse(''.join(line_list))
line_list = []
line_list.append(line)
#add the loaded file state to the undo/redo list
# self.add_file_version()
def parse(self, line):
'''
Method for parsing a genbank line. The term line is used very flexibly and indicates all the lines belonging to a certain keyword.
It matches certain keywords to the beginning of the line and parses accordingly.
'''
if 'LOCUS' in line[0:12]:
#LOCUS A short mnemonic name for the entry, chosen to suggest the sequence's definition. Mandatory keyword/exactly one record.
#match line with re
m = re.match(self._re_locus, line)
#assign values
self.gbfile['locus']['name'] = m.group(1) #locus id
self.gbfile['locus']['length'] = m.group(2) #sequence length
self.gbfile['locus']['type'] = m.group(3) #type of sequence
self.gbfile['locus']['topology'] = m.group(4) #linear or circular
self.gbfile['locus']['division'] = m.group(5) #which GenBank division the sequence belongs to
self.gbfile['locus']['date'] = m.group(6) #modification date
elif 'DEFINITION' in line[0:12]:
#A concise description of the sequence. Mandatory keyword/one or more records.
line_list = line[12:].split('\n') #split by line
self.gbfile['definition'] = ''.join([re.sub(' +', ' ', x) for x in line_list]) #remove spaces longer than one and empty entries
elif 'ACCESSION' in line[0:12]:
#The primary accession number is a unique, unchanging identifier assigned to each GenBank sequence record. (Please use this identifier when citing information from GenBank.) Mandatory keyword/one or more records.
self.gbfile['accession'] = line[12:].strip('\t\n\x0b\x0c\r ')
elif 'VERSION' in line[0:12]:
#A compound identifier consisting of the primary accession number and a numeric version number associated with the current version of the sequence data in the record. This is optionally followed by an integer identifier (a "GI") assigned to the sequence by NCBI. Mandatory keyword/exactly one record.
m = re.match(self._re_version, line)
self.gbfile['version'] = m.group(1)
self.gbfile['gi'] = m.group(2)
elif 'NID' in line[0:3]:
#An alternative method of presenting the NCBI GI identifier (described above).
#NOTE: The NID linetype is obsolete and was removed from the GenBank flatfile format in December 1999.
if self.gbfile['gi'] == None: #if the gi has not yet been assigned
self.gbfile['gi'] = ''.join(line[0:12].split('\n')).strip()
else:
pass
elif 'PROJECT' in line[0:12]:
#The identifier of a project (such as a Genome Sequencing Project) to which a GenBank sequence record belongs. Optional keyword/one or more records.
#NOTE: The PROJECT linetype is obsolete and was removed from the GenBank flatfile format after Release 171.0 in April 2009.
self.gbfile['project'] = ''.join(line[12:].split('\n')).strip()
elif 'DBLINK' in line[0:12]:
#Provides cross-references to resources that support the existence a sequence record, such as the Project Database and the NCBI Trace Assembly Archive. Optional keyword/one or more records.
line_list = line[12:].split('\n') #split by line only
self.gbfile['dblink'] = ' '.join([s.strip() for s in line[12:].split('\n')])
elif 'KEYWORDS' in line[0:12]:
#Short phrases describing gene products and other information about an entry. Mandatory keyword in all annotated entries/one or more records.
line_list = re.split('[\n ]', line[12:]) #split by line and space
self.gbfile['keywords'] = ' '.join([re.sub(' +', ' ', x) for x in line_list if x != '']) #remove spaces longer than one, and also empty entries
elif 'SEGMENT' in line[0:12]:
#Information on the order in which this entry appears in a series of discontinuous sequences from the same molecule. Optional keyword (only in segmented entries)/exactly one record.
self.gbfile['segment'] = line[12:].strip()
elif 'SOURCE' in line[0:6]:
#Common name of the organism or the name most frequently used in the literature. Mandatory keyword in all annotated entries/one or more records/includes one subkeyword.
#contains the sub-class ORGANISM, Formal scientific name of the organism (first line) and taxonomic classification levels (second and subsequent lines). Mandatory subkeyword in all annotated entries/two or more records.
line_list = line[12:].split('\n') #split by line break
index = next(line_list.index(x) for x in line_list if 'ORGANISM' in x) #find the index of 'ORGANISM'
#the free-format organism information (which may stretch over several lines)
self.gbfile['source'] = ' '.join([re.sub('[ .\n]+', ' ', x) for x in line_list[0:index]]) #the first entry (the source line)
#The formal scientific name for the source organism
self.gbfile['organism'] = []
self.gbfile['organism'].append(line_list[index][12:]) #this is the 'organism' line
#here comes the taxonomy
taxon = ''.join(line_list[index+1:]).split(';') #join the rest of the entries and split on the ; delimiter
self.gbfile['organism'].extend([re.sub('[ .]+', '', x.replace('[','').replace(']','')) for x in taxon]) #now remove spaces and punctuations and add the taxonomy to the global data structure
elif 'REFERENCE' in line[0:12]:
#Citations for all articles containing data reported in this entry. Includes seven subkeywords and may repeat. Mandatory keyword/one or more records.
#AUTHORS - Lists the authors of the citation. Optional subkeyword/one or more records.
#CONSRTM - Lists the collective names of consortiums associated with the citation (eg, International Human Genome Sequencing Consortium), rather than individual author names. Optional subkeyword/one or more records.
#TITLE - Full title of citation. Optional subkeyword (present in all but unpublished citations)/one or more records.
#JOURNAL - Lists the journal name, volume, year, and page numbers of the citation. Mandatory subkeyword/one or more records.
#MEDLINE - Provides the Medline unique identifier for a citation. Optional subkeyword/one record.
#NOTE: The MEDLINE linetype is obsolete and was removed
#PUBMED - Provides the PubMed unique identifier for a citation. Optional subkeyword/one record.
#REMARK - Specifies the relevance of a citation to an entry. Optional subkeyword/one or more records. from the GenBank flatfile format in April 2005.
if self.gbfile['references'] == None:
self.gbfile['references'] = []
current_ref = {}
current_ref['reference'] = None
current_ref['authors'] = None
current_ref['consrtm'] = None
current_ref['title'] = None
current_ref['journal'] = None
current_ref['medline'] = None
current_ref['pubmed'] = None
current_ref['remark'] = None
ref_lines = re.split('\n(?! )', line) #match newline only if it is not matched by 12 whitespace characters
for l in ref_lines:
if 'REFERENCE' in l[0:12]:
current_ref['reference'] = ' '.join([s.strip() for s in l[12:].split('\n')])
elif 'AUTHORS' in l[0:12]:
current_ref['authors'] = ' '.join([s.strip() for s in l[12:].split('\n')])
elif 'CONSRTM' in l[0:12]:
current_ref['consrtm'] = ' '.join([s.strip() for s in l[12:].split('\n')])
elif 'TITLE' in l[0:12]:
current_ref['title'] = ' '.join([s.strip() for s in l[12:].split('\n')])
elif 'JOURNAL' in l[0:12]:
current_ref['journal'] = ' '.join([s.strip() for s in l[12:].split('\n')])
elif 'MEDLINE' in l[0:12]:
current_ref['medline'] = ' '.join([s.strip() for s in l[12:].split('\n')])
elif 'NOTE:' in l[0:12]:
pass
elif 'PUBMED' in l[0:12]:
current_ref['pubmed'] = ' '.join([s.strip() for s in l[12:].split('\n')])
elif 'REMARK' in l[0:12]:
current_ref['remark'] = ' '.join([s.strip() for s in l[12:].split('\n')])
self.gbfile['references'].append(current_ref)
elif 'COMMENT' in line[0:12]:
#Cross-references to other sequence entries, comparisons to other collections, notes of changes in LOCUS names, and other remarks. Optional keyword/one or more records/may include blank records.
if self.gbfile['comments'] == None:
self.gbfile['comments'] = []
line_list = line[12:].split('\n') #split by line
self.gbfile['comments'].append(''.join([re.sub(' +', ' ', x) for x in line_list if x != ''])) #remove spaces longer than one and empty entries
elif 'DBSOURCE' in line[0:12]: #should I really include this one?
self.gbfile['dbsource'] = ''.join(line[12:].split('\n')).strip()
elif 'PRIMARY' in line[0:12]: #should I really include this one?
self.gbfile['primary'] = ''.join(line[12:].split('\n')).strip()
#see gi_625194262
elif 'FEATURES' in line[0:12]:
#Table containing information on portions of the sequence that code for proteins and RNA molecules and information on experimentally determined sites of biological significance. Optional keyword/one or more records.
feature_lines = re.split('\n(?! )', line) #match newline only if it is not matched by 21 whitespace characters
if self.gbfile['features'] == None:
self.gbfile['features'] = []
for l in feature_lines:
if l != '':
self.parse_feature_line(l)
elif 'BASE COUNT' in line[0:12]:
#Summary of the number of occurrences of each basepair code (a, c, t, g, and other) in the sequence. Optional keyword/exactly one record.
#NOTE: The BASE COUNT linetype is obsolete and was removed from the GenBank flatfile format in October 2003.
pass
elif 'ORIGIN' in line[0:12]:
#Specification of how the first base of the reported sequence is operationally located within the genome. Where possible, this includes its location within a larger genetic map. Mandatory keyword/exactly one record.
self.gbfile['origin'] = line[12:].strip()
elif ' 1 ' in line[0:10]:
#the DNA/RNA/protein sequence
self.gbfile['dna'] = ''.join([re.match('[a-zA-Z]', b).group(0) for b in line if re.match('[a-zA-Z]', b) is not None]) #make the DNA string while skipping anything that is not a-z
#sometimes I get a \t inside there. I don't know why. This is a temporary fix.
self.gbfile['dna'] = "".join(self.gbfile['dna'].split())
elif 'CONTIG' in line[0:12]:
#This linetype provides information about how individual sequence
#records can be combined to form larger-scale biological objects, such as
#chromosomes or complete genomes. Rather than presenting actual sequence
#data, a special join() statement on the CONTIG line provides the accession
#numbers and basepair ranges of the underlying records which comprise the object.
#It is an alternative to providing a sequence.
self.gbfile['contig'] = ''.join(line[12:].split('\n')).strip()
else:
raise ValueError, 'Unparsed line: "%s" in record %s' % (line, self.gbfile['locus']['name'])
#check the stored features for Vector NTI and ApE clutter and store result
self.clutter = self.ApEandVNTI_clutter()
def parse_feature_line(self, inputline):
'''
Takes a feature line consisting info for an entire feature and parses them into the DNApy data format.
'''
assert type(inputline) == str, 'Error, the input has to be a string.'
if 'FEATURES' in inputline[0:12]:
pass
else:
#first I need to go through the input and see if there are any info that wraps over several lines
linelist = inputline.split('\n')
wholelinelist = [] #for storing the complete un-wrapped lines
whole_line = ''
for line in linelist:
if whole_line == '': #to catch the first line
whole_line = line
elif line[0:21] == 21*' ' and line[21] != '/': #continuation of line which is broken on several lines
whole_line += line
elif line == '': #catch empty lines (that should not be there in any case) and move to next line
pass
elif line[0:21] == 21*' ' and line[21] == '/': #new qualifier line
wholelinelist.append(whole_line)
whole_line = line
wholelinelist.append(whole_line) #catch the last one
#now parse the whole lines into the correct data structure
feature = {}
feature['qualifiers'] = []
for line in wholelinelist:
assert type(line) is str, "Error parsing genbank line. Input line is not a string, it is %s:" % str(type(line))
#the line either starts with 5 blanks and then a feature key (feature key line), or it start with 21 blanks and then / (qualifier line)
if line[0:5] == 5*' ' and (line[5] in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ35') == True:
key = line[5:20].rstrip('\t\n\x0b\x0c\r ')
location = line[21:].rstrip('\t\n\x0b\x0c\r ')
feature["key"] = key
feature['location'], feature['complement'], feature['join'], feature['order'] = self.parse_location(location)
elif line[0:21] == ' ' and line[21] == '/':
if '/translation' in line:
qualifier = re.sub('[ \n]+', '', line[21:]) #remove newline characters and all spaces
else:
qualifier = re.sub('[ \n]+', ' ', line[21:]) #remove newline characters and spaces longer than 1
feature['qualifiers'].append(qualifier)
else:
print('error parsing feature line', line)
self.gbfile['features'].append(copy.deepcopy(feature)) #add feature to the global data structure
def parse_location(self, locationstring):
'''get whether complement or not, join or not, order or not'''
assert type(locationstring) == str, "Error, locationstring must be a string"
if 'complement' in locationstring:
complement = True
else:
complement = False
if 'join' in locationstring:
join = True
else:
join = False
if 'order' in locationstring:
order = True
else:
order = False
#get location numbering
## need to add single base support!!!! ##
tempsites = []
commasplit = locationstring.split(',')
for entry in commasplit:
tempstr = ''
for n in range(len(entry)):
if entry[n] in '0123456789<>.':
tempstr += entry[n]
tempsites.append(tempstr)
location = tempsites
return location, complement, join, order
def clean_clutter(self):
'''Method for removing ApE- and Vector NTI-specific codes in the qualifiers.'''
deletionlist = []
for i in range(len(self.gbfile['features'])):
for n in range(len(self.gbfile['features'][i]['qualifiers'])):
if 'ApEinfo' in self.gbfile['features'][i]['qualifiers'][n] or 'vntifkey' in self.gbfile['features'][i]['qualifiers'][n] :
deletionlist.append((i, n))
# elif ''\'' in self.gbfile['features'][i]['qualifiers'][n]:
# self.gbfile['features'][i]['qualifiers'][n] = self.gbfile['features'][i]['qualifiers'][n].replace(''\'', ' ')
#remove qualifiers based on deletionlist
while len(deletionlist)>0:
index, number = deletionlist[-1]
del self.gbfile['features'][index]['qualifiers'][number]
del deletionlist[-1]
############# undo and redo functions #################
def get_file_version(self):
'''
Get the current file version
'''
return self.file_versions[self.get_file_version_index()]
def add_file_version(self):
'''
Add another file version to the version list.
This should be added after the current version and should delete all later versions if there are any.
'''
index = self.get_file_version_index()
if len(self.file_versions) == 0: #the first version of the file
self.file_versions += (copy.deepcopy(self.gbfile),)
elif index == len(self.file_versions)-1: #if the current version is the last one
self.file_versions += (copy.deepcopy(self.gbfile),)
self.set_file_version_index(index+1)
else:
self.file_versions = self.file_versions[0:index]+(copy.deepcopy(self.gbfile),)
self.set_file_version_index(index+1)
def get_file_version_index(self):
'''
Get the index of the current file version
'''
return self.file_version_index
def set_file_version_index(self, index):
'''Set the index of the current file version'''
assert type(index) == int, 'Error, the index %s is not an integer.' % str(index)
self.file_version_index = index
def Undo(self):
'''Function for undoing user action (such as deleting or adding dna or features).
Function intended for use by the user.'''
if self.get_file_version_index() <= 0:
print("Can't undo there are no previous versions")
else:
old_index = self.get_file_version_index()
new_index = old_index-1
self.set_file_version_index(new_index)
self.gbfile = self.get_file_version()
print('index after undo', self.get_file_version_index())
def Redo(self):
'''Function for redoing user action (such as deleting or adding dna or features).
Function intended for use by the user.'''
if self.get_file_version_index() >= len(self.file_versions)-1:
print("Can't redo, there are no later versions")
else:
old_index = self.get_file_version_index()
new_index = old_index+1
self.set_file_version_index(new_index)
self.gbfile = self.get_file_version()
print('index after redo', self.get_file_version_index())
####################################################################
##### Get and Set methods #####
#Feature#
def get_all_features(self):
return self.gbfile['features']
def get_feature(self, index):
"""Returns the entire feature from a certain index"""
assert -1<=index<len(self.get_all_features()), 'This is not a valid index'
return self.gbfile['features'][index]
def get_feature_index(self, feature):
'''Get the index of a feature in the self.gbfile data structure'''
if len(self.gbfile['features']) == 0:
print('Error, no index found')
return False
else:
for i in range(len(self.gbfile['features'])):
if self.gbfile['features'][i]['key'] != feature['key']: continue
if self.gbfile['features'][i]['location'] != feature['location']: continue
if self.gbfile['features'][i]['qualifiers'][0] != feature['qualifiers'][0]: continue
if self.gbfile['features'][i]['complement'] == feature['complement']: #it is == here
return i
print('Error, no index found')
return False
def get_feature_label(self, index):
"""This method extracts the first qualifier and returns that as a label.
Index should be an integer."""
assert type(index) == int, "Error, index must be an integer."
try:
return self.gbfile['features'][index]['qualifiers'][0].split('=')[1]
except:
print('This is not a valid index')
return False
def get_feature_type(self, index):
'''Get feature type (key) for feature with given index'''
try:
return self.gbfile['features'][index]['key']
except:
print('This is not a valid index')
return False
def set_feature_type(self, feature, newkey):
'''Changes feature type of the feature passed to method'''
index = self.get_feature_index(feature)
if index is False:
print('Error, no index found')
else:
self.gbfile['features'][index]['key'] = newkey
self.add_file_version()
def get_feature_complement(self, index):
'''Get whether a feature is on leading or complement DNA strand'''
try:
return self.gbfile['features'][index]['complement']
except:
print('This is not a valid index')
return False
def set_feature_complement(self, feature, complement):
'''Changes whether a feature is on leading or complement DNA strand'''
index = self.get_feature_index(feature)
if index is False:
print('Error, no index found')
else:
self.gbfile['features'][index]['complement'] = complement
self.add_file_version()
def get_feature_join(self, index):
'''Get whether a feature with multiple locations should be joined or not'''
try:
return self.gbfile['features'][index]['join']
except:
print('This is not a valid index')
return False
def set_feature_join(self, feature, join):
'''Change whether a feature with multiple locations should be joined or not'''
index = self.get_feature_index(feature)
if index is False:
print('Error, no index found')
else:
self.gbfile['features'][index]['join'] = join
self.add_file_version()
def get_feature_order(self, index):
'''Get whether a feature with multiple locations should be indicated as having the specified order or not'''
try:
return self.gbfile['features'][index]['order']
except:
print('This is not a valid index')
return False
def set_feature_order(self, feature, order):
'''Change whether a feature with multiple locations should be indicated as having the specified order or not'''
index = self.get_feature_index(feature)
if index is False:
print('Error, no index found')
else:
self.gbfile['features'][index]['order'] = order
self.add_file_version()
def get_feature_location(self, index):
'''Gets all locations for a feature'''
try:
return self.gbfile['features'][index]['location']
except:
print('This is not a valid index')
return False
def set_feature_location(self, feature, newlocation):
'''Sets all location for a feature'''
index = self.get_feature_index(feature)
if index is False:
print('Error, no index found')
else:
self.gbfile['features'][index]['location'] = newlocation
self.add_file_version()
def get_location(self, entry):
'''Returns start and end location for an entry of a location list'''
tempentry = ''
for n in range(len(entry)):
if entry[n] != '<' and entry[n] != '>':
tempentry += entry[n]
start, finish = tempentry.split('..')
return int(start), int(finish)
def GetFirstLastLocation(self, feature):
'''
Returns ultimate first and ultimate last position of a feature,
regardless of how many pieces it is broken into.
'''
index = self.get_feature_index(feature)
if index is False:
print('Error, no index found')
else:
locations = self.gbfile['features'][index]['location']
start = locations[0].split('..')[0]
finish = locations[-1].split('..')[1]
# print(start, finish)
return int(start), int(finish)
def remove_location(self, index, number):
'''Removes locaiton in self.gbfile['features'][index]['location'][number]'''
del self.gbfile['features'][index]['location'][number]
if len(self.gbfile['features'][index]['location']) == 0: # if no locations are left for that feature, delete feature
self.remove_feature(self.gbfile['features'][index])
def IsValidLocation(self, locationlist):
'''Takes a location list and tests whether it is valid'''
result = True
try:
assert type(locationlist) == list
for location in locationlist:
start, finish = location.split('..')
start = int(start)
finish = int(finish)
assert (start == 0 and finish == 0) == False
assert start <= finish
assert finish <= len(self.GetDNA())
except:
result = False
return result
def get_qualifiers(self, index):
'''Returns all qualifiers for a feature'''
try:
return self.gbfile['features'][index]['qualifiers']
except:
raise ValueError('This is not a valid index')
def get_qualifier(self, index, number):
'''Returns specified qualifier for specified feature'''
try:
return self.gbfile['features'][index]['qualifiers'][number][1:].split('=')
except:
raise ValueError('Index or number is not valid')
def set_qualifier(self, index, number, qualifier, tag):
'''Sets the qualifier and tag for a given qualifier'''
assert type(index) is int, "Index is not an integer: %s" % str(index)
assert type(number) is int, "Number is not an integer: %s" % str(number)
assert type(qualifier) is str, "Qualifier is not a string: %s" % str(qualifier)
assert type(tag) is str, "Tag is not a string: %s" % str(tag)
try:
self.gbfile['features'][index]['qualifiers'][number] = '/%s=%s' % (qualifier, tag)
self.add_file_version()
except:
raise IOError('Error setting qualifier')
##### DNA modification methods #####
def Upper(self, start=1, finish=-1):
'''Change DNA selection to uppercase characters.
Start and finish are optional arguments (integers). If left out change applies to the entire DNA molecule.
If specified, start and finish determines the range for the change.'''
if finish == -1:
finish = len(self.GetDNA())
assert (type(start) == int and type(finish) == int), 'Function requires two integers.'
assert start <= finish, 'Startingpoint must be before finish'
string = self.GetDNA(start, finish)
self.changegbsequence(start, finish, 'r', string.upper())
self.add_file_version()
def Lower(self, start=1, finish=-1):
'''Change DNA selection to lowercase characters.
Start and finish are optional arguments (integers). If left out change applies to the entire DNA molecule.
If specified, start and finish determines the range for the change.'''
if finish == -1:
finish = len(self.GetDNA())
assert (type(start) == int and type(finish) == int), 'Function requires two integers.'
assert start <= finish, 'Startingpoint must be before finish'
string = self.GetDNA(start, finish)
self.changegbsequence(start, finish, 'r', string.lower())
self.add_file_version()
def reverse_complement_clipboard(self, clipboard):
'''Reverse-complements the DNA and all features in clipboard'''
clipboard['dna'] = dna.RC(clipboard['dna']) #change dna sequence
for i in range(len(clipboard['features'])): #checks self.allgbfeatures to match dna change
if clipboard['features'] [i]['complement'] == True:
clipboard['features'] [i]['complement'] = False
elif clipboard['features'] [i]['complement'] == False:
clipboard['features'] [i]['complement'] = True
for n in range(len(clipboard['features'][i]['location'])):
start, finish = self.get_location(clipboard['features'][i]['location'][n])
featurelength = finish - start #how much sequence in feature?
trail = len(clipboard['dna']) - finish # how much sequence after feature?
clipboard['features'][i]['location'][n] = self.add_or_subtract_to_locations(clipboard['features'][i]['location'][n], -finish+(trail+featurelength+1), 'f')
clipboard['features'][i]['location'][n] = self.add_or_subtract_to_locations(clipboard['features'][i]['location'][n], -start+trail+1, 's')
clipboard['features'][i]['location'].reverse() #reverse order of list elements
return clipboard
def RCselection(self, start, finish):
'''Reverse-complements current DNA selection'''
assert (type(start) == int and type(finish) == int), 'Function requires two integers.'
assert start <= finish, 'Startingpoint must be before finish'
self.RichCopy(start, finish, True) # RichCopy
#self.reverse_complement_clipboard()
self.Delete(start, finish, visible=False)
self.RichPaste(start)
def Delete(self, start, finish, visible=True):
'''Deletes current DNA selection.
Start and finish should be integers.
The optional variable 'hidden' can be set to True or False.
If set to True, no file versions are added to the undo/redo record.
If set to False, it does add file versions to the undo/redo record.'''
assert (type(start) == int and type(finish) == int), 'Function requires two integers.'
assert start <= finish, 'Startingpoint must be before finish'
deletedsequence = self.GetDNA(start, finish)
self.changegbsequence(start, finish, 'd', deletedsequence)
if visible == True:
self.add_file_version()
def Cut(self, start, finish, complement=False):
'''Cuts selection and place it in clipboard together with any features present on that DNA'''
assert (type(start) == int and type(finish) == int), 'Function requires two integers.'
assert start <= finish, 'Startingpoint must be before finish'
self.RichCopy(start, finish, complement) # changed to RichCopy
deletedsequence = self.GetDNA(start, finish)
self.changegbsequence(start, finish, 'd', deletedsequence)
self.add_file_version()
def CutRC(self, start, finish):
'''Cuts the reverese-complement of a selection and place it in clipboard together with any features present on that DNA'''
assert (type(start) == int and type(finish) == int), 'Function requires two integers.'
assert start <= finish, 'Startingpoint must be before finish'
self.Cut(start, finish, True)
def Paste(self, ip, DNA=None):
'''Paste DNA present in clipboard and any features present on that DNA
If a string is passed to DNA then this will over-ride anything that is present in the clipboard'''
assert type(ip) == int, 'The insertion point must be an integer.'
if DNA == None:
system_clip = re.sub(r'\s+', '', pyperclip.paste()) #remove whitespace from item in system clipboard
if self.clipboard['dna'] != system_clip: #if internal and system clipboard is not same, then system clipboard takes presidence
self.clipboard['dna'] = system_clip
self.clipboard['features'] = []
DNA = copy.copy(self.clipboard['dna'])
self.changegbsequence(ip, ip, 'i', DNA) #change dna sequence
for i in range(len(self.clipboard['features'])): #add features from clipboard
self.paste_feature(self.clipboard['features'][i], ip-1)
else:
self.changegbsequence(ip, ip, 'i', DNA) #change dna sequence
self.add_file_version()
def PasteRC(self, ip):
'''Paste reverse complement of DNA in clipboard'''
assert type(ip) == int, 'The insertion point must be an integer.'
self.RichPaste(ip,True)
def CopyRC(self, start, finish):
'''Copy the reverse complement of DNA and all the features for a certain selection'''
assert (type(start) == int and type(finish) == int), 'Function requires two integers.'
assert start <= finish, 'Startingpoint must be before finish'
self.RichCopy(start, finish, True)
def RichCopy(self, start, finish, complement=False):
'''a method to copy not only dna to clipboard but exchange features and dna
beetween two windows
this depreciates the Copy method from this file
'''
assert (type(start) == int and type(finish) == int), 'Function requires two integers.'
dna = self.GetDNA(start, finish)
dnapyClipboard = {}
dnapyClipboard['dna'] = self.GetDNA(start, finish) #copy to internal clipboard
dnapyClipboard['features'] = []
self.allgbfeatures_templist = copy.deepcopy(self.gbfile['features'])
for i in range(len(self.gbfile['features'])): #checks to match dna change
if len(self.gbfile['features'][i]['location']) == 1:
featurestart, featurefinish = self.get_location(self.gbfile['features'][i]['location'][0])
else:
n = 0
featurestart = self.get_location(self.gbfile['features'][i]['location'][n])[0]
n = len(self.gbfile['features'][i]['location'])-1
featurefinish = self.get_location(self.gbfile['features'][i]['location'][n])[1]
if (start<=featurestart and featurefinish<=finish) == True: #if change encompasses whole feature
dnapyClipboard['features'].append(self.allgbfeatures_templist[i])
for n in range(len(self.gbfile['features'][i]['location'])):
newlocation = self.add_or_subtract_to_locations(self.gbfile['features'][i]['location'][n], -start+1, 'b')
dnapyClipboard['features'][-1]['location'][n] = newlocation
# if complement copy is hoped for, reverse it here:
if complement == True:
dnapyClipboard = self.reverse_complement_clipboard(dnapyClipboard)
# save simple dna as txt
self.richClipboard = wx.DataObjectComposite()
text = wx.TextDataObject(dnapyClipboard['dna'])
# save clipboard to json string
JSONdnapyClipboard = json.dumps(dnapyClipboard)
dnapy = wx.CustomDataObject("application/DNApy")
dnapy.SetData(JSONdnapyClipboard)
self.richClipboard.Add(text, True) # add clear dna text as preffered object
self.richClipboard.Add(dnapy) # add rich dna info as json
# save to the clipboard
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(self.richClipboard)
wx.TheClipboard.Close()
return True
def RichPaste(self, ip, complement=False):
'''Paste DNA present in clipboard and any features present on that DNA
If a string is passed to DNA then this will over-ride anything that is present in the clipboard
this depreciates the Paste method from this file
'''
assert type(ip) == int, 'The insertion point must be an integer.'
self.textClipboard = wx.TextDataObject()
self.dnaClipboard = wx.CustomDataObject("application/DNApy")