-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsimpleNMR.py
1770 lines (1419 loc) · 65.5 KB
/
simpleNMR.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 sys
import os
import pathlib
import json
import webbrowser
import math
import PyQt5
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5.QtCore import QUrl
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QFileDialog
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QLineEdit
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QSplitter
from PyQt5.QtWidgets import QMenu
from PyQt5.QtWidgets import QSpinBox
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QAction
from qtutils import warning_dialog
from functools import partial
from matplotlib.backends.backend_qt5agg import (
FigureCanvasQTAgg,
NavigationToolbar2QT as NavigationToolbar,
)
from rdkit import Chem
# from rdkit.Chem import AllChem
from rdkit.Chem import Draw
# import networkx as nx
# import nx_pylab
import numpy as np
import pandas as pd
from inspect import currentframe, getframeinfo
pd.options.mode.chained_assignment = "raise"
from PIL import Image
import platform
import nmrProblem
# from test_excel_simplenmr import TestExcelSimpleNMR
from qt5_tabs_001 import EditDataFrameDialog
from moleculePlot import MatplotlibMoleculePlot
from spectraPlot import MatplotlibH1C13Plot
from xy3_dialog import XY3dialog
from about_dialog import Aboutdialog
import problemtohtml
import java
import exampleProblems
from smiles_dialog import SmilesDialog
import simpleNMRutils
import mnovautils
import problemToD3html
PLOTLINECOLORS = ("blue", "orange", "green", "red", "purple")
SCATTERFACECOLORS = ("blue", "orange", "green", "red", "purple")
SCATTEREDGECOLORS = ("blue", "orange", "green", "red", "purple")
PLOTLINECOLORS = ['#377eb8', '#ff7f00', '#4daf4a',
'#f781bf', '#a65628', '#984ea3',
'#999999', '#e41a1c', '#dede00']
SCATTERFACECOLORS = ['#377eb8', '#ff7f00', '#4daf4a',
'#f781bf', '#a65628', '#984ea3',
'#999999', '#e41a1c', '#dede00']
SCATTEREDGECOLORS = ['#377eb8', '#ff7f00', '#4daf4a',
'#f781bf', '#a65628', '#984ea3',
'#999999', '#e41a1c', '#dede00']
YELLOW = (1.0, 1.0, 0.0, 1.0)
RED = (1.0, 0.0, 0.0, 1.0)
WHITE = (1.0, 1.0, 1.0, 1.0)
CB_color_cycle = ['#377eb8', '#ff7f00', '#4daf4a',
'#f781bf', '#a65628', '#984ea3',
'#999999', '#e41a1c', '#dede00']
# Test if we can run JAVA
# global JAVA_AVAILABLE
# global JAVA_COMMAND
# JAVA_AVAILABLE = False
# JAVA_COMMAND = "Undefined"
# Test what system we are running on
# global WINDOWS_OS
# global LINUX_OS
# global MAC_OS
# WINDOWS_OS = False
# LINUX_OS = False
# MAC_OS = False
# global XYDIM
# XYDIM = 800
# # set current working directory to the directory of this file
os.chdir(os.path.dirname(os.path.realpath(__file__)))
class MoleculePlotCanvas(FigureCanvasQTAgg):
def __init__(self, fig, parent=None):
super(MoleculePlotCanvas, self).__init__(fig)
class MainWidget(QMainWindow):
def __init__(self, nmrproblem, parent=None):
self.nmrproblem = nmrproblem
self.hmbc_edge_colors = nmrproblem.hmbc_edge_colors
self.old_node = ""
self.new_node = ""
self.selection = None
super().__init__(parent)
self.setGeometry(100, 100, 1200, 900)
self.setWindowTitle(self.nmrproblem.problemDirectory)
self._createActions()
self._createMenuBar()
# self._createToolBars()
# Uncomment the call to ._createContextMenu() below to create a context
# menu using menu policies. To test this out, you also need to
# comment .contextMenuEvent() and uncomment ._createContextMenu()
# self._createContextMenu()
self._connectActions()
self._createStatusBar()
self.centralWidget = QWidget()
# self.centralWidget.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
self.setCentralWidget(self.centralWidget)
if self.nmrproblem.data_complete:
print("line 142")
print("nmrproblem.c13")
print(nmrproblem.c13)
print("nmrproblem.h1")
print(self.nmrproblem.h1)
print("nmrproblem.hsqc")
print(self.nmrproblem.hsqc)
nmrproblem.save_dataframes_in_nmrproblem_to_json()
self.initiate_windows(self.nmrproblem)
def initiate_windows(self, nmrproblem):
del self.centralWidget
self.centralWidget = QWidget()
# self.centralWidget.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
self.setCentralWidget(self.centralWidget)
self.nmrproblem = nmrproblem
jsmewidget = QWidget()
moleculewidget = QWidget()
spectrawidget = QWidget()
self.moleculePlot = MatplotlibMoleculePlot(self.nmrproblem)
self.spectraPlot = MatplotlibH1C13Plot(self.nmrproblem)
self.spectraCanvas = MoleculePlotCanvas(self.spectraPlot)
self.spectraCanvas.setGeometry(0, 0, 600, 1100)
self.moleculeCanvas = MoleculePlotCanvas(self.moleculePlot)
self.moleculeCanvas.setGeometry(0, 0, 300, 300)
self.moltoolbar = NavigationToolbar(self.moleculeCanvas, self)
self.spctoolbar = NavigationToolbar(self.spectraCanvas, self)
# self.webEngineView = QWebEngineView()
# self.loadPage()
# self.smilesInput = QLineEdit()
# self.button = QPushButton("Display Smiles Molecule", self)
self.sync_button = QPushButton("Synchronize with MesReNova", self)
self.sync_button.clicked.connect(self.on_sync_click)
# connect button to function on_click
# self.button.clicked.connect(self.on_click)
splitter1 = QSplitter(Qt.Vertical)
splitter2 = QSplitter(Qt.Horizontal)
hbox = QHBoxLayout()
molvbox = QVBoxLayout()
jsmevbox = QVBoxLayout()
spcvbox = QVBoxLayout()
spcvbox.addWidget(self.spctoolbar)
spcvbox.addWidget(self.spectraCanvas)
spectrawidget.setLayout(spcvbox)
molvbox.addWidget(self.moltoolbar)
molvbox.addWidget(self.moleculeCanvas)
moleculewidget.setLayout(molvbox)
jsmevbox.addWidget(self.sync_button)
# jsmevbox.addWidget(self.smilesInput)
# jsmevbox.addWidget(self.button)
jsmewidget.setLayout(jsmevbox)
splitter1.addWidget(moleculewidget)
splitter1.addWidget(jsmewidget)
splitter2.addWidget(splitter1)
splitter2.addWidget(spectrawidget)
hbox.addWidget(splitter2)
# hbox.addLayout(molvbox)
self.centralWidget.setLayout(hbox)
splitter2.setSizes([600, 600])
self.centralWidget.show()
# add callbacks to the moleculeCanvas
self.node_pick_ind = None
self.node_hover_ind = None
self.node_picked = False
self.highlighted_peak_lbl = None
self.old_lbl = None
self.moleculePlot.canvas.mpl_connect(
"button_release_event",
lambda event: self.button_release_molecule(
event, specplot=self.spectraPlot, molplot=self.moleculePlot
),
)
self.moleculePlot.canvas.mpl_connect(
"motion_notify_event",
lambda event: self.motion_notify_callback(
event, specplot=self.spectraPlot, molplot=self.moleculePlot
),
)
self.moleculePlot.canvas.mpl_connect(
"pick_event",
lambda event: self.pick_molecule(
event,
event_name="pick_event",
specplot=self.spectraPlot,
molplot=self.moleculePlot,
),
)
self.spectraPlot.canvas.mpl_connect(
"motion_notify_event",
lambda event: self.hover_over_specplot(
event, specplot=self.spectraPlot, molplot=self.moleculePlot
),
)
self.setWindowTitle(self.nmrproblem.problemDirectory)
self.wcLabel.setText(
f"Molecule: {self.nmrproblem.moleculeAtomsStr} DBE: {int(self.nmrproblem.dbe)}"
)
# self.spectraPlot.canvas.draw_idle()
# self.moleculePlot.canvas.draw_idle()
def hover_over_specplot(self, event, specplot, molplot):
# just return if toolbar is active
if (self.moltoolbar.mode != "") or (self.spctoolbar.mode != ""):
return
in_plot = []
in_plot_label = []
in_plot_index = []
pos = None
self.mol_nodes = molplot.mol_nodes
for k, v in specplot.peak_overlays_dict.items():
# in_c13plots, c13plots_index = v["highlight"].contains(event)
in_c13plots, c13plots_index = v.contains(event)
in_plot.append(in_c13plots)
in_plot_label.append(k)
in_plot_index.append(c13plots_index)
if any(in_plot):
lbl = in_plot_label[in_plot.index(True)]
# if lbl != self.highlighted_peak_lbl:
# highlight new peak
specplot.peak_overlays_dict[lbl].set_visible(True)
specplot.peak_overlays_dict[lbl].set_color(RED)
specplot.peak_overlays_dict[lbl].set_linewidth(1.2)
# annotate new peak
if "H" in lbl:
# set the annotation to the peak
atom_index = int(lbl[1:])
ppm = self.nmrproblem.h1.loc[atom_index, "ppm"]
integral = float(self.nmrproblem.h1.loc[atom_index, "integral"])
jcoupling = self.nmrproblem.h1.loc[atom_index, "jCouplingClass"]
jcouplingvals = self.nmrproblem.h1.loc[atom_index, "jCouplingVals"]
jcouplingvals = simpleNMRutils.stringify_vals(jcouplingvals)
annot_text = f"{lbl}: {ppm:.2f} ppm\nInt:{integral:.1f}\nJ: {jcoupling}: {jcouplingvals} Hz"
specplot.annot_H1.xy = (event.xdata, event.ydata)
specplot.annot_H1.set_text(annot_text)
specplot.annot_H1.set_visible(True)
elif "C" in lbl:
# set the annotation to the peak
atom_index = int(lbl[1:])
ppm = self.nmrproblem.c13.loc[atom_index, "ppm"]
annot_text = f"{lbl}: {ppm:.1f} ppm"
x = event.xdata
y = event.ydata
specplot.annot_C13.set_text(annot_text)
specplot.annot_C13.xy = (x, y)
specplot.annot_C13.set_visible(True)
self.highlighted_peak_lbl = lbl
if "H" in lbl:
try:
clbl = self.nmrproblem.hsqc[self.nmrproblem.hsqc.f2H_i == lbl][
"f1C_i"
].values[0]
except IndexError:
print(f"no HSQC peak found for this H1 peak {lbl}")
clbl = ""
else:
clbl = lbl
if "C" not in clbl:
specplot.canvas.draw_idle()
return
self.node_hover_lbl = clbl
# update molplot highlights
self.update_molplot_highlights(molplot, specplot, clbl)
# uddate specplot canvas
specplot.canvas.draw_idle()
# uddate title in molplot
c13_ind = int(clbl[1:])
ppm_val = self.nmrproblem.c13.loc[c13_ind]["ppm"]
attached_protons = self.nmrproblem.c13.loc[c13_ind]["attached_protons"]
title_str = (
f"{clbl}: {ppm_val:.1f} ppm, attached protons: {attached_protons}"
)
self.moleculePlot.ax.set_title(title_str)
else:
# unhilight old peak
if self.highlighted_peak_lbl is not None:
self.mol_nodes.set_fc(self.mol_nodes.scatter_facecolors_rgba)
self.mol_nodes.set_ec(self.mol_nodes.scatter_edgecolors_rgba)
self.moleculePlot.hide_hmbc_graph_networks()
specplot.reset_peak_overlays_eeh()
specplot.hide_annotation(specplot.annot_C13)
specplot.hide_annotation(specplot.annot_H1)
# unhighlight distributions
specplot.reset_distributions_eeh()
# uddate specplot canvas
specplot.canvas.draw_idle()
molplot.canvas.draw_idle()
def update_molplot_highlights(self, molplot, specplot, lbl):
molplot.mol_nodes.node_highlighted = True
ind = int(lbl[1:]) - 1
scatter_facecolors_highlight = molplot.mol_nodes.get_facecolors()
scatter_edgecolors_highlight = molplot.mol_nodes.get_edgecolors()
scatter_facecolors_highlight[ind] = WHITE
scatter_edgecolors_highlight[ind] = RED
molplot.mol_nodes.set_fc(scatter_facecolors_highlight)
if lbl in self.nmrproblem.hmbc_graphs.keys():
# self.hide_hmbc_graph_networks()
self.moleculePlot.draw_hmbc_graph_network(lbl)
# higlight C13 hmbc peaks
specplot.highlight_hmbc_C13_peaks(lbl)
# self.redraw_axes()
# highlight H1 hmbc peaks
specplot.highlight_H1_HMBC_peaks(lbl)
# highlight C13 peak in graph x1
specplot.highlight_C13_peak(lbl)
# higlight H1 peaks in graph x1
specplot.highlight_H1_peaks_from_highlighted_carbon_atom(lbl)
# self.c13_plots[lbl]['highlight'].set_visible(True)
# annotate C13 peak in graph x1
specplot.display_annotation_C13_from_molplot(lbl, specplot.annot_C13)
# annotate H1 peaks in graph x1
specplot.display_annotation_H1_from_molplot(
lbl, specplot.annot_H1, self.nmrproblem
)
# annotate distributions
hpks = self.nmrproblem.hsqc[self.nmrproblem.hsqc.f1C_i == lbl]["f2H_i"].values
cpks = [lbl]
self.display_distributions(cpks, hpks, specplot)
molplot.canvas.draw_idle()
specplot.canvas.draw_idle()
def display_distributions(self, C_pks, H_pks, specplot):
# add highlighted distributions
colors = ["b", "g", "r", "c", "m", "y", "k"]
# used to dsplay legends of highlighted distributions
plinesH = []
plabelsH = []
plinesC = []
plabelsC = []
ppmH = []
ppmC = []
# set visible
# circle through colors
# create proton distribution legends
for pk in H_pks:
numplots = len(specplot.h1c13distlist[0][pk]) - 1
for i, aa in enumerate(specplot.h1c13distlist[0][pk]):
ppmH.append(self.nmrproblem.udic[0]["info"].loc[pk, "ppm"])
# sel.extras.append(self.cursor.add_highlight(aa))
aa.set_visible(True)
aa.set_linewidth(0.75)
aa.set_color(colors[i % 7])
# do not add legend info if plot is just single line showing where peak pos is
if i < numplots:
plabelsH.append(aa.get_label())
plinesH.append(aa)
# create carbon distribution legends
for pk in C_pks:
numplots = len(specplot.h1c13distlist[1][pk]) - 1
for i, aa in enumerate(specplot.h1c13distlist[1][pk]):
ppmC.append(self.nmrproblem.udic[1]["info"].loc[pk, "ppm"])
# sel.extras.append(self.cursor.add_highlight(aa))
aa.set_visible(True)
aa.set_linewidth(0.75)
aa.set_color(colors[i % 7])
if i < numplots:
plabelsC.append(aa.get_label())
plinesC.append(aa)
# adjust x-axis width H1 and C13 of distribution plots
# and add legend information
if len(ppmH) > 0:
# calculate average position of peaks which will be used to adjust the x axis ppm range
ppmmmH = np.mean(ppmH)
specplot.h1dist_ax.set_xlim(ppmmmH + 2, ppmmmH - 2)
specplot.h1dist_ax.legend(plinesH, plabelsH)
if len(ppmC) > 0:
ppmmmC = np.mean(ppmC)
specplot.c13dist_ax.set_xlim(ppmmmC + 50, ppmmmC - 50)
specplot.c13dist_ax.legend(plinesC, plabelsC)
def button_release_molecule(self, event, molplot, specplot):
if (self.moltoolbar.mode != "") or (self.spctoolbar.mode != ""):
return
self.mol_nodes.set_fc(self.mol_nodes.scatter_facecolors_rgba)
self.mol_nodes.set_ec(self.mol_nodes.scatter_edgecolors_rgba)
self.moleculePlot.hide_hmbc_graph_networks()
specplot.reset_peak_overlays_eeh()
specplot.hide_annotation(specplot.annot_C13)
specplot.hide_annotation(specplot.annot_H1)
# unhighlight distributions
specplot.reset_distributions_eeh()
molplot.canvas.draw_idle()
specplot.canvas.draw_idle()
self.node_pick_ind = None
self.node_hover_ind = None
self.node_picked = False
self.node_moved = False
def motion_notify_callback(self, event, specplot, molplot):
if (self.moltoolbar.mode != "") or (self.spctoolbar.mode != ""):
return
self.hover_over_molecule(
event, event_name="motion_notify_event", molplot=molplot, specplot=specplot
)
if not hasattr(self, "label_id"):
# print("not hasattr(self, 'label_id')")
return
# else:
# print("self.label_id: ", self.label_id)
in_node, _ = self.mol_nodes.contains(event)
if (not in_node) and (event.button != 1):
self.mol_nodes.node_highlighted = False
self.mol_nodes.set_fc(self.mol_nodes.scatter_facecolors_rgba)
self.mol_nodes.set_ec(self.mol_nodes.scatter_edgecolors_rgba)
self.moleculePlot.hide_hmbc_graph_networks()
specplot.reset_peak_overlays_eeh()
specplot.hide_annotation(specplot.annot_C13)
specplot.hide_annotation(specplot.annot_H1)
# unhighlight distributions
specplot.reset_distributions_eeh()
molplot.canvas.draw_idle()
specplot.canvas.draw_idle()
return
if event.button != 1:
# print("event.button != 1, return")
return
self.node_moved = True
x, y = event.xdata, event.ydata
# if x or y is None: return mouse beyond plotting area
if x is None:
return
if y is None:
return
self.hmbc_graph_plots = self.moleculePlot.hmbc_graph_plots
self.mol_nodes = self.moleculePlot.mol_nodes
self.mol_edges = self.moleculePlot.mol_edges
self.mol_labels = self.moleculePlot.mol_labels
self.mol_ind = self.node_pick_ind
# move nodes, edges and labels associated with hmbc network for each carbon atom
for n in self.nmrproblem.nx_graph_molecule.nodes:
if n in self.hmbc_graph_plots:
hmbc_nodes = self.hmbc_graph_plots[n]["hmbc_nodes"]
hmbc_edges = self.hmbc_graph_plots[n]["hmbc_edges"]
hmbc_labels = self.hmbc_graph_plots[n]["hmbc_labels"]
hmbc_vertices_moved = self.hmbc_graph_plots[n]["hmbc_vertices_moved"]
if self.label_id in hmbc_labels.keys():
self.hmbc_ind = [list(hmbc_labels.keys()).index(self.label_id)]
# readjust coords of nodes in hmbc network
xy = np.asarray(hmbc_nodes.get_offsets())
xy[self.hmbc_ind[0]] = np.array([x, y])
hmbc_nodes.set_offsets(xy)
# readjust coords of labels in hmbc network
hmbc_labels[self.label_id].set_x(x)
hmbc_labels[self.label_id].set_y(y)
if not isinstance(hmbc_edges, list):
verts = []
for i, e in enumerate(hmbc_edges.get_paths()):
v = []
for j, c in enumerate(e.vertices):
if hmbc_vertices_moved[i][j] == True:
v.append([x, y])
else:
v.append(c)
verts.append(v)
# readjust coords of edges in hmbc network
hmbc_edges.set_verts(verts)
# move nodes, edges and labels associated with molecule
xy = np.asarray(self.mol_nodes.get_offsets())
xy[self.mol_ind] = np.array([x, y])
# readjust coords of nodes in molecule network
self.mol_nodes.set_offsets(xy)
# readjust coords of labels in molecule network
self.mol_labels[self.label_id].set_x(x)
self.mol_labels[self.label_id].set_y(y)
verts = []
if not isinstance(self.mol_edges, list):
for i, e in enumerate(self.mol_edges.get_paths()):
v = []
for j, c in enumerate(e.vertices):
if self.moleculePlot.mol_vertices_moved[i][j] == True:
v.append([x, y])
else:
v.append(c)
verts.append(v)
# readjust coords of edges in molecule network
self.mol_edges.set_verts(verts)
self.moleculePlot.ax.figure.canvas.draw_idle()
self.moved_node = self.mol_ind
self.moved_x = x
self.moved_y = y
def hover_over_molecule(self, event, event_name, molplot, specplot):
self.mol_nodes = molplot.mol_nodes
self.mol_labels = molplot.mol_labels
in_node, node_index = self.mol_nodes.contains(event)
if self.node_picked:
self.mol_nodes.node_highlighted = False
return
if in_node:
self.mol_nodes.node_highlighted = True
ind = node_index["ind"][0]
lbl = f"{self.mol_nodes.my_labels[ind]}"
x, y = self.mol_nodes.get_offsets()[ind]
self.node_hover_ind = ind
self.node_hover_lbl = lbl
self.node_hover_x = x
self.node_hover_y = y
if lbl != self.old_lbl:
self.old_lbl = lbl
self.mol_nodes.node_highlighted = False
self.mol_nodes.set_fc(self.mol_nodes.scatter_facecolors_rgba)
self.mol_nodes.set_ec(self.mol_nodes.scatter_edgecolors_rgba)
self.moleculePlot.hide_hmbc_graph_networks()
specplot.reset_peak_overlays_eeh()
specplot.hide_annotation(specplot.annot_C13)
specplot.hide_annotation(specplot.annot_H1)
# unhighlight distributions
specplot.reset_distributions_eeh()
molplot.canvas.draw_idle()
specplot.canvas.draw_idle()
c13_ind = int(lbl[1:])
ppm_val = self.nmrproblem.c13.loc[c13_ind]["ppm"]
attached_protons = self.nmrproblem.c13.loc[c13_ind]["attached_protons"]
title_str = (
f"{lbl}: {ppm_val:.1f} ppm, attached protons: {attached_protons}"
)
self.moleculePlot.ax.set_title(title_str)
scatter_facecolors_highlight = self.mol_nodes.get_facecolors()
scatter_edgecolors_highlight = self.mol_nodes.get_edgecolors()
scatter_facecolors_highlight[ind] = WHITE
scatter_edgecolors_highlight[ind] = RED
self.mol_nodes.set_fc(scatter_facecolors_highlight)
if lbl in self.nmrproblem.hmbc_graphs.keys():
# self.hide_hmbc_graph_networks()
self.moleculePlot.draw_hmbc_graph_network(lbl)
# higlight C13 hmbc peaks
specplot.highlight_hmbc_C13_peaks(lbl)
# self.redraw_axes()
# highlight H1 hmbc peaks
specplot.highlight_H1_HMBC_peaks(lbl)
# highlight C13 peak in graph x1
specplot.highlight_C13_peak(lbl)
# higlight H1 peaks in graph x1
specplot.highlight_H1_peaks_from_highlighted_carbon_atom(lbl)
# self.c13_plots[lbl]['highlight'].set_visible(True)
# annotate C13 peak in graph x1
specplot.display_annotation_C13_from_molplot(lbl, specplot.annot_C13)
# annotate H1 peaks in graph x1
specplot.display_annotation_H1_from_molplot(
lbl, specplot.annot_H1, self.nmrproblem
)
# annotate distributions
hpks = self.nmrproblem.hsqc[self.nmrproblem.hsqc.f1C_i == lbl][
"f2H_i"
].values
cpks = [lbl]
self.display_distributions(cpks, hpks, specplot)
molplot.canvas.draw_idle()
specplot.canvas.draw_idle()
else:
# if self.mol_nodes.node_highlighted:
self.mol_nodes.node_highlighted = False
self.mol_nodes.set_fc(self.mol_nodes.scatter_facecolors_rgba)
self.mol_nodes.set_ec(self.mol_nodes.scatter_edgecolors_rgba)
self.moleculePlot.hide_hmbc_graph_networks()
specplot.reset_peak_overlays_eeh()
specplot.hide_annotation(specplot.annot_C13)
specplot.hide_annotation(specplot.annot_H1)
# unhighlight distributions
specplot.reset_distributions_eeh()
molplot.canvas.draw_idle()
specplot.canvas.draw_idle()
def pick_molecule(self, event, event_name, specplot, molplot):
global JAVA_AVAILABLE
in_node, node_index = self.moleculePlot.mol_nodes.contains(event.mouseevent)
print("in_node: ", in_node)
print("node_index: ", node_index)
print("event_name: ", event_name)
print("event.mouseevent: ", event.mouseevent)
print(dir(event))
if in_node:
self.node_picked = True
# self.mol_ind = event.ind
# self.node_pick_ind = event.ind
self.node_pick_ind = node_index["ind"][0]
ptcoords = np.ma.compressed(
self.moleculePlot.mol_nodes.get_offsets()[self.node_pick_ind]
)
# find label id
self.label_id = list(self.moleculePlot.mol_labels.keys())[self.node_pick_ind]
print("self.label_id: ", self.label_id, self.node_pick_ind, f"C{self.node_pick_ind+1}")
# hide all highlights before dragging node
if self.mol_nodes.node_highlighted:
self.mol_nodes.set_fc(self.mol_nodes.scatter_facecolors_rgba)
self.mol_nodes.set_ec(self.mol_nodes.scatter_edgecolors_rgba)
self.moleculePlot.hide_hmbc_graph_networks()
specplot.reset_peak_overlays_eeh()
specplot.hide_annotation(specplot.annot_C13)
specplot.hide_annotation(specplot.annot_H1)
# unhighlight distributions
specplot.reset_distributions_eeh()
specplot.canvas.draw_idle()
molplot.canvas.draw_idle()
# for each carbon atom in moleule check to see if it is in
# the associated hmbc network then set the vertices_moved flag
# to true if the picked node is in the network
# update edges, nodes and labels
# update them even if they are not visible so that keep in sync
# with the moved display
for n in self.nmrproblem.nx_graph_molecule.nodes:
hmbc_nodes = self.moleculePlot.hmbc_graph_plots[n]["hmbc_nodes"]
hmbc_edges = self.moleculePlot.hmbc_graph_plots[n]["hmbc_edges"]
hmbc_labels = self.moleculePlot.hmbc_graph_plots[n]["hmbc_labels"]
hmbc_vertices_moved = self.moleculePlot.hmbc_graph_plots[n][
"hmbc_vertices_moved"
]
# check if picked node is in hmbc network and then
# if the picked coords match of the edges match set them to True
# so that the values of the edges will be moved during the motion notify
# event
if self.label_id in hmbc_labels.keys():
self.hmbc_ind = [list(hmbc_labels.keys()).index(self.label_id)]
if not isinstance(hmbc_edges, list):
for i, e in enumerate(hmbc_edges.get_paths()):
for j, c in enumerate(e.vertices):
if c[0] == ptcoords[0] and c[1] == ptcoords[1]:
hmbc_vertices_moved[i][j] = True
else:
hmbc_vertices_moved[i][j] = False
else:
# if the hmbc fragment does not contain the picked node
# set all the moved_vertices to False
if not isinstance(hmbc_edges, list):
for i, e in enumerate(hmbc_edges.get_paths()):
for j, c in enumerate(e.vertices):
hmbc_vertices_moved[i][j] = False
self.hmbc_ind = None
# do the same for the molecule network
if self.label_id in self.moleculePlot.mol_labels.keys():
if not isinstance(self.moleculePlot.mol_edges, list):
for i, e in enumerate(self.moleculePlot.mol_edges.get_paths()):
for j, c in enumerate(e.vertices):
if c[0] == ptcoords[0] and c[1] == ptcoords[1]:
self.moleculePlot.mol_vertices_moved[i][j] = True
else:
self.moleculePlot.mol_vertices_moved[i][j] = False
else:
if not isinstance(self.moleculePlot.mol_edges, list):
for i, e in enumerate(self.moleculePlot.mol_edges.get_paths()):
for j, c in enumerate(e.vertices):
self.moleculePlot.mol_vertices_moved[i][j] = False
def _createMenuBar(self):
menuBar = self.menuBar()
# File menu
fileMenu = QMenu("&File", self)
menuBar.addMenu(fileMenu)
# fileMenu.addAction(self.newAction)
fileMenu.addAction(self.newFromMresNovaAction)
# fileMenu.addAction(self.newFromTopspinAction)
fileMenu.addAction(self.openAction)
# Open Recent submenu
# self.openRecentMenu = fileMenu.addMenu("Open Recent")
fileMenu.addAction(self.saveAction)
# Separator
fileMenu.addSeparator()
fileMenu.addAction(self.exitAction)
# # exampleProblems menu
# exampleProblemsMenu = menuBar.addMenu("&Example Problems")
examples_menu = menuBar.addMenu("Examples")
self.initExampleMenu(examples_menu)
# for action in self.exampleProblemsActions:
# exampleProblemsMenu.addAction(action)
# Edit menu
# editMenu = menuBar.addMenu("&Edit")
# editMenu.addAction(self.copyAction)
# editMenu.addAction(self.pasteAction)
# editMenu.addAction(self.cutAction)
# Separator
# editMenu.addSeparator()
# Find and Replace submenu
# findMenu = editMenu.addMenu("Find and Replace")
# findMenu.addAction("Find...")
# findMenu.addAction("Replace...")
# Help menu
# helpMenu = menuBar.addMenu(QIcon(":help-content.svg"), "&Help")
helpMenu = menuBar.addMenu("&Help")
helpMenu.addAction(self.helpContentAction)
helpMenu.addAction(self.aboutAction)
def initExampleMenu(self, menu):
self.exampleProblems = exampleProblems.exampleproblems_names
for actionName in self.exampleProblems:
qa = QAction(actionName, self)
menu.addAction(qa)
qa.triggered.connect(self.exampleProblem_selected)
def exampleProblem_selected(self):
action = self.sender()
exampleproblem_name = action.text()
self.excel_path, self.tmpdir = exampleProblems.create_tmp_excel_file(
exampleproblem_name, exampleProblems.exampleproblems_df[exampleproblem_name]
)
data_info = nmrProblem.parse_argv(
my_argv=[
"simplepy",
self.tmpdir.name,
]
)
xy3_dlg = XY3dialog(
java_available=java.JAVA_AVAILABLE,
sheets_missing=nmrProblem.get_missing_sheets(data_info["excel_fn"], True),
)
if xy3_dlg.exec():
xy3_calc_method, expts_available = xy3_dlg.get_method()
# add "molecule" to expts_available
expts_available.append("molecule")
self.nmrproblem = nmrProblem.NMRproblem(
data_info,
java_available=java.JAVA_AVAILABLE,
xy3_calc_method=xy3_calc_method,
java_command=java.JAVA_COMMAND,
expts_available=expts_available,
)
if self.nmrproblem.data_complete:
print("line 918")
print("nmrproblem.c13")
print(self.nmrproblem.c13)
print("nmrproblem.h1")
print(self.nmrproblem.h1)
print("nmrproblem.hsqc")
print(self.nmrproblem.hsqc)
self.nmrproblem.initiate_df_data_complete()
self.initiate_windows(self.nmrproblem)
else:
print("xy3_dlg.exec() failed")
def _createToolBars(self):
# File toolbar
fileToolBar = self.addToolBar("File")
fileToolBar.setMovable(False)
# fileToolBar.addAction(self.newAction)
fileToolBar.addAction(self.newFromMresNovaAction)
# fileToolBar.addAction(self.newFromTopspinAction)
fileToolBar.addAction(self.openAction)
fileToolBar.addAction(self.saveAction)
# Edit toolbar
# editToolBar = QToolBar("Edit", self)
# self.addToolBar(editToolBar)
# editToolBar.addAction(self.copyAction)
# editToolBar.addAction(self.pasteAction)
# editToolBar.addAction(self.cutAction)
# Widgets
self.fontSizeSpinBox = QSpinBox()
self.fontSizeSpinBox.setFocusPolicy(Qt.NoFocus)
# editToolBar.addWidget(self.fontSizeSpinBox)
def _createStatusBar(self):
self.statusbar = self.statusBar()
# Temporary message
self.statusbar.showMessage("Ready", 3000)
# Permanent widget
self.wcLabel = QLabel(
f"Molecule: {self.nmrproblem.moleculeAtomsStr} DBE: {int(self.nmrproblem.dbe)}"
)
self.statusbar.addPermanentWidget(self.wcLabel)
def _createActions(self):
# File actions
self.newAction = QAction(self)
self.newAction.setText("&New")
self.newFromMresNovaAction = QAction(self)
self.newFromMresNovaAction.setText("New from MNova")
# self.newFromTopspinAction = QAction(self)
# self.newFromTopspinAction.setText("New from Topspin")
# self.newAction.setIcon(QIcon(":file-new.svg"))
# self.openAction = QAction(QIcon(":file-open.svg"), "&Open...", self)
# self.saveAction = QAction(QIcon(":file-save.svg"), "&Save", self)
self.openAction = QAction("&Open...", self)
self.saveAction = QAction("&Save", self)
self.exitAction = QAction("&Exit", self)
# String-based key sequences
# self.newAction.setShortcut("Ctrl+N")