-
Notifications
You must be signed in to change notification settings - Fork 7
/
Draw_Energy_Diagram_XML.py
1643 lines (1342 loc) · 67.6 KB
/
Draw_Energy_Diagram_XML.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
# -*- coding: utf-8 -*-
__author__ = 'LiYuanhe'
# 自动防止重叠(改成非贪心)
# Num tag 在同一行时Tag的加粗
# 支持MECP画点
# 支持纵轴切掉一部分
import numpy as np
from Python_Lib.My_Lib_PyQt6 import *
from openpyxl import load_workbook
import ctypes
import matplotlib
matplotlib.use("QtAgg")
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as MpFigureCanvas
from matplotlib.backends.backend_qtagg import NavigationToolbar2QT as MpNavToolBar
from matplotlib import pyplot
import matplotlib.patches as patches
from matplotlib.figure import Figure as MpFigure
from matplotlib import pylab
FONT_SIZE_ENERGY_MPL = 17
FONT_SIZE_TAG_MPL = 17
X_OFFSET = 200 # spaces left on the left in cdxml
Y_OFFSET = 100 # spaces left on the top in cdxml
PIXEL_FACTOR = 0.6 # factor from the pixel in matplotlib to chemdraw
TEXT_LINE_HEIGHT = 10 # how many ChemDraw pixels are one line of text took
# ChemDraw Z轴编号从多少开始,无所谓,足够大就行
Z_START = 50
NODE_ID_START = 2000 # 足够大就可以了
FONT_INDEX = 4 # 目前没法换其他的font
SIZE_OF_TAG = 10
FONTSIZE_ENERGY = 10
FONT_FACE_TAG = 'Bold'
FONT_FACE_NUMBER = 'Normal'
LINE_AVOIDANCE_HEIGHT = 3 # how many ChemDraw pixels are needed to put a text on top a line
import platform
if platform.system() == 'Windows':
matplotlib.rcParams.update({'font.family': 'Times New Roman'})
temp_folder = os.path.join(filename_class(sys.argv[0]).path, 'TEMP')
if not os.path.isdir(temp_folder):
os.mkdir(temp_folder)
Application = QtWidgets.QApplication(sys.argv)
if platform.system() == 'Windows':
import ctypes
APPID = 'LYH.DrawEnergyDiagram.3.4'
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APPID)
Application.setWindowIcon(QtGui.QIcon('UI/Draw_Energy_Diagram_Icon.png'))
matplotlib_DPI_setting = get_matplotlib_DPI_setting(1)
if __name__ == '__main__':
pyqt_ui_compile('Draw_Energy_Diagram_UI_XML.py')
from UI.Draw_Energy_Diagram_UI_XML import Ui_Draw_Energy_Diagram_Form
def sort_key(x: str):
# 整理一下,好与chemdraw标准文件比对(其实没用,无大碍)
if x.startswith('<b'):
return 2
if x.startswith('<n'):
return 1
if x.startswith('<t'):
return 3
if x.startswith('<a'):
return 4
return 0
# doc header
default_document = '''<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE CDXML SYSTEM "http://www.cambridgesoft.com/xml/cdxml.dtd" >
<CDXML
CreationProgram="ChemDraw 17.0.0.206"
Name="temp.cdxml"
BoundingBox="226.92 96.70 607.08 337.20"
WindowPosition="0 0"
WindowSize="-2147483648 -2147483648"
WindowIsZoomed="yes"
LabelFont="3"
LabelSize="10"
LabelFace="96"
CaptionFont="4"
CaptionSize="10"
HashSpacing="2.49"
MarginWidth="1.59"
LineWidth="0.60"
BoldWidth="2.01"
BondLength="14.40"
BondSpacing="18"
PrintMargins="99.21 70.87 99.21 70.87"
color="0"
bgcolor="1"
>'''
# font table, id is in the ChemDraw program, cannot be changed, ignore the change font function
default_fonts = '''<fonttable>
<font id="3" charset="iso-8859-1" name="Arial"/>
<font id="4" charset="iso-8859-1" name="Times New Roman"/>'''
default_fonts_end = '''</fonttable>'''
fonts_template = '''<font id="[Font_ID]" charset="[Font_CharSet]" name="[Font_Name]"/>'''
# color table, r.g.b with a maximum of one
colors_list = '''<colortable>
<color r="1" g="1" b="1"/>
<color r="0" g="0" b="0"/>
<color r="1" g="0" b="0"/>
<color r="1" g="1" b="0"/>
<color r="0" g="1" b="0"/>
<color r="0" g="1" b="1"/>
<color r="0" g="0" b="1"/>
<color r="1" g="0" b="1"/>
<color r="0.12109375" g="0.46484375" b="0.703125"/>
<color r="0.99609375" g="0.49609375" b="0.0546875"/>
<color r="0.171875" g="0.625" b="0.171875"/>
<color r="0.8359375" g="0.15234375" b="0.15625"/>
<color r="0.578125" g="0.40234375" b="0.73828125"/>
<color r="0.546875" g="0.3359375" b="0.29296875"/>
<color r="0.88671875" g="0.46484375" b="0.7578125"/>
<color r="0.49609375" g="0.49609375" b="0.49609375"/>
<color r="0.734375" g="0.73828125" b="0.1328125"/>
<color r="0.08984375" g="0.7421875" b="0.80859375"/>
<color r="0" g="0" b="0"/>'''.splitlines()
default_colors_end = '''</colortable>'''
color_matplotlib_translate = {
'B': 'tab:blue',
'O': 'tab:orange',
'G': 'tab:green',
'R': 'tab:red',
'P': 'tab:purple',
'BR': 'tab:brown',
'PI': 'tab:pink',
'GR': 'tab:gray',
'OL': 'tab:olive',
'C': 'tab:cyan'}
# 似乎它的index是从colortable从2开始数的
colors_translate = {'b': 8,
'g': 6,
'r': 4,
'c': 7,
'm': 9,
'y': 5,
'k': 3,
'w': 2,
'B': 10,
'O': 11,
'G': 12,
'R': 13,
'P': 14,
'BR': 15,
'PI': 16,
'GR': 17,
'OL': 18,
'C': 19,
"K": 20}
# add a color, return the proper color index. If the color doesn't exist in the color table, add it, then return the index
def add_color(r, g=None, b=None):
"""
:param r: in 0~1 float
:param g:
:param b:
:return: a index, pointing to the newly built color
"""
global colors_translate
global colors_list
if r.replace('TAG', "") in colors_translate:
if g is not None and b is not None:
alert_UI("Add_color function error. Report bug.", 'Add_color function error')
return colors_translate[r]
if r.startswith('#'):
# in the format of #DDEEFF
if g is not None and b is not None:
alert_UI("Add_color function error. Report bug.", 'Add_color function error')
r = r.replace('#', '0x')
# XXXXXX --> (0.XX, 0.XX, 0.XX)
b = (eval(r) % 0x100) / 0x100
g = (int(eval(r) / 0x100) % 0x100) / 0x100
r = (int(eval(r) / 0x10000)) / 0x100
if (r, g, b) in colors_translate:
return colors_translate[(r, g, b)]
color_template = '''<color r="[R_Value]" g="[G_Value]" b="[B_Value]"/>''' # in 0~1 float
insert_line = color_template.replace("[R_Value]", str(r)).replace("[G_Value]", str(g)).replace("[B_Value]", str(b))
colors_list.append(insert_line)
colors_translate[(r, g, b)] = len(colors_list)
return len(colors_list)
default_document_end = '''</CDXML>'''
# doesn't matter, 3*3 page is large enough
page_template = '''<page
id="[ID]"
BoundingBox="0 0 [Page_Height_Pixel] [Page_Width_Pixel]"
HeaderPosition="36"
FooterPosition="36"
PrintTrimMarks="yes"
HeightPages="[Page_Height_Page_Count]"
WidthPages="[Page_Width_Page_Count]"
>'''
def add_page(page_height_count, page_width_count):
height = 1930.48 / 3 * page_height_count
width = 1360.76 / 3 * page_width_count
return page_template.replace("[Page_Height_Pixel]", str(height)) \
.replace("[Page_Width_Pixel]", str(width)) \
.replace("[Page_Height_Page_Count]", str(page_height_count)) \
.replace('[ID]', str(random.randint(1000000, 2000000))) \
.replace("[Page_Width_Page_Count]", str(page_width_count))
page_template_end = '''</page>'''
# add fragment only to bond connections, do not add it to graphic and texts
fragment_template = '''<fragment
id="45600"
BoundingBox="0 0 0 0"
Z="28"
>'''
# add a group, with integral-yes, then the user cannot move each elements before de-froze it
group_template = '''<group
id="453612182"
BoundingBox="156.80 154.98 531.20 261.66"
Z="[Z]"
Integral="yes"
>'''
# the Z determines which element will cover which one, and which bond is broken if overlapped
def add_group(Z):
global group_template
return group_template.replace('[Z]', str(Z))
group_template_end = "</group>"
# add an atom, then a bond can be made between atoms
def add_node(node_id, X, Y, Z):
node_template = '''<n
id="[ID]"
p="[X] [Y]"
Z="[Z]"
AS="N"
/>'''
return node_template.replace('[ID]', str(node_id)).replace('[X]', str(X)).replace('[Y]', str(Y)).replace('[Z]', str(Z))
# add a bold, horizontal bond between two atoms,
def add_state_Bond(color_index, begin_index, Z, end_index=None):
state_line_template = '''<b
id="[ID]"
Z="[Z]"
color="[Color_index]"
B="[Begin_index]"
E="[End_index]"
Display="Bold"
BS="N"
/>'''
bond_id = str(random.randint(2000000, 3000000))
if end_index is None:
end_index = begin_index + 1
return state_line_template.replace('[Color_index]', str(color_index)) \
.replace('[Begin_index]', str(begin_index)) \
.replace('[ID]', str(bond_id)) \
.replace('[End_index]', str(end_index)) \
.replace('[Z]', str(Z))
# add a dashed bond between two bonded states
def add_dash_link_Bond(color_index, begin_index, Z, end_index=None):
link_line_dash_template = '''<b
id="[ID]"
Z="[Z]"
color="[Color_index]"
B="[Begin_index]"
E="[End_index]"
Display="Dash"
BS="N"
/>'''
if end_index is None:
end_index = begin_index + 1
return link_line_dash_template.replace('[Color_index]', str(color_index)) \
.replace('[Begin_index]', str(begin_index)) \
.replace('[ID]', str(random.randint(3000000, 4000000))) \
.replace('[End_index]', str(end_index)) \
.replace('[Z]', str(Z))
# add a solid bond between two bonded states
def add_solid_link_Bond(color_index, begin_index, Z, end_index=None):
link_line_single_template = '''<b
id="[ID]"
Z="[Z]"
color="[Color_index]"
B="[Begin_index]"
E="[End_index]"
BS="N"
/>'''
if end_index is None:
end_index = begin_index + 1
return link_line_single_template.replace('[Color_index]', str(color_index)) \
.replace('[Begin_index]', str(begin_index)) \
.replace('[End_index]', str(end_index)) \
.replace('[ID]', str(random.randint(4000000, 5000000))) \
.replace('[Z]', str(Z))
def add_text(text, X, Y, Z, font_index, size, color_index, face_index, vertical=False, right_align=False):
"""
add text, at x, y, Z
:param text:
:param X:
:param Y:
:param Z:
:param font_index:
:param size:
:param color_index:
:param face_index:
:param vertical: for Y axis label
:param right_align: for Y axis number
:return:
"""
if text is None:
return ""
text = str(text)
if text.strip() == "":
return ""
# 似乎当text只有一个字母的时候总是向右偏一点
if len(text) == 1:
X -= 3
faces = {'Bold': 1, "Normal": 0}
if face_index in faces:
face_index = faces[face_index]
text_template = '''<t
id="[ID]"
p="[X] [Y]"
BoundingBox="0 0 110 110"
Z="[Z]"
CaptionJustification="Center"
Justification="Center"
[vertical]
LineHeight="auto"
><s font="[Font_index]" size="[Size]" color="[Color_index]" face="[Face_index]">[Text]</s></t>'''
if vertical:
text_template = text_template.replace('[vertical]', 'RotationAngle="17694720"')
else:
text_template = text_template.replace('[vertical]\n', '')
if right_align:
text_template = text_template.replace('"Center"\n', '"Right"\n')
return text_template.replace('[X]', str(X)) \
.replace('[Y]', str(Y)) \
.replace('[Z]', str(Z)) \
.replace('[Font_index]', str(font_index)) \
.replace('[Size]', str(size)) \
.replace('[ID]', str(random.randint(5000000, 6000000))) \
.replace('[Color_index]', str(color_index)) \
.replace('[Face_index]', str(face_index)) \
.replace('[Text]', text)
# add an anchor point, also serve as a water mark
def test(start_x, start_y, Z=0):
# a water mark pointing right up
x2 = start_x
x1 = x2 + 1.2
y2 = start_y
y1 = y2 - 1.2
# x2,x1 = x1,x2
# y2,y1 = y1,y2
template = '''<graphic
id="453611"
BoundingBox="[x1] [y1] [x2] [y2]"
Z="[Z]"
GraphicType="Orbital"
OrbitalType="lobeFilled"
/>'''
return template.replace('[x1]', str(x1)) \
.replace('[x2]', str(x2)) \
.replace('[y1]', str(y1)) \
.replace('[y2]', str(y2)) \
.replace('[Z]', str(Z))
# add graphic line of states (bold), and dashed/non-dashed links
def add_graphic_line(x1, x2, y1, y2, Z, color_index=3, dash=False, bold=False, width=0.6):
arrow_id = str(random.randint(6000000, 7000000))
# these two elements must exist in order to be able to freeze it using Integral group
graphic_line_template = '''<graphic
id="''' + str(random.randint(7000000, 8000000)) + '''"
SupersededBy="''' + arrow_id + '''"
BoundingBox="481.66 244.50 306 244.50"
Z="[Z]"
[Line_type]
GraphicType="Line"
/>
<arrow
id="''' + arrow_id + '''"
BoundingBox="226 296.43 423 297.56"
Z="[Z]"
FillType="None"
ArrowheadType="Solid"
color="[Color_Index]"
Head3D="[x2] [y2] 0"
LineWidth="[Width]"
Tail3D="[x1] [y1] 0"
Center3D="538.50 445.75 0"
MajorAxisEnd3D="735.50 445.75 0"
MinorAxisEnd3D="538.50 642.75 0"
[Line_type]
/>'''
if not bold and not dash:
graphic_line_template = graphic_line_template.replace(' [Line_type]\n', "")
elif bold:
graphic_line_template = graphic_line_template.replace('[Line_type]', 'LineType="Bold"')
elif dash:
graphic_line_template = graphic_line_template.replace('[Line_type]', 'LineType="Dashed"')
return graphic_line_template.replace('[x2]', str(x2)) \
.replace('[x1]', str(x1)) \
.replace('[y1]', str(y1)) \
.replace('[y2]', str(y2)) \
.replace('[Z]', str(Z)) \
.replace('[Color_Index]', str(color_index)) \
.replace('[Width]', str(width))
fragment_template_end = '''</fragment>'''
class State_Line:
def __init__(self, state, x_center, span=0.6, style='-', color='k', width=4):
# print(state)
# if color==None:
# color = 'k'
self.tag = state[0]
self.energy = state[1]
self.x_center = x_center
self.span = span
self.width = width
self.style = style
self.color = color
self.x_start = self.x_center - self.span / 2
self.x_end = self.x_center + self.span / 2
self.x = (self.x_start, self.x_end)
self.y = (self.energy, self.energy)
self.annotate = True # annotate(energy label) required
def __hash__(self):
return hash((self.x, self.y, self.span, self.style, self.width))
def __eq__(self, other):
return hash(self) == hash(other)
class Connecting_Line:
def __init__(self, state_line1: State_Line, state_line2: State_Line, style='-', color='k', width=1):
if state_line1.x_center > state_line2.x_center: # swap 1 & 2 if reversed order
state_line1, state_line2 = state_line2, state_line1
# if color==None:
# color = 'k'
self.state_line1 = state_line1
self.state_line2 = state_line2
# the connecting line will intrude the state line due to line width
self.x_start = self.state_line1.x_end + 0.02
self.x_end = self.state_line2.x_start - 0.01
self.y_start = self.state_line1.energy
self.y_end = self.state_line2.energy
self.x = (self.x_start, self.x_end)
self.y = (self.y_start, self.y_end)
self.style = style
self.color = color
self.width = width
self.annotate = False # not annotate required
def __hash__(self):
return hash((self.x_start, self.x_end, self.y_start, self.y_end, self.style, self.width))
def __eq__(self, other):
return hash(self) == hash(other)
class Collision_Box:
def __init__(self,
x_center=None, x_length=None, x_left=None, x_right=None,
y_center=None, y_height=None, y_bottom=None, y_top=None):
self.x_left = x_left
self.x_right = x_right
self.y_bottom = y_bottom
self.y_top = y_top
if x_center is not None and x_length is not None:
self.x_left = x_center - x_length / 2
self.x_right = x_center + x_length / 2
if y_center is not None and y_height is not None:
self.y_bottom = y_center - y_height / 2
self.y_top = y_center + y_height / 2
if y_bottom is not None and y_height is not None:
self.y_bottom = y_bottom
self.y_top = y_bottom + y_height
def collide(self, other):
if other.x_left > self.x_right:
return False
if other.x_right < self.x_left:
return False
if other.y_top < self.y_bottom:
return False
if other.y_bottom > self.y_top:
return False
return True
class MpWidget_Energy_Diagram(QtWidgets.QWidget):
def __init__(self, parent=None, y=()):
super(MpWidget_Energy_Diagram, self).__init__()
self.setParent(parent)
self.dpi = matplotlib_DPI_setting
self.fig = pyplot.figure(figsize=(2, 2), dpi=self.dpi)
self.diagram_subplot = pyplot.subplot(1, 1, 1)
self.fig.subplots_adjust(wspace=0.12, left=0.04, right=0.98)
self.canvas = MpFigureCanvas(self.fig)
self.canvas.setParent(self)
self.diagram_subplot.clear()
self.diagram_subplot.plot(range(len(y)), y, 'r')
self.canvas.draw()
self.mpl_toolbar = MpNavToolBar(self.canvas, self)
self.mpl_toolbar.setIconSize(QtCore.QSize(18, 18))
self.mpl_toolbar.layout().setSpacing(6)
self.hLayout = QtWidgets.QHBoxLayout()
self.hLayout.addWidget(self.mpl_toolbar)
self.vLayout = QtWidgets.QVBoxLayout()
self.vLayout.addWidget(self.canvas)
self.vLayout.addLayout(self.hLayout)
self.vLayout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.vLayout)
self.fluctuation_warned = False
self.diagram_limit = (-1, 0)
self.occupied_spaces = [] # list of previous collision boxes
self.paths = []
self.connecting_lines = []
self.printed_states = []
self.annotate_objects = []
self.xs_for_adjust_text = []
self.ys_for_adjust_text = []
self.diagram_subplot.clear()
self.diagram_subplot.tick_params(axis='x', labelbottom='off')
self.diagram_subplot.tick_params(axis='y',
labelsize='xx-large')
if os.path.isfile("Energy_Diagram_Y_Axis_Text.txt"):
with open('Energy_Diagram_Y_Axis_Text.txt') as text_file:
y_axis_text = text_file.readline()
else:
with open('Energy_Diagram_Y_Axis_Text.txt', 'w') as text_file:
y_axis_text = "Solvated Gibbs free energy (kJ/mol)"
text_file.write(y_axis_text)
pyplot.ylabel(y_axis_text,
fontsize='xx-large',
weight='bold')
pyplot.xticks(np.arange(5), [])
pyplot.subplots_adjust(left=0.12, right=0.93, top=0.95)
def diagram_Update(self, diagram_states, x_span, y_span, state_line_span, color='k', num_with_tag=False):
"""
:param diagram_states: the Energy contains Tag and Energy like: [('S', 0), ('TS1', 183), ('IM1', 75), ('P', 24)]
:param x_span:
:param y_span:
:param state_line_span:
:param color: set style of line, default None, meaning 'k'
:param num_with_tag:
:return:
"""
# if color==None:
# color = 'k'
if 'TAG' in color:
return None
if diagram_states not in self.printed_states:
print(diagram_states)
self.printed_states.append(diagram_states)
# verify data
invalid_data = [x[1] for x in diagram_states if not (isinstance(x[1], float) or isinstance(x[1], int) or x[1] is None)]
if invalid_data:
QtWidgets.QMessageBox.critical(self, 'Invalid Data Found.', f'Invalid Data Found:\n'
f'{invalid_data}\n'
'Only numbers was allowed in the data section.\n'
'Remove formula by Ctrl+Alt+V if used.\n'
'Program Terminating...',
QtWidgets.QMessageBox.Abort)
self.diagram_subplot.set_xlim(*x_span)
self.diagram_subplot.set_ylim(*y_span)
self.canvas.draw()
current_states = []
for count, state in enumerate(diagram_states):
if state[1] is not None:
print(state)
state_line = State_Line(state, count, color=color, span=state_line_span)
self.draw_line(state_line, num_with_tag=num_with_tag)
current_states.append(state_line)
print("------")
self.paths.append(current_states)
if 'tag' not in color.lower():
for count in range(len(current_states) - 1):
connecting_line = Connecting_Line(current_states[count], current_states[count + 1], color=color)
self.draw_line(connecting_line)
self.connecting_lines.append(connecting_line)
self.diagram_subplot.tick_params(axis='x', labelbottom='off')
self.diagram_subplot.tick_params(axis='y')
if os.path.isfile("Energy_Diagram_Y_Axis_Text.txt"):
with open('Energy_Diagram_Y_Axis_Text.txt') as text_file:
y_axis_text = text_file.readline()
else:
with open('Energy_Diagram_Y_Axis_Text.txt', 'w') as text_file:
y_axis_text = "Solvated Gibbs free energy (kJ/mol)"
text_file.write(y_axis_text)
pyplot.ylabel(y_axis_text,
fontsize='xx-large',
weight='normal')
pyplot.subplots_adjust(left=0.12, right=0.93, top=0.95)
self.canvas.draw()
def max_steps(self):
return max([len(x) for x in self.paths])
def all_states(self):
return sum(self.paths, [])
def draw_line(self, line_object: Union[State_Line, Connecting_Line], num_with_tag=False):
if line_object in sum(self.paths, []) + self.connecting_lines:
return None
if isinstance(line_object, State_Line):
self.xs_for_adjust_text += [line_object.x[0], line_object.x[1]]
self.ys_for_adjust_text += [line_object.y[0], line_object.y[1]]
# 把本程序自定义的符号翻译成matplotlib支持的颜色名称
line_matplotlib_color = line_object.color.replace('tag', "")
if line_matplotlib_color in color_matplotlib_translate:
line_matplotlib_color = color_matplotlib_translate[line_matplotlib_color]
if 'tag' not in line_object.color.lower(): # independent tag 用color做了标记
self.diagram_subplot.plot(line_object.x,
line_object.y,
line_object.style,
color=line_matplotlib_color,
lw=line_object.width)
if 'tag' not in line_object.color.lower(): # independent tag 用color做了标记
if line_object.annotate:
text = "{:.1f}".format(line_object.energy)
if num_with_tag: # number和tag一起显示
if hasattr(line_object, 'tag') and line_object.tag:
text = str(line_object.tag) + ' ' + text
energy_annotate = self.diagram_subplot.annotate(text,
(line_object.x_center, line_object.energy + 3),
fontsize=FONT_SIZE_ENERGY_MPL,
verticalalignment='bottom',
horizontalalignment='center',
color=line_matplotlib_color,
weight='normal')
self.annotate_objects.append(energy_annotate)
# energy_annotate.draggable()
if not num_with_tag or 'tag' in line_object.color.lower(): # 如果要求num和tag一起显示,这里就用不着了;但是如果是用tag标记的independent tag,仍然从这里显示
if hasattr(line_object, 'tag') and line_object.tag:
tag = self.diagram_subplot.annotate(line_object.tag,
(line_object.x_center, line_object.energy),
verticalalignment='top',
horizontalalignment='center',
xytext=(0, -8), textcoords='offset points',
fontsize=FONT_SIZE_TAG_MPL,
color=line_matplotlib_color, # independent tag 用color做了标记
weight='bold')
# tag.draggable()
self.annotate_objects.append(tag)
class Draw_Energy_Diagram_XML_GUI(Ui_Draw_Energy_Diagram_Form, QtWidgets.QWidget, Qt_Widget_Common_Functions):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.energy_diagram = MpWidget_Energy_Diagram()
self.energy_diagram.setSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Preferred)
self.verticalLayout.insertWidget(1, self.energy_diagram, 1)
self.open_config_file()
connect_once(self.load_file_pushButton, self.choose_xlsx)
connect_once(self.update_file_pushButton, self.update_xlsx)
# connect_once(self.drag_drop_textEdit.drop_accepted_signal, self.xlsx_dropped)
connect_once(self.x_lower_limit_spinBox, self.x_limits_change)
connect_once(self.x_upper_limit_spinBox, self.x_limits_change)
connect_once(self.Y_lower_limit_spinBox, self.y_limits_change)
connect_once(self.Y_upper_limit_spinBox, self.y_limits_change)
connect_once(self.num_with_tag_checkBox, self.update_xlsx)
connect_once(self.save_cdx_pushButton, self.save_cdxml)
connect_once(self.Y_label_lineEdit.textChanged, self.store_Y_label_to_file)
connect_once(self.Y_tick_auto_checkBox.clicked, self.toggle_auto_Y_tick)
connect_once(self.save_cdx_pushButton_2, self.save_cdx_pushButton.click)
self.dash_solid_button_group = QtWidgets.QButtonGroup()
self.dash_solid_button_group.addButton(self.dash_line_radioButton)
self.dash_solid_button_group.addButton(self.solid_line_radioButton)
self.line_bond_button_group = QtWidgets.QButtonGroup()
self.line_bond_button_group.addButton(self.use_lines_radioButton)
self.line_bond_button_group.addButton(self.use_bonds_radioButton)
self.state_precision_spinBox.setValue(self.load_config('State Precision Digits', 1))
self.state_line_span_doubleSpinBox.setValue(self.load_config('State Line Span', 0.6))
self.Auto_collision_avoidance_checkBox.setChecked(self.load_config('Auto_collision_avoidance', True))
self.allow_overlap_states_checkBox.setChecked(self.load_config('allow_overlap_states_checkBox', False))
self.num_with_tag_checkBox.setChecked(self.load_config('Num with Tag', False))
self.solid_line_radioButton.setChecked(self.load_config('Use Solid Link', True))
self.dash_line_radioButton.setChecked(not self.load_config('Use Solid Link', True))
self.use_lines_radioButton.setChecked(self.load_config('Use Lines', True))
self.use_bonds_radioButton.setChecked(not self.load_config('Use Lines', True))
self.Y_tick_auto_checkBox.setChecked(self.load_config('Y_tick_auto_checkBox', True))
self.Y_label_precision_spinBox.setValue(self.load_config('Y_label_precision_spinBox', 0))
self.Y_label_lineEdit.setText(self.load_config('Y_label_lineEdit', "Solvated Free Energy (kJ/mol)"))
self.use_temp_file_checkBox.setChecked(self.load_config('use_temp_file_checkBox', True))
self.with_MECP_checkBox.hide()
self.X_tick_checkBox.setChecked(self.load_config('X_tick_checkBox', True))
self.Y_tick_checkBox.setChecked(self.load_config('Y_tick_checkBox', True))
self.x_limits_changed = False
self.y_limits_changed = False
self.paths_for_cdx_drawing = []
self.colors_for_cdx_drawing = []
self.resize(self.load_config('Draw_energy_diagram_window_width', 1011),
self.load_config('Draw_energy_diagram_window_height', 580))
self.toggle_auto_Y_tick()
self.center_the_widget()
update_UI()
# if os.path.isfile('Draw_Energy_Diagram_XML_CheckUpdate.exe'):
# subprocess.Popen(['Draw_Energy_Diagram_XML_CheckUpdate.exe'])
# else:
# subprocess.Popen(['python','Draw_Energy_Diagram_XML_CheckUpdate.py'])
def toggle_auto_Y_tick(self):
self.Y_tick_doubleSpinBox.setEnabled(not self.Y_tick_auto_checkBox.isChecked())
self.Y_number_doubleSpinBox.setEnabled(not self.Y_tick_auto_checkBox.isChecked())
self.Y_label_precision_spinBox.setEnabled(not self.Y_tick_auto_checkBox.isChecked())
def store_Y_label_to_file(self):
with open(os.path.join(filename_class(sys.argv[0]).path, 'Energy_Diagram_Y_Axis_Text.txt'), 'w') as Y_axis_text_file:
Y_axis_text_file.write(self.Y_label_lineEdit.text())
def x_limits_change(self):
if self.x_upper_limit_spinBox.value() > self.x_lower_limit_spinBox.value():
self.x_limits_changed = True
else:
self.x_limits_changed = False
self.update_xlsx()
def y_limits_change(self):
if self.Y_upper_limit_spinBox.value() > self.Y_lower_limit_spinBox.value():
self.y_limits_changed = True
else:
self.y_limits_changed = False
self.update_xlsx()
def choose_xlsx(self):
# self.xlsx_dropped(r"C:\Users\LiYuanhe\Desktop\temp.xlsx")
# self.save_cdxml()
xlsx_filename = QtWidgets.QFileDialog.getOpenFileName(self, 'Choose Input XLSX file', self.load_config('Energy Diagram Last Path'),
filter="xlsx File (*.xlsx)")
if xlsx_filename:
xlsx_filename = xlsx_filename[0]
self.xlsx_dropped(xlsx_filename)
def update_xlsx(self):
if self.xlsx_file_lineEdit.text():
self.xlsx_dropped(self.xlsx_file_lineEdit.text(), called_from_update=True)
def xlsx_dropped(self, xlsx_filename, called_from_update=False):
"""
read xlsx data. The first column can be the format setting, e.g. 'r'
"""
# re-initiate
self.paths_for_cdx_drawing = []
self.colors_for_cdx_drawing = []
self.energy_diagram.setParent(None)
self.energy_diagram = MpWidget_Energy_Diagram()
self.energy_diagram.setSizePolicy(QtWidgets.QSizePolicy.Policy.Preferred, QtWidgets.QSizePolicy.Policy.Preferred)
self.verticalLayout.insertWidget(1, self.energy_diagram, 1)
# 防止因为改变x, y limit 触发多次limit changed. 在函数末尾重新 connect
disconnect_all(self.x_lower_limit_spinBox, self.x_limits_change)
disconnect_all(self.x_upper_limit_spinBox, self.x_limits_change)
disconnect_all(self.Y_lower_limit_spinBox, self.y_limits_change)
disconnect_all(self.Y_upper_limit_spinBox, self.y_limits_change)
if isinstance(xlsx_filename, list): # drop area 给出的是一个list,可以接受多个文件
xlsx_filename = xlsx_filename[0]
if filename_class(xlsx_filename).append != 'xlsx':
return None
self.config['Energy Diagram Last Path'] = filename_class(xlsx_filename).path
self.save_config()
self.xlsx_file_lineEdit.setText(xlsx_filename)
self.load_xlsx(xlsx_filename)
if [route[0][1] for route in self.routes if not (isinstance(route[0][1], float) or isinstance(route[0][1], int) or route[0][1] is None)]: # 存在格式设定
color_of_lines = [route[0][1] for route in self.routes]
# save something like [None,'r']
else:
color_of_lines = []
x_span = [-1, max([len(route) for route in self.routes]) - 1]
if not called_from_update:
self.x_limits_changed = False
self.x_lower_limit_spinBox.setValue(x_span[0] + 2)
self.x_upper_limit_spinBox.setValue(x_span[1])
else:
if self.x_limits_changed:
x_span = [self.x_lower_limit_spinBox.value() - 2, self.x_upper_limit_spinBox.value()]
self.x_upper_limit_spinBox.setMinimum(self.x_lower_limit_spinBox.value() + 1)
self.x_lower_limit_spinBox.setMaximum(self.x_upper_limit_spinBox.value() - 1)
get_y_range = [state[1] for state in sum(self.routes, [])]
get_y_range = [x for x in get_y_range if is_float(x)]
min_energy = min(get_y_range)
max_energy = max(get_y_range)
y_span = max_energy - min_energy
y_span = [min_energy - y_span * 0.3, max_energy + y_span * 0.5]
if not called_from_update:
self.y_limits_changed = False
self.Y_lower_limit_spinBox.setValue(y_span[0])
self.Y_upper_limit_spinBox.setValue(y_span[1])
else:
if self.y_limits_changed:
y_span = [self.Y_lower_limit_spinBox.value(), self.Y_upper_limit_spinBox.value()]
for count, route in enumerate(self.routes):
if color_of_lines: # have format setting
self.energy_diagram.diagram_Update(route[1:], x_span=x_span, y_span=y_span, color=color_of_lines[count],
num_with_tag=self.num_with_tag_checkBox.isChecked(),
state_line_span=self.state_line_span_doubleSpinBox.value())
self.paths_for_cdx_drawing.append(route[1:])
self.colors_for_cdx_drawing.append(color_of_lines[count])
else: # doesn't have format setting
self.energy_diagram.diagram_Update(route, x_span=x_span, y_span=y_span, num_with_tag=self.num_with_tag_checkBox.checked(),
state_line_span=self.state_line_span_doubleSpinBox.value())
self.paths_for_cdx_drawing.append(route)
self.colors_for_cdx_drawing.append('k')
connect_once(self.x_lower_limit_spinBox, self.x_limits_change)
connect_once(self.x_upper_limit_spinBox, self.x_limits_change)
connect_once(self.Y_lower_limit_spinBox, self.y_limits_change)
connect_once(self.Y_upper_limit_spinBox, self.y_limits_change)
self.center_the_widget()
self.show()
def save_cdxml(self):
# 保存各种设置
self.config['State Precision Digits'] = self.state_precision_spinBox.value()
self.config['State Line Span'] = self.state_line_span_doubleSpinBox.value()
self.config['Auto_collision_avoidance'] = self.Auto_collision_avoidance_checkBox.isChecked()
self.config['allow_overlap_states_checkBox'] = self.allow_overlap_states_checkBox.isChecked()
self.config['Num with Tag'] = self.num_with_tag_checkBox.isChecked()
self.config['Use Solid Link'] = self.solid_line_radioButton.isChecked()
self.config['Use Lines'] = self.use_lines_radioButton.isChecked()
# print(self.config['Use Lines'])
self.config['X_tick_checkBox'] = self.X_tick_checkBox.isChecked()
self.config['Y_tick_checkBox'] = self.Y_tick_checkBox.isChecked()
self.config['Y_tick_auto_checkBox'] = self.Y_tick_auto_checkBox.isChecked()
self.config['Y_label_precision_spinBox'] = self.Y_label_precision_spinBox.value()
self.config['Y_label_lineEdit'] = self.Y_label_lineEdit.text()
self.config['Draw_energy_diagram_window_width'] = self.width()
self.config['Draw_energy_diagram_window_height'] = self.height()
self.config['use_temp_file_checkBox'] = self.use_temp_file_checkBox.isChecked()
self.save_config()
if self.xlsx_file_lineEdit.text() == "":
self.choose_xlsx()
fonts_list = [default_fonts, default_fonts_end]
# 获得Energy diagram 与ChemDraw 文档的坐标对应关系
x_range = self.energy_diagram.diagram_subplot.get_xlim() # the x coordinate range
y_range = self.energy_diagram.diagram_subplot.get_ylim() # the y coordinate range
width = self.energy_diagram.canvas.width() # height of diagram in pixels
height = self.energy_diagram.canvas.height() # height of diagram in pixels
# 两个轴的Matplotlib-->ChemDraw转换函数
# map function coordinate to pixel
x_mapping = lambda x: width / (x_range[1] - x_range[0]) * x * PIXEL_FACTOR + X_OFFSET
# map function coordinate to pixel
y_mapping = lambda y: height / (y_range[1] - y_range[0]) * (y_range[1] - y) * PIXEL_FACTOR + Y_OFFSET