-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathVisualize.py
3235 lines (3104 loc) · 158 KB
/
Visualize.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
import functools
from collections import Counter
from typing import List, Union
import ipywidgets as widgets
import pandas as pd
from IPython.display import Markdown, clear_output, display
from ipywidgets import Layout
from rdkit import Chem # Importing RDKit
from rdkit.Chem import Draw, rdChemReactions # Reaction processing
from rdkit.Chem.Draw import IPythonConsole
from AnalgCompds import getCarrierFrags0
from FunctionsDB import getmixturefrags
from MainFunctions import (
drawReaction,
highlightsubstruct,
molfromsmiles,
)
from MapRxns import maprxn
from Standalone import balance_rxn_dp, rxn_center_dp
# (
# rxnsmiles0,
# balrxnsmiles,
# msg,
# LHSids,
# RHSids,
# hcrct,
# hcprod,
# LHSdata,
# RHSdata,
# mappedrxn,
# conf,
# msg1,
# ) = balance_rxn_dp(
# "Brc1csc2ccccc12.OB(O)c1ccc2c(c1)c1ccccc1n2-c1ccccc1>>c1ccc(-n2c3ccccc3c3cc(-c4csc5ccccc45)ccc32)cc1"
# )
# (
# specmap,
# rnbmap,
# rxncentermapnum,
# LHSdata,
# msg,
# outfrag,
# outfg,
# outneighbor,
# unusedanalogue,
# ) = rxn_center_dp(mappedrxn, LHSdata, RHSdata)
def visfragment1(smiles: str, pattlist: List):
return display(highlightsubstruct(smiles, pattlist=pattlist))
def verifyindex(
df: pd.DataFrame, idxcol: Union[str, List[str]] = ["ReactionID", "Instance"]
):
if isinstance(idxcol, list) and len(idxcol) == 1:
idxcol = idxcol[0]
if isinstance(idxcol, str):
idx = df.index.name
if idx and idx != idxcol:
df.reset_index(inplace=True)
df.set_index(idxcol, inplace=True)
elif not idx:
df.set_index(idxcol, inplace=True)
else:
idx = df.index.names
if idx and idx != idxcol:
df.reset_index(inplace=True)
df.set_index(idxcol, inplace=True)
elif not idx:
df.set_index(idxcol, inplace=True)
return df
def vismaster(**kwargs):
# Setting up buttons
dataminingbutton = widgets.Button(
description="Data Mining",
button_style="success",
layout=widgets.Layout(width="20%", height="auto"),
)
dataprocessingbutton = widgets.Button(
description="Data Processing",
button_style="success",
layout=widgets.Layout(width="20%", height="auto"),
)
impuritypredictionbutton = widgets.Button(
description="Impurity Prediction",
button_style="success",
layout=widgets.Layout(width="20%", height="auto"),
)
impurityrankingbutton = widgets.Button(
description="Impurity Ranking",
button_style="success",
layout=widgets.Layout(width="20%", height="auto"),
)
allbutton = widgets.Button(
description="All",
button_style="success",
layout=widgets.Layout(width="25%", height="auto"),
)
uibutton = widgets.HBox(
[
allbutton,
dataminingbutton,
dataprocessingbutton,
impuritypredictionbutton,
impurityrankingbutton,
],
layout=widgets.Layout(border="5px solid green"),
)
display(Markdown("#### <center>Select a stage to visualize</center>"))
display(uibutton)
outmaster = widgets.Output()
def on_button_clicked(b, stages: List = []):
with outmaster:
clear_output()
tracemaster(stages=stages, **kwargs)
dataminingbutton.on_click(
functools.partial(on_button_clicked, stages=["Data Mining"])
)
dataprocessingbutton.on_click(
functools.partial(on_button_clicked, stages=["Data Processing"])
)
impuritypredictionbutton.on_click(
functools.partial(on_button_clicked, stages=["Impurity Prediction"])
)
impurityrankingbutton.on_click(
functools.partial(on_button_clicked, stages=["Impurity Ranking"])
)
allbutton.on_click(
functools.partial(
on_button_clicked,
stages=[
"Data Mining",
"Data Processing",
"Impurity Prediction",
"Impurity Ranking",
],
)
)
display(outmaster)
def tracemaster(
stages=["Data Mining", "Data Processing", "Impurity Prediction"], **kwargs
):
global displaywidget, optionschanged
displaywidget = False
optionschanged = False
for stage in stages:
if stage == "Data Mining":
display(Markdown("<h1><center><strong>Data Mining</strong></center></h1>"))
if "fragdbsource" in kwargs and isinstance(
kwargs["fragdbsource"], pd.DataFrame
):
fragdb = kwargs["fragdbsource"]
fragdb = verifyindex(fragdb, idxcol=["FragmentSmiles", "SubstanceID"])
else:
fragdb = None
for i, iq in enumerate(
["inputquery_analg_updated", "inputquery_analg", "inputquery"]
):
if iq in kwargs and kwargs[iq] is not None:
inputquery = kwargs[iq]
userinput = inputquery["smiles"]
display(
Markdown(
f"<h2><center><strong>1. Query Reaction</strong></center></h2>"
)
)
display(
drawReaction(
userinput,
useSmiles=True
)
)
display(Markdown(f"`Query Reaction SMILES: {userinput}`"))
queryspecies = list(inputquery["species"].keys())
queryspec = widgets.Dropdown(
options=[""] + queryspecies,
style={"description_width": "initial"},
description="Query Species",
continuous_update=False,
)
queryfrag = widgets.Dropdown(
description="Fragment", options=[""], continuous_update=False
)
queryexpand = widgets.IntSlider(
description="Expand",
min=0,
max=10,
step=1,
value=1,
continuous_update=False,
)
queryresformat = widgets.Dropdown(
options=["smiles", "smarts"],
style={"description_width": "initial"},
description="Result Format",
value="smiles",
)
def on_update_queryspec_widget(*args):
if queryspec.value:
if (
queryresformat.value == "smiles"
and queryexpand.value == 1
):
queryfrags = list(
inputquery["species"][queryspec.value].keys()
)
else:
if "." in queryspec.value: # Mixture
queryfrags = getmixturefrags(
queryspec.value,
expand=queryexpand.value,
resFormat=queryresformat.value,
)
else:
queryfrags = getCarrierFrags0(
queryspec.value,
expand=queryexpand.value,
resFormat=queryresformat.value,
)
queryfrag.options = [""] + list(Counter(queryfrags).keys())
else:
queryfrag.options = [""]
def on_update_queryexpand_widget(*args):
if queryspec.value:
if (
queryexpand.value != 1
or queryresformat.value != "smiles"
):
if "." in queryspec.value: # Mixture
queryfrags = getmixturefrags(
queryspec.value,
expand=queryexpand.value,
resFormat=queryresformat.value,
)
else:
queryfrags = getCarrierFrags0(
queryspec.value,
expand=queryexpand.value,
resFormat=queryresformat.value,
)
else:
queryfrags = list(
inputquery["species"][queryspec.value].keys()
)
queryfrag.options = [""] + list(Counter(queryfrags).keys())
else:
queryfrag.options = [""]
def on_update_queryresformat_widget(*args):
if queryspec.value:
if (
queryresformat.value != "smiles"
or queryexpand.value != 1
):
if "." in queryspec.value: # Mixture
queryfrags = getmixturefrags(
queryspec.value,
expand=queryexpand.value,
resFormat=queryresformat.value,
)
else:
queryfrags = getCarrierFrags0(
queryspec.value,
expand=queryexpand.value,
resFormat=queryresformat.value,
)
else:
queryfrags = list(
inputquery["species"][queryspec.value].keys()
)
queryfrag.options = [""] + list(Counter(queryfrags).keys())
else:
queryfrag.options = [""]
def visfragment_(queryspec: str, frag: str):
if frag:
img, count = highlightsubstruct(
queryspec, [frag], returncount=True
)
display(img)
display(Markdown(f"Species SMILES: {queryspec}"))
display(Markdown(f"Fragment SMILES: {frag}"))
display(Markdown(f"Fragment count:{count[0]}"))
if i < 2:
specdata = inputquery["species"][queryspec]
if frag in specdata:
analoguepool = specdata[frag]["analoguepool"]
combinedui, fragui, outfrag = visfragment(
analoguepool=analoguepool,
analoguefrag=frag,
displayres=False,
**kwargs,
)
display(
Markdown(
"<h2><center><strong>3. Fragment Visualization (Analogue Species)</strong></center></h2>"
)
)
display(
Markdown(
f"The chosen carrier fragment is {frag}"
)
)
display(
Markdown(
"<h3><center><strong>Analogue Species</strong></center></h3>"
)
)
display(combinedui)
display(
Markdown(
"<h3><center><strong>Fragments</strong></center></h3>"
)
)
display(fragui)
display(outfrag)
else:
display(
Markdown(
f"<h3><center><strong>No analogue species information detected</strong></center></h3>"
)
)
queryspec.observe(on_update_queryspec_widget, "value")
queryexpand.observe(on_update_queryexpand_widget, "value")
queryresformat.observe(on_update_queryresformat_widget, "value")
queryui_ = widgets.HBox([queryfrag, queryexpand, queryresformat])
queryui = widgets.VBox([queryspec, queryui_])
outmain = widgets.interactive_output(
visfragment_,
{
"queryspec": queryspec,
"frag": queryfrag,
},
)
display(
Markdown(
"<h2><center><strong>2. Fragment Visualization (Query Species)</strong></center></h2>"
)
)
display(queryui)
display(outmain)
break
if stage == "Data Processing":
displaywidget = False
reactionid_dp = widgets.SelectionSlider(
options=[""], description="Reaction ID", continuous_update=False
)
instance_dp = widgets.SelectionSlider(
description="Instance", options=[0], continuous_update=False
)
reactionid_dptext = widgets.Text(description="Reaction ID", value="")
customrxnsmiles_dp = widgets.Text(
description="Custom Reaction SMILES",
style={"description_width": "initial"},
)
# analgrawcheck = widgets.Checkbox(
# value=True,
# description="Restrict available reactions to analogue reactions from step 4",
# disabled=False,
# indent=False,
# )
# analgcheck = widgets.Checkbox(
# value=False,
# description="Restrict available reactions to this step",
# disabled=False,
# indent=False,
# )
# analgbalcheck = widgets.Checkbox(
# value=False,
# description="Restrict available reactions to this step",
# disabled=False,
# indent=False,
# )
# analgmapcheck = widgets.Checkbox(
# value=False,
# description="Restrict available reactions to this step",
# disabled=False,
# indent=False,
# )
# analgcentcheck = widgets.Checkbox(
# value=False,
# description="Restrict available reactions to this step",
# disabled=False,
# indent=False,
# )
# def on_update_analgcheckraw(*args):
# if analgrawcheck.value and kwargs["analoguerxns"] is not None:
# (
# reactionid_dp,
# reactionid_dptext,
# instance_dp,
# customrxnsmiles_dp,
# ) = updatereactionwidget(
# reactionid_dp, instance_dp, kwargs["analoguerxns"]
# )
# analgcheck.value = False
# analgbalcheck.value = False
# analgmapcheck.value = False
# analgcentcheck.value = False
# def on_update_analgcheck(*args):
# if analgcheck.value and kwargs["analoguerxnsbal"] is not None:
# (
# reactionid_dp,
# reactionid_dptext,
# instance_dp,
# customrxnsmiles_dp,
# ) = updatereactionwidget(
# reactionid_dp, instance_dp, kwargs["analoguerxnsbal"]
# )
# analgrawcheck.value = False
# analgbalcheck.value = False
# analgmapcheck.value = False
# analgcentcheck.value = False
# elif all(
# [
# not i.value
# for i in [analgbalcheck, analgmapcheck, analgcentcheck]
# ]
# ):
# analgrawcheck.value = True
# def on_update_analgbalcheck(*args):
# if analgbalcheck.value and kwargs["analoguerxnsmapped"] is not None:
# (
# reactionid_dp,
# reactionid_dptext,
# instance_dp,
# customrxnsmiles_dp,
# ) = updatereactionwidget(
# reactionid_dp, instance_dp, kwargs["analoguerxnsmapped"]
# )
# analgrawcheck.value = False
# analgcheck.value = False
# analgbalcheck.value = False
# analgcentcheck.value = False
# elif all(
# [not i.value for i in [analgcheck, analgmapcheck, analgcentcheck]]
# ):
# analgrawcheck.value = True
# def on_update_analgmapcheck(*args):
# if analgmapcheck.value and kwargs["analoguerxnsassigned"] is not None:
# (
# reactionid_dp,
# reactionid_dptext,
# instance_dp,
# customrxnsmiles_dp,
# ) = updatereactionwidget(
# reactionid_dp, instance_dp, kwargs["analoguerxnsassigned"]
# )
# analgrawcheck.value = False
# analgcheck.value = False
# analgbalcheck.value = False
# analgcentcheck.value = False
# elif all(
# [not i.value for i in [analgcheck, analgbalcheck, analgcentcheck]]
# ):
# analgrawcheck.value = True
# def on_update_analgcentcheck(*args):
# if analgcentcheck.value and kwargs["analoguerxnsfinal"] is not None:
# (
# reactionid_dp,
# reactionid_dptext,
# instance_dp,
# customrxnsmiles_dp,
# ) = updatereactionwidget(
# reactionid_dp, instance_dp, kwargs["analoguerxnsfinal"]
# )
# analgrawcheck.value = False
# analgcheck.value = False
# analgbalcheck.value = False
# analgmapcheck.value = False
# elif all(
# [not i.value for i in [analgcheck, analgbalcheck, analgmapcheck]]
# ):
# analgrawcheck.value = True
# analgrawcheck.observe(on_update_analgcheckraw, "value")
# analgcheck.observe(on_update_analgcheck, "value")
# analgbalcheck.observe(on_update_analgbalcheck, "value")
# analgmapcheck.observe(on_update_analgmapcheck, "value")
# analgcentcheck.observe(on_update_analgcentcheck, "value")
display(
Markdown("<h1><center><strong>Data Processing</strong></center></h1>")
)
optionschanged = False
for i, dfname in enumerate(
[
"analoguerxns",
"analoguerxns_updated",
"analoguerxnsbal",
"analoguerxnsmapped",
"analoguerxnsparsed",
"analoguerxnsassigned",
"analoguerxnscent",
"analoguerxnsvalid",
"analoguerxnsfinal",
]
): # All important inputs for data processing
if dfname in kwargs:
df = kwargs[dfname]
if df is not None:
df = verifyindex(df)
if not optionschanged and i in [0, 2, 3, 5, 8]:
(
reactionid_dp,
reactionid_dptext,
instance_dp,
customrxnsmiles_dp,
) = updatereactionwidget(
reactionid_dp,
instance_dp,
df,
reactionid_dptext,
customrxnsmiles_dp,
)
optionschanged = True
# if i == 0:
# analgrawcheck.value = True
# elif i == 2:
# analgcheck.value = True
# elif i == 3:
# analgbalcheck.value = True
# elif i == 5:
# analgmapcheck.value = True
# elif i == 8:
# analgcentcheck.value = True
else:
kwargs[dfname] = None
def tracedprxns(
reactionid: int,
instance: int,
customrxnsmiles: str,
# analgrawcheck: bool,
# analgcheck: bool,
# analgbalcheck: bool,
# analgmapcheck: bool,
# analgcentcheck: bool,
):
global displaywidget, success
if kwargs["analoguerxns"] is not None:
display(
Markdown(
"<h2><center><strong>Analogue Reactions</strong></center></h2>"
)
)
display(
Markdown(
f"<center><strong>{len(kwargs['analoguerxns'])} reactions retrieved</strong></center>"
)
)
reactionidui = widgets.VBox([reactionid_dp, reactionid_dptext])
display(widgets.HBox([reactionidui, instance_dp, customrxnsmiles_dp]))
displaywidget = True
if (
customrxnsmiles
): # User has defined a custom reaction SMILES (custom workflow is called)
try:
(
rxnsmiles0,
balrxnsmiles,
msg,
LHSids,
RHSids,
hcrct,
hcprod,
LHSdata,
RHSdata,
mappedrxn,
conf,
msg1,
) = balance_rxn_dp(customrxnsmiles)
(
specmap,
rnbmap,
rxncentermapnum,
LHSdata,
msg,
outfrag,
outfg,
outneighbor,
unusedanalogue,
) = rxn_center_dp(mappedrxn, LHSdata, RHSdata)
except Exception as e:
print(e)
else: # User can play around with existing reactions in supplied data frames
for i, dfname in enumerate(
[
"analoguerxnsfinal",
"analoguerxnsvalid",
"analoguerxnscent",
"analoguerxnsassigned",
"analoguerxnsparsed",
"analoguerxnsmapped",
"analoguerxnsbal",
"analoguerxns",
]
):
global success
success = False
if kwargs[dfname] is not None:
df = kwargs[dfname]
if (reactionid, instance) in df.index:
success = True
reactiondf = df.xs((reactionid, instance))
if i <= 7:
if "rxnsmiles0" in reactiondf:
display(
Markdown(
"<h2><center><strong>5. Analogue Reaction (Reaxys)</strong></center></h2>"
)
)
rxninfo = {}
if kwargs["analoguerxns_updated"] is not None:
identifiers1 = [
"Rdata",
"Pdata",
"Rgtdata",
"Solvdata",
]
rxninfo = (
kwargs["analoguerxns_updated"]
.xs((reactionid, instance))[
identifiers1
]
.to_dict()
)
if kwargs["analoguerxns"] is not None:
identifiers2 = [
"MissingReactant",
"MissingProduct",
"MissingSolvent",
"NameDict",
"CatalystID",
"MissingCatalyst",
"Temperature",
"Pressure",
"ReactionTime",
"YearPublished",
"NumRefs",
"NumSteps",
"NumStages",
]
rxninfo1 = (
kwargs["analoguerxns"]
.xs((reactionid, instance))[
identifiers2
]
.to_dict()
)
rxninfo.update(rxninfo1)
visreaction(reactiondf.rxnsmiles0, **rxninfo)
if kwargs["analoguerxnsbal"] is not None:
display(
Markdown(
f"<center><strong>{len(kwargs['analoguerxnsbal'])} reactions remaining after filtering</strong></center>"
)
)
if "balrxnsmiles" in reactiondf:
display(
Markdown(
"<h2><center><strong>6. Balanced Reaction</strong></center></h2>"
)
)
if reactiondf.balrxnsmiles != "Error":
visreaction(reactiondf.balrxnsmiles)
display(
Markdown(
f"<strong>Message: {reactiondf.msg}</center>"
)
)
if kwargs["analoguerxnsmapped"] is not None:
display(
Markdown(
f"<center><strong>{len(kwargs['analoguerxnsmapped'])} reactions remaining after filtering</strong></center>"
)
)
if "mapped_rxn" in reactiondf:
display(
Markdown(
"<h2><center><strong>7. Mapped Reaction</strong></center></h2>"
)
)
if reactiondf.mapped_rxn != "Error":
visreaction(reactiondf.mapped_rxn)
display(
Markdown(
f"Confidence: {reactiondf.confidence}"
)
)
else:
display(Markdown("Error"))
if i <= 4:
display(
Markdown(
f"<strong>Message: {reactiondf.msg1}</center>"
)
)
if i <= 3:
if reactiondf.msg2 != reactiondf.msg1:
display(
Markdown(
f"<strong>Message: {reactiondf.msg2}</center>"
)
)
if kwargs["analoguerxnsassigned"] is not None:
display(
Markdown(
f"<center><strong>{len(kwargs['analoguerxnsassigned'])} reactions remaining after filtering</strong></center>"
)
)
if i <= 2:
if "rxncentermapnum" in reactiondf:
display(
Markdown(
"<h2><center><strong>8. Reaction Center</strong></center></h2>"
)
)
if reactiondf.rxncenter:
display(
Markdown(
f"<center><strong>Reaction center map numbers: {reactiondf.rxncentermapnum}</strong></center>"
)
)
elif reactiondf.rnbmap:
display(
Markdown(
f"<center><strong>Reacting unmapped atoms: {reactiondf.rnbmap}</strong></center>"
)
)
else:
display(
Markdown(
"<center><strong>Reaction does not have a reaction center</strong></center>"
)
)
IPythonConsole.drawOptions.setHighlightColour(
(0.7, 1, 0.7)
)
IPythonConsole.drawOptions.minFontSize = 7
IPythonConsole.drawOptions.useBWAtomPalette()
IPythonConsole.drawOptions.legendFraction = 0.5
IPythonConsole.drawOptions.legendFontSize = 50
# IPythonConsole.drawOptions.legendFraction = 0.6
# IPythonConsole.drawOptions.useDefaultAtomPalette()
if i <= 1:
colors = [(0.7, 1, 0.7), (1, 0.7, 0.7)]
LHSdata = reactiondf.LHSdata
drawsettings = {rctid: {} for rctid in LHSdata}
for rctid in LHSdata:
for ridx in LHSdata[rctid]["fragloc"]:
highlightAtomList = [
atm
for frag in LHSdata[rctid]["fragloc"][
ridx
]
for match in LHSdata[rctid]["fragloc"][
ridx
][frag]["corrmatches"]
for atm in match
]
if isinstance(ridx, tuple):
rctmol = Chem.AddHs(
molfromsmiles(
LHSdata[rctid]["mappedsmiles"][
ridx[0]
][ridx[1]]
)
)
else:
rctmol = Chem.AddHs(
molfromsmiles(
LHSdata[rctid]["mappedsmiles"][
ridx
]
)
)
highlightAtomColor = {
atm: colors[0]
for atm in highlightAtomList
}
legend = f"Species {rctid}, instance {ridx} \n Mapped SMILES: {LHSdata[rctid]['mappedsmiles'][ridx]}"
if "reacfrag" in LHSdata[rctid] and LHSdata[
rctid
]["reacfrag"].get(ridx):
legend += f"\n Reacting carrier fragment(s): {', '.join(LHSdata[rctid]['reacfrag'][ridx].keys())}"
drawsettings[rctid].update(
{
ridx: [
rctmol,
highlightAtomList,
highlightAtomColor,
legend,
{}, # highlightBondColor
]
}
)
RHSdata = reactiondf.RHSdata
drawsettingsp = {prodid: {} for prodid in RHSdata}
for prodid in RHSdata:
for i, mappedsmiles in enumerate(
RHSdata[prodid]["mappedsmiles"]
):
if isinstance(mappedsmiles, tuple):
for j, mappedsmiles_ in enumerate(
mappedsmiles
):
pidx = (i, j)
prodmol = Chem.AddHs(
molfromsmiles(mappedsmiles_)
)
drawsettingsp[prodid].update(
{
pidx: [
prodmol,
[],
{},
f"Species {prodid}, instance {pidx} \n Mapped SMILES: {mappedsmiles_}",
{},
]
}
)
else:
pidx = i
prodmol = Chem.AddHs(
molfromsmiles(mappedsmiles)
)
drawsettingsp[prodid].update(
{
pidx: [
prodmol,
[],
{},
f"Species {prodid}, instance {pidx} \n Mapped SMILES: {mappedsmiles}",
{},
]
}
)
RCs = [
reactiondf.rxncentermapnum,
set(reactiondf.rnbmap.keys()),
]
mapdicts = [reactiondf.specmap, reactiondf.rnbmap]
for RC, mapdict in zip(RCs, mapdicts):
for changemapnum in RC:
rctid = mapdict[changemapnum][0]
ridx = mapdict[changemapnum][1]
idxr = mapdict[changemapnum][2]
prodid = mapdict[changemapnum][3]
pidx = mapdict[changemapnum][4]
idxp = mapdict[changemapnum][5]
if (
idxr not in drawsettings[rctid][ridx][1]
): # Reaction center outside
nbatoms = [
atom.GetIdx()
for atom in drawsettings[rctid][
ridx
][0]
.GetAtomWithIdx(idxr)
.GetNeighbors()
if atom.GetIdx()
in drawsettings[rctid][ridx][1]
]
if nbatoms:
drawsettings[rctid][ridx][4].update(
{
drawsettings[rctid][ridx][0]
.GetBondBetweenAtoms(
atomidx, idxr
)
.GetIdx(): colors[1]
for atomidx in nbatoms
}
)
drawsettings[rctid][ridx][1].append(
idxr
)
drawsettings[rctid][ridx][2].update(
{idxr: colors[1]}
)
else:
drawsettings[rctid][ridx][2][
idxr
] = colors[1]
drawsettingsp[prodid][pidx][1].append(idxp)
drawsettingsp[prodid][pidx][2].update(
{idxp: colors[1]}
)
# print(drawsettings)
# print(drawsettingsp)
display(
Markdown(
"<h4><center><strong>Reactants</strong></center></h4>"
)
)
display(
Draw.MolsToGridImage(
[
drawsettings[rctid][ridx][0]
for rctid in drawsettings
for ridx in drawsettings[rctid]
],
subImgSize=(500, 500),
legends=[
drawsettings[rctid][ridx][3]
for rctid in drawsettings
for ridx in drawsettings[rctid]
],
highlightAtomLists=[
drawsettings[rctid][ridx][1]
for rctid in drawsettings
for ridx in drawsettings[rctid]
],
highlightAtomColors=[
drawsettings[rctid][ridx][2]
for rctid in drawsettings
for ridx in drawsettings[rctid]
],
highlightBondColors=[
drawsettings[rctid][ridx][4]
for rctid in drawsettings
for ridx in drawsettings[rctid]
],
useSVG=True,
)
)
display(
Markdown(
f"<h4><center><strong>Products</strong></center></h4>"
)
)
IPythonConsole.drawOptions.setHighlightColour(
(1, 0.7, 0.7)
)
display(
Draw.MolsToGridImage(
[
drawsettingsp[prodid][pidx][0]
for prodid in drawsettingsp
for pidx in drawsettingsp[prodid]
],
subImgSize=(500, 500),
legends=[
drawsettingsp[prodid][pidx][3]
for prodid in drawsettingsp
for pidx in drawsettingsp[prodid]
],
highlightAtomLists=[
drawsettingsp[prodid][pidx][1]
for prodid in drawsettingsp
for pidx in drawsettingsp[prodid]
],
highlightAtomColors=[
drawsettingsp[prodid][pidx][2]
for prodid in drawsettingsp
for pidx in drawsettingsp[prodid]
],
highlightBondColors=[
drawsettingsp[prodid][pidx][4]
for prodid in drawsettingsp
for pidx in drawsettingsp[prodid]
],
useSVG=True,
)
)
display(
Markdown(
f"<center><strong>Message:{reactiondf.msg3}</strong></center>"
)