-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhomogeneous_reaction_set_equilibrium.py
More file actions
2394 lines (2248 loc) · 101 KB
/
Copy pathhomogeneous_reaction_set_equilibrium.py
File metadata and controls
2394 lines (2248 loc) · 101 KB
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 -*-
"""
Created on Fri Nov 27 20:48:42 2015
@author: Santiago Salas
@ref: Denbigh, p. 298
"""
import os
import sys
import logging
import re
import pandas as pd
import numpy as np
import csv
import bisect
import uuid
from urllib.request import pathname2url
from pathlib import Path
import matplotlib
import colormaps
import ctypes # Needed to set the app icon correctly
from functools import partial
from reaction_equilibrium import calc_xieq
from datetime import datetime
#matplotlib.use('Qt4Agg')
#matplotlib.rcParams['backend.qt5'] = 'PySide'
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
from qtpy import QtGui, QtCore, QtWebEngineWidgets, QtWidgets
from mplcursors import cursor as datacursor
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromutf8(s):
return s
try:
_encoding = QtWidgets.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtWidgets.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtWidgets.QApplication.translate(context, text, disambig)
def take_float(x):
return float(x.rpartition('=')[-1])
def take_list(x):
separator = ','
raw_list = x.rpartition('=')[-1].replace('[', '').replace(']', '')
output_string = np.fromstring(raw_list, dtype=float, sep=separator)
if x.find('j') > -1:
square_dim = int(round(np.sqrt(len(output_string))))
output_string = output_string.reshape(square_dim, square_dim)
return output_string
def take_int(x):
return int(x.rpartition('=')[-1])
def take_bool(x):
return x.rpartition('=')[-1] == 'True'
def take_date(x):
return datetime.strptime(x, '%Y-%m-%d %H:%M:%S,%f')
# Variables used
colormap_colors = colormaps.viridis.colors + colormaps.inferno.colors
markers = matplotlib.markers.MarkerStyle.filled_markers
fillstyles = matplotlib.markers.MarkerStyle.fillstyles
# Structure of input files
# Header of components will match this expression, only need to find
# indexes in file.
header_comps_input_model = [
'i', 'Comp.', 'z', 'M/(g/mol)', 'w0/g', 'xw0',
'n0/mol', 'x0', 'c0/(mol/L)',
'm0/(mol/kg_{solvent})',
'-log10(xw0)', '-log10(x0)', '-log10(c0)',
'-log10(m0)', '-log10(a0)'
]
comp_variable_input_names = [
'index', 'comp_id', 'z', 'molar_mass',
'w0', 'xw0', 'n0', 'x0', 'c0', 'm0',
'mlog10xw0', 'mlog10x0', 'mlog10c0',
'mlog10m0', 'mlog10a0'
]
header_comps_output_model = [
'weq/g', 'xweq', 'neq/mol', 'xeq',
'ceq/(mol/L)', 'meq/(mol/kg_{solvent})',
'rhoeq/(g/mL)',
'\gamma_{eq}^{II}', '\gamma_{eq}^{III}',
'aeq',
'-log10(\gamma_{eq}^{II})',
'-log10(\gamma_{eq}^{III})',
'-log10(xweq)', '-log10(xeq)', '-log10(ceq)',
'-log10(meq)', '-log10(aeq)'
]
comp_variable_output_names = [
'weq', 'xweq', 'neq', 'xeq',
'ceq', 'meq',
'rhoeq',
'gammaeq_ii', 'gammaeq_iii',
'aeq',
'mlog10gammaeq_ii',
'mlog10gammaeq_iii',
'mlog10xweq', 'mlog10xeq', 'mlog10ceq',
'mlog10meq', 'mlog10aeq',
]
# First two columns of the header of reacions will match this
# expression, need to find indexes in file and append coefficient
# matrix.
header_reacs_model = ['j', 'pKa']
# Store programatic name vs. header name in a dict.
comp_names_headers = \
dict(zip(header_comps_input_model + header_comps_output_model,
comp_variable_input_names + comp_variable_output_names))
# Regular expression compilations
float_re = re.compile(r'(([+-]?\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)')
matchingHLine = re.compile('=+')
# Default component and reaction headers according to structure
# [j, pKa, nu_ij(i=1), nu_ij(i=2),...]
# Sample resulting regex groups when applied to text values:
# 'j' ['j', None, None, None, None]
# 'pKaj' [None, 'pKaj', None, None, None]
# 'nu2000j' [None, None, 2000, None, None]
# 'nu2j(i=99)' [None, None, 2, (i=99), 99]
reac_headers_re = re.compile(
r'(\bj$)' +
r'|(^pKaj$)' +
r'|nu_?i?([0-9]+)?j(\(i=([0-9]+)\))?')
comp_headers_re = re.compile(
r'(\bi$)|(Comp\.?i?)|([z|Z]_?i?)|(M_?i?)|(w_?0_?i?)|(x_?w_?0?)|' +
r'(n_?0?_?i?)|(x_?0)|([c|C]_?0_?i?)|(m_?0)')
doc_hline_re = re.compile(
r'(\s*-{3,})')
html_title = re.compile('<title>(.*?)</title>',
re.IGNORECASE | re.DOTALL)
main_window_title = 'Homogeneous EC.'
class UiGroupBox(QtWidgets.QWidget):
_was_canceled = False
def __init__(self, parent):
QtWidgets.QWidget.__init__(self, parent)
# Assignments
self.verticalLayout_2 = QtWidgets.QVBoxLayout(parent)
self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.open_button = QtWidgets.QPushButton()
self.save_button = QtWidgets.QPushButton()
self.info_button = QtWidgets.QPushButton()
self.log_button = QtWidgets.QPushButton()
self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
self.label_3 = QtWidgets.QLabel()
self.equilibrate_button = QtWidgets.QPushButton()
self.spinBox_3 = QtWidgets.QSpinBox()
self.label_4 = QtWidgets.QLabel()
self.label = QtWidgets.QLabel()
self.spinBox = QtWidgets.QSpinBox()
self.tableComps = QtWidgets.QTableView()
self.label_9 = QtWidgets.QLabel()
self.progress_var = QtWidgets.QProgressBar(parent)
self.cancelButton = QtWidgets.QPushButton(parent)
self.doubleSpinBox_5 = ScientificDoubleSpinBox()
self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
self.label_5 = QtWidgets.QLabel()
self.comboBox_3 = QtWidgets.QComboBox()
self.label_6 = QtWidgets.QLabel()
self.doubleSpinBox_6 = QtWidgets.QDoubleSpinBox()
self.label_2 = QtWidgets.QLabel()
self.spinBox_2 = QtWidgets.QSpinBox()
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.tableReacs = QtWidgets.QTableView()
self.verticalLayout = QtWidgets.QVBoxLayout()
self.label_7 = QtWidgets.QLabel()
self.comboBox = QtWidgets.QComboBox()
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.doubleSpinBox = ScientificDoubleSpinBox()
self.doubleSpinBox_2 = ScientificDoubleSpinBox()
self.plotButton = QtWidgets.QPushButton()
self.radio_group = QtWidgets.QHBoxLayout()
self.radio_b_1 = QtWidgets.QRadioButton()
self.radio_b_2 = QtWidgets.QRadioButton()
self.radio_b_3 = QtWidgets.QRadioButton()
self.groupBox = None # self.groupBox will contain either the plotBox or logBox
# Object names
parent.setObjectName(_fromutf8("GroupBox"))
self.verticalLayout_2.setObjectName(_fromutf8("verticalLayout_2"))
self.horizontalLayout_2.setObjectName(_fromutf8("horizontalLayout_2"))
self.horizontalLayout_3.setObjectName(_fromutf8("horizontalLayout_3"))
self.open_button.setObjectName(_fromutf8("open_button"))
self.save_button.setObjectName(_fromutf8("save_button"))
self.info_button.setObjectName(_fromutf8("info_button"))
self.log_button.setObjectName(_fromutf8("log_button"))
self.horizontalLayout_5.setObjectName(_fromutf8("horizontalLayout_5"))
self.label_3.setObjectName(_fromutf8("max_it_label"))
self.spinBox_3.setObjectName(_fromutf8("max_it_spinbox"))
self.label_4.setObjectName(_fromutf8("tol_label"))
self.doubleSpinBox_5.setObjectName(_fromutf8("tol_spinbox"))
self.label.setObjectName(_fromutf8("label"))
self.spinBox.setObjectName(_fromutf8("spinBox"))
self.tableComps.setObjectName(_fromutf8("tableComps"))
self.horizontalLayout_6.setObjectName(_fromutf8("horizontalLayout_6"))
self.label_5.setObjectName(_fromutf8("solvent_label"))
self.label_6.setObjectName(_fromutf8("c_solvent_tref"))
self.doubleSpinBox_6.setObjectName(
_fromutf8("c_solvent_tref_doublespinbox"))
self.label_2.setObjectName(_fromutf8("label_2"))
self.spinBox_2.setObjectName(_fromutf8("spinBox_2"))
self.horizontalLayout.setObjectName(_fromutf8("horizontalLayout"))
self.tableReacs.setObjectName(_fromutf8("tableReacs"))
self.verticalLayout.setObjectName(_fromutf8("verticalLayout"))
self.label_7.setObjectName(_fromutf8("horizontalAxisLabel"))
self.comboBox.setObjectName(_fromutf8("comboBox"))
self.horizontalLayout_3.setObjectName(_fromutf8("horizontalLayout_3"))
self.doubleSpinBox.setObjectName(_fromutf8("doubleSpinBox"))
self.doubleSpinBox_2.setObjectName(_fromutf8("doubleSpinBox_2"))
self.plotButton.setObjectName(_fromutf8("plotButton"))
self.radio_group.setObjectName(_fromutf8("radio_group"))
self.radio_b_1.setObjectName(_fromutf8("radio_b_1"))
self.radio_b_2.setObjectName(_fromutf8("radio_b_2"))
self.radio_b_3.setObjectName(_fromutf8("radio_b_3"))
# Operations
self.horizontalLayout_2.addWidget(self.open_button)
self.horizontalLayout_2.addWidget(self.save_button)
self.horizontalLayout_2.addWidget(self.log_button)
self.horizontalLayout_2.addWidget(self.info_button)
self.verticalLayout_2.addWidget(self.equilibrate_button)
self.radio_group.addWidget(self.radio_b_1)
self.radio_group.addWidget(self.radio_b_2)
self.radio_group.addWidget(self.radio_b_3)
self.radio_b_1.setChecked(True)
self.radio_b_1.setToolTip('<b>%s</b><br><img src="%s">' %
('Ideal solution',
'utils/Ideal_solution.png'))
self.radio_b_2.setToolTip('<b>%s</b><br><img src="%s">' %
('Debye-Hueckel',
'utils/Debye-Hueckel.png'))
self.radio_b_3.setToolTip('<b>%s</b><br><img src="%s">' %
('Davies (DH ext.)',
'utils/Davies.png'))
self.verticalLayout_2.addLayout(self.radio_group)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
self.label_3.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignCenter)
self.horizontalLayout_5.addWidget(self.label_3)
self.spinBox_3.setMaximum(2000)
self.spinBox_3.setMinimum(2)
self.spinBox_3.setProperty("value", 1000)
self.horizontalLayout_5.addWidget(self.spinBox_3)
self.label_4.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignCenter)
self.horizontalLayout_5.addWidget(self.label_4)
self.doubleSpinBox_5.setDecimals(
int(-np.log10(np.finfo(float).eps) + 1))
self.doubleSpinBox_5.setMaximum(float(1))
self.doubleSpinBox_5.setMinimum(np.finfo(float).eps * 2)
self.doubleSpinBox_5.setSingleStep(
0.1 / 100.0 * (1.0 - np.finfo(float).eps))
self.doubleSpinBox_5.setProperty("value", float(1.0e-08))
self.horizontalLayout_5.addWidget(self.doubleSpinBox_5)
self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignCenter)
self.horizontalLayout_5.addWidget(self.label)
self.spinBox.setProperty("value", 0)
self.horizontalLayout_5.addWidget(self.spinBox)
self.verticalLayout_2.addLayout(self.horizontalLayout_5)
self.tableComps.setMinimumSize(QtCore.QSize(0, 210))
#item.setTextAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
self.tableComps.horizontalHeader().setCascadingSectionResizes(False)
self.tableComps.horizontalHeader().setDefaultSectionSize(100)
self.tableComps.horizontalHeader().setMinimumSectionSize(27)
self.tableComps.horizontalHeader().setSortIndicatorShown(True)
self.tableComps.verticalHeader().setVisible(False)
self.verticalLayout_2.addWidget(self.tableComps)
self.label_9.setAlignment(QtCore.Qt.AlignTop)
self.label_9.setFrameStyle(QtWidgets.QFrame.Box | QtWidgets.QFrame.Raised)
self.verticalLayout_2.addWidget(self.label_9)
self.horizontalLayout_7.setAlignment(QtCore.Qt.AlignRight)
self.horizontalLayout_7.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
self.horizontalLayout_7.addStrut(max(
[self.progress_var.frameSize().height(),
self.cancelButton.frameSize().height()]))
self.horizontalLayout_7.setAlignment(QtCore.Qt.AlignLeft)
self.horizontalLayout_7.addWidget(self.cancelButton)
self.horizontalLayout_7.addWidget(self.progress_var)
self.cancelButton.setEnabled(False)
self.progress_var.setEnabled(False)
self.verticalLayout_2.addLayout(self.horizontalLayout_7)
self.label_5.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignCenter)
self.horizontalLayout_6.addWidget(self.label_5)
self.horizontalLayout_6.addWidget(self.comboBox_3)
self.label_6.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignCenter)
self.horizontalLayout_6.addWidget(self.label_6)
self.doubleSpinBox_6.setDecimals(
int(-np.log10(np.finfo(float).eps) + 1))
self.doubleSpinBox_6.setMaximum(float(1000))
self.doubleSpinBox_6.setMinimum(np.finfo(float).eps * 1.1)
self.doubleSpinBox_6.setSingleStep(1.0e-2)
self.horizontalLayout_6.addWidget(self.doubleSpinBox_6)
self.label_2.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignCenter)
self.horizontalLayout_6.addWidget(self.label_2)
self.spinBox_2.setProperty("value", 0)
self.horizontalLayout_6.addWidget(self.spinBox_2)
self.verticalLayout_2.addLayout(self.horizontalLayout_6)
self.tableReacs.horizontalHeader().setVisible(True)
self.tableReacs.verticalHeader().setVisible(False)
self.horizontalLayout.addWidget(self.tableReacs)
self.label_7.setAlignment(
QtCore.Qt.AlignHCenter | QtCore.Qt.AlignCenter)
self.verticalLayout.addWidget(self.label_7)
self.verticalLayout.addWidget(self.comboBox)
self.doubleSpinBox.setMinimum(0.0)
self.horizontalLayout_3.addWidget(self.doubleSpinBox)
self.doubleSpinBox_2.setMinimum(0.0)
self.horizontalLayout_3.addWidget(self.doubleSpinBox_2)
self.verticalLayout.addLayout(self.horizontalLayout_3)
self.verticalLayout.addWidget(self.plotButton)
self.horizontalLayout.addLayout(self.verticalLayout)
self.verticalLayout_2.addLayout(self.horizontalLayout)
# Events
self.open_button.clicked.connect(partial(self.open_file))
self.save_button.clicked.connect(partial(self.save_file))
self.plotButton.clicked.connect(partial(self.solve_intervals))
self.equilibrate_button.clicked.connect(
partial(self.recalculate_after_cell_edit, 0, 0))
self.info_button.clicked.connect(partial(self.display_about_info))
self.log_button.clicked.connect(partial(self.show_log))
self.cancelButton.clicked.connect(partial(self.cancel_loop))
self.comboBox.currentIndexChanged.connect(
partial(self.populate_input_spinboxes))
# Icons
icon0 = QtGui.QIcon()
icon0.addPixmap(QtGui.QPixmap(
_fromutf8("utils/glyphicons-145-folder-open.png")),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(
_fromutf8("utils/glyphicons-415-disk-save.png")),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(
_fromutf8("utils/glyphicons-41-stats.png")),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(
_fromutf8("utils/glyphicons-82-refresh.png")),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap(
_fromutf8("utils/glyphicons-196-circle-info.png")),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
icon5 = QtGui.QIcon()
icon5.addPixmap(QtGui.QPixmap(
_fromutf8("utils/glyphicons-88-log-book.png")),
QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.open_button.setIcon(icon0)
self.save_button.setIcon(icon1)
self.plotButton.setIcon(icon2)
self.equilibrate_button.setIcon(icon3)
self.info_button.setIcon(icon4)
self.log_button.setIcon(icon5)
# Retranslate, connect
self.retranslate_ui(parent)
QtCore.QMetaObject.connectSlotsByName(parent)
def retranslate_ui(self, parent):
parent.setWindowTitle(_translate("parent", main_window_title, None))
parent.setTitle(QtWidgets.QApplication.translate(
"parent", main_window_title[-3:], None))
__sortingEnabled = self.tableComps.isSortingEnabled()
self.open_button.setText(_translate("parent", "Open", None))
self.save_button.setText(_translate("parent", "Save", None))
self.log_button.setText(_translate("parent", "Log", None))
self.info_button.setText(_translate("parent", "About", None))
self.equilibrate_button.setText(
_translate("parent", "Equilibrate", None))
self.radio_b_1.setText(
_translate("parent", "Ideal solution", None))
self.radio_b_2.setText(
_translate("parent", "Debye-Hückel", None))
self.radio_b_3.setText(
_translate("parent", "Davies (DH ext.)", None))
self.tableComps.setSortingEnabled(__sortingEnabled)
self.plotButton.setText(_translate("parent", "Plot", None))
self.label_2.setText(_translate("parent", "nr (Reac.)", None))
self.label.setText(_translate("parent", "n (Comp.)", None))
self.label_3.setText(_translate("parent", "max. it", None))
self.label_4.setText(_translate("parent", "tol", None))
self.label_5.setText(_translate("parent", "solvent", None))
self.label_6.setText(_translate("parent", "C_solvent (25C)", None))
self.label_7.setText(_translate("parent", "Horizontal 'X' axis", None))
self.label_9.setText(
_translate(
"parent",
'Currently unequilibrated',
None))
self.cancelButton.setText('cancel')
def cancel_loop(self):
self._was_canceled = True
self.progress_var.setValue(0)
def populate_input_spinboxes(self, index):
comps = self.comps
c0_component = self.c0[index]
self.doubleSpinBox.setValue(c0_component / 10.0 ** 7)
self.doubleSpinBox_2.setValue(c0_component * (1 + 20 / 100.0))
def remove_canceled_status(self):
self._was_canceled = False
def was_canceled(self):
return self._was_canceled
def open_file(self):
(filename, _) = \
QtWidgets.QFileDialog.getOpenFileName(None,
caption='Open file',
dir=os.path.join(
sys.path[0], 'DATA'),
filter='*.csv')
if os.path.isfile(filename):
# Reset solution state and order of items
if hasattr(self, 'acceptable_solution'):
delattr(self, 'acceptable_solution')
if hasattr(self, 'component_order_in_table'):
delattr(self, 'component_order_in_table')
if hasattr(self, 'reaction_order_in_table'):
delattr(self, 'reaction_order_in_table')
# Load csv data into form variables
self.load_csv(filename)
# Continue with typical solution and table population procedure
self.gui_equilibrate()
self.tableComps.sortByColumn(0, QtCore.Qt.AscendingOrder)
self.tableReacs.sortByColumn(0, QtCore.Qt.AscendingOrder)
def load_csv(self, filename):
with open(filename) as csv_file:
n = 0
nr = 0
header_comps = []
header_reacs = []
reader = csv.reader(csv_file, dialect='excel')
reading_comps = False
reading_reacs = False
comps = []
reacs = []
for row in reader:
row_without_whitespace = [x.replace(' ', '') for x in row]
row_without_blanks = [
x for x in row_without_whitespace if len(x) > 0]
if len(row_without_blanks) == 0:
pass # skip empty line
elif 'COMP' in row:
reading_comps = True
reading_reacs = False
header_comps = next(reader)
# Get column mappings of form
# [
# [output_index_1, input_index_1],
# [output_index_2, input_index_2],
# ...]
io_column_index_map = []
for (col_no, column) in enumerate(header_comps):
old_index = col_no
matches = \
comp_headers_re.match(column.replace(' ', ''))
if matches is not None:
new_index = [j for j, match
in enumerate(matches.groups())
if match is not None][0]
io_column_index_map.append(
[new_index, old_index]
)
elif 'REAC' in row:
reading_reacs = True
reading_comps = False
header_reacs = next(reader)
# Get column mappings of form
# [
# [output_index_1, input_index_1],
# [output_index_2, input_index_2],
# ...]
io_column_index_map = []
for (col_no, column) in enumerate(header_reacs):
old_index = col_no
matches = \
reac_headers_re.match(column.replace(' ', ''))
if matches is not None:
re_index = [(j, match) for j, match
in enumerate(matches.groups())
if match is not None]
# When index is
# 0: 'j', 1: 'pKa'
# 2: X , 3: '(i=Y)',
# 4: Y
if len(re_index) == 1:
first_index = re_index[0][0]
if first_index in [0, 1]:
# 0: 'j', 1: 'pKa'
new_index = first_index
else:
# In 'nu_Xj'
# 2: X
# add 0 + 1 for j, pKa
new_index = \
int(re_index[0][1]) + 0 + 1
elif len(re_index) > 2: # In 'nu_iX(i=Y)'
# 2: X , 3: '(i=Y)',
# 4: Y
# Prioritize 4
# add 0 + 1 for j, pKa
new_index = \
int(re_index[-1][1]) + 0 + 1
elif len(re_index) == 2: # In 'nu_iX(i=Y)'
# 3: '(i=Y)',
# 4: Y
# Prioritize 4
# add 0 + 1 for j, pKa
new_index = \
int(re_index[-1][1]) + 0 + 1
io_column_index_map.append(
[new_index, old_index]
)
elif reading_comps:
n += 1
# put 0 instead of blank and keep all columns to add in
# model
row_to_add = [''] * len(header_comps_input_model)
for new_index, old_index in io_column_index_map:
text_with_number = row_without_whitespace[old_index]
if new_index!=1 and len(text_with_number) == 0:
row_to_add[new_index] = float(0)
elif new_index!=1:
row_to_add[new_index] = float(text_with_number)
else:
row_to_add[new_index] = row_without_whitespace[old_index]
comps.append(row_to_add)
elif reading_reacs:
nr += 1
sorted_io_column_index_map =\
sorted(io_column_index_map, key=lambda x: x[1])
max_column_no = max([item[0]
for item in io_column_index_map]) + 1
row_to_add = [''] * max_column_no
# put 0 instead of blank and keep only columns to add
for new_index, old_index in sorted_io_column_index_map:
text_with_number = row_without_whitespace[old_index]
if len(text_with_number) == 0:
row_to_add[new_index] = float(0)
else:
row_to_add[new_index] = float(text_with_number)
reacs.append(row_to_add)
csv_file.close()
self.parentWidget().setWindowTitle(
main_window_title[:-1] + ' - ' + os.path.basename(filename))
column_of_index_comps = comp_variable_input_names.index('index')
column_of_index_reacs = header_reacs_model.index('j')
# First, sort by existing order, if available
sorted_comps = sorted(comps, key=lambda x: x[column_of_index_comps])
sorted_reacs = sorted(reacs, key=lambda x: x[column_of_index_reacs])
# Add indexes or replace existing indexes with simple ones.
for k, row in enumerate(sorted_comps):
row[column_of_index_comps] = k + 1
for k, row in enumerate(sorted_reacs):
row[column_of_index_reacs] = k + 1
header_comps = comp_variable_input_names \
+ comp_variable_output_names
header_reacs = header_reacs_model \
+ ['nu_' + str(x + 1) + 'j' for x in range(n)]
comps = np.array(sorted_comps, dtype=object) # do not convert yet
reacs = np.array(sorted_reacs, dtype=object) # do not convert yet
# Grow comps and reacs to their final widths from the start.
# Width of reactions matrix could not be known before this step.
header_comps_complete = \
header_comps_input_model + header_comps_output_model
header_reacs_complete = \
header_reacs + ['xieq']
comps_column_width = len(header_comps_complete)
reacs_column_width = len(header_reacs_complete)
comps_completed_matrix = np.empty(
[comps.shape[0], comps_column_width], dtype=object
)
comps_completed_matrix[:, 0:comps.shape[1]] = comps
reacs_completed_matrix = np.empty(
[reacs.shape[0], reacs_column_width], dtype=object
)
reacs_completed_matrix[:, 0:reacs.shape[1]] = reacs
self.spinBox.setProperty("value", n)
self.spinBox_2.setProperty("value", nr)
self.comps_model = MatrixModel(
comps_completed_matrix,
header_comps_complete,
editable_columns=range(len(header_comps_input_model))
)
self.reacs_model = MatrixModel(
reacs_completed_matrix,
header_reacs_complete,
editable_columns=range(len(header_reacs_complete) - 1)
)
self.tableComps.setSortingEnabled(False)
self.tableReacs.setSortingEnabled(False)
# Set modelsfor tables and connect datachanged signals
self.tableComps.setModel(self.comps_model)
self.tableReacs.setModel(self.reacs_model)
self.tableComps.model().change_data.connect(
self.recalculate_after_cell_edit)
self.tableReacs.model().change_data.connect(
self.recalculate_after_cell_edit)
# Pass variables to self before loop start
variables_to_pass = ['header_comps', 'comps',
'header_comps_complete',
'comps_completed_matrix',
'header_reacs', 'reacs',
'header_reacs_complete',
'reacs_completed_matrix',
'n', 'nr'
]
for var in variables_to_pass:
setattr(self, var, locals()[var])
def load_variables_from_form(self):
comps_completed_matrix = \
self.tableComps.model().return_data()
reacs_completed_matrix = \
self.tableReacs.model().return_data()
header_comps = self.tableComps.model().return_headers()
header_reacs = self.tableReacs.model().return_headers()
n = len(comps_completed_matrix)
nr = len(reacs_completed_matrix)
index_of_component_order_in_table = \
header_comps.index('i')
index_of_reaction_order_in_table = \
header_reacs.index('j')
component_order_in_table = \
(comps_completed_matrix[
:, index_of_component_order_in_table
] - 1).tolist()
reaction_order_in_table = \
(reacs_completed_matrix[
:, index_of_reaction_order_in_table
] - 1).tolist()
# Pass variables to self before loop start
variables_to_pass = ['header_comps',
'comps_completed_matrix',
'header_reacs',
'reacs_completed_matrix',
'component_order_in_table',
'reaction_order_in_table']
for var in variables_to_pass:
setattr(self, var, locals()[var])
self.gui_setup_and_variables()
def gui_setup_and_variables(self):
# Collect variables
n = self.n
nr = self.nr
comps = np.array(sorted(
self.comps_completed_matrix, key=lambda x: x[0]))
reacs = np.array(sorted(
self.reacs_completed_matrix, key=lambda x: x[0]))
header_comps = self.header_comps
header_reacs = self.header_reacs
molar_masses_valid = False
unset_variables = []
for col, name in enumerate(comp_variable_input_names):
if name in ['comp_id']:
data_type = str
elif name in ['index']:
data_type = int
else:
data_type = float
# take floats, replace empty strings for 0.0
column_vector = np.array([float(x) if not isinstance(x,str) else 0.0 for x in comps[:,col] ])
if all(column_vector == 0):
unset_variables.append(name)
if data_type != float:
try:
column_vector = np.array(comps[:, col], dtype=data_type)
except ValueError as detail:
# print detail
unset_variables.append(name)
column_vector = np.empty([n, 1])
column_vector[:] = np.nan
if name in ['index', 'comp_id', 'z']:
raise Exception('Input field missing: '
+ name)
# Put / Reset values of each column name into self by name
if hasattr(self, name):
delattr(self, name)
setattr(self, name, column_vector)
index = self.index
comp_id = self.comp_id
z = self.z
molar_mass = self.molar_mass
n0 = self.n0
w0 = self.w0
xw0 = self.xw0
x0 = self.x0
c0 = self.c0
m0 = self.m0
rho_solvent = 0.997 # TODO: Adjust density with temperature
positive_molar_masses = \
all(molar_mass > 0)
can_calculate_n_from_w = \
'molar_mass' not in unset_variables and \
('xw0' not in unset_variables or
'w0' not in unset_variables)
mol_variables_empty = \
all(map(lambda x: x in unset_variables,
['n0', 'x0', 'c0']))
# Gui setup with calculated values
# First determine concentration variables from available data, and
# determine the index of the solvent.
highest_n0_indexes = []
index_of_solvent = []
c_solvent_tref = []
if mol_variables_empty:
# If number of moles cannot be determined, reaction quotients
# cannot be determined either, request molar mass inputs.
if not can_calculate_n_from_w or \
not positive_molar_masses:
raise Exception('Need positive molar masses defined')
else:
# calculate n0 from w0 or xw0
if 'w0' in unset_variables:
w0 = xw0
elif 'xw0' in unset_variables:
xw0 = w0 / sum(w0)
n0 = np.divide(w0, molar_mass)
elif 'n0' in unset_variables and \
'c0' not in unset_variables:
# moles not given, but molarity given:
# overwrite mole number based on 1L of molarity
n0 = c0
elif 'w0' in unset_variables and \
'xw0' not in unset_variables and \
'molar_mass' not in unset_variables:
# only w% given, use weight in base 1.
w0 = xw0
n0 = np.divide(w0, molar_mass)
elif 'n0' not in unset_variables:
# moles and molar masses given:
# use as main generators
pass
highest_n0_indexes = np.argpartition(n0.flatten(), (-1, -2))
index_of_solvent = highest_n0_indexes[-1]
# Calculate concentration types based on n0, M
x0 = n0 / sum(n0)
if positive_molar_masses:
mm0 = molar_mass[index_of_solvent]
n0_mm0 = n0[index_of_solvent] * mm0
# always calculate weight values & fract.
w0 = np.multiply(n0, molar_mass)
xw0 = w0 / sum(w0)
else:
# Default molar mass of solvent
molar_mass[index_of_solvent] = 18.01528
mm0 = molar_mass[index_of_solvent]
n0_mm0 = n0[index_of_solvent] * mm0
# overwrite molality and molarity based on available n0.
# molarity has units mol/g, leave conversion to mol/kg
# for the end.
m0 = n0 / (n0_mm0)
c0 = m0 * rho_solvent * 1000
# \frac{x_i}{m_i} = \frac{M_0}{1 + sum_{j\neq0}{m_j M_0}}
mi_mm0_over_xi = \
1 + sum([m_j for j, m_j in enumerate(m0 * mm0) if
j != index_of_solvent])
rho0 = (mi_mm0_over_xi) * rho_solvent
gamma0_ii = np.ones_like(m0)
gamma0_iii = np.ones_like(m0)
a0 = np.multiply(gamma0_iii, m0) * np.nan
rho0_i = np.multiply(c0, mm0)
c_solvent_tref = c0[index_of_solvent].item()
# Overwrite logarithmic calculations, no need to keep
# supplied values
mlog10xw0 = -np.log10(xw0)
mlog10x0 = -np.log10(x0)
mlog10c0 = -np.log10(c0)
mlog10m0 = -np.log10(m0)
mlog10a0 = -np.log10(a0)
nu_ij = np.array([row[2:2 + n] for row in reacs], dtype=float).T
pka = np.array([row[1] for row in reacs], dtype=float).T
max_it = int(self.spinBox_3.value())
tol = float(self.doubleSpinBox_5.value())
# Determine second highest component for plotting possibilities
if len(n0) > 1:
index_of_second_highest_n0 = highest_n0_indexes[-2]
else:
index_of_second_highest_n0 = highest_n0_indexes[-1]
n_second_highest_n0_tref = n0[index_of_second_highest_n0].item()
# Calculated variables to output for other functions.
variables_to_pass = [
'index_of_solvent', 'molar_mass',
'rho0', 'rho_solvent', 'c_solvent_tref',
'max_it', 'tol',
'n_second_highest_n0_tref',
'positive_molar_masses',
'can_calculate_n_from_w',
'comps', 'reacs'
] + comp_variable_input_names \
+ ['nu_ij', 'pka']
for var in variables_to_pass:
setattr(self, var, locals()[var])
# Setup plotting tools
self.comboBox.clear()
self.comboBox_3.clear()
for item in comps[:, 0:2]:
self.comboBox.addItem('c0_' + str(item[0]) +
' {' + item[1] + '}')
self.comboBox_3.addItem(item[1])
self.comboBox.setCurrentIndex(index_of_second_highest_n0)
self.doubleSpinBox.setValue(n_second_highest_n0_tref / 10.0 ** 7)
self.doubleSpinBox_2.setValue(
n_second_highest_n0_tref * (1 + 20 / 100.0))
self.comboBox_3.setCurrentIndex(index_of_solvent)
self.doubleSpinBox_6.setValue(c_solvent_tref)
self.doubleSpinBox_6.setPrefix('(mol/L)')
def retabulate(self):
n = self.n
nr = self.nr
header_comps_complete = self.header_comps_complete
header_reacs_complete = self.header_reacs_complete
reacs = self.reacs
xieq = self.xieq
if hasattr(self, 'component_order_in_table'):
i = getattr(self, 'component_order_in_table')
else:
i = range(0, n)
if hasattr(self, 'reaction_order_in_table'):
j = getattr(self, 'reaction_order_in_table')
else:
j = range(0, nr)
self.tableComps.blockSignals(True)
self.tableReacs.blockSignals(True)
self.comboBox.blockSignals(True)
# As usual, problems occurr when sorting is combined with setting QTableView.
# Therefore disable sorting, then set model and finally
# reenable sorting.
self.tableComps.setSortingEnabled(False)
self.tableReacs.setSortingEnabled(False)
for column, column_name in enumerate(header_comps_complete):
var_name = comp_names_headers[column_name]
# Keep original order from table
column_data = getattr(self, var_name)[i]
if var_name in ['m0', 'meq']:
# Present units converted: mol/gsolvent to mol/kgsolvent
column_data = 1000 * column_data
elif var_name in ['mlog10m0', 'mlog10meq']:
# Present units converted: mol/gsolvent to mol/kgsolvent.
# Add -log10(10^3)
column_data = column_data - 3
self.comps_model.set_column(column, column_data)
for column, column_name in enumerate(header_reacs_complete):
if column != n + 0 + 1 + 1:
# Keep original order from table in sorted_reacs
column_data = reacs[j, column]
elif column == n + 0 + 1 + 1:
# Keep original order from table
column_data = getattr(self, column_name)[j]
self.reacs_model.set_column(column, column_data)
# Widths and heights, re-enable sorting
self.tableComps.setSortingEnabled(True)
self.tableComps.horizontalHeader().setSectionResizeMode(
QtWidgets.QHeaderView.ResizeToContents)
self.tableComps.verticalHeader().setSectionResizeMode(
QtWidgets.QHeaderView.ResizeToContents)
self.tableReacs.setSortingEnabled(True)
self.tableReacs.horizontalHeader().setSectionResizeMode(
QtWidgets.QHeaderView.ResizeToContents)
self.tableReacs.verticalHeader().setSectionResizeMode(
QtWidgets.QHeaderView.ResizeToContents)
self.tableComps.blockSignals(False)
self.tableReacs.blockSignals(False)
self.comboBox.blockSignals(False)
def save_file(self):
pass
def solve_intervals(self):
variables_to_check = [
'ceq_series',
'xieq_series',
'indep_var_series',
'dep_var_series',
'index_of_variable']
for var in variables_to_check:
if hasattr(self, var):
delattr(self, var)
n_points = 20
index_of_variable = self.comboBox.currentIndex()
comps = self.comps
c0 = self.c0
n = self.n
nr = self.nr
c0_variable_comp = c0[index_of_variable]
rho_solvent = self.rho_solvent
xieq = self.xieq
ceq = self.ceq
ceq_series = np.array(np.zeros([n_points + 1, n]))
xieq_series = np.array(np.zeros([n_points + 1, nr]))
# Keep current solution intact for after plotting range
self.stored_solution_ceq = self.ceq
self.stored_solution_xieq = self.xieq
# TODO: Get plotting to work with format QTableView model (comps
# matrix)
indep_var_label = 'c0_{' + str(comps[index_of_variable, 0]) + ', ' + \
comps[index_of_variable, 1] + '}/(mol/L)'
dep_var_labels = \
['ceq_' + '{' + str(item[0]) + ', ' + item[1] + '}/(mol/L)' for item in comps[:, 0:2]] + \
['\\xi eq_' +
'{' + str(item) + '}/(mol/L)' for item in range(1, nr + 1, 1)]
min_value = self.doubleSpinBox.value()
max_value = self.doubleSpinBox_2.value()
indep_var_series_single = \
[min_value + x
for x in np.arange(n_points + 1) * (max_value - min_value) / n_points]
mid_index = bisect.bisect(
indep_var_series_single,
c0_variable_comp) - 1
dep_var_series = dict(
zip(dep_var_labels, np.empty(n + nr, dtype=np.ndarray)))
indep_var_series = dict.fromkeys(
dep_var_labels, indep_var_series_single)
for j in range(mid_index, -1, -1):
# input is in molar conc. Get molal, n, x
self.c0[index_of_variable] = indep_var_series_single[j]
self.m0[index_of_variable] = \
self.c0[index_of_variable] / rho_solvent
self.x0 = self.c0 / sum(self.c0)
tot_n0_const = sum(self.n0)
self.n0[index_of_variable] = \
tot_n0_const * self.x0[index_of_variable]
self.equilibrate()
ceq_series[j, :] = self.ceq.T
xieq_series[j, :] = self.xieq.T
self.ceq = self.stored_solution_ceq
self.xieq = self.stored_solution_xieq
for j in range(mid_index + 1, n_points + 1, +1):
# input is in molar conc. Get molal, n, x
self.c0[index_of_variable] = indep_var_series_single[j]
self.m0[index_of_variable] = \
self.c0[index_of_variable] / rho_solvent
self.x0 = self.c0 / sum(self.c0)
tot_n0_const = sum(self.n0)
self.n0[index_of_variable] = \
tot_n0_const * self.x0[index_of_variable]
self.equilibrate()
ceq_series[j, :] = self.ceq.T
xieq_series[j, :] = self.xieq.T
for j in range(n):
dep_var_series[dep_var_labels[j]] = ceq_series[:, j]
for j in range(nr):
dep_var_series[dep_var_labels[n + j]] = xieq_series[:, j]
self.ceq = self.stored_solution_ceq
self.xieq = self.stored_solution_xieq
self.ceq_series = ceq_series
self.xieq_series = xieq_series
self.indep_var_series = indep_var_series
self.dep_var_series = dep_var_series
self.dep_var_labels = dep_var_labels
self.indep_var_label = indep_var_label
self.index_of_variable = index_of_variable
self.initiate_plot()
def initiate_plot(self):
n = self.n
nr = self.nr
dep_var_labels = self.dep_var_labels
labels_to_plot = [x for x in self.dep_var_labels if x.find('ceq') >= 0]
# dict, keys:ceq_labels; bindings: plottedseries
plotted_series = dict(
zip(dep_var_labels, np.empty(n + nr, dtype=object)))
dep_var_labels = self.dep_var_labels
dep_var_series = self.dep_var_series
indep_var_series = self.indep_var_series
indep_var_label = self.indep_var_label
self.groupBox = QtWidgets.QGroupBox()
self.groupBox.plotBox = UiGroupBoxPlot(self.groupBox)