-
Notifications
You must be signed in to change notification settings - Fork 1
/
plug_helices.py
executable file
·1662 lines (1515 loc) · 60.5 KB
/
plug_helices.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
from tkinter import *
import tkinter.simpledialog
import tkinter.messagebox
import tkinter.colorchooser
import tkinter.filedialog
import sys
import string
import re
import os
import csv
import urllib.request, urllib.parse, urllib.error
import gzip
import platform
from pymol import stored, cmd, selector, movie
stored.organism = "saccharomyces_cerevisiae"
helices_path = None
try:
helices_path = os.environ["HELICES_HOME"]
except:
helices_path = os.environ["PYMOL_DATA"]
sys.path.append(helices_path)
datadir = None
if platform.system() == "Windows":
datadir = "C:\\Program Files\\PyMOL\\ribosome_pymol\\helices_data\\"
else:
datadir = helices_path + "/helices_data/"
global molecule_list
molecule_list = []
global original_list
original_list = []
global helices_list
helices_list = []
global default_colors
default_colors = {
'default' : 'gray10',
'helix' : 'red',
'RACK' : 'cyan',
'SSU_protein' : 'cyan',
'LSU_protein' : 'skyblue',
'unknown' : 'green',
'tRNA' : 'slate',
'mRNA' : 'forest',
'SSU_RNA' : 'gray20',
'LSU_RNA' : 'gray30',
'5S_RNA' : 'gray40',
'5.8S_RNA' : 'gray50',
'RNA' : 'gray60',
'other' : 'red'
}
## Small subunit should have full subunit, bacterial then eukaryotic
## Then the RNA bacterial/euk
## Large subunit should be full bac/euk, then the big RNA, then little
global small_subunit_rnas
global large_subunit_rnas
global small_subunit_prot
global large_subunit_prot
small_subunit_rnas = ['18S', '16S']
large_subunit_rnas = ['26S', '25S', '23S', '5.8S', '5S']
small_subunit_prot = ['40S', '30S']
large_subunit_prot = ['60S', '50S']
## The function 'fetch_then_chains' was taken with very minor changes
## from remote_pdb_load.py. The copyright notice is at the bottom of
## this file as well as the README
## Set up the directory where the data files live and some global variables
## which will be used to store the names of the molecules and helices from the
## PDB files.
## This function loads into the pymol menu system and creates 'Ribosome' menu.
def __init__(self):
cmd.unset("ignore_case")
cmd.set("orthoscopic", 1)
cmd.set("ray_shadows", 1)
cmd.set("depth_cue", 1)
cmd.set("ray_trace_fog", 1)
cmd.set("antialias", 1.0)
cmd.set("cartoon_ring_mode", 3)
self.menuBar.addcascademenu('Plugin', 'Ribosome')
self.menuBar.addmenuitem('Ribosome', 'command', 'Load from PDB',
label='Load from PDB',
command=lambda s=self : fetch_then_chains(s))
self.menuBar.addmenuitem('Ribosome', 'command', 'Extract chains',
label='Extract chains',
command=lambda: random_chains())
self.menuBar.addmenuitem('Ribosome', 'command', 'Helices',
label='Helices',
command=lambda: helices())
self.menuBar.addmenuitem('Ribosome', 'command', 'Load another session',
label="Load another session",
command=lambda: load_session(""))
self.menuBar.addcascademenu('Ribosome', 'Colors')
self.menuBar.addmenuitem('Colors', 'command', 'Color by attribute',
label='Color by attribute',
command= lambda: color_by_aa_residue_type())
self.menuBar.addmenuitem('Colors', 'command', 'Color by amino acid',
label='Color by amino acid',
command=lambda: color_by_amino_acid())
self.menuBar.addmenuitem('Colors', 'command', 'Modified Bases',
label='Modified Bases',
command=lambda: chain_color("modified"))
self.menuBar.addmenuitem('Colors', 'command', 'Custom file',
label='Custom file',
command=lambda: chain_color("custom"))
## Added for Suna to make some bases opaque, but the rest transparent
self.menuBar.addmenuitem('Colors', 'command', 'Custom file trans.',
label='Custom file trans.',
command=lambda: chain_color("trans"))
self.menuBar.addcascademenu('Ribosome','Delete objects')
self.menuBar.addmenuitem('Delete objects', 'command', 'Original',
label='Original',
command=lambda: delete_original())
self.menuBar.addmenuitem('Delete objects', 'command', 'ALL_RNA',
label='ALL_RNA',
command=lambda: delete_all_rna())
self.menuBar.addmenuitem('Delete objects', 'command', 'LSU_RNA',
label='LSU_RNA',
command=lambda: delete_lsu_rna())
self.menuBar.addmenuitem('Delete objects', 'command', 'SSU_RNA',
label='SSU_RNA',
command=lambda: delete_ssu_rna())
self.menuBar.addmenuitem('Delete objects', 'command', 'All_protein',
label='All_protein',
command=lambda: delete_all_protein())
self.menuBar.addmenuitem('Delete objects', 'command', 'LSU_protein',
label='LSU_protein',
command=lambda: delete_lsu_protein())
self.menuBar.addmenuitem('Delete objects', 'command', 'SSU_protein',
label='SSU_protein',
command=lambda: delete_ssu_protein())
self.menuBar.addmenuitem('Delete objects', 'command', 'All_helices',
label='All_helices',
command=lambda: delete_all_helices())
self.menuBar.addmenuitem('Delete objects', 'command', 'LSU_helices',
label='LSU_helices',
command=lambda: delete_lsu_helices())
self.menuBar.addmenuitem('Delete objects', 'command', 'SSU_helices',
label='SSU_helices',
command=lambda: delete_ssu_helices())
self.menuBar.addmenuitem('Ribosome', 'command', '2dHelices',
label='2dHelices',
command=lambda: twod_helices())
self.menuBar.addmenuitem('Ribosome', 'command', 'Get_Sequence',
label='Get_Sequence',
command=lambda: get_seq())
self.menuBar.addmenuitem('Ribosome', 'command', 'Edit_Ribosomes',
label='Edit_Ribosomes',
command=lambda: edit_ribosomes())
specific_ribosome_menu(self)
def specific_ribosome_menu(self):
"""
specific_ribosome_menu:
Called by init to load ribosomes by year/species/author using a CSV spreadsheet
in the 'data' directory.
"""
infile = datadir + "structures.csv"
ribosome_species = dict({})
ribosome_years = dict({})
ribosome_authors = dict({})
csvfile = open(infile)
dialect = csv.Sniffer().sniff(csvfile.read())
csvfile.seek(0)
reader = csv.reader(csvfile, dialect)
for datum in reader:
species = datum[0]
author = datum[1]
year = datum[2]
accession = datum[3]
title = datum[4]
if species not in ribosome_species:
ribosome_species[species] = [(species, author, year, accession, title)]
else:
ribosome_species[species].append((species, author, year, accession, title))
if year not in ribosome_years:
ribosome_years[year] = [(species, author, year, accession, title)]
else:
ribosome_years[year].append((species, author, year, accession, title))
if author not in ribosome_authors:
ribosome_authors[author] = [(species, author, year, accession, title)]
else:
ribosome_authors[author].append((species, author, year, accession, title))
self.menuBar.addcascademenu('Ribosome','Ribosomes by Species')
for spec in sorted(ribosome_species.keys()):
self.menuBar.addcascademenu('Ribosomes by Species', spec)
entry_list = ribosome_species[spec]
for entry in entry_list:
entry_name = entry[1] + "-" + entry[2] + "-" + entry[3]
self.menuBar.addmenuitem(spec, 'command', entry_name,
label=entry_name,
command=lambda s=entry : check_fetch(s))
self.menuBar.addcascademenu('Ribosome','Ribosomes by Year')
for year in sorted(ribosome_years.keys()):
self.menuBar.addcascademenu('Ribosomes by Year', year)
year_list = ribosome_years[year]
for entry in year_list:
entry_name = entry[1] + "-" + entry[0] + "-" + entry[3]
self.menuBar.addmenuitem(year, 'command', entry_name,
label=entry_name,
command=lambda s=entry: check_fetch(s))
self.menuBar.addcascademenu('Ribosome','Ribosomes by Author')
for author in sorted(ribosome_authors.keys()):
self.menuBar.addcascademenu('Ribosomes by Author', author)
author_list = ribosome_authors[author]
for entry in author_list:
entry_name = entry[2] + "-" + entry[0] + "-" + entry[3]
self.menuBar.addmenuitem(author, 'command', entry_name,
label=entry_name,
command=lambda s=entry: check_fetch(s))
def edit_ribosomes():
"""
edit_ribosomes: Opens the ribosome database in openoffice/excel
"""
my_type = platform.system()
ribosomes_path = datadir + "structures.csv"
open_command = ""
if my_type == "Linux":
open_command = "xdg-open"
elif my_type == "MacOS":
open_command = "open"
elif my_type == "Darwin":
open_command = "open"
elif my_type == "Windows":
open_command = "explorer"
os.system(open_command + " " + ribosomes_path + " &")
def del_enabled():
mols = cmd.get_names(enabled_only=1)
for mol in mols:
cmd.delete(mol)
def thick_lines_enabled(width):
"""
thick_lines_enabled
Attempts to set the width of the enabled molecules.
"""
mols = cmd.get_names(enabled_only=1)
for mol in mols:
cmd.set("line_width", width, mol)
def delete_all_helices():
"""
delete_all_helices
Attempts to delete all helices to save memory
"""
delete_ssu_helices()
delete_lsu_helices()
def delete_all_rna():
"""
delete_all_rna
Attempts to delete all the RNA molecules to save memory
"""
delete_ssu_rna()
delete_lsu_rna()
delete_mrna()
delete_trna()
def delete_all_protein():
"""
delete_all_protein
Attempts to delete all the proteins to save memory
"""
delete_lsu_protein()
delete_ssu_protein()
def delete_ssu_helices():
"""
delete_ssu_helices
Attempts to delete the small subunit helices to save memory
"""
for helix in helices_list:
helix = helix.lstrip('/')
if helix.find('SSU_h') > -1:
cmd.delete(helix)
def delete_lsu_helices():
"""
delete_lsu_helices
Attempts to delete the large subunit helices to save memory
"""
for helix in helices_list:
helix = helix.lstrip('/')
helix = str(helix)
if helix.find('LSU_H') > -1:
cmd.delete(helix)
def delete_ssu_protein():
"""
delete_ssu_protein
Attempts to delete the small subunit proteins to save memory
"""
for mol in molecule_list:
mol = mol.lstrip('/')
for ssu in small_subunit_prot:
ssu_name = ssu + '_S'
if mol.find(ssu_name) > -1:
cmd.delete(mol)
def delete_lsu_protein():
"""
delete_lsu_protein
Attempts to delete large subunit proteins to save memory
"""
for mol in molecule_list:
mol = mol.lstrip('/')
for lsu in large_subunit_prot:
lsu_mol = lsu + '_L'
if mol.find(lsu_mol) > -1:
cmd.delete(mol)
def delete_ssu_rna():
"""
delete_ssu_rna
Attempts to delete small subunit rna to save memory
"""
for mol in molecule_list:
mol = mol.lstrip('/')
for ssu in small_subunit_rnas:
ssu_mol = ssu + '_RRNA'
if mol.find(ssu_mol) > -1:
cmd.delete(mol)
def delete_lsu_rna():
"""
delete_lsu_rna
Attempts to delete the large subunit rna to save memory
"""
for mol in molecule_list:
mol = mol.lstrip('/')
for lsu in large_subunit_rnas:
lsu_mol = lsu + '_RRNA'
if mol.find(lsu_mol) > -1:
cmd.delete(mol)
def delete_trna():
"""
delete_trna
Attempts to delete any tRNAs to save memory
"""
for mol in molecule_list:
mol = mol.lstrip('/')
if mol.find('TRNA') > -1:
cmd.delete(mol)
def delete_mrna():
"""
delete_mrna
Attempts to delete any mRNA molecules to save memory
"""
for mol in molecule_list:
mol = mol.lstrip('/')
if mol.find('MRNA') > -1:
cmd.delete(mol)
def delete_original():
"""
delete_original
Delete the original pdb entries to save memory
"""
for original_molecule in original_list:
cmd.delete(original_molecule)
def delete_lsuh():
"""
delete_lsuh
Delete the helices of the large subunit
"""
counter = 0
while (counter <= 104):
counter = counter + 1
string = "LSU_H", counter
cmd.delete(string)
def delete_ssuh():
"""
delete_ssuh
Delete the helices of the small subunit
"""
counter = 0
while (counter <= 45):
counter = counter + 1
string = "SSU_h", counter
cmd.delete(string)
## I changed like 2 lines from remote_load_pdb.py
## The main change is at the end of fetch()
class fetch_then_chains:
"""
fetch_then_chains
Take in a PDB accession, download the file, parse its header
and display the pieces.
"""
def __init__(self, app):
pdbCode = tkinter.simpledialog.askstring('PDB Loader Service',
'Please enter a 4-digit pdb code:',
parent=app.root)
if pdbCode: # None is returned for user cancel
pdbCode = string.upper(pdbCode)
fetch(pdbCode,"")
def check_fetch(information):
"""
check_fetch
Print some information about a ribosomal pdb before fetching it.
This information lies in helices_data/structures.csv
"""
mymessage = "The pdb " + information[3] + ", species: " + str(information[0]) + " came from the " + str(information[1]) + " lab in " + str(information[2]) + " described by:\n" + str(information[4]) + "\nClick 'yes' if you wish to view this pdb file."
response = tkinter.messagebox.askyesno(title=information[3], message=mymessage)
if response:
fetch(information[3], "")
def color_saccharomyces():
"""
Color the yusupov 2011 ribosome according to Dr. Dinman's preferences.
"""
protein_colors = {
'P1_ALPHA' : 'blue',
'P2_BETA' : 'hotpink',
'60S_L2' : 'blue',
'60S_L3' : 'green',
'60S_L4' : 'hotpink',
'60S_L5' : 'limon',
'60S_L6' : 'forest',
'60S_L7' : 'palegreen',
'60S_L8' : 'tv_green',
'60S_L9' : 'limegreen',
'60S_L10' : 'red',
'60S_L11' : 'cyan',
'60S_L13' : 'orange',
'60S_L14' : 'tv_blue',
'60S_L15' : 'lightmagenta',
'60S_L16' : 'magenta',
'60S_L17' : 'smudge',
'60S_L18' : 'slate',
'60S_L19' : 'marine',
'60S_L20' : 'brightorange',
'60S_L21' : 'purpleblue',
'60S_L22' : 'purple',
'60S_L23' : 'slate',
'60S_L24' : 'yellow',
'60S_L25' : 'violet',
'60S_L26' : 'teal',
'60S_L27' : 'sand',
'60S_L28' : 'chocolate',
'60S_L29' : 'blue',
'60S_L30' : 'red',
'60S_L31' : 'warmpink',
'60S_L32' : 'marine',
'60S_L33' : 'tv_green',
'60S_L34' : 'orange',
'60S_L35' : 'limon',
'60S_L36' : 'magenta',
'60S_L37' : 'chocolate',
'60S_L38' : 'limegreen',
'60S_L39' : 'chocolate',
'UBIQUITIN-60S_L40' : 'chocolate',
'60S_ACIDIC_P0' : 'chocolate',
'60S_L41' : 'red',
'60S_L42' : 'wheat',
'60S_L43' : 'smudge',
'40S_S0' : 'cyan',
'40S_S1' : 'purpleblue',
'40S_S2' : 'teal',
'40S_S3' : 'yellow',
'40S_S4' : 'forest',
'40S_S5' : 'chartreuse',
'40S_S6' : 'orange',
'40S_S7' : 'chartreuse',
'40S_S8' : 'red',
'40S_S9' : 'yellow',
'40S_S10' : 'red',
'40S_S11' : 'marine',
'40S_S12' : 'tv_green',
'40S_S13' : 'wheat',
'40S_S14' : 'tv_red',
'40S_S15' : 'orange',
'40S_S16' : 'slate',
'40S_S17' : 'red',
'40S_S18' : 'blue',
'40S_S19' : 'violetpurple',
'40S_S20' : 'deepolive',
'40S_S21' : 'red',
'40S_S22' : 'orange',
'40S_S23' : 'blue',
'40S_S24' : 'density',
'40S_S25' : 'red',
'40S_S26' : 'yellow',
'40S_S27' : 'deepblue',
'40S_S28' : 'orange',
'40S_S29' : 'marine',
'40S_S30' : 'raspberry',
'UBIQUITIN-40S_S31' : 'magenta',
'GUANINE_NUCLEOTIDE-BINDING_SUBUNIT_BETA-LIKE' : 'chocolate',
'SUPPRESSOR_STM1' : 'olive',
}
for item in (list(protein_colors.keys())):
string = '/' + item
try:
cmd.color(protein_colors[item], string)
except:
print("Failed " + string)
def fetch(pdb, splitp):
"""
fetch
As per load_pdb, the only difference is that it calls to the following
function, random_chains
"""
try:
filename = urllib.request.urlretrieve('http://www.rcsb.org/pdb/files/' + pdb + '.pdb.gz')[0]
except:
tkinter.messagebox.showerror('Connection Error',
'Can not access to the PDB database.\n'+
'Please check your Internet access.',)
else:
if (os.path.getsize(filename) > 0): # If 0, then pdb code was invalid
fpin = gzip.open(filename)
outputname = os.path.dirname(filename) + os.sep + pdb + '.pdb'
fpout = open(outputname, 'w')
pdb_content = fpin.read()
fpout.buffer.write(pdb_content)
fpin.close()
fpout.close()
cmd.load(outputname,quiet=0) # Load the fresh pdb
## This is the change from Trey, a callout to random_chains()
random_chains(outputname, splitp)
else:
tkinter.messagebox.showerror('Invalid Code', 'You entered an invalid pdb code:' + pdb)
os.remove(filename) # Remove tmp file (leave the pdb)
## chain_color will color arbitrary bases/residues with the colors
## specified in data/color_definitions.txt
## The residues chosen should be in a text file as per
## data/modifications.txt
def chain_color(bases):
"""
chain_color
read over helices_data/color_definitions.txt to get an idea
of likely colors for chains and residues.
"""
## The next 8 lines attempts to figure out what file
## to use to define the residues to color
input_file = ""
if bases == "modified":
input_file = datadir + 'modifications.txt'
else:
tmp_filename = tkinter.filedialog.askopenfile(title="Open a session")
if not tmp_filename: return
input_file = tmp_filename.name
comment = ''
if bases == "trans":
objects = cmd.get_names()
for o in objects:
for v in ["cartoon_ring_transparency" , "cartoon_transparency" , "stick_transparency"]:
cmd.set(v, 1.0, o)
## From here until 'if input_file:' the color definitions
## are specified
colors_file = datadir + 'color_definitions.txt'
colors = dict({None : 'gray', })
transp = dict({None : '0.0', })
if colors_file:
color_lines = file(colors_file).readlines()
for color_line in color_lines:
color_datum = color_line.split()
colors[color_datum[0]] = color_datum[1]
try:
transp[color_datum[0]] = color_datum[2]
except:
transp[color_datum[0]] = "0.0"
## Now read the input file and select the appropriate residues
## and color them according to the rules in the colors dictionary
if input_file:
lines = file(input_file).readlines()
else:
lines = sys.stdin.readlines()
subunit = ''
chain = ''
for line in lines:
chain = ""
if re.compile('^#').search(line) is not None: # skip commented lines
tmpre = re.compile('^#')
tmpre = tmpre.sub('', line)
try:
(subunit, chain) = tmpre.split()
except:
subunit = tmpre.strip()
else:
datum = line.split()
try:
num = datum[0].strip()
if chain == "":
selection_string = '/' + subunit + '///' + num
selection_name = subunit + '_' + num
else:
selection_string = '/' + subunit + '//' + chain + '/' + num
selection_name = subunit + '_' + chain + '_' + num
color_choice = datum[1].strip()
color_name = colors[color_choice]
print("Setting color to: " + color_name)
try:
print("In the try.")
cmd.color(color_name, selection_string)
except:
print("In the except.")
cmd.color(colors[None], selection_string)
print("TESMTE: " + transp[color_choice])
if str(transp[color_choice]) != "0.0":
print("Setting trans to: " + my_trans)
cmd.set("cartoon_ring_transparency", my_trans, selection_string)
cmd.set("cartoon_transparency", my_trans, selection_string)
cmd.set("stick_transparency", my_trans, selection_string)
except:
print("Cannot find your selection, perhaps you must split the chains first")
def make_pretty():
## These are some settings our professor prefers.
cmd.bg_color("white")
cmd.show("cartoon")
# cmd.set("cartoon_ring_mode", 3)
## End of make_pretty
## This function is the toplevel function to make pretty helices
## Change the default_colors['helix'] to whatever color you prefer.
def helices(new_organism=stored.organism):
"""
helices
read a file in helices_data/ which corresponds to the species
of this ribosome. These contain definitions for every ribosomal
helix. Create individual pymol objects for every helix.
"""
make_chains(stored.organism, 'sticks', default_colors['helix'])
## This should ask for the relevant data file and call the
## cheater perl scripts I wrote
def twod_helices():
"""
twod_helices
Ask the user for an input file named either:
18S_rRNA.txt, 25S_rRNA_3p.txt, or 25S_rRNA_5p.txt
These files should contain base numbers followed by
an integer 'color.' This will then color a 2d representation
of the Saccharomyces cerevisiae ribosome with these colors.
"""
print("Provide the text file you wish to use to color, the filename")
print("Should be one of: 18S_rRNA.txt, 25S_rRNA_3p.txt, 25S_rRNA_5p.txt")
print("Otherwise this is not smart enough to understand what you want.")
twod_textfile = tkinter.filedialog.askopenfile(parent=app.root,
mode='rb',
title='Choose a file')
new_twod = twod_filename
new_twod = re.sub('txt$', 'ps', str(twod_textfile))
old_twod = os.path.basename(new_twod)
old_twod = datadir + str(old_twod)
file_new_twod = open(new_twod, 'w')
file_old_twod = open(old_twod, 'r')
file_twod_tex = open(twod_textfile, 'r')
## First get the numbers from the text file.
if file(file_twod_text) is not None:
twod_text_lines = file(file_twod_text).readlines()
color_list = []
for li in twod_text_lines:
(num, col) = li.split()
color_list.append(col)
file.close(file_twod_text)
if file(file_old_twod) is not None:
test_string = ""
if str(file_old_twod) == '18S_rRNA.ps':
test_string = "290.00 -105.33 290.00 -98.67 lwline"
elif str(fold_old_twod) == '25S_rRNA_3p.ps':
test_string = "-148.33 -1010.00 -141.67 -1010.00 lwline"
elif str(fold_old_twod) == '25S_rRNA_5p.ps':
test_string = "360.00 0.00 1.00 1.00 1.00 431.01 154.00 lwfarc"
count = None
list_count = 0
for li in file_old_twod:
file_new_twod.write(li)
if li == test_string:
count = 0
elif count == 0:
count = count + 1
elif count == 1:
count = count - 1
chosen_color = color_list[list_count] ## A number from the input file
if (chosen_color == 0): ## black
file_new_twod.write("0 0 0 setrgbcolor\n")
elif (chosen_color == 10): ## gray
file_new_twod.write("0.6 0.6 0.6 setrgbcolor\n")
elif (chosen_color == 11): ## neon pink
file_new_twod.write("0.85 0.30 0.64 setrgbcolor\n")
elif (chosen_color == -4): ## purple
file_new_twod.write("0.36 0.18 0.64 setrgbcolor\n")
elif (chosen_color == -3): ## blue
file_new_twod.write("0.08 0.25 1.0 setrgbcolor\n")
elif (chosen_color == -2): ## greenblue
file_new_twod.write("0.25 0.90 0.92 setrgbcolor\n")
elif (chosen_color == -1): ## green
file_new_twod.write("0.1 0.90 0.1 setrgbcolor\n")
elif (chosen_color == 1): ## yellow
file_new_twod.write("0.9 0.9 0.15 setrgbcolor\n")
elif (chosen_color == 2): ## yelloworange
file_new_twod.write("0.90 0.60 0.10 setrgbcolor\n")
elif (chosen_color == 3): ## orangered
file_new_twod.write("0.92 0.34 0.08 setrgbcolor\n")
elif (chosen_color == 4): ## red
file_new_twod.write("0.92 0.10 0.10 setrgbcolor\n")
else:
file_new_twod.write("0.57 0.08 0.32 setrgbcolor\n")
file.close(file_old_twod)
file.close(file_new_twod)
def make_chains(chains, showastype, showascolor):
"""
make_chains
Running make_chains should have pymol read a file in helices_data
which contains specifications of every ribosomal helix and some
special features (the PTC for instance)
Pymol will use this information to create objects corresponding to
every object.
"""
## Start out figuring out the data file to specify the helices
## Currently I just have a stupid if/elif chain for the few species
## I have annotated.
cmd.set("auto_zoom", "off")
cmd.set("auto_show_selections", "off")
cmd.set("cartoon_fancy_helices", 1)
test_chains = datadir + '/' + str(chains) + '/helices.txt'
chains_avail = os.access(test_chains, os.R_OK)
if (chains_avail):
chains_file = open(test_chains, 'r')
chains_filenames = [ test_chains , ]
else:
chains_filenames = [ datadir + 'wtf.txt', ]
for chains_filename in chains_filenames:
chains_file = open(chains_filename, 'r')
if chains_filename:
chains_lines = chains_file.readlines()
for ch in chains_lines:
if re.compile('^#').search(ch) is not None:
continue
name = ''
location = ''
## Each line of the file is a name, pymol_specification
## so just split by comma and run with it
(name, location) = ch.split(',')
if re.compile('-[A-Z]$').search(name) is not None:
name = re.sub('-[A-Z]$', '', name)
try:
cmd.create(name, location)
cmd.disable(name)
new_selection = "/" + name
if showastype:
helices_list.append(new_selection)
cmd.show(showastype, new_selection)
if showascolor:
cmd.color(showascolor, new_selection)
except:
print("There was an error.")
## Zoom to something sane
chains_file.close()
cmd.zoom("all")
def load_session(filename):
filename = tkinter.filedialog.askopenfile(title="Open a session")
if not filename: return
file_path = filename.name
cmd.load(file_path)
def split_cif(cif_file="/home/trey/downloads/4v4a.cif"):
"""
This reads a cif file in order to extract the various chains within it,
select them, and create individual objects for each chain.
"""
if cif_file is None:
cif_file = tkinter.filedialog.askopenfile(title="Open a cif file.")
if not cif_file:
return
## cif_filename is the full filename
## cif_shortname is the 2WGD or whathaveyou
## cif_basename is the path it lives in
## cif_file is the file object which has all the attributes etc
cif_filename = str(cif_file)
cif_basename = os.path.basename(cif_filename)
cif_shortname = os.path.splitext(cif_basename)
cif_shortname = cif_shortname[0]
cif_file = open(cif_filename, 'r')
##original_list.append(cif_shortname)
cmd.load(cif_filename)
cif_lines = cif_file.readlines()
## This will be dictionary with keys as names and values as a tuple [(number, idetifier])
chain_dict = dict({})
interesting = False
for cif_line in cif_lines:
if (re.compile("^_entity\.details").search(cif_line) is not None):
interesting = True
continue
elif (re.compile("^[0-9]").search(cif_line) is not None):
## The set of polymers by number
interesting = True
if (interesting is False):
continue
if (re.compile("^_entity_poly_seq").search(cif_line) is not None):
break
if (interesting is True):
print("Checking " + cif_line)
if (re.compile("^#").search(cif_line) is not None):
break
elif (re.compile("( |\\\'.*?\\\'|;.*?')").search(cif_line) is not None):
## Search for lines like this:
## 1 polymer nat '16S RIBOSOMAL RNA' 498797.375 1 ? ? ? ?
## and pull out the number and name.
pieces = [p for p in re.split("( |\\\'.*?\\\'|;.*?')", cif_line) if p.strip()]
chain_num = pieces[0]
chain_name = pieces[3]
print("Set " + chain_num + " to " + chain_name)
chain_dict[chain_num] = chain_name
interesting = False
re_string = ""
for cif_line in cif_lines:
if (re.compile("^_entity_poly\.pdbx_target_identifier").search(cif_line) is not None):
print("Second interesting start.")
interesting = True
continue
if (interesting is False):
continue
if (interesting is True):
if (re.compile("^#").search(cif_line) is not None):
break
## Num of chain name no no seq id ?
print("Working on " + cif_line)
re_string += cif_line
## Now we should have a relatively large multiline string to play with.
## First just drop the newlines
re_string = re.sub(r'\n', '', re_string)
## Each entry ends with a '?', so replace those with newlines.
re_string = re.sub(r'\s+\?\s+', '\n', re_string)
## Finally, replace the various semicolons with spaces
re_string = re.sub(r'\;', ' ', re_string)
## Now we should have 1 line / entry, always beginning with the chain number and
## ending in the 2 character chain ID.
for t in re_string.splitlines():
regex = r'^(\d+).*\s+(\w{2})\s*$'
comp = re.compile(regex).search(t)
dict_num = comp.group(1)
chain_id = comp.group(2)
print("Got " + dict_num + " and " + chain_id + ".")
mol_name = chain_dict[dict_num]
## Now we have a mapping from the number to a name and a chain ID.
## The final thing to do is to define the color as per the pdb function...
color = choose_color(mol_name)
selection_string = '/' + cif_shortname + '//' + chain_id
define_chain(selection_string, color, mol_name)
make_pretty()
cif_file.close()
def choose_color(chain_name):
color = default_colors['default']
## This section needs to be generalized using
## large_subunit_rnas and the similar globals
if (chain_name.find('PROTEIN') > -1):
matched = 0
if (chain_name.find('RACK') > -1):
color = default_colors['RACK']
matched = 1
for ssu in small_subunit_prot:
if (chain_name.find(ssu) > -1):
color = default_colors['SSU_protein']
matched = 1
for lsu in large_subunit_prot:
if (chain_name.find(lsu) > -1):
color = default_colors['LSU_protein']
matched = 1
if matched == 0:
color = default_colors['unknown']
elif (chain_name.find('RNA') > -1):
if (chain_name.find('TRNA') > -1):
color = default_colors['tRNA']
elif (chain_name.find('MRNA') > -1 or chain_name.find('MESSENGER') > -1):
color = default_colors['mRNA']
elif (chain_name.find('RRNA') > -1 or chain_name.find('S_RNA') > -1 or chain_name.find('RIBOSOMAL') > -1):
matched = 0
for lsr in large_subunit_rnas:
if (chain_name.find(lsr) > -1):
color = default_colors['LSU_RNA']
matched = 1
for ssr in small_subunit_rnas:
if (chain_name.find(ssr) > -1):
color = default_colors['SSU_RNA']
matched = 1
if matched == 0:
color = default_colors['RNA']
else:
color = default_colors['other']
return(color)
## This function will split apart ribosomal PDB files into
## the individual pieces by reading the header and attempting
## to choose sane names from the information there.
def split_pdb(pdb_file=None, splitp=""):
"""
This reads a pdb file's header in order to discover a few things:
a) Is there more than 1 pdb file in this complete image?
b) What species is this from?
c) What are the proteins, RNAs, and ligands in this image?
With this information it will attempt to create individual
objects for every chain in the pdb file which have helpful
colors and names.
"""
if pdb_file is None:
pdb_file = tkinter.filedialog.askopenfile(title="Open a pdb file.")
if not pdb_file:
return
## pdb_filename is the full filename
## pdb_shortname is the 2WGD or whathaveyou
## pdb_basename is the path it lives in
## pdb_file is the file object which has all the attributes etc
pdb_filename = str(pdb_file)
pdb_basename = os.path.basename(pdb_filename)
pdb_shortname = os.path.splitext(pdb_basename)
pdb_shortname = pdb_shortname[0]
pdb_file = open(pdb_filename, 'r')
original_list.append(pdb_shortname)
cmd.load(pdb_filename)
pdb_lines = pdb_file.readlines()
chain = ''
source_count = 0
## The following lines are attempting to properly decide
## when to stop reading a PDB file
for pdb_line in pdb_lines:
if re.compile("^HEADER").search(pdb_line) is not None:
continue
if re.compile("^TITLE").search(pdb_line) is not None:
continue
## If a PDB file has a SPLIT entry, then it is part of
## a group. So make a list of all entries in the group
## and fetch/split them all.
## Go recursion!
if re.compile("^SPLIT").search(pdb_line) is not None:
if splitp == "":
chains_list = pdb_line.split()
chains_list.pop(0)
for pdb_id in chains_list:
if (pdb_id != pdb_shortname):
fetch(pdb_id, "1")
else:
continue
if re.compile("^CAVEAT").search(pdb_line) is not None:
continue
## The SOURCE stanza contains the species and so will be useful
## for figuring out the helices later if need be.
if re.compile("^SOURCE").search(pdb_line) is not None:
source_count = source_count + 1