-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUserInterface.py
1504 lines (1321 loc) · 50 KB
/
UserInterface.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
'''
User Interface, Testing
env = chem
'''
# %% Imports
import easygui
import yaml
import sys
import os
from pathlib import Path
# %%% Resolve Paths
frozen = getattr(sys, 'frozen', False)
if frozen:
wd = Path(sys.executable).parent
os.chdir(wd)
print('os.getcwd is', os.getcwd() )
# %%% Import Customs
from MSPMaker import MSPMaker, Fragmenter
from Molecules import Molecule, AminoAcid, Peptide, Glycan, Peptidoglycan
from Generator import Generator
from base.Exceptions import InputError
from base.Common import TIME_STRING, MEMORY
# %% GUI
def get_preselect_integers(full_range, preselect_range):
"""
Helper function for easygui.multchoicebox(). Returns indexes of all strings
from preselect_range in full_range (if found).
Parameters
----------
full_range : list
List of options (as strings)
preselect_range : list
List of pre-selected options (as strings)
Returns
-------
preselect : list
List of indexes. If there is no overlap, return 0.
"""
if preselect_range == 0:
return 0
preselect = []
for i, obj in enumerate(full_range):
if obj in preselect_range:
preselect.append(i)
if len(preselect) == 0:
return 0
else:
return preselect
class GUI():
PARAM_FOLDER = Path("settings/ui")
PARAM_FILEPATH = Path("settings/ui/parameters.yaml")
HISTORY_MAX = 10
def __init__(self):
self.init_title = "PGN_MS2"
self._history = [self.init_title]
self.generator = None
self.maker = None
self.settings = {}
self.load_GUI_settings()
self.name = None
self.backtracks = 0
self.max_backtracks = 3
self.start_step = 0
self.title = self.init_title
def rename_generator(self):
"""
Renames the Generator.
Returns
-------
None.
"""
name = easygui.enterbox("Enter a name.",
self.title, default="test")
self.name = name
self.history = f"Name: {self.name}"
if self.generator is not None:
self.generator.refresh_name(self.name)
else:
self.create_generator()
def update_title(self):
if self.name is None:
self.title = self.init_title # reset
else:
self.title = f"{self.init_title} // {self.name} // Step {self.start_step}"
@property
def history(self):
return "\n".join(self._history)+"\n\n"
@history.setter
def history(self, text):
if text not in (None, ""):
self._history.append(text)
if len(self._history) > GUI.HISTORY_MAX:
self._history.pop(0)
def clear_history(self):
"""
Clears self.history.
Returns
-------
None.
"""
self._history = [self.title]
def start(self):
"""
Starts the GUI.
Returns
-------
None.
"""
if self.generator is None:
self.create_generator()
num_errors = 0
prog_run = True
while num_errors < 3 and prog_run:
try:
prog_run = self.run()
except Exception as exc:
print(exc)
easygui.exceptionbox()
num_errors += 1
sys.exit()
def run(self):
"""
Main loop of GUI.
Returns
-------
boolean
Returns False to kill loop.
"""
choice = 0
while choice not in ["Exit", None]:
msg = '''Select an option.'''
choices = [
"Build", "Load",
"Edit", "Clear",
"Run", "More Options",
"Exit"]
choice = easygui.choicebox(
self.history+msg, self.title, choices=choices)
if choice == "Build":
self.gen_build_settings()
elif choice == "Load":
self.gen_load_settings()
elif choice == "Edit":
self.gen_edit_settings()
elif choice == "Clear":
self.create_generator(force=True)
elif choice == "Run":
return self.gen_execute()
elif choice == "More Options":
self.run_extra_options()
return False
def run_extra_options(self):
"""
Runs additional, less used options.
Raises
------
Exception
Raises exception (for testing only)..
Returns
-------
boolean
Returns False to kill loop.
"""
choice = 0
while choice not in ["Exit", None]:
msg = '''Select an option.'''
choices = [
"Fragment Single Compound",
"GUI Settings", "Raise Exception",
"Reduce Cache", "Delete Cache",
"Exit"]
choice = easygui.choicebox(
self.history+msg, self.title, choices=choices)
if choice == "Fragment Single Compound":
self.frag_single_compound()
elif choice == "GUI Settings":
self.menu_GUI_settings()
elif choice == "Raise Exception":
raise Exception("Testing!")
elif choice == "Reduce Cache":
print("Reducing cache... please wait!")
MEMORY.reduce_size()
elif choice == "Delete Cache":
print("Deleting cache... please wait!")
MEMORY.clear(warn=False)
else:
pass
return False
# %%% GUI Settings
def menu_GUI_settings(self):
"""
Submenu for editting GUI settings.
Returns
-------
None.
"""
msg = "Select an option."
choice = 0
choices = [
"Load",
"Load Default",
"Save",
"Return"]
while choice not in ["Return", None]:
choice = easygui.choicebox(
self.history+msg, self.title, choices=choices)
if choice == "Load":
self.load_GUI_settings(use_default=False)
elif choice == "Load Default":
self.load_GUI_settings(use_default=True)
elif choice == "Save":
self.save_GUI_settings()
else:
pass
def load_GUI_settings(self, use_default=True):
"""
Loads settings for the GUI.
Parameters
----------
use_default : boolean, optional
If True, uses the hardcoded settings; else loads settings from
a file The default is True.
Returns
-------
None.
"""
if use_default:
self.load_default_GUI_settings()
else:
msg = "Open a settings file (.yaml)"
file = easygui.fileopenbox(
msg,
default=GUI.PARAM_FOLDER/"*.yaml",
filetypes=["*.yaml"])
filepath = Path(file)
with open(filepath, "r") as f:
self.settings = yaml.safe_load(f)
self.history = f"Loaded settings from: {filepath}"
def load_default_GUI_settings(self):
"""
Loads the default hardcoded settings.
Returns
-------
None.
"""
self.settings = {}
self.settings["default_Glc_types"] = "GlcNAc,GlcN,GlcNAcOAc"
self.settings["default_Mur_types"] = "MurNAc,MurN,MurNAcOAc,anMurNAc"
self.settings["default_tripeptide"] = {1: "Ala",
2: "γ Glu,γ isoGln",
3: "mDAP,mDAP(NH2),Lys,Orn"}
self.settings["full_AA_range"] = \
"Ala,Gly,Lys,Phe,Cys,Leu,Pro,Met,Trp,Tyr,His,Arg,Ser,Asp,Asn"
self.settings["limited_AA_range"] = '''Ala,Gly,Lys'''
self.history = "Loaded default settings"
def save_GUI_settings(self, overwrite_default=False):
"""
Saves the GUI settings.
Parameters
----------
overwrite_default : boolean, optional
If True, overwrites, the default parameter file at GUI.PARAM_FILEPATH.
The default is False.
Returns
-------
None.
"""
filepath = None
if overwrite_default:
filepath = GUI.PARAM_FILEPATH
else:
if self.name is None:
self.rename_generator()
filepath = Path(f"settings/ui/{self.name}_parameters.yaml")
with open(filepath, "w") as f:
yaml.safe_dump(self.settings, f)
self.history = f"Saved settings as {filepath}"
# %%% Generator
def create_generator(self, force=False):
"""
Creates a Generator with same name as GUI.
Parameters
----------
force : boolean, optional
If False, creates a Generator only if it doesn't exist or if its name
doesn't match. The default is False.
Returns
-------
bool
Returns True if a new Generator is created.
"""
if self.generator is None or self.generator.name != self.name or force:
self.generator = Generator(self.name)
self.history = "Generator created."
return True
else:
return False
def gen_load_settings(self):
"""
Loads settings for the Generator from a .yaml file.
Returns
-------
boolean
Returns True if settings loaded successfully.
"""
try:
default = "*.yaml"
settings_file = Path(easygui.fileopenbox(default=default))
if settings_file.suffix == ".yaml":
self.generator.import_settings_as_yaml(settings_file)
elif settings_file.suffix == ".pickle":
self.generator.import_settings_as_pickle(settings_file)
else:
self.history = "Not a valid settings file."
return False
except TypeError:
return False
self.history = f"Generator settings loaded from \n{settings_file}"
return True
def gen_build_settings(self, exit_step=12):
"""
Builds settings for the Generator.
Settings are generated in 12 steps:
1: Peptide, Glycan Lengths
2: Glc-Type Glycans
3: Mur-Type Glycans
4-8: Peptide Residues for positions 1-5
9: Bridge Peptide
10: Modifications
11: Polymerisation
12: Difference Calculator
Parameters
----------
exit_step : int, optional
Indicates the integer of the last step.
Use 12 to exit after Difference Calculator. The default is 12.
Returns
-------
None.
"""
if self.start_step == 0:
self.start_step += 1
self.backtracks = 0
defaults = [
"Ala",
"γ-Glu,γ-isoGln",
"mDAP,mDAP(NH2),Lys,Orn",
self.settings["full_AA_range"],
self.settings["full_AA_range"]]
self.history =\
f'''\nTo backtrack, use the cancel or [X] button. You may backtrack up to {self.max_backtracks} times.
To exit and return to main menu, backtrack {self.max_backtracks} times.\n'''
# Loop
while self.backtracks <= self.max_backtracks and exit_step >= self.start_step:
# Length
if self.start_step == 1:
self.rename_generator()
self.gen_set_length(mod_values=[0, 2, 0, 5, 1])
# Glycans - Glc-type
if self.start_step == 2:
self.gen_set_glycan("Glc",
default=self.settings["default_Glc_types"])
# Glycans - Mur-type
if self.start_step == 3:
self.gen_set_glycan("Mur",
default=self.settings["default_Mur_types"])
if self.start_step == 4:
# Check for reduction
reduced_muro = False
for glycan in self.generator.glycan_units["Mur"]:
if "[r]" in glycan:
reduced_muro = True
reduced_msg = "Reduced Mur-type sugars preferred in subsequent settings."
print(reduced_msg)
# Peptide
if 4 <= self.start_step < 9:
idx = self.start_step-3
self.gen_set_peptide(idx, default=defaults[idx-1])
# Bridge Peptides
if self.start_step == 9:
self.gen_set_bridge_peptides()
# Modifications
if self.start_step == 10:
self.gen_set_modifications()
# Crosslinks
if self.start_step == 11:
self.gen_choose_default_polymerisations(
prefer_reduced=reduced_muro)
# DiffCalc
if self.start_step == 12:
self.history = self.generator.set_diffcalc_units(1, [1])
if reduced_muro:
gly_range = [None, "GlcNAc", "MurNAc[r]", "anMurNAc"]
else:
gly_range = [None, "GlcNAc", "MurNAc", "anMurNAc"]
if self.generator.modifications["EPase P1"] or \
self.generator.modifications["EPase P2"]:
gly_len = [0, 2]
else:
gly_len = [2]
self.gen_set_diffcalc_params(gly_len=gly_len,
gly_range=gly_range,
pep_len=[4, 5])
# Terminate
self.history = "Returning to main menu..."
self.start_step = 0
self.backtracks = 0
def gen_edit_settings(self):
"""
Opens a menu that allows the user to edit the settings for Generator
after the initial sequence.
Returns
-------
None.
"""
msg = "Select an option."
choice = 0
choices = ["Modifications", "Length",
"Glycan Units", "Peptide Residues",
"Bridge Peptides", "Polymerisations",
"Diffcalc Units", "Diffcalc Params",
"Return"]
while choice not in ("Return", None):
choice = easygui.choicebox(
self.history+msg, self.title, choices=choices)
if choice == "Modifications":
self.gen_set_modifications()
elif choice == "Length":
self.gen_set_length()
elif choice == "Glycan Units":
self.gen_set_cpds("glycan")
elif choice == "Peptide Residues":
self.gen_set_cpds("peptide")
# Bridge Peptides
elif choice == "Bridge Peptides":
self.gen_set_bridge_peptides()
# Crosslinks
elif choice == "Polymerisations":
self.gen_choose_default_polymerisations()
elif choice == "Diffcalc Units":
self.gen_set_diffcalc_units()
elif choice == "Diffcalc Params":
self.gen_set_diffcalc_params()
else:
pass
def register_step(self, success=True):
"""
Helper function to help keep track of gen_build_settings.
Parameters
----------
success : boolean, optional
If True, current step ran successfully. The default is True.
Returns
-------
None.
"""
if success:
self.start_step += 1
print(f"Advancing to step [{self.start_step}]")
self.update_title()
else:
self.backtracks += 1
if self.start_step > 1:
self.start_step -= 1
trace_msg = f"--- Returning to previous step [{self.start_step}] {self.backtracks}/{self.max_backtracks}---"
self.update_title()
self.history = trace_msg
# %%%% Modifications
def gen_set_modifications(self):
"""
Selects modifications for PGN Generator.
Returns
-------
None.
"""
msg = "Select modifications. Pick 'Explain modifications' to open a textbox that explains selected modification(s)."
choices = list(self.generator.modifications.keys())
selected = [i for i, mod in enumerate(
choices) if self.generator.modifications[mod]]
choices.append("No modifications")
choices.append("Explain modifications")
picking = True
picked = None
while picking:
picked = easygui.multchoicebox(
self.history+msg, self.title, choices=choices, preselect=selected)
if picked is None:
picking = False
self.register_step(False) #backtrack
elif "Explain modifications" in picked:
self.gen_explain_modifications(picked)
continue
# pick again
elif "No modifications" in picked:
picked = []
picking = False
self.history = "No modifications added."
self.register_step(True)
else:
picking = False
self.history = self.generator.add_modifications(picked)
self.register_step(True)
def gen_explain_modifications(self, picked):
"""
Gives a textbox with an explanation of each modification.
Returns
-------
None.
"""
explanations = {
"Alanine/Lactate Substitution": "Lactate is added at position 5 instead of Ala",
"Lactoyl Peptide": "Both disaccharides are removed, leaving behind a lactoyl group attached to the stem peptide’s N-terminus.",
"Muramic Lactam": "A lactam is formed between amino group on C2 and the lactoyl group on C3 on the muramyl sugar. No stem peptide is present.",
"Amidase": "Generates glycans without stem peptides and vice versa. Ignore this option as it is already included as default.",
"EPase P1": "Creates stem peptides with no glycan and no amino acid in position 1.",
"EPase P2": "Creates stem peptides with no glycan and no amino acid in positions 1 and 2.",
"Braun LPP": "Adds ε-Lys-Arg (kR) dipeptide to positions 4 and 5 respectively."
}
msg_parts = [f"\n{x}:\n{explanations[x]}\n" for x in picked if x in explanations]
msg_parts.insert(0,"####Explanations####")
msg = "\n".join(msg_parts)
easygui.msgbox(msg=msg, title=self.title)
# %%%% Length
def gen_set_length(self, mod_values=None):
"""
Selects glycan length, peptide length and number of polymerisations.
Parameters
----------
mod_values : list
User-modified values for glycan length, peptide length and number
of crosslinks.
Returns
-------
None.
"""
if mod_values is None:
msg = "Set parameters."
fields = ["Glycan min", "Glycan max",
"Peptide min", "Peptide max",
"Num. Polymerisations"]
field_values = [self.generator.glycan_lmin,
self.generator.glycan_lmax,
self.generator.peptide_lmin,
self.generator.peptide_lmax,
self.generator.num_polymerisations]
mod_values = easygui.multenterbox(self.history+msg, self.title,
fields=fields, values=field_values)
if mod_values is None:
self.register_step(False) # Cancel
else:
self.history = self.generator.set_length(
"glycan", *map(int, mod_values[0:2]))
self.history = self.generator.set_length(
"peptide", *map(int, mod_values[2:4]))
self.history = self.generator.set_num_polymerisations(
int(mod_values[4]))
self.register_step(True)
# %%%% Glycan / Peptide
def gen_set_cpds(self, cpd):
"""
Initial stage of selection for glycan/peptides.
Parameters
----------
cpd : string
Type of compound. "peptide" or "glycan" accepted.
Raises
------
InputError
Raised if cpd is not valid.
Returns
-------
None.
"""
if cpd == "glycan":
msg = "Select a glycan type"
gtype = easygui.choicebox(
self.history+msg,
self.title,
choices=["Glc", "Mur"])
self.gen_set_glycan(gtype)
elif cpd == "peptide":
msg = "Select position in stem peptide"
idx = int(easygui.choicebox(
self.history+msg,
self.title,
choices=range(1, 6)))
self.gen_set_peptide(idx)
else:
raise InputError("Glycan/Peptide",
f"{cpd} not recognised")
def gen_set_glycan(self, gtype, default=None):
"""
Next stage of selection for glycans.
Parameters
----------
gtype : string
Type of glycan. "Glc" or "Mur" accepted.
default : list, optional
Default list of compounds. The default is None.
Raises
------
InputError
Raised if gtype is not valid.
Returns
-------
None.
"""
# type mode
if gtype not in ["Glc", "Mur"]:
raise InputError("Glycan",
f"{gtype} not recognised.")
msg = f'''
Type {gtype}-type glycan units, separated by a ','.
e.g. {gtype}NAc, {gtype}N, {gtype}NAcOAc
Reduced 'Mur'-type glycans are denoted with [r]; e.g. MurNAc[r]
'''
selected = easygui.enterbox(
self.history+msg, self.title, default=default)
if selected is None:
self.register_step(False)
else:
selected = selected.split(",")
selected = set(map(str.strip, selected))
self.history = self.generator.set_glycan_units(gtype, selected)
self.register_step(True)
def gen_set_peptide(self, idx, default=None):
"""
Next stage of selection for peptides.
Parameters
----------
idx : int
Position of amino acid(s) to be added.
default : list, optional
Default list of compounds. The default is None.
Returns
-------
None.
"""
# type mode
if idx < 1 or idx > 20:
raise InputError("Peptide",
"{idx} outside of range 1-20.")
msg = f'''
Type AAs for position {idx}, separated by a ','.
e.g. Ala, Ser
'''
selected = easygui.enterbox(
self.history+msg, self.title, default=default)
if selected is None:
self.register_step(False)
else:
selected = selected.split(",")
selected = set(map(str.strip, selected))
condition = None
if idx == 5:
conditional_bool = easygui.boolbox(
msg=\
'''Use conditional addition?
With conditional addition, amino acids at the fifth position will only be added if the fourth amino acid is from a defined range of amino acids.
This avoids nonsensical peptide sequences like "AemHH".''')
if conditional_bool:
msg = f'''
Add AAs at {idx} only if preceding AA is from ...
'''
condition = easygui.enterbox(
self.history+msg, self.title).strip().split(",")
condition = set(map(str.strip, condition))
if condition == [""]:
condition = None
self.history = self.generator.set_peptide_residues(
idx, selected, precAA_lst=condition)
self.register_step(True)
def gen_set_bridge_peptides(self):
"""
Selects bridge peptides.
Returns
-------
None.
"""
msg = \
'''Select position of bridge peptide on the stem peptide or 0 to skip.
For most gram-positive species, the bridge peptide is attached to the 3rd position of the stem peptide (Lys/Orn)'''
idx = easygui.choicebox(
self.history+msg,
self.title,
choices=range(0, 6))
if idx is None:
self.register_step(False)
return
idx = int(idx)
if idx == 0:
self.register_step(True)
return
msg = \
f'''Select connection type.
COOH --> COOH group of AA at position {idx} forms isopeptide bond with bridge peptide's N-terminus.
NH2 --> NH2 group of AA at position {idx} forms isopeptide bond with bridge peptide's C-terminus.
'''
grp = easygui.choicebox(
self.history+msg,
self.title,
choices=["COOH", "NH2"])
# type mode
msg = \
f'''Type AAs which have a bridge peptide at position {idx}-{grp}, separated by a ','.
'any'\t--> any AA can be used.
'diamino'\t--> any diamino AA can be used (e.g. Lys, mDAP).
'dicarboxy'\t--> any dicarboxy AA can be used (e.g. Glu).
'''
if grp == "COOH":
default = "dicarboxy"
elif grp == "NH2":
default = "diamino"
else:
self.register_step(False)
return
valid = easygui.enterbox(
self.history+msg, self.title, default=default)
if valid is None:
self.register_step(False)
else:
valid = valid.split(",")
valid = set(map(str.strip, valid))
msg = \
f'''Type bridge peptide(s) that connect to {idx}-{valid}-{grp}, separated by a ','.
Amino acids are typed from nearest to stem peptide to furthest and separated by a '>'
e.g. β-Asp, Ala>Ala, Ser>Ala>Thr>Ala
'''
chains = easygui.enterbox(
self.history+msg, self.title)
if chains is None:
self.register_step(False)
return
chains = chains.split(",")
chain_lst = [chain.split(">") for chain in chains]
self.history = self.generator.set_bridge_peptides(
idx, grp, chain_lst, valid_AAs=valid)
self.register_step(True)
def gen_retrieve_AAs(self, idx="all"):
"""
Retrieve AAs from Generator for positions {idx} and returns a combined,
sorted list.
Parameters
----------
idx : list, optional
List of positions to retrieve. The default is "all", which retrieves
for positions 1 - 6.
Returns
-------
AAs : list
Sorted list of amino acids.
"""
AAs = []
if idx == "all":
idx = [1, 6]
for i in range(*idx):
if i in self.generator.peptide_residues:
AAs.extend(self.generator.peptide_residues[i]["AAs"])
else:
AAs = Generator.valid_AAs
AAs = sorted(list(set(AAs)))
return AAs
# %%%% Polymerisations
def gen_choose_default_polymerisations(self, prefer_reduced=False):
"""
Select polymerisations with default options.
Parameters
----------
prefer_reduced : boolean, optional
If True, polymerisations will prefer the reduced Mur-type sugars
over non-reduced sugars. The default is False.
Returns
-------
None.
"""
if self.generator.num_polymerisations == 0:
self.history = "No polymerisations picked."
self.register_step(True)
msg = "Pick polymerisations."
crosslink_options = ["G-G",
"3s-3", "3s-4",
"3br-3", "3br-4",
"Clear existing polymerisations",
"No polymerisations"]
polymerisations = easygui.multchoicebox(
self.history+msg, self.title, choices=crosslink_options)
preselect = 0
if polymerisations is None:
self.register_step(False)
return
else:
if "No polymerisations" in polymerisations:
self.history = "No polymerisations picked."
self.register_step(True)
if "Clear existing polymerisations" in polymerisations:
self.history = self.generator.clear_polymerisations()
if "G-G" in polymerisations:
preselect = \
self.gen_add_default_glycan_polymerisation(
"G-G", prefer_reduced, preselect)
if "3s-3" in polymerisations:
preselect = \
self.gen_add_default_peptide_polymerisation(
"3s-3", 3, False, prefer_reduced, preselect)
if "3s-4" in polymerisations:
preselect = \
self.gen_add_default_peptide_polymerisation(
"3s-4", 4, False, prefer_reduced, preselect)
if "3br-3" in polymerisations:
preselect = \
self.gen_add_default_peptide_polymerisation(
"3br-3", 3, True, prefer_reduced, preselect)
if "3br-4" in polymerisations:
preselect = \
self.gen_add_default_peptide_polymerisation(
"3br-4", 4, True, prefer_reduced, preselect)
self.register_step(True)
def gen_add_default_glycan_polymerisation(self, name,
prefer_reduced,
preselect=0):
"""
Select default glycosidic polymerisation (G-G) with preset options.
Parameters
----------
name : string
Name of polymerisation.
prefer_reduced : boolean, optional
If True, polymerisations will prefer the reduced Mur-type sugars
over non-reduced sugars. The default is False.
preselect : list, optional
List of integers that correspond to AAs. These will appear as the
default option. The default is 0 (No amino acids).
Returns
-------
preselect : list
List of integers that correspond to AAs. These will appear as the
default option in future selections.
"""
msg = f"Set acceptable AAs in position 4 and 5 in the stem peptide\
of {name} polymerisation."
AAs = self.gen_retrieve_AAs(idx=[4, 5])
if self.generator.modifications["Alanine/Lactate Substitution"]:
AAs.append("Lac") # add Lactate if modification used
AA_lst = easygui.multchoicebox(
self.history+msg,
self.title,
choices=AAs,
preselect=preselect)
if AA_lst is None:
self.history = f"{name} polymerisation not added - no AAs provided."
return preselect
AA_lst.append(None)
P1 = {"pep_len": [3, 4, 5],
4: {"allowed": AA_lst},
5: {"allowed": AA_lst},
"gly_len": [2],
"gly_rejected": ["anMurNAc", "anMurN", "anMurNGlyc", # anhydro
"MurN[r]", "MurNAc[r]", "MurNAcP[r]", # reduced
"MurNGlyc[r]", "MurNAcOAc[r]"]}
if prefer_reduced:
gly_accepted = ["GlcNAc", "MurNAc[r]", "anMurNAc"]
else:
gly_accepted = ["GlcNAc", "MurNAc", "anMurNAc"]
P2 = {"pep_len": [3, 4, 5],
4: {"allowed": AA_lst},
5: {"allowed": AA_lst},
"gly_len": [2],
"gly_accepted": gly_accepted}
P1_bond = [0, "glycan", "glycan", "Acc"]
P2_bond = [0, "glycan", "glycan", "Dnr"]
self.history = self.generator.set_polymerisation_types(P1, P2,
P1_bond, P2_bond)
preselect = get_preselect_integers(AAs, AA_lst)
return preselect
def gen_add_default_peptide_polymerisation(self, name, length_p2,