├── .gitattributes ├── .gitignore ├── Batch ├── Batch_Example1.Erying_Eq_Output.xlsx ├── Batch_Example1.xlsx ├── Batch_Example2.Erying_Eq_Output.xlsx ├── Batch_Example2.xlsx └── Batch_Template.xltx ├── Eyring_Eq.py ├── LICENSE ├── Lib.py ├── Pipfile ├── Pipfile.lock ├── Python_Lib ├── My_Lib.py ├── My_Lib_Create_Symlink.bat ├── My_Lib_PyQt6.py ├── My_Lib_PyQt6_Create_Symlink.bat ├── My_Lib_Stock.py └── My_Lib_Stock_Create_Symlink.bat ├── README.md ├── UI ├── Eyring_Eq.ico ├── Eyring_Eq.png ├── Eyring_Eq.py ├── Eyring_Eq.txt └── Eyring_Eq.ui ├── Verification ├── Batch_Example1.xlsx ├── Batch_Example2.xlsx └── Verification.py └── pyinstaller.py /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /UI/Eyring_Eq.psd 2 | /.idea/ 3 | *.pyc 4 | *.spec 5 | /Pyinstaller_Packing/ 6 | /Obsolete packing/ 7 | /.venv/ 8 | *.iml 9 | -------------------------------------------------------------------------------- /Batch/Batch_Example1.Erying_Eq_Output.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liyuanhe211/Chemical_Kinetics_Calculator/74e0ec973d4b5b0629ae75015e7e5d4cca70761b/Batch/Batch_Example1.Erying_Eq_Output.xlsx -------------------------------------------------------------------------------- /Batch/Batch_Example1.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liyuanhe211/Chemical_Kinetics_Calculator/74e0ec973d4b5b0629ae75015e7e5d4cca70761b/Batch/Batch_Example1.xlsx -------------------------------------------------------------------------------- /Batch/Batch_Example2.Erying_Eq_Output.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liyuanhe211/Chemical_Kinetics_Calculator/74e0ec973d4b5b0629ae75015e7e5d4cca70761b/Batch/Batch_Example2.Erying_Eq_Output.xlsx -------------------------------------------------------------------------------- /Batch/Batch_Example2.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liyuanhe211/Chemical_Kinetics_Calculator/74e0ec973d4b5b0629ae75015e7e5d4cca70761b/Batch/Batch_Example2.xlsx -------------------------------------------------------------------------------- /Batch/Batch_Template.xltx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liyuanhe211/Chemical_Kinetics_Calculator/74e0ec973d4b5b0629ae75015e7e5d4cca70761b/Batch/Batch_Template.xltx -------------------------------------------------------------------------------- /Eyring_Eq.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Abandon 写clear每个输入框的按钮(已经放了,但是没功能) 4 | # Done: 冰冰姐的建议:1. A+B->P初始浓度不同时,最好在前台明确提醒一下算的是哪个物质的反应时间。 5 | # Done: 冰冰姐的建议:2. 强烈建议增加kcal/mol单位 6 | # Abandon: 冰冰姐的建议:3. 能垒与速率常数可以考虑旁边设一个toggle,因为不可能同时设置这两个参数的 7 | # Done: 让程序记住上次算的是哪两个参数,比如k和conv。 8 | # 新增一个按钮,按钮的文本随上次计算的参数变化而变化,比如上次计算的是k和conv,按钮的文本就是Recalculate k & conv,按钮在计算前会清空这两个框 9 | # 然后要做的就是改一个浓度,点这个按钮;改一个浓度,点这个按钮 10 | # Done: 支持并测试batch 11 | 12 | __author__ = 'LiYuanhe' 13 | 14 | from datetime import datetime 15 | import openpyxl 16 | from Python_Lib.My_Lib_PyQt6 import * 17 | from Python_Lib.My_Lib import read_xlsx, write_xlsx 18 | from Lib import * 19 | 20 | if not QtWidgets.QApplication.instance(): 21 | Application = QtWidgets.QApplication(sys.argv) 22 | if platform.system() == 'Windows': 23 | import ctypes 24 | 25 | APPID = 'LYH.EyringEq.0.1' 26 | ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APPID) 27 | Application.setWindowIcon(QtGui.QIcon('UI/Eyring_Eq.png')) 28 | 29 | pyqt_ui_compile('Eyring_Eq.py') 30 | from UI.Eyring_Eq import Ui_Eyring_Eq 31 | 32 | 33 | def evaluate_expression(expression: str) -> Optional[float]: 34 | if "~" in expression: # 处理近似为100表示为“~100”时,程序认为“~”是bitwise not操作符的问题。 35 | return None 36 | expression = expression.replace(' × 10^', 'E') 37 | try: 38 | ret = eval(expression) 39 | if is_float(ret): 40 | return ret 41 | except Exception: 42 | return None 43 | 44 | 45 | class myWidget(Ui_Eyring_Eq, QtWidgets.QWidget, Qt_Widget_Common_Functions): 46 | 47 | def __init__(self): 48 | super(self.__class__, self).__init__() 49 | self.setupUi(self) 50 | self.setMinimumWidth(550) 51 | self.setMinimumHeight(366) 52 | 53 | self.k1_UNIT_HTML = "
s-1
" 54 | self.k2_UNIT_HTML = "M-1·s-1
" 55 | 56 | self.MODE_MAPPING = {"AB": self.bimolecular_AB_radioButton, 57 | "AA": self.bimolecular_AA_radioButton, 58 | "Acat": self.bimolecular_A_Cat_radioButton, 59 | "A": self.unimolecular_radioButton} 60 | self.INPUT_MAPPING: Dict[str, Qt.QLineEdit] = OrderedDict([("G", self.G_neq_lineEdit), 61 | ("T", self.temp_lineEdit), 62 | ("σ", self.sigma_lineEdit), 63 | ("kTST", self.kTST_lineEdit), 64 | ("conc1", self.conc1_lineEdit), 65 | ("conc2", self.conc2_lineEdit), 66 | ("conv", self.conversion_lineEdit), 67 | ("t", self.total_time_lineEdit)]) 68 | self.RECALC_MAPPING = {"G": "ΔG≠", 69 | "T": "temp.", 70 | "t": "time", 71 | "conv": "conv.", 72 | "kTST": "kTST"} 73 | 74 | connect_once(self.unimolecular_radioButton, self.mode_change) 75 | connect_once(self.bimolecular_AA_radioButton, self.mode_change) 76 | connect_once(self.bimolecular_AB_radioButton, self.mode_change) 77 | connect_once(self.bimolecular_A_Cat_radioButton, self.mode_change) 78 | connect_once(self.reset_all_pushButton, self.reset_all) 79 | connect_once(self.calculate_pushButton, self.calc) 80 | connect_once(self.batch_pushButton, self.batch) 81 | connect_once(self.recalc_pushButton, self.recalc) 82 | 83 | connect_once(self.conversion_lineEdit, self.check_fill_status) 84 | connect_once(self.total_time_lineEdit, self.check_fill_status) 85 | connect_once(self.temp_lineEdit, self.check_fill_status) 86 | connect_once(self.G_neq_lineEdit, self.check_fill_status) 87 | connect_once(self.kTST_lineEdit, self.check_fill_status) 88 | connect_once(self.conc2_lineEdit, self.check_fill_status) 89 | connect_once(self.conc1_lineEdit, self.check_fill_status) 90 | connect_once(self.sigma_lineEdit, self.check_fill_status) 91 | connect_once(self.total_time_lineEdit, self.smart_display_total_time) 92 | 93 | connect_once(self.temp_lineEdit, self.clear_kTST) 94 | connect_once(self.G_neq_lineEdit, self.clear_kTST) 95 | connect_once(self.sigma_lineEdit, self.clear_kTST) 96 | 97 | connect_once(self.energy_unit_comboBox.currentTextChanged, self.G_neq_unit_changed) 98 | connect_once(self.time_unit_comboBox.currentTextChanged, self.time_unit_changed) 99 | 100 | self.clear_conc1_pushButton.hide() 101 | self.clear_conc2_pushButton.hide() 102 | self.clear_G_pushButton.hide() 103 | self.clear_k_pushButton.hide() 104 | self.clear_T_pushButton.hide() 105 | self.clear_t_pushButton.hide() 106 | self.clear_conv_pushButton.hide() 107 | self.clear_sigma_pushButton.hide() 108 | 109 | self.energy_unit_comboBox_before_change = self.energy_unit_comboBox.currentText() 110 | self.time_unit_comboBox_before_change = self.time_unit_comboBox.currentText() 111 | 112 | self.last_unknowns = [] # remember which parameters to be recalculated 113 | 114 | # This is not a space. 115 | # This is an unicode blank to tell the program that the kTST is calculated, instead of user input. 116 | self.kTST_is_calculated_marker = "⠀" 117 | 118 | # 动一下,触发信号 119 | self.unimolecular_radioButton.click() 120 | self.check_fill_status() 121 | self.show() 122 | self.center_the_widget() 123 | self.resize(self.minimumSizeHint()) 124 | 125 | # def clear_G(self): 126 | # self.G_neq_lineEdit.setText("") 127 | 128 | def mode_change(self): 129 | self.check_fill_status() 130 | self.clear_kTST() 131 | if self.sender() == self.unimolecular_radioButton: 132 | print("Unimolecular Mode") 133 | self.conc1_lineEdit.hide() 134 | self.conc2_lineEdit.hide() 135 | self.conc1_label.hide() 136 | self.conc2_label.hide() 137 | self.conc1_unit_label.hide() 138 | self.conc2_unit_label.hide() 139 | self.conc1_lineEdit.setText("") 140 | self.conc2_lineEdit.setText("") 141 | self.conc1_lineEdit.setEnabled(False) 142 | self.conc2_lineEdit.setEnabled(False) 143 | self.conc1_lineEdit.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus) 144 | self.conc2_lineEdit.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus) 145 | self.kTST_unit_label.setText(self.k1_UNIT_HTML) 146 | 147 | elif self.sender() == self.bimolecular_AA_radioButton: 148 | print("A+A mode") 149 | self.conc1_lineEdit.show() 150 | self.conc2_lineEdit.hide() 151 | self.conc1_label.show() 152 | self.conc2_label.hide() 153 | self.conc1_unit_label.show() 154 | self.conc2_unit_label.hide() 155 | self.conc1_lineEdit.setEnabled(True) 156 | self.conc2_lineEdit.setEnabled(False) 157 | self.conc1_lineEdit.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus) 158 | self.conc2_lineEdit.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus) 159 | self.conc2_lineEdit.setText("") 160 | self.conc2_label.setText("Conc. A") 161 | self.kTST_unit_label.setText(self.k2_UNIT_HTML) 162 | 163 | elif self.sender() == self.bimolecular_AB_radioButton: 164 | print("A+B mode") 165 | self.conc1_lineEdit.show() 166 | self.conc2_lineEdit.show() 167 | self.conc1_label.show() 168 | self.conc2_label.show() 169 | self.conc1_unit_label.show() 170 | self.conc2_unit_label.show() 171 | self.conc1_lineEdit.setEnabled(True) 172 | self.conc2_lineEdit.setEnabled(True) 173 | self.conc1_lineEdit.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus) 174 | self.conc2_lineEdit.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus) 175 | self.kTST_unit_label.setText(self.k2_UNIT_HTML) 176 | self.conc2_label.setText("Conc. B") 177 | 178 | elif self.sender() == self.bimolecular_A_Cat_radioButton: 179 | print("A+Cat mode") 180 | self.conc1_lineEdit.hide() 181 | self.conc2_lineEdit.show() 182 | self.conc1_label.hide() 183 | self.conc2_label.show() 184 | self.conc1_unit_label.hide() 185 | self.conc2_unit_label.show() 186 | self.conc1_lineEdit.setEnabled(False) 187 | self.conc2_lineEdit.setEnabled(True) 188 | self.conc1_lineEdit.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus) 189 | self.conc2_lineEdit.setFocusPolicy(QtCore.Qt.FocusPolicy.StrongFocus) 190 | self.kTST_unit_label.setText(self.k2_UNIT_HTML) 191 | self.conc2_label.setText("Conc. Cat") 192 | 193 | def reset_all(self): 194 | self.G_neq_lineEdit.setText("") 195 | self.energy_unit_comboBox.setCurrentText("kJ/mol") 196 | self.temp_lineEdit.setText("") 197 | self.conc1_lineEdit.setText("") 198 | self.conc2_lineEdit.setText("") 199 | self.sigma_lineEdit.setText("1") 200 | self.total_time_lineEdit.setText("") 201 | self.time_unit_comboBox.setCurrentText("s") 202 | self.conversion_lineEdit.setText("98") 203 | # self.unimolecular_radioButton.click() 204 | 205 | def clear_kTST(self): 206 | if self.kTST_lineEdit.text().startswith(self.kTST_is_calculated_marker): 207 | self.kTST_lineEdit.setText("") 208 | 209 | def smart_display_total_time(self): 210 | if self.data["t"] and self.data["t"] > 60: 211 | self.total_time_display_label.setText("= " + smart_print_time(self.data["t"])) 212 | else: 213 | self.total_time_display_label.setText("") 214 | 215 | def G_neq_unit_changed(self, energy_unit): 216 | if self.data['G'] is None: 217 | ret_lineEdit_content = "" 218 | elif energy_unit == 'kJ/mol': 219 | ret_lineEdit_content = self.data['G'] / 1000 220 | elif energy_unit == "kcal/mol": 221 | ret_lineEdit_content = self.data['G'] / 1000 / kcal__kJ 222 | elif energy_unit == "eV": 223 | ret_lineEdit_content = self.data['G'] / 1000 / eV__kJ 224 | else: 225 | raise Exception("ComboBox Error") 226 | 227 | # 统一保留5位有效数字 228 | if ret_lineEdit_content: 229 | if ret_lineEdit_content > 100000: 230 | ret_lineEdit_content = str(int(ret_lineEdit_content)) 231 | else: 232 | ret_lineEdit_content = "{:.5g}".format(ret_lineEdit_content) 233 | 234 | self.G_neq_lineEdit.setText(ret_lineEdit_content) 235 | self.energy_unit_comboBox_before_change = energy_unit 236 | 237 | def time_unit_changed(self, t_unit): 238 | if self.data['t'] is None: 239 | ret_lineEdit_content = "" 240 | elif t_unit == 's': 241 | ret_lineEdit_content = self.data['t'] 242 | elif t_unit == 'min': 243 | ret_lineEdit_content = self.data['t'] / 60 244 | elif t_unit == 'h': 245 | ret_lineEdit_content = self.data['t'] / 3600 246 | elif t_unit == 'd': 247 | ret_lineEdit_content = self.data['t'] / 86400 248 | elif t_unit == 'year': 249 | ret_lineEdit_content = self.data['t'] / 86400 / 365 250 | else: 251 | raise Exception("ComboBox Error") 252 | 253 | # 统一保留5位有效数字 254 | if ret_lineEdit_content: 255 | if ret_lineEdit_content > 100000: 256 | ret_lineEdit_content = str(int(ret_lineEdit_content)) 257 | else: 258 | ret_lineEdit_content = "{:.4g}".format(ret_lineEdit_content) 259 | 260 | self.total_time_lineEdit.setText(ret_lineEdit_content) 261 | self.time_unit_comboBox_before_change = t_unit 262 | 263 | def set_kTST_lineEdit(self, kTST): 264 | if self.unimolecular_radioButton.isChecked(): 265 | self.kTST_lineEdit.setText(self.kTST_is_calculated_marker + smart_format_float(kTST)) 266 | else: 267 | self.kTST_lineEdit.setText(self.kTST_is_calculated_marker + smart_format_float(kTST * 1000)) 268 | 269 | def check_reasonable_input(self): 270 | 271 | self.G_neq_lineEdit.setStyleSheet("") 272 | self.temp_lineEdit.setStyleSheet("") 273 | self.total_time_lineEdit.setStyleSheet("") 274 | self.sigma_lineEdit.setStyleSheet("") 275 | self.kTST_lineEdit.setStyleSheet("") 276 | self.conc1_lineEdit.setStyleSheet("") 277 | self.conc2_lineEdit.setStyleSheet("") 278 | self.conversion_lineEdit.setStyleSheet("") 279 | 280 | if self.data['G'] is not None and self.data['G'] <= 0: 281 | self.G_neq_lineEdit.setStyleSheet("background-color: rgb(255, 219, 219);") 282 | self.data['G'] = None 283 | 284 | if self.data['t'] is not None and self.data['t'] <= 0: 285 | self.total_time_lineEdit.setStyleSheet("background-color: rgb(255, 219, 219);") 286 | self.data['t'] = None 287 | 288 | if self.data['T'] is not None and self.data['T'] <= 1: 289 | self.temp_lineEdit.setStyleSheet("background-color: rgb(255, 219, 219);") 290 | self.data['T'] = None 291 | 292 | if self.data['c1'] is not None and self.data['c1'] <= 0: 293 | self.conc1_lineEdit.setStyleSheet("background-color: rgb(255, 219, 219);") 294 | self.data['c1'] = None 295 | 296 | if self.data['c2'] is not None and self.data['c2'] <= 0: 297 | self.conc2_lineEdit.setStyleSheet("background-color: rgb(255, 219, 219);") 298 | self.data['c2'] = None 299 | 300 | if self.data['conv'] is not None and not 0 < self.data['conv'] < 100: 301 | self.conversion_lineEdit.setStyleSheet("background-color: rgb(255, 219, 219);") 302 | self.data['conv'] = None 303 | 304 | def check_fill_status(self): 305 | self.data = {"G": evaluate_expression(self.G_neq_lineEdit.text()), 306 | "T": evaluate_expression(self.temp_lineEdit.text()), 307 | "c1": evaluate_expression(self.conc1_lineEdit.text()), 308 | "c2": evaluate_expression(self.conc2_lineEdit.text()), 309 | "t": evaluate_expression(self.total_time_lineEdit.text()), 310 | "conv": evaluate_expression(self.conversion_lineEdit.text()), 311 | "σ": evaluate_expression(self.sigma_lineEdit.text())} 312 | 313 | self.conv_label.setText("Conv. A") 314 | if self.bimolecular_AB_radioButton.isChecked(): 315 | if self.data["c1"] is not None and self.data["c2"] is not None: 316 | if self.data["c1"] <= self.data["c2"]: 317 | self.conv_label.setText("Conv. A") 318 | else: 319 | self.conv_label.setText("Conv. B") 320 | 321 | # Change to SI units 322 | if self.data['G'] is not None: 323 | G_unit = self.energy_unit_comboBox.currentText() 324 | if G_unit == 'kJ/mol': 325 | self.data['G'] *= 1000 # kJ-> J 326 | elif G_unit == "kcal/mol": 327 | self.data['G'] *= 1000 * kcal__kJ # kcal-> J 328 | elif G_unit == "eV": 329 | self.data['G'] *= 1000 * eV__kJ # kcal-> J 330 | else: 331 | raise Exception("ComboBox Error") 332 | 333 | if self.data['t'] is not None: 334 | t_unit = self.time_unit_comboBox.currentText() 335 | if t_unit == 's': 336 | pass 337 | elif t_unit == 'min': 338 | self.data['t'] *= 60 339 | elif t_unit == 'h': 340 | self.data['t'] *= 3600 341 | elif t_unit == 'd': 342 | self.data['t'] *= 86400 343 | elif t_unit == 'year': 344 | self.data['t'] *= 86400 * 365 345 | else: 346 | raise Exception("ComboBox Error") 347 | 348 | if self.data['T'] is not None: 349 | self.data['T'] += 273 350 | 351 | if self.data['c1'] is not None: 352 | self.data['c1'] *= 1000 # mol/L -> mol/m^3 353 | 354 | if self.data['c2'] is not None: 355 | self.data['c2'] *= 1000 # mol/L -> mol/m^3 356 | 357 | if self.data['conv'] is not None: 358 | self.data['conv'] /= 100 # percent to number 359 | 360 | if self.kTST_lineEdit.text().startswith(self.kTST_is_calculated_marker): 361 | self.data['kTST'] = None 362 | else: 363 | self.data['kTST'] = evaluate_expression(self.kTST_lineEdit.text()) 364 | if not self.unimolecular_radioButton.isChecked() and self.data['kTST']: 365 | self.data['kTST'] /= 1000 # L/mol·s --> m3/mol·s 366 | 367 | self.check_reasonable_input() 368 | 369 | self.is_None = set([key for key, value in self.data.items() if value is None]) 370 | if self.unimolecular_radioButton.isChecked(): 371 | self.is_None.discard("c2") 372 | self.is_None.discard("c1") 373 | elif self.bimolecular_AA_radioButton.isChecked(): 374 | self.is_None.discard("c2") 375 | elif self.bimolecular_A_Cat_radioButton.isChecked(): 376 | self.is_None.discard("c1") 377 | 378 | allowed_missing_situations = [["G", 'kTST'], 379 | ["T", 'kTST'], 380 | ["t", 'kTST'], 381 | ["conv", 'kTST'], 382 | ["G", 't'], 383 | ["G", 'conv'], 384 | ["T", 't'], 385 | ["T", 'conv']] 386 | 387 | calc_allowed = any([set(x) == self.is_None for x in allowed_missing_situations]) 388 | self.calculate_pushButton.setEnabled(calc_allowed) 389 | 390 | if len(self.last_unknowns) == 2: 391 | recalc_allowed = any([set(x) == set(list(self.is_None) + self.last_unknowns) for x in allowed_missing_situations]) 392 | self.recalc_pushButton.setEnabled(recalc_allowed) 393 | else: 394 | self.recalc_pushButton.setEnabled(False) 395 | 396 | def calc(self): 397 | self.last_unknowns = [] 398 | 399 | # 确定各模式的Eyring方程的delta-n, 指定各模式动力学的求解函数 400 | if self.unimolecular_radioButton.isChecked(): 401 | Δn = 0 402 | 403 | def k_from_kinetics(conv, time, conc1=None, conc2=None): 404 | return first_order_k_TST(conv, time) 405 | 406 | def t_from_kinetics(kTST, conv, conc1=None, conc2=None): 407 | return first_order_reaction_time(kTST, conv) 408 | 409 | def conv_from_kinetics(kTST, time, conc1=None, conc2=None): 410 | return first_order_conversion(kTST, time) 411 | 412 | elif self.bimolecular_AA_radioButton.isChecked(): 413 | Δn = 1 414 | 415 | def k_from_kinetics(conv, time, conc1, conc2=None): 416 | return second_order_k_TST_A_plus_A(conv, time, conc1) 417 | 418 | def t_from_kinetics(kTST, conv, conc1, conc2=None): 419 | return second_order_reaction_time_A_plus_A(kTST, conv, conc1) 420 | 421 | def conv_from_kinetics(kTST, time, conc1, conc2=None): 422 | return second_order_conv_A_plus_A(kTST, time, conc1) 423 | 424 | elif self.bimolecular_AB_radioButton.isChecked(): 425 | Δn = 1 426 | 427 | def k_from_kinetics(conv, time, conc1, conc2): 428 | if conc1 == conc2: 429 | return second_order_k_TST_A_plus_A(conv, time, conc1) 430 | else: 431 | return second_order_k_TST_A_plus_B(conv, time, conc1, conc2) 432 | 433 | def t_from_kinetics(kTST, conv, conc1, conc2): 434 | if conc1 == conc2: 435 | return second_order_reaction_time_A_plus_A(kTST, conv, conc1) 436 | else: 437 | return second_order_reaction_time_A_plus_B(kTST, conv, conc1, conc2) 438 | 439 | def conv_from_kinetics(kTST, time, conc1, conc2): 440 | if conc1 == conc2: 441 | return second_order_conv_A_plus_A(kTST, time, conc1) 442 | else: 443 | return second_order_conv_A_plus_B(kTST, time, conc1, conc2) 444 | 445 | elif self.bimolecular_A_Cat_radioButton.isChecked(): 446 | Δn = 1 447 | 448 | # 把浓度并入速率常数,变成一级动力学 449 | def k_from_kinetics(conv, time, conc1, conc_cat): 450 | return first_order_k_TST(conv, time) / conc_cat 451 | 452 | def t_from_kinetics(kTST, conv, conc1, conc_cat): 453 | return first_order_reaction_time(kTST * conc_cat, conv) 454 | 455 | def conv_from_kinetics(kTST, time, conc1, conc_cat): 456 | return first_order_conversion(kTST * conc_cat, time) 457 | else: 458 | raise Exception("None of the radioButtons is checked.") 459 | 460 | G, T, c1, c2, t, conv, σ, kTST = [self.data[key] for key in ["G", "T", "c1", "c2", "t", "conv", "σ", 'kTST']] 461 | 462 | # 知道动力学,从动力学逆推kTST 463 | if "t" not in self.is_None and 'conv' not in self.is_None: 464 | kTST = k_from_kinetics(conv, t, c1, c2) 465 | self.set_kTST_lineEdit(kTST) 466 | self.last_unknowns.append("kTST") 467 | 468 | if kTST: 469 | if "G" in self.is_None: # 知道G不知道T 470 | G = solve_for_ΔG(kTST, Δn, σ, T) 471 | # 把能量时间单位换回kJ/mol,填入答案,再把单位切换到想要的单位,这样对应的slot会自动换算单位 472 | current_energy_unit = self.energy_unit_comboBox.currentText() 473 | self.energy_unit_comboBox.setCurrentText("kJ/mol") 474 | self.G_neq_lineEdit.setText(smart_format_float(G / 1000, precision=4)) 475 | self.last_unknowns.append("G") 476 | self.energy_unit_comboBox.setCurrentText(current_energy_unit) 477 | 478 | elif "T" in self.is_None: # 知道T不知道G 479 | T = solve_for_T(kTST, Δn, σ, G) 480 | self.temp_lineEdit.setText(smart_format_float(T - 273.15, scientific_notation_limit=6)) 481 | self.last_unknowns.append("T") 482 | 483 | # 不知道动力学,从kTST算时间、转化率 484 | if "G" not in self.is_None and "T" not in self.is_None: 485 | print(f"Calculating rate constant from TST.\n Δn: {Δn}, σ: {σ}, T: {T} K, ΔG: {G} J/mol.") 486 | kTST = get_k_TST(Δn, σ, T, G) 487 | self.set_kTST_lineEdit(kTST) 488 | self.last_unknowns.append("kTST") 489 | if "t" in self.is_None: 490 | t = t_from_kinetics(kTST, conv, c1, c2) 491 | 492 | # 把时间单位换回秒,填入答案,再把单位切换到想要的单位,这样对应的slot会自动换算单位 493 | current_time_unit = self.time_unit_comboBox.currentText() 494 | self.time_unit_comboBox.setCurrentText("s") 495 | self.total_time_lineEdit.setText(smart_format_float(t)) 496 | self.last_unknowns.append("t") 497 | self.time_unit_comboBox.setCurrentText(current_time_unit) 498 | 499 | elif 'conv' in self.is_None: 500 | conv = conv_from_kinetics(kTST, t, c1, c2) 501 | self.last_unknowns.append("conv") 502 | if conv == 1: 503 | self.conversion_lineEdit.setText("~100") 504 | else: 505 | self.conversion_lineEdit.setText(smart_format_float(conv * 100)) 506 | 507 | self.last_unknowns = list(set(self.last_unknowns)) 508 | assert len(self.last_unknowns) == 2 509 | self.recalc_pushButton.setText("Recalc. " + self.RECALC_MAPPING[self.last_unknowns[0]] + " && " + 510 | self.RECALC_MAPPING[self.last_unknowns[1]]) 511 | print("---------------------------------\n\n") 512 | 513 | def automation(self, 514 | input_data: Dict[str, str or Real], 515 | units: Sequence[str], 516 | missing_parameters: Sequence[str] = (), 517 | redirect_sys_output=False): 518 | """ 519 | 520 | Args: 521 | units: a 2-tuple [energy_unit (kJ/mol, kcal/mol, eV), time_unit (s, min, h, d, year)] 522 | input_data: a dict missing the correct parameters for calculation, the unit of the data is the unit used in the GUI 523 | 524 | missing_parameters: This parameter is only used in Verification.py, 525 | Include to calculate and return which parameter, select from the standard key of standard keys 526 | 527 | redirect_sys_output: This is used in verification.py, to suppress excessive output when testing multiple cases 528 | 529 | (standard keys: mode, G, T, kTST, conc1, conc2, conv, t) 530 | 531 | e.g. missing kTST and t: { 532 | "mode": "AB", 533 | "T": 25, 534 | "conc1": 0.5, 535 | "conc2": 1.2, 536 | "G": 15, 537 | "conv": 15 538 | }, 539 | Returns: 540 | The value of the missed parameters 541 | 542 | """ 543 | if redirect_sys_output: 544 | old_stdout = sys.stdout 545 | sys.stdout = None 546 | 547 | self.reset_all() 548 | self.conversion_lineEdit.setText("") 549 | 550 | self.energy_unit_comboBox.setCurrentText(units[0]) 551 | self.time_unit_comboBox.setCurrentText(units[1]) 552 | 553 | for key in input_data: 554 | if key == 'mode': 555 | self.MODE_MAPPING[input_data[key]].click() 556 | else: 557 | self.INPUT_MAPPING[key].setText(str(input_data[key])) 558 | 559 | # automation test case 有问题 560 | if not self.calculate_pushButton.isEnabled(): 561 | print(input_data, units, missing_parameters) 562 | for key, value in self.MODE_MAPPING.items(): 563 | print(key, repr(value.isChecked())) 564 | for key, value in self.INPUT_MAPPING.items(): 565 | print(key, repr(value.text())) 566 | print("Energy Unit:", self.energy_unit_comboBox.currentText()) 567 | print("Time Unit:", self.time_unit_comboBox.currentText()) 568 | raise Exception("Calculate PushButton not enabled error.") 569 | 570 | self.calculate_pushButton.click() 571 | Application.processEvents() 572 | 573 | ret = [] 574 | if missing_parameters: 575 | for i in missing_parameters: 576 | ret.append(self.INPUT_MAPPING[i].text()) 577 | 578 | if redirect_sys_output: 579 | sys.stdout = old_stdout 580 | 581 | return ret 582 | 583 | def recalc(self): 584 | for i in self.last_unknowns: 585 | self.INPUT_MAPPING[i].setText("") 586 | if self.calculate_pushButton.isEnabled(): 587 | self.calculate_pushButton.click() 588 | 589 | def batch(self): 590 | opened_xlsxs = get_open_file_UI(self, 591 | "", 592 | 'xlsx', 593 | 'Select batch input file created by filling the table from Batch_Template.xltx') 594 | for opened_xlsx in opened_xlsxs: 595 | self.run_batch(opened_xlsx) 596 | 597 | def run_batch(self, xlsx_input): 598 | """ 599 | Run batch calculation from an xlsx input 600 | Args: 601 | xlsx_input: an xlsx input file created by filling Batch/Batch_Template.xltx 602 | 603 | Returns: 604 | 605 | """ 606 | 607 | # build output xlsx 608 | xlsx_output = get_unused_filename(filename_class(os.path.realpath(xlsx_input)).replace_append_to("Eyring_Eq_Output.xlsx"), 609 | use_proper_filename=False) 610 | xlsx_content = read_xlsx(xlsx_input) 611 | workbook = openpyxl.load_workbook(xlsx_input) 612 | worksheet = workbook[workbook.sheetnames[0]] 613 | 614 | HEADER_TO_DICT_KEY = {"Mode (A, AA, AB, Acat)": "mode", 615 | "ΔG≠ (selected unit)": "G", 616 | "ΔG≠ unit\n(kJ/mol, kcal/mol, eV)": "energy_unit", 617 | "Temperature (°C)": "T", 618 | "σ (default 1)": "σ", 619 | "kTST (s-1 or M-1·s-1)": "kTST", 620 | "Conc. 1 (mol/L)": "conc1", 621 | "Conc. 2 (mol/L)": "conc2", 622 | "Conversion (%)": "conv", 623 | "Reaction time (selected unit)": "t", 624 | "Reaction time unit\n(s, min, h, d, year)": "time_unit"} 625 | 626 | xlsx_content = transpose_2d_list(xlsx_content) # 横纵交换,一行一个case 627 | HEADER_TO_DICT_KEY_XLSX_ORDER = OrderedDict() 628 | # reorder the header so it's in the same order as the input xlsx 629 | for header in xlsx_content[0]: 630 | HEADER_TO_DICT_KEY_XLSX_ORDER[header] = HEADER_TO_DICT_KEY[header] 631 | 632 | for case_count, test_case in enumerate(xlsx_content[1:]): 633 | xlsx_input_dict = {} 634 | for parameter_count, parameter in enumerate(xlsx_content[0]): 635 | xlsx_input_dict[HEADER_TO_DICT_KEY_XLSX_ORDER[parameter]] = test_case[parameter_count] 636 | units = [xlsx_input_dict.pop('energy_unit'), xlsx_input_dict.pop('time_unit')] 637 | 638 | self.automation(xlsx_input_dict, units) 639 | Application.processEvents() 640 | 641 | ret = [xlsx_input_dict.pop('mode')] 642 | for key in xlsx_input_dict.keys(): 643 | ret.append(self.INPUT_MAPPING[key].text()) 644 | HEADER_VALUE_LIST = list(HEADER_TO_DICT_KEY_XLSX_ORDER.values()) 645 | ret.insert(HEADER_VALUE_LIST.index("energy_unit"), self.energy_unit_comboBox.currentText()) 646 | ret.insert(HEADER_VALUE_LIST.index("time_unit"), self.time_unit_comboBox.currentText()) 647 | 648 | for row_count, data in enumerate(ret): 649 | cell = worksheet.cell(row=row_count + 1, column=case_count + 2, value=data.strip(self.kTST_is_calculated_marker)) 650 | cell.alignment = openpyxl.styles.Alignment(horizontal='center', vertical='center') 651 | 652 | workbook.save(xlsx_output) 653 | open_explorer_and_select(xlsx_output) 654 | print(f"Batch processing of {xlsx_input} finished.") 655 | 656 | 657 | if __name__ == '__main__': 658 | my_Qt_Program = myWidget() 659 | my_Qt_Program.show() 660 | 661 | sys.exit(Application.exec()) 662 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Attribution-NonCommercial-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International 58 | Public License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-NonCommercial-ShareAlike 4.0 International Public License 63 | ("Public License"). To the extent this Public License may be 64 | interpreted as a contract, You are granted the Licensed Rights in 65 | consideration of Your acceptance of these terms and conditions, and the 66 | Licensor grants You such rights in consideration of benefits the 67 | Licensor receives from making the Licensed Material available under 68 | these terms and conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-NC-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution, NonCommercial, and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. NonCommercial means not primarily intended for or directed towards 126 | commercial advantage or monetary compensation. For purposes of 127 | this Public License, the exchange of the Licensed Material for 128 | other material subject to Copyright and Similar Rights by digital 129 | file-sharing or similar means is NonCommercial provided there is 130 | no payment of monetary compensation in connection with the 131 | exchange. 132 | 133 | l. Share means to provide material to the public by any means or 134 | process that requires permission under the Licensed Rights, such 135 | as reproduction, public display, public performance, distribution, 136 | dissemination, communication, or importation, and to make material 137 | available to the public including in ways that members of the 138 | public may access the material from a place and at a time 139 | individually chosen by them. 140 | 141 | m. Sui Generis Database Rights means rights other than copyright 142 | resulting from Directive 96/9/EC of the European Parliament and of 143 | the Council of 11 March 1996 on the legal protection of databases, 144 | as amended and/or succeeded, as well as other essentially 145 | equivalent rights anywhere in the world. 146 | 147 | n. You means the individual or entity exercising the Licensed Rights 148 | under this Public License. Your has a corresponding meaning. 149 | 150 | 151 | Section 2 -- Scope. 152 | 153 | a. License grant. 154 | 155 | 1. Subject to the terms and conditions of this Public License, 156 | the Licensor hereby grants You a worldwide, royalty-free, 157 | non-sublicensable, non-exclusive, irrevocable license to 158 | exercise the Licensed Rights in the Licensed Material to: 159 | 160 | a. reproduce and Share the Licensed Material, in whole or 161 | in part, for NonCommercial purposes only; and 162 | 163 | b. produce, reproduce, and Share Adapted Material for 164 | NonCommercial purposes only. 165 | 166 | 2. Exceptions and Limitations. For the avoidance of doubt, where 167 | Exceptions and Limitations apply to Your use, this Public 168 | License does not apply, and You do not need to comply with 169 | its terms and conditions. 170 | 171 | 3. Term. The term of this Public License is specified in Section 172 | 6(a). 173 | 174 | 4. Media and formats; technical modifications allowed. The 175 | Licensor authorizes You to exercise the Licensed Rights in 176 | all media and formats whether now known or hereafter created, 177 | and to make technical modifications necessary to do so. The 178 | Licensor waives and/or agrees not to assert any right or 179 | authority to forbid You from making technical modifications 180 | necessary to exercise the Licensed Rights, including 181 | technical modifications necessary to circumvent Effective 182 | Technological Measures. For purposes of this Public License, 183 | simply making modifications authorized by this Section 2(a) 184 | (4) never produces Adapted Material. 185 | 186 | 5. Downstream recipients. 187 | 188 | a. Offer from the Licensor -- Licensed Material. Every 189 | recipient of the Licensed Material automatically 190 | receives an offer from the Licensor to exercise the 191 | Licensed Rights under the terms and conditions of this 192 | Public License. 193 | 194 | b. Additional offer from the Licensor -- Adapted Material. 195 | Every recipient of Adapted Material from You 196 | automatically receives an offer from the Licensor to 197 | exercise the Licensed Rights in the Adapted Material 198 | under the conditions of the Adapter's License You apply. 199 | 200 | c. No downstream restrictions. You may not offer or impose 201 | any additional or different terms or conditions on, or 202 | apply any Effective Technological Measures to, the 203 | Licensed Material if doing so restricts exercise of the 204 | Licensed Rights by any recipient of the Licensed 205 | Material. 206 | 207 | 6. No endorsement. Nothing in this Public License constitutes or 208 | may be construed as permission to assert or imply that You 209 | are, or that Your use of the Licensed Material is, connected 210 | with, or sponsored, endorsed, or granted official status by, 211 | the Licensor or others designated to receive attribution as 212 | provided in Section 3(a)(1)(A)(i). 213 | 214 | b. Other rights. 215 | 216 | 1. Moral rights, such as the right of integrity, are not 217 | licensed under this Public License, nor are publicity, 218 | privacy, and/or other similar personality rights; however, to 219 | the extent possible, the Licensor waives and/or agrees not to 220 | assert any such rights held by the Licensor to the limited 221 | extent necessary to allow You to exercise the Licensed 222 | Rights, but not otherwise. 223 | 224 | 2. Patent and trademark rights are not licensed under this 225 | Public License. 226 | 227 | 3. To the extent possible, the Licensor waives any right to 228 | collect royalties from You for the exercise of the Licensed 229 | Rights, whether directly or through a collecting society 230 | under any voluntary or waivable statutory or compulsory 231 | licensing scheme. In all other cases the Licensor expressly 232 | reserves any right to collect such royalties, including when 233 | the Licensed Material is used other than for NonCommercial 234 | purposes. 235 | 236 | 237 | Section 3 -- License Conditions. 238 | 239 | Your exercise of the Licensed Rights is expressly made subject to the 240 | following conditions. 241 | 242 | a. Attribution. 243 | 244 | 1. If You Share the Licensed Material (including in modified 245 | form), You must: 246 | 247 | a. retain the following if it is supplied by the Licensor 248 | with the Licensed Material: 249 | 250 | i. identification of the creator(s) of the Licensed 251 | Material and any others designated to receive 252 | attribution, in any reasonable manner requested by 253 | the Licensor (including by pseudonym if 254 | designated); 255 | 256 | ii. a copyright notice; 257 | 258 | iii. a notice that refers to this Public License; 259 | 260 | iv. a notice that refers to the disclaimer of 261 | warranties; 262 | 263 | v. a URI or hyperlink to the Licensed Material to the 264 | extent reasonably practicable; 265 | 266 | b. indicate if You modified the Licensed Material and 267 | retain an indication of any previous modifications; and 268 | 269 | c. indicate the Licensed Material is licensed under this 270 | Public License, and include the text of, or the URI or 271 | hyperlink to, this Public License. 272 | 273 | 2. You may satisfy the conditions in Section 3(a)(1) in any 274 | reasonable manner based on the medium, means, and context in 275 | which You Share the Licensed Material. For example, it may be 276 | reasonable to satisfy the conditions by providing a URI or 277 | hyperlink to a resource that includes the required 278 | information. 279 | 3. If requested by the Licensor, You must remove any of the 280 | information required by Section 3(a)(1)(A) to the extent 281 | reasonably practicable. 282 | 283 | b. ShareAlike. 284 | 285 | In addition to the conditions in Section 3(a), if You Share 286 | Adapted Material You produce, the following conditions also apply. 287 | 288 | 1. The Adapter's License You apply must be a Creative Commons 289 | license with the same License Elements, this version or 290 | later, or a BY-NC-SA Compatible License. 291 | 292 | 2. You must include the text of, or the URI or hyperlink to, the 293 | Adapter's License You apply. You may satisfy this condition 294 | in any reasonable manner based on the medium, means, and 295 | context in which You Share Adapted Material. 296 | 297 | 3. You may not offer or impose any additional or different terms 298 | or conditions on, or apply any Effective Technological 299 | Measures to, Adapted Material that restrict exercise of the 300 | rights granted under the Adapter's License You apply. 301 | 302 | 303 | Section 4 -- Sui Generis Database Rights. 304 | 305 | Where the Licensed Rights include Sui Generis Database Rights that 306 | apply to Your use of the Licensed Material: 307 | 308 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 309 | to extract, reuse, reproduce, and Share all or a substantial 310 | portion of the contents of the database for NonCommercial purposes 311 | only; 312 | 313 | b. if You include all or a substantial portion of the database 314 | contents in a database in which You have Sui Generis Database 315 | Rights, then the database in which You have Sui Generis Database 316 | Rights (but not its individual contents) is Adapted Material, 317 | including for purposes of Section 3(b); and 318 | 319 | c. You must comply with the conditions in Section 3(a) if You Share 320 | all or a substantial portion of the contents of the database. 321 | 322 | For the avoidance of doubt, this Section 4 supplements and does not 323 | replace Your obligations under this Public License where the Licensed 324 | Rights include other Copyright and Similar Rights. 325 | 326 | 327 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 328 | 329 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 330 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 331 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 332 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 333 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 334 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 335 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 336 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 337 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 338 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 339 | 340 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 341 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 342 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 343 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 344 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 345 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 346 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 347 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 348 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 349 | 350 | c. The disclaimer of warranties and limitation of liability provided 351 | above shall be interpreted in a manner that, to the extent 352 | possible, most closely approximates an absolute disclaimer and 353 | waiver of all liability. 354 | 355 | 356 | Section 6 -- Term and Termination. 357 | 358 | a. This Public License applies for the term of the Copyright and 359 | Similar Rights licensed here. However, if You fail to comply with 360 | this Public License, then Your rights under this Public License 361 | terminate automatically. 362 | 363 | b. Where Your right to use the Licensed Material has terminated under 364 | Section 6(a), it reinstates: 365 | 366 | 1. automatically as of the date the violation is cured, provided 367 | it is cured within 30 days of Your discovery of the 368 | violation; or 369 | 370 | 2. upon express reinstatement by the Licensor. 371 | 372 | For the avoidance of doubt, this Section 6(b) does not affect any 373 | right the Licensor may have to seek remedies for Your violations 374 | of this Public License. 375 | 376 | c. For the avoidance of doubt, the Licensor may also offer the 377 | Licensed Material under separate terms or conditions or stop 378 | distributing the Licensed Material at any time; however, doing so 379 | will not terminate this Public License. 380 | 381 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 382 | License. 383 | 384 | 385 | Section 7 -- Other Terms and Conditions. 386 | 387 | a. The Licensor shall not be bound by any additional or different 388 | terms or conditions communicated by You unless expressly agreed. 389 | 390 | b. Any arrangements, understandings, or agreements regarding the 391 | Licensed Material not stated herein are separate from and 392 | independent of the terms and conditions of this Public License. 393 | 394 | 395 | Section 8 -- Interpretation. 396 | 397 | a. For the avoidance of doubt, this Public License does not, and 398 | shall not be interpreted to, reduce, limit, restrict, or impose 399 | conditions on any use of the Licensed Material that could lawfully 400 | be made without permission under this Public License. 401 | 402 | b. To the extent possible, if any provision of this Public License is 403 | deemed unenforceable, it shall be automatically reformed to the 404 | minimum extent necessary to make it enforceable. If the provision 405 | cannot be reformed, it shall be severed from this Public License 406 | without affecting the enforceability of the remaining terms and 407 | conditions. 408 | 409 | c. No term or condition of this Public License will be waived and no 410 | failure to comply consented to unless expressly agreed to by the 411 | Licensor. 412 | 413 | d. Nothing in this Public License constitutes or may be interpreted 414 | as a limitation upon, or waiver of, any privileges and immunities 415 | that apply to the Licensor or You, including from the legal 416 | processes of any jurisdiction or authority. 417 | 418 | ======================================================================= 419 | 420 | Creative Commons is not a party to its public 421 | licenses. Notwithstanding, Creative Commons may elect to apply one of 422 | its public licenses to material it publishes and in those instances 423 | will be considered the “Licensor.” The text of the Creative Commons 424 | public licenses is dedicated to the public domain under the CC0 Public 425 | Domain Dedication. Except for the limited purpose of indicating that 426 | material is shared under a Creative Commons public license or as 427 | otherwise permitted by the Creative Commons policies published at 428 | creativecommons.org/policies, Creative Commons does not authorize the 429 | use of the trademark "Creative Commons" or any other trademark or logo 430 | of Creative Commons without its prior written consent including, 431 | without limitation, in connection with any unauthorized modifications 432 | to any of its public licenses or any other arrangements, 433 | understandings, or agreements concerning use of licensed material. For 434 | the avoidance of doubt, this paragraph does not form part of the 435 | public licenses. 436 | 437 | Creative Commons may be contacted at creativecommons.org. -------------------------------------------------------------------------------- /Lib.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | __author__ = 'LiYuanhe' 3 | 4 | from Python_Lib.My_Lib_Stock import * 5 | from scipy.optimize import fsolve 6 | import numpy as np 7 | 8 | 9 | # All SI units 10 | # conc: Concentration in mol/m^3 11 | # P: Pressure in pa 12 | # ΔG: Activation Gibbs free energy in J/mol 13 | # T: Temperature in K 14 | # t: Time 15 | # σ: degeneracy,http://sobereva.com/310 16 | # Δn: 0 for unimolecular, 1 for bimolecular 17 | # k_TST: TST kinetic constant, first order s^-1, second order m^3·mol^-1·s^-1 18 | 19 | 20 | def get_k_TST(Δn, σ, T, ΔG): 21 | """ 22 | 23 | TST rate constant 24 | k_TST = (σ k_B T / h) * (R T/P0)^(n_TS - n_Sub) * exp( -ΔG≠ / R T) 25 | 26 | Returns: 27 | 28 | """ 29 | return (σ * k_B * T / h) * ((R * T / atm__Pa) ** Δn) * math.exp(-ΔG / R / T) 30 | 31 | 32 | get_k_TST_vectorize = np.vectorize(get_k_TST) 33 | 34 | 35 | # print(get_k_TST(1,1,298,15000)) 36 | 37 | 38 | def solve_equation(func, initial_guess): 39 | root = fsolve(func, initial_guess) 40 | print("Original root:", root) 41 | ret = [] 42 | for i in root: 43 | if np.isclose(func(i), 0.): 44 | if not any(np.isclose(x, i) for x in ret): 45 | ret.append(i) 46 | if len(ret) == 1: 47 | return ret[0] 48 | else: 49 | print("Solution not singular.") 50 | from Python_Lib.My_Lib_PyQt6 import warning_UI 51 | warning_UI("No valid solution find in the range set by the author.") 52 | return ret 53 | 54 | 55 | def solve_for_ΔG(k_TST, Δn, σ, T): 56 | k_TST_unit = "m3·mol-1·s-1" if Δn else "s-1" 57 | 58 | def func(ΔG): 59 | return np.log(get_k_TST_vectorize(Δn, σ, T, ΔG) / k_TST) 60 | 61 | ret = solve_equation(func, 50000) 62 | 63 | print(f"Solve ΔG from TST.\n" 64 | f" Δn: {Δn}, σ: {σ}, T: {T} K, rate constant: {k_TST} {k_TST_unit}. Answer: {ret} J/mol.") 65 | return ret 66 | 67 | 68 | # print(solve_for_ΔG(0.89/1000,1,1,298)) 69 | 70 | def solve_for_T(k_TST, Δn, σ, ΔG): 71 | k_TST_unit = "m3·mol-1·s-1" if Δn else "s-1" 72 | 73 | def func(T): 74 | return np.log(get_k_TST_vectorize(Δn, σ, T, ΔG) / k_TST) 75 | 76 | ret = solve_equation(func, 300) 77 | print(f"Solve T from TST.\n" 78 | f" Δn: {Δn}, σ: {σ}, ΔG: {ΔG} J/mol, rate constant: {k_TST} {k_TST_unit}. Answer: {ret} K.") 79 | return ret 80 | 81 | 82 | def first_order_reaction_time(k_TST, conv): 83 | half_life_count = math.log((1 - conv), 1 / 2) 84 | half_life = math.log(2) / k_TST 85 | ret = half_life_count * half_life 86 | print(f"Calculate time from first order kinetics.\n" 87 | f" Rate constant: {k_TST} s^-1, conversion: {conv}. Answer: {ret} s.") 88 | return ret 89 | 90 | 91 | def first_order_conversion(k_TST, rxn_time): 92 | half_life = math.log(2) / k_TST 93 | half_life_count = rxn_time / half_life 94 | if half_life_count > 100: # conversion too complete, return 100% 95 | ret = 1 96 | else: 97 | ret = 1 - 1 / 2 ** half_life_count 98 | print(f"Calculate conv from first order kinetics.\n" 99 | f" Rate constant: {k_TST} s^-1, time: {rxn_time} s. Answer: {ret}.") 100 | return ret 101 | 102 | 103 | def first_order_k_TST(conv, rxn_time): 104 | half_life_count = math.log((1 - conv), 1 / 2) 105 | half_life = rxn_time / half_life_count 106 | ret = math.log(2) / half_life 107 | print(f"Calculate k from first order kinetics.\n" 108 | f" Conversion: {conv}, time: {rxn_time} s. Answer: {ret} s^-1.") 109 | return ret 110 | 111 | 112 | def second_order_reaction_time_A_plus_A(k_TST, conv, conc): 113 | """ 114 | 1 / [A] = k_TST * t + 1 / [A]_0 115 | (1 / [A] - 1 / [A]_0) / k_TST 116 | """ 117 | 118 | target_conc = conc * (1 - conv) 119 | ret = (1 / target_conc - 1 / conc) / k_TST 120 | print(f"Calculate time from A+A second order kinetics.\n" 121 | f" Rate constant: {k_TST} m^3·mol^-1·s^-1, conversion: {conv} s, concentration: {conc} mol/m^3. Answer: {ret} s.") 122 | return ret 123 | 124 | 125 | def second_order_conv_A_plus_A(k_TST, rxn_time, conc): 126 | """ 127 | 1 / [A] = k_TST * t + 1 / [A]_0 128 | """ 129 | 130 | end_conc = 1 / (k_TST * rxn_time + 1 / conc) 131 | conv = 1 - end_conc / conc 132 | print(f"Calculate conv from second order kinetics.\n" 133 | f" Rate constant: {k_TST} m^3·mol^-1·s^-1, time: {rxn_time} s, concentration: {conc} mol/m^3. Answer: {conv}.") 134 | return conv 135 | 136 | 137 | def second_order_k_TST_A_plus_A(conv, rxn_time, conc): 138 | """ 139 | 1 / [A] = k_TST * t + 1 / [A]_0 140 | (1 / A - 1 / A0)/t = k_TST 141 | """ 142 | 143 | A = conc * (1 - conv) 144 | A0 = conc 145 | ret = (1 / A - 1 / A0) / rxn_time 146 | print(f"Calculate k from A+A second order kinetics.\n" 147 | f" Conversion: {conv}, time: {rxn_time} s, concentration: {conc} mol/m^3. Answer: {ret} m3·mol-1·s-1.") 148 | return ret 149 | 150 | 151 | def second_order_reaction_time_A_plus_B(k_TST, conv, conc1, conc2): 152 | """ 153 | ln([A]/[B]) = k_TST * ([A]_0 - [B]_0) * time + ln([A]_0/[B]_0) 154 | """ 155 | A0, B0 = min(conc1, conc2), max(conc1, conc2) 156 | A, B = A0 - A0 * conv, B0 - A0 * conv 157 | ret = (math.log(A / B) - math.log(A0 / B0)) / k_TST / (A0 - B0) 158 | print( 159 | f"Calculate time from A+B second order kinetics.\n" 160 | f" Rate constant: {k_TST} m^3·mol^-1·s^-1, conversion: {conv} s, concentrations: {conc1}, {conc2} mol/m^3. Answer: {ret} s.") 161 | 162 | return ret 163 | 164 | 165 | def second_order_conv_A_plus_B(k_TST, rxn_time, conc1, conc2): 166 | """ 167 | ln([A]/[B]) = k_TST * ([A]_0 - [B]_0) * time + ln([A]_0/[B]_0) 168 | ln((A0-x)/(B0-x)) = k_TST * (A0 - B0) * time + ln(A0/B0) 169 | """ 170 | 171 | A0, B0 = min(conc1, conc2), max(conc1, conc2) 172 | left = k_TST * (A0 - B0) * rxn_time + math.log(A0 / B0) # ln((A0-x)/(B0-x)) 173 | after_exp = math.exp(left) # (A0-x)/(B0-x) 174 | x = (after_exp * B0 - A0) / (after_exp - 1) 175 | conv = x / A0 176 | print(f"Calculate conv from second order kinetics.\n" 177 | f" Rate constant: {k_TST} m^3·mol^-1·s^-1, time: {rxn_time} s, concentrations: {conc1}, {conc2} mol/m^3. Answer: {conv}.") 178 | return conv 179 | 180 | 181 | def second_order_k_TST_A_plus_B(conv, rxn_time, conc1, conc2): 182 | """ 183 | ln([A]/[B]) = k_TST * ([A]_0 - [B]_0) * time + ln([A]_0/[B]_0) 184 | ln(A/B) - ln(A0/B0) = k_TST * (A0 - B0) * time 185 | (ln(A/B) - ln(A0/B0))/time/(A0-B0) = k_TST 186 | """ 187 | 188 | A0, B0 = min(conc1, conc2), max(conc1, conc2) 189 | A = A0 - A0 * conv 190 | B = B0 - A0 * conv 191 | ret = (math.log(A / B) - math.log(A0 / B0)) / rxn_time / (A0 - B0) 192 | print(f"Calculate k from A+B second order kinetics.\n" 193 | f" Conversion: {conv}, time: {rxn_time} s, concentrations: {conc1}, {conc2} mol/m^3. Answer: {ret} m3·mol-1·s-1") 194 | return ret 195 | 196 | # print(solve_for_T(math.log(2)/(8*3600),0,1,118700)) 197 | 198 | # print(second_order_conv_A_plus_A(0.89/1000,2.50E4,4.5E-2)) 199 | # print(second_order_reaction_time_A_plus_A(0.89/1000,0.5,4.5E-2)) 200 | 201 | # print(get_k_TST(1,1,298,15000)) 202 | # print(second_order_reaction_time_A_plus_B(356590343,0.451,0.5E3,1.2E3)) 203 | -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | url = "https://pypi.org/simple" 3 | verify_ssl = true 4 | name = "pypi" 5 | 6 | [packages] 7 | scipy = "*" 8 | pyqt6 = "~=6.4.2" 9 | pyinstaller = "*" 10 | pyexcel-xlsx = "*" 11 | xlsxwriter = "*" 12 | 13 | [dev-packages] 14 | pyinstaller = "*" 15 | 16 | [requires] 17 | python_version = "3.9" 18 | -------------------------------------------------------------------------------- /Pipfile.lock: -------------------------------------------------------------------------------- 1 | { 2 | "_meta": { 3 | "hash": { 4 | "sha256": "762019445e0099c3356d11df7e8389be194e24a951b8726b264245ad4424dab0" 5 | }, 6 | "pipfile-spec": 6, 7 | "requires": { 8 | "python_version": "3.9" 9 | }, 10 | "sources": [ 11 | { 12 | "name": "pypi", 13 | "url": "https://pypi.org/simple", 14 | "verify_ssl": true 15 | } 16 | ] 17 | }, 18 | "default": { 19 | "altgraph": { 20 | "hashes": [ 21 | "sha256:ad33358114df7c9416cdb8fa1eaa5852166c505118717021c6a8c7c7abbd03dd", 22 | "sha256:c8ac1ca6772207179ed8003ce7687757c04b0b71536f81e2ac5755c6226458fe" 23 | ], 24 | "version": "==0.17.3" 25 | }, 26 | "et-xmlfile": { 27 | "hashes": [ 28 | "sha256:8eb9e2bc2f8c97e37a2dc85a09ecdcdec9d8a396530a6d5a33b30b9a92da0c5c", 29 | "sha256:a2ba85d1d6a74ef63837eed693bcb89c3f752169b0e3e7ae5b16ca5e1b3deada" 30 | ], 31 | "markers": "python_version >= '3.6'", 32 | "version": "==1.1.0" 33 | }, 34 | "lml": { 35 | "hashes": [ 36 | "sha256:57a085a29bb7991d70d41c6c3144c560a8e35b4c1030ffb36d85fa058773bcc5", 37 | "sha256:ec06e850019942a485639c8c2a26bdb99eae24505bee7492b649df98a0bed101" 38 | ], 39 | "version": "==0.1.0" 40 | }, 41 | "numpy": { 42 | "hashes": [ 43 | "sha256:003a9f530e880cb2cd177cba1af7220b9aa42def9c4afc2a2fc3ee6be7eb2b22", 44 | "sha256:150947adbdfeceec4e5926d956a06865c1c690f2fd902efede4ca6fe2e657c3f", 45 | "sha256:2620e8592136e073bd12ee4536149380695fbe9ebeae845b81237f986479ffc9", 46 | "sha256:2eabd64ddb96a1239791da78fa5f4e1693ae2dadc82a76bc76a14cbb2b966e96", 47 | "sha256:4173bde9fa2a005c2c6e2ea8ac1618e2ed2c1c6ec8a7657237854d42094123a0", 48 | "sha256:4199e7cfc307a778f72d293372736223e39ec9ac096ff0a2e64853b866a8e18a", 49 | "sha256:4cecaed30dc14123020f77b03601559fff3e6cd0c048f8b5289f4eeabb0eb281", 50 | "sha256:557d42778a6869c2162deb40ad82612645e21d79e11c1dc62c6e82a2220ffb04", 51 | "sha256:63e45511ee4d9d976637d11e6c9864eae50e12dc9598f531c035265991910468", 52 | "sha256:6524630f71631be2dabe0c541e7675db82651eb998496bbe16bc4f77f0772253", 53 | "sha256:76807b4063f0002c8532cfeac47a3068a69561e9c8715efdad3c642eb27c0756", 54 | "sha256:7de8fdde0003f4294655aa5d5f0a89c26b9f22c0a58790c38fae1ed392d44a5a", 55 | "sha256:889b2cc88b837d86eda1b17008ebeb679d82875022200c6e8e4ce6cf549b7acb", 56 | "sha256:92011118955724465fb6853def593cf397b4a1367495e0b59a7e69d40c4eb71d", 57 | "sha256:97cf27e51fa078078c649a51d7ade3c92d9e709ba2bfb97493007103c741f1d0", 58 | "sha256:9a23f8440561a633204a67fb44617ce2a299beecf3295f0d13c495518908e910", 59 | "sha256:a51725a815a6188c662fb66fb32077709a9ca38053f0274640293a14fdd22978", 60 | "sha256:a77d3e1163a7770164404607b7ba3967fb49b24782a6ef85d9b5f54126cc39e5", 61 | "sha256:adbdce121896fd3a17a77ab0b0b5eedf05a9834a18699db6829a64e1dfccca7f", 62 | "sha256:c29e6bd0ec49a44d7690ecb623a8eac5ab8a923bce0bea6293953992edf3a76a", 63 | "sha256:c72a6b2f4af1adfe193f7beb91ddf708ff867a3f977ef2ec53c0ffb8283ab9f5", 64 | "sha256:d0a2db9d20117bf523dde15858398e7c0858aadca7c0f088ac0d6edd360e9ad2", 65 | "sha256:e3ab5d32784e843fc0dd3ab6dcafc67ef806e6b6828dc6af2f689be0eb4d781d", 66 | "sha256:e428c4fbfa085f947b536706a2fc349245d7baa8334f0c5723c56a10595f9b95", 67 | "sha256:e8d2859428712785e8a8b7d2b3ef0a1d1565892367b32f915c4a4df44d0e64f5", 68 | "sha256:eef70b4fc1e872ebddc38cddacc87c19a3709c0e3e5d20bf3954c147b1dd941d", 69 | "sha256:f64bb98ac59b3ea3bf74b02f13836eb2e24e48e0ab0145bbda646295769bd780", 70 | "sha256:f9006288bcf4895917d02583cf3411f98631275bc67cce355a7f39f8c14338fa" 71 | ], 72 | "markers": "python_version >= '3.8'", 73 | "version": "==1.24.2" 74 | }, 75 | "openpyxl": { 76 | "hashes": [ 77 | "sha256:a0266e033e65f33ee697254b66116a5793c15fc92daf64711080000df4cfe0a8", 78 | "sha256:f06d44e2c973781068bce5ecf860a09bcdb1c7f5ce1facd5e9aa82c92c93ae72" 79 | ], 80 | "markers": "python_version >= '3.6'", 81 | "version": "==3.1.1" 82 | }, 83 | "pefile": { 84 | "hashes": [ 85 | "sha256:82e6114004b3d6911c77c3953e3838654b04511b8b66e8583db70c65998017dc", 86 | "sha256:da185cd2af68c08a6cd4481f7325ed600a88f6a813bad9dea07ab3ef73d8d8d6" 87 | ], 88 | "markers": "sys_platform == 'win32'", 89 | "version": "==2023.2.7" 90 | }, 91 | "pyexcel-io": { 92 | "hashes": [ 93 | "sha256:19ff1d599a8a6c0982e4181ef86aa50e1f8d231410fa7e0e204d62e37551c1d6", 94 | "sha256:f6084bf1afa5fbf4c61cf7df44370fa513821af188b02e3e19b5efb66d8a969f" 95 | ], 96 | "markers": "python_version >= '3.6'", 97 | "version": "==0.6.6" 98 | }, 99 | "pyexcel-xlsx": { 100 | "hashes": [ 101 | "sha256:16530f96a77c97ebcba7941517d2756ac52d3ce2903d81eecd7f300778d5242a", 102 | "sha256:55754f764252461aca6871db203f4bd1370ec877828e305e6be1de5f9aa6a79d" 103 | ], 104 | "index": "pypi", 105 | "version": "==0.6.0" 106 | }, 107 | "pyinstaller": { 108 | "hashes": [ 109 | "sha256:314fb883caf3cbf06adbea2b77671bb73c3481568e994af0467ea7e47eb64755", 110 | "sha256:3b74f50a57b1413047042e47033480b7324b091f23dff790a4494af32b377d94", 111 | "sha256:4f4d818588e2d8de4bf24ed018056c3de0c95898ad25719e12d68626161b4933", 112 | "sha256:502a2166165a8e8c3d99c19272e923d2548bac2132424d78910ef9dd8bb11705", 113 | "sha256:5c9632a20faecd6d79f0124afb31e6557414d19be271e572765b474f860f8d76", 114 | "sha256:8d004699c5d71c704c14a5f81eec233faa4f87a3bf0ae68e222b87d63f5dd17e", 115 | "sha256:a62ee598b137202ef2e99d8dbaee6bc7379a6565c3ddf0331decb41b98eff1a2", 116 | "sha256:bacf236b5c2f8f674723a39daca399646dceb470881f842f52e393b9a67ff2f8", 117 | "sha256:bf1f7b7e88b467d7aefcdb2bc9cbd2e856ca88c5ab232c0efe0848f146d3bd5f", 118 | "sha256:ded780f0d3642d7bfc21d97b98d4ec4b41d2fe70c3f5c5d243868612f536e011", 119 | "sha256:e68bcadf32edc1171ccb06117699a6a4f8e924b7c2c8812cfa00fd0186ade4ee", 120 | "sha256:f9361eff44c7108c2312f39d85ed768c4ada7e0aa729046bbcef3ef3c1577d18" 121 | ], 122 | "index": "pypi", 123 | "version": "==5.8.0" 124 | }, 125 | "pyinstaller-hooks-contrib": { 126 | "hashes": [ 127 | "sha256:29d052eb73e0ab8f137f11df8e73d464c1c6d4c3044d9dc8df2af44639d8bfbf", 128 | "sha256:bd578781cd6a33ef713584bf3726f7cd60a3e656ec08a6cc7971e39990808cc0" 129 | ], 130 | "markers": "python_version >= '3.7'", 131 | "version": "==2023.0" 132 | }, 133 | "pyqt6": { 134 | "hashes": [ 135 | "sha256:18d1daf98d9236d55102cdadafd1056f5802f3c9288fcf7238569937b71a89f0", 136 | "sha256:25bd399b4a95dce65d5f937c1aa85d3c7e14a21745ae2a4ca14c0116cd104290", 137 | "sha256:740244f608fe15ee1d89695c43f31a14caeca41c4f02ac36c86dfba4a5d5813d", 138 | "sha256:c128bc0f17833e324593e3db83e99470d451a197dd17ff0333927b946c935bd9" 139 | ], 140 | "index": "pypi", 141 | "version": "==6.4.2" 142 | }, 143 | "pyqt6-qt6": { 144 | "hashes": [ 145 | "sha256:9f07c3c100cb46cca4074965e7494d4df4f0fc016497d5303c1fe135822876e1", 146 | "sha256:a29b8c858babd523e80c8db5f8fd19792641588ec04eab49af18b7a4423eb99f", 147 | "sha256:c0e91d0275d428496cacff717a9b719c52bfa52b21f124d638b79cc2217bc81e", 148 | "sha256:d19c4e72615762cd6f0b043f23fa5f0b02656091427ce6de1efccd58e10e6a53" 149 | ], 150 | "version": "==6.4.2" 151 | }, 152 | "pyqt6-sip": { 153 | "hashes": [ 154 | "sha256:0df998f2b6ceeacfd10de773441572e215be0c9cae566cc7dd36e231bf714a12", 155 | "sha256:224575e84805c4317bacd5d1b8e93e0ad5c48685dadbbe1e902d4ebe16f22828", 156 | "sha256:36ae29cdc223cacc1257d0f5075cf81474550c6d26b728f922487a2aa935f130", 157 | "sha256:3a674c591d4274d4ea8127205290e927a7dab0eb87a0038d4f4ea1d430782649", 158 | "sha256:3ef9392e4ae29d393b79237d85840cdc6b8831f36eed5d56c7d9b329b380cc8d", 159 | "sha256:43935873d60f57719632840d517afee04ef8f30e92cfe0dadc7e6326691920fc", 160 | "sha256:5731f22618435654352ef07684549a17be82b75254227fc80b4b5b0b59fc6656", 161 | "sha256:5bc4beb6fb1de4c9ba8beee7b1a4a813fa888c3b095206dafcd25d7e6e4ed2a7", 162 | "sha256:5c36ab984402e96792eebf4b031abfaa589aa20af3190a79c54502c16964d97e", 163 | "sha256:a2a0461992c6657f343308b150c4d6b57e9e7a0e5c2f79538434e7fb869ea827", 164 | "sha256:a81490ee84d7a41a126b116081bd97d758f41bf706aee0a8cec24d6e4c660184", 165 | "sha256:e00e287ea05bbc293fc6e2198301962af9b7b622bd2daf4288f925a88ae35dc9", 166 | "sha256:e670a7b2fb7e32204ce67d274017bfff3e21139d217d60cebbfcb75b019c91ee", 167 | "sha256:ee06f255787a0b4957f357f93b78d2a11ca3761916833e3afa83f1381d4d1a46", 168 | "sha256:fbee0d554e0e98f56dbf6d94b00a28cc32425938ad7ae98fd91f8822c5b24d45", 169 | "sha256:fcc6d78314783f4a193f02353f431b7ea4d357f47c3c7a7d0740e723f69c64dc" 170 | ], 171 | "markers": "python_version >= '3.7'", 172 | "version": "==13.4.1" 173 | }, 174 | "pywin32-ctypes": { 175 | "hashes": [ 176 | "sha256:24ffc3b341d457d48e8922352130cf2644024a4ff09762a2261fd34c36ee5942", 177 | "sha256:9dc2d991b3479cc2df15930958b674a48a227d5361d413827a4cfd0b5876fc98" 178 | ], 179 | "markers": "sys_platform == 'win32'", 180 | "version": "==0.2.0" 181 | }, 182 | "scipy": { 183 | "hashes": [ 184 | "sha256:049a8bbf0ad95277ffba9b3b7d23e5369cc39e66406d60422c8cfef40ccc8415", 185 | "sha256:07c3457ce0b3ad5124f98a86533106b643dd811dd61b548e78cf4c8786652f6f", 186 | "sha256:0f1564ea217e82c1bbe75ddf7285ba0709ecd503f048cb1236ae9995f64217bd", 187 | "sha256:1553b5dcddd64ba9a0d95355e63fe6c3fc303a8fd77c7bc91e77d61363f7433f", 188 | "sha256:15a35c4242ec5f292c3dd364a7c71a61be87a3d4ddcc693372813c0b73c9af1d", 189 | "sha256:1b4735d6c28aad3cdcf52117e0e91d6b39acd4272f3f5cd9907c24ee931ad601", 190 | "sha256:2cf9dfb80a7b4589ba4c40ce7588986d6d5cebc5457cad2c2880f6bc2d42f3a5", 191 | "sha256:39becb03541f9e58243f4197584286e339029e8908c46f7221abeea4b749fa88", 192 | "sha256:43b8e0bcb877faf0abfb613d51026cd5cc78918e9530e375727bf0625c82788f", 193 | "sha256:4b3f429188c66603a1a5c549fb414e4d3bdc2a24792e061ffbd607d3d75fd84e", 194 | "sha256:4c0ff64b06b10e35215abce517252b375e580a6125fd5fdf6421b98efbefb2d2", 195 | "sha256:51af417a000d2dbe1ec6c372dfe688e041a7084da4fdd350aeb139bd3fb55353", 196 | "sha256:5678f88c68ea866ed9ebe3a989091088553ba12c6090244fdae3e467b1139c35", 197 | "sha256:79c8e5a6c6ffaf3a2262ef1be1e108a035cf4f05c14df56057b64acc5bebffb6", 198 | "sha256:7ff7f37b1bf4417baca958d254e8e2875d0cc23aaadbe65b3d5b3077b0eb23ea", 199 | "sha256:aaea0a6be54462ec027de54fca511540980d1e9eea68b2d5c1dbfe084797be35", 200 | "sha256:bce5869c8d68cf383ce240e44c1d9ae7c06078a9396df68ce88a1230f93a30c1", 201 | "sha256:cd9f1027ff30d90618914a64ca9b1a77a431159df0e2a195d8a9e8a04c78abf9", 202 | "sha256:d925fa1c81b772882aa55bcc10bf88324dadb66ff85d548c71515f6689c6dac5", 203 | "sha256:e7354fd7527a4b0377ce55f286805b34e8c54b91be865bac273f527e1b839019", 204 | "sha256:fae8a7b898c42dffe3f7361c40d5952b6bf32d10c4569098d276b4c547905ee1" 205 | ], 206 | "index": "pypi", 207 | "version": "==1.10.1" 208 | }, 209 | "setuptools": { 210 | "hashes": [ 211 | "sha256:e5fd0a713141a4a105412233c63dc4e17ba0090c8e8334594ac790ec97792330", 212 | "sha256:f106dee1b506dee5102cc3f3e9e68137bbad6d47b616be7991714b0c62204251" 213 | ], 214 | "markers": "python_version >= '3.7'", 215 | "version": "==67.4.0" 216 | }, 217 | "xlsxwriter": { 218 | "hashes": [ 219 | "sha256:ec77335fb118c36bc5ed1c89e33904d649e4989df2d7980f7d6a9dd95ee5874e", 220 | "sha256:f5c7491b8450cf49968428f062355de16c9140aa24eafc466c9dfe107610bd44" 221 | ], 222 | "index": "pypi", 223 | "version": "==3.0.8" 224 | } 225 | }, 226 | "develop": { 227 | "altgraph": { 228 | "hashes": [ 229 | "sha256:ad33358114df7c9416cdb8fa1eaa5852166c505118717021c6a8c7c7abbd03dd", 230 | "sha256:c8ac1ca6772207179ed8003ce7687757c04b0b71536f81e2ac5755c6226458fe" 231 | ], 232 | "version": "==0.17.3" 233 | }, 234 | "pefile": { 235 | "hashes": [ 236 | "sha256:82e6114004b3d6911c77c3953e3838654b04511b8b66e8583db70c65998017dc", 237 | "sha256:da185cd2af68c08a6cd4481f7325ed600a88f6a813bad9dea07ab3ef73d8d8d6" 238 | ], 239 | "markers": "sys_platform == 'win32'", 240 | "version": "==2023.2.7" 241 | }, 242 | "pyinstaller": { 243 | "hashes": [ 244 | "sha256:314fb883caf3cbf06adbea2b77671bb73c3481568e994af0467ea7e47eb64755", 245 | "sha256:3b74f50a57b1413047042e47033480b7324b091f23dff790a4494af32b377d94", 246 | "sha256:4f4d818588e2d8de4bf24ed018056c3de0c95898ad25719e12d68626161b4933", 247 | "sha256:502a2166165a8e8c3d99c19272e923d2548bac2132424d78910ef9dd8bb11705", 248 | "sha256:5c9632a20faecd6d79f0124afb31e6557414d19be271e572765b474f860f8d76", 249 | "sha256:8d004699c5d71c704c14a5f81eec233faa4f87a3bf0ae68e222b87d63f5dd17e", 250 | "sha256:a62ee598b137202ef2e99d8dbaee6bc7379a6565c3ddf0331decb41b98eff1a2", 251 | "sha256:bacf236b5c2f8f674723a39daca399646dceb470881f842f52e393b9a67ff2f8", 252 | "sha256:bf1f7b7e88b467d7aefcdb2bc9cbd2e856ca88c5ab232c0efe0848f146d3bd5f", 253 | "sha256:ded780f0d3642d7bfc21d97b98d4ec4b41d2fe70c3f5c5d243868612f536e011", 254 | "sha256:e68bcadf32edc1171ccb06117699a6a4f8e924b7c2c8812cfa00fd0186ade4ee", 255 | "sha256:f9361eff44c7108c2312f39d85ed768c4ada7e0aa729046bbcef3ef3c1577d18" 256 | ], 257 | "index": "pypi", 258 | "version": "==5.8.0" 259 | }, 260 | "pyinstaller-hooks-contrib": { 261 | "hashes": [ 262 | "sha256:29d052eb73e0ab8f137f11df8e73d464c1c6d4c3044d9dc8df2af44639d8bfbf", 263 | "sha256:bd578781cd6a33ef713584bf3726f7cd60a3e656ec08a6cc7971e39990808cc0" 264 | ], 265 | "markers": "python_version >= '3.7'", 266 | "version": "==2023.0" 267 | }, 268 | "pywin32-ctypes": { 269 | "hashes": [ 270 | "sha256:24ffc3b341d457d48e8922352130cf2644024a4ff09762a2261fd34c36ee5942", 271 | "sha256:9dc2d991b3479cc2df15930958b674a48a227d5361d413827a4cfd0b5876fc98" 272 | ], 273 | "markers": "sys_platform == 'win32'", 274 | "version": "==0.2.0" 275 | }, 276 | "setuptools": { 277 | "hashes": [ 278 | "sha256:e5fd0a713141a4a105412233c63dc4e17ba0090c8e8334594ac790ec97792330", 279 | "sha256:f106dee1b506dee5102cc3f3e9e68137bbad6d47b616be7991714b0c62204251" 280 | ], 281 | "markers": "python_version >= '3.7'", 282 | "version": "==67.4.0" 283 | } 284 | } 285 | } 286 | -------------------------------------------------------------------------------- /Python_Lib/My_Lib.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | __author__ = 'LiYuanhe' 3 | 4 | import sys 5 | import os 6 | import re 7 | import string 8 | import copy 9 | import math 10 | from collections import OrderedDict 11 | 12 | import pathlib 13 | 14 | Python_Lib_path = str(pathlib.Path(__file__).parent.resolve()) 15 | sys.path.append(Python_Lib_path) 16 | from My_Lib_Stock import * 17 | 18 | def video_duration_s(filename): 19 | import cv2 20 | video = cv2.VideoCapture(filename) 21 | 22 | fps = video.get(cv2.CAP_PROP_FPS) 23 | frame_count = video.get(cv2.CAP_PROP_FRAME_COUNT) 24 | # print(filename,fps,frame_count) 25 | assert fps, filename 26 | return frame_count / fps 27 | 28 | def get_image_size(image_file): 29 | """ 30 | read an image file, return (width, height) of the image file 31 | :param image_file: 32 | :return: 33 | """ 34 | from PIL import Image 35 | return Image.open(image_file).size 36 | 37 | 38 | def screen_capture(output_filename): 39 | import pyautogui 40 | myScreenshot = pyautogui.screenshot() 41 | myScreenshot.save(output_filename) 42 | 43 | def interpolation_with_grouping(Xs, Ys, kind): 44 | """ 45 | When X have duplicate values, interp1d fails. 46 | It is averaged so to be as an single value function 47 | """ 48 | from scipy.interpolate import interp1d 49 | from statistics import mean 50 | from itertools import groupby 51 | 52 | process_XYs = list(zip(Xs, Ys)) 53 | process_XYs.sort(key=lambda x: x[0]) 54 | grouper = groupby(process_XYs, key=lambda x: x[0]) 55 | process_XYs = [[x, mean(yi[1] for yi in y)] for x, y in grouper] 56 | interp1d_X = [x[0] for x in process_XYs] 57 | interp1d_Y = [x[1] for x in process_XYs] 58 | 59 | # print(len(interp1d_X)) 60 | # print(len(set(interp1d_X))) 61 | 62 | return interp1d(interp1d_X, interp1d_Y, kind=kind) 63 | 64 | 65 | def hide_cwd_window(): 66 | import ctypes 67 | import os 68 | import win32process 69 | 70 | hwnd = ctypes.windll.kernel32.GetConsoleWindow() 71 | if hwnd != 0: 72 | ctypes.windll.user32.ShowWindow(hwnd, 0) 73 | ctypes.windll.kernel32.CloseHandle(hwnd) 74 | _, pid = win32process.GetWindowThreadProcessId(hwnd) 75 | os.system('taskkill /PID ' + str(pid) + ' /f') 76 | 77 | 78 | def toggle_layout(layout, hide=-1, show=-1): 79 | """ 80 | Hide (or show) all elements in layout 81 | :param layout: 82 | :param hide: to hide layout 83 | :param show: to show layout 84 | :return: 85 | """ 86 | 87 | for i in reversed(range(layout.count())): 88 | assert hide != -1 or show != -1 89 | assert isinstance(hide, bool) or isinstance(show, bool) 90 | 91 | if isinstance(show, bool): 92 | hide = not show 93 | 94 | if hide: 95 | if layout.itemAt(i).widget(): 96 | layout.itemAt(i).widget().hide() 97 | else: 98 | if layout.itemAt(i).widget(): 99 | layout.itemAt(i).widget().show() 100 | 101 | 102 | class SSH_Account: 103 | def __init__(self, input_str: str): 104 | """ 105 | :param input_str: name 100.100.101.123:1823 username password 106 | or with ssh private key name 100.100.101.123:1234 username E:\path_to_key_file\keyfile.openssh 107 | """ 108 | input_str = input_str.strip().split(" ") 109 | self.tag = input_str[0] 110 | self.ip_port = input_str[1] 111 | self.ip, self.port = self.ip_port.split(":") 112 | 113 | try: 114 | self.port = int(self.port) 115 | except: 116 | self.port = 22 117 | 118 | self.username = input_str[2] 119 | self.password = input_str[3] 120 | 121 | def __str__(self): 122 | return self.username + ' @ ' + self.tag 123 | 124 | 125 | def download_sftp_file(ssh_account: SSH_Account, remote_filepath, local_filepath, transport_object=None, sftp_object=None): 126 | # 产生一个随机的临时文件,然后改名为想要的文件名,某种程度上保证原子性 127 | remove_append = filename_class(local_filepath).only_remove_append 128 | append = filename_class(local_filepath).append 129 | 130 | local_temp_filepath = remove_append + "_TEMP_For_atomicity." + append 131 | 132 | import paramiko 133 | if not transport_object: 134 | transport = paramiko.Transport((ssh_account.ip, ssh_account.port)) 135 | transport.connect(username=ssh_account.username, password=ssh_account.password) 136 | else: 137 | transport = transport_object 138 | 139 | if not sftp_object: 140 | sftp = paramiko.SFTPClient.from_transport(transport) 141 | else: 142 | sftp = sftp_object 143 | 144 | ssh_for_homedir = paramiko.SSHClient() 145 | ssh_for_homedir.load_system_host_keys() 146 | ssh_for_homedir.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 147 | 148 | ssh_for_homedir.connect(ssh_account.ip, ssh_account.port, username=ssh_account.username, password=ssh_account.password) 149 | 150 | stdin, stdout, stderr = ssh_for_homedir.exec_command("echo " + remote_filepath) 151 | remote_filepath = stdout.read().decode('utf-8').strip() 152 | 153 | sftp.get(remote_filepath, local_temp_filepath) 154 | 155 | if os.path.isfile(local_filepath): 156 | os.remove(local_filepath) 157 | os.rename(local_temp_filepath, local_filepath) 158 | 159 | if not sftp_object: 160 | sftp.close() 161 | 162 | ssh_for_homedir.close() 163 | 164 | 165 | def find_range_for_certain_percentage(data, percentage=80, offset=0): 166 | """ 167 | try to find the smallest data range, where it can cover certain percentage of the data 168 | :param data: a list of numbers, or any shape of numpy array, which will be flatened 169 | :param offset:a number, if it is 0.1, then the color map will be shifted up for 10% of max(Z)-min(Z) 170 | :return: a 2-tuple, the desired smallest range 171 | """ 172 | import numpy as np 173 | data = np.array(data) 174 | data_dist = max(data) - min(data) 175 | data = np.sort(data, axis=None) 176 | data_count = data.size 177 | target_count = math.ceil(data_count * percentage / 100) 178 | ranges = [] 179 | for i in range(0, data_count - target_count + 1): 180 | ranges.append((data[i], data[i + target_count - 1])) 181 | ranges.sort(key=lambda x: x[1] - x[0]) 182 | ret = list(ranges[0]) 183 | print(ret) 184 | ret[0] = ret[0] + data_dist * offset 185 | ret[1] = ret[1] + data_dist * offset 186 | print(ret) 187 | return ret 188 | 189 | 190 | def Chronyk_new(input_time: str): # chronyk will give a 1 day less result when wap arround time string 191 | from chronyk import Chronyk 192 | if isinstance(input_time, float): 193 | return Chronyk(input_time) 194 | elif isinstance(input_time, str): 195 | return Chronyk(Chronyk(input_time).timestamp() + 86400) 196 | 197 | 198 | def remove_forbidden_char_from_filename(filename): 199 | chars = r'<>:"/\|?*' 200 | for char in chars: 201 | filename = filename.replace(char, '_') 202 | return filename 203 | 204 | 205 | def quote_url(url): 206 | from urllib import parse 207 | return parse.quote(url, safe=':?/=') 208 | 209 | 210 | # def get_response_header_using_cookie(url): 211 | # import requests 212 | # r = requests.get(url) 213 | # header = r.headers 214 | # # cookie = r.cookies 215 | # r = requests.get(url,cookies = cookie) 216 | # print(r.headers) 217 | 218 | def open_url_with_chrome(url): 219 | import webbrowser 220 | webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe")) 221 | webbrowser.get('chrome').open_new_tab(url) 222 | 223 | 224 | def open_phantomJS(url, use_chrome=False): 225 | os.environ["PATH"] += r';D:\常用程序\Chrome;D:\常用程序\phantomjs-2.1.1-windows\bin' 226 | if os.path.isfile('PhantomJS_Path.txt'): 227 | with open('PhantomJS_Path.txt') as PhantomJS_Path_file: 228 | os.environ["PATH"] += ";" + PhantomJS_Path_file.read().strip() 229 | 230 | from selenium import webdriver 231 | 232 | from selenium.webdriver.support.ui import WebDriverWait 233 | from selenium.webdriver.support import expected_conditions 234 | from selenium.webdriver.common.keys import Keys 235 | from selenium.webdriver.common.by import By 236 | from selenium.webdriver.common.desired_capabilities import DesiredCapabilities 237 | 238 | if not use_chrome: 239 | # Connect_to_PhantomJS 240 | dcap = dict(DesiredCapabilities.PHANTOMJS) 241 | dcap[ 242 | "phantomjs.page.settings.userAgent"] = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36" 243 | test_driver = webdriver.PhantomJS(desired_capabilities=dcap) 244 | 245 | if use_chrome: 246 | test_driver = webdriver.Chrome() 247 | 248 | test_driver.get(url) 249 | return test_driver 250 | 251 | 252 | def urlopen_inf_retry(url, prettify=True, use_cookie=False, retry_limit=100, opener=None, timeout=60, print_out=True): 253 | from bs4 import BeautifulSoup 254 | 255 | from http.cookiejar import CookieJar 256 | import urllib 257 | from urllib import request 258 | import socket 259 | 260 | html = None 261 | 262 | def request_page(requrest_url, request_page_opener, request_page_timeout=60): 263 | if use_cookie: 264 | if not request_page_opener: 265 | request_page_opener = request.build_opener(request.HTTPCookieProcessor(CookieJar())) 266 | return request_page_opener.open(requrest_url, timeout=request_page_timeout) 267 | else: 268 | req = request.Request(requrest_url, headers={ 269 | 'User-Agent': "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"}) 270 | return request.urlopen(req, timeout=request_page_timeout) 271 | 272 | fail = True 273 | retry_count = 1 274 | while fail and retry_count <= retry_limit: 275 | if print_out: 276 | print("Requesting:", url, end='\t') 277 | try: 278 | html = request_page(url, opener, request_page_timeout=timeout).read() 279 | fail = False 280 | if print_out: 281 | print("Request Finished.") 282 | except (socket.gaierror, urllib.error.URLError, ConnectionResetError, TimeoutError, socket.timeout, UnboundLocalError) as e: 283 | if print_out: 284 | print('\nURL open failure. Retrying... ' + str(retry_count) + '/' + str(retry_limit), e) 285 | retry_count += 1 286 | import time 287 | time.sleep(2) 288 | 289 | if not html: 290 | return "" 291 | if prettify: 292 | html = BeautifulSoup(html, "lxml").prettify() 293 | return BeautifulSoup(html, "lxml") 294 | else: 295 | return html 296 | 297 | 298 | def match_attr_bs4(bs_object, key, value, match_full=False): 299 | # time.sleep(1) 300 | if not match_full: 301 | if bs_object.get(key): 302 | if value in bs_object[key]: 303 | return True 304 | else: 305 | if bs_object.get(key): 306 | target = bs_object[key] 307 | target = " ".join([" ".join(x.split()) for x in target]) 308 | value = " ".join(value.split) 309 | if target == value: 310 | return True 311 | return False 312 | 313 | 314 | def open_tab(url): 315 | import webbrowser 316 | webbrowser.register('brave', None, webbrowser.BackgroundBrowser(r"C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe")) 317 | browser = webbrowser.get('brave') 318 | browser.open_new_tab(url) 319 | 320 | 321 | def get_canonical_smiles(original_smiles): 322 | import subprocess 323 | if not original_smiles: 324 | return "" 325 | 326 | indigo_path = os.path.join(filename_class(os.path.realpath(__file__)).path, 'indigo-cano.exe').replace('/', '\\') 327 | 328 | print("Calling", ' '.join([indigo_path, '-', original_smiles])) 329 | 330 | try: 331 | ret = subprocess.check_output([indigo_path, '-', original_smiles]) 332 | except subprocess.CalledProcessError: 333 | print("Indigo SMILES Bug Detected:", original_smiles) 334 | try: 335 | ret = subprocess.check_output(" ".join(['"' + indigo_path + '"', '-', '"' + original_smiles + '"', '-smiles', '-no-arom']), shell=True) 336 | except subprocess.CalledProcessError: 337 | return "" 338 | 339 | return ret.decode('utf-8').strip() 340 | 341 | # if not original_smiles: 342 | # return "" 343 | # 344 | # from indigo.indigo import Indigo 345 | # indigo = Indigo() 346 | # try: 347 | # mol = indigo.loadMolecule(original_smiles) 348 | # except: 349 | # print("Ineffective SMILES:",original_smiles) 350 | # return "" 351 | # 352 | # mol.aromatize() 353 | # try: 354 | # ret = mol.canonicalSmiles() #有时有问题 355 | # except: 356 | # ret = original_smiles 357 | # print("Indigo SMILES Bug Detected:",original_smiles) 358 | # 359 | # # print("Canonicalization time","{:.2f}".format(time.time()-t1)) 360 | # 361 | # return ret 362 | 363 | 364 | def load_xlsx_as_list(filename, sheet=0, column_as_inner_list=False): 365 | import pyexcel 366 | if isinstance(sheet, int): 367 | excel_book_dict = pyexcel.get_book_dict(file_name=filename) 368 | excel_object = excel_book_dict[list(excel_book_dict.keys())[sheet]] 369 | else: 370 | excel_object = pyexcel.get_book_dict(file_name=filename)[sheet] 371 | 372 | if not column_as_inner_list: 373 | return excel_object 374 | 375 | else: # 转置 376 | excel_object = [[r[col] for r in excel_object] for col in range(len(excel_object[0]))] 377 | for i in excel_object: 378 | print(i) 379 | return excel_object 380 | 381 | # for line in scaling_factor_database: 382 | # # 储存一个原始的,一个最后的 383 | # line['Basis'] = [line['Basis'], unify_basis(line['Basis'])] 384 | # line['Method'] = [line['Method'], unify_method(line['Method'])] 385 | # 386 | # return scaling_factor_database 387 | 388 | 389 | def excel_formula(formula: str, *cells): 390 | if isinstance(cells[0], list): 391 | cells = cells[0] 392 | for count, current_cell in enumerate(cells): 393 | formula = formula.replace('[cell' + str(count + 1) + ']', current_cell) 394 | 395 | return formula 396 | 397 | 398 | def cell(column_num, row_num): 399 | # start from 0 400 | if column_num < 26: 401 | return chr(ord('A') + column_num) + str(row_num + 1) 402 | if column_num >= 26: 403 | return chr(ord('A') + int(column_num / 26) - 1) + chr(ord('A') + column_num % 26) + str(row_num + 1) 404 | 405 | 406 | def read_xlsx(file, sheet=0, all_sheets=False): 407 | """ 408 | 409 | :param file: A xlsx file 410 | :param sheet: which sheet to read, using numbers 411 | :param all_sheets: read all sheet, return an ordered dict, with sheet name as key 412 | :return: if not all_sheets, return a 2D-list, all sub-list are the same length 413 | """ 414 | import pyexcel_xlsx 415 | import json 416 | data = pyexcel_xlsx.get_data(file, skip_hidden_row_and_column=False) 417 | 418 | if all_sheets: 419 | import collections 420 | ret = collections.OrderedDict() 421 | for key, value in data.items(): 422 | ret[key] = same_length_2d_list(value) 423 | return ret 424 | else: 425 | ret = data[list(data)[sheet]] 426 | return same_length_2d_list(ret) 427 | 428 | 429 | def read_csv(file): 430 | """ 431 | Read a csv file, return a same_length_2D_list 432 | :return: return a 2D-list, same as the csv file, all sub-list are the same length. If the content is 'floatable', it will be convert to float 433 | """ 434 | 435 | with open(file) as input_file: 436 | input_file_content = input_file.readlines() 437 | 438 | input_file_content = [x.strip().split(',') for x in input_file_content] 439 | data = [[(float(y) if is_float(y) else y) for y in x] for x in input_file_content] 440 | return same_length_2d_list(data) 441 | 442 | 443 | def read_txt_table(file, separater='\t'): 444 | data = open(file).readlines() 445 | data = [x.split(separater) for x in data] 446 | return same_length_2d_list(data) 447 | 448 | 449 | def read_txt_and_transpose(file, separater='\t'): 450 | return transpose_2d_list(read_txt_table(file, separater=separater)) 451 | 452 | 453 | def write_xlsx(filename, list_2D, transpose=False): 454 | """ 455 | A simple function for writing a 2D list to a xlsx file 456 | :param filename: 457 | :param list_2D: 458 | :param transpose: if False, the outer-layer of list-2D will be rows 459 | :return: 460 | """ 461 | 462 | import xlsxwriter 463 | workbook = xlsxwriter.Workbook(filename) 464 | worksheet = workbook.add_worksheet() 465 | 466 | for row_count, row in enumerate(list_2D): 467 | for column_count, current_cell in enumerate(row): 468 | if not transpose: 469 | worksheet.write(row_count, column_count, current_cell) 470 | else: 471 | worksheet.write(column_count, row_count, current_cell) 472 | 473 | workbook.close() 474 | 475 | 476 | def mix_two_colors(color1, color2, percentage, mixing_order=2): 477 | """ 478 | :param color1: color in hex, e.g. "00FF00" 479 | :param color2: color in hex, e.g. "00FF00" 480 | :param mixing_order: 481 | :param percentage: if =0, color1, if =1, color2, else, return an interpolation of the color 482 | :return: a mixed color in hex number 483 | """ 484 | if mixing_order == 'hsv': 485 | import colorsys 486 | if percentage == 0: 487 | return color1 488 | if percentage == 1: 489 | return color2 490 | 491 | color1 = [eval('0x' + x) for x in [color1[0:2], color1[2:4], color1[4:6]]] 492 | color2 = [eval('0x' + x) for x in [color2[0:2], color2[2:4], color2[4:6]]] 493 | 494 | def mixing(value1, value2, percentage, mixing_order): 495 | return round((value1 ** mixing_order + (value2 ** mixing_order - value1 ** mixing_order) * percentage) ** (1 / mixing_order)) 496 | 497 | def hsv_mixing(color1, color2, percentage): 498 | color1 = [x / 255 for x in color1] 499 | color2 = [x / 255 for x in color2] 500 | color1 = colorsys.rgb_to_hsv(*color1) 501 | color2 = colorsys.rgb_to_hsv(*color2) 502 | ret = colorsys.hsv_to_rgb(*[color1[x] + percentage * (color2[x] - color1[x]) for x in range(3)]) 503 | return (round(x * 255) for x in ret) 504 | 505 | if mixing_order == 'hsv': 506 | ret = hsv_mixing(color1, color2, percentage) 507 | else: 508 | ret = [mixing(color1[x], color2[x], percentage, mixing_order) for x in range(3)] 509 | 510 | ret = ''.join('{:02X}'.format(int(round(num))) for num in ret) 511 | return ret 512 | 513 | 514 | def color_scale(colors, ref_points, value, mixing_order=2): 515 | ''' 516 | generate a color scale, extract color for a value 517 | :param colors: list of colors corresponds to list of ref_points, color in Hex like FFFFFF 518 | :param ref_points: 519 | :param value: 520 | :return: 521 | ''' 522 | 523 | assert sorted(ref_points) == ref_points or sorted(ref_points, reverse=True) == ref_points, 'Color Ref Points need to be in sequence.' 524 | if sorted(ref_points, reverse=True) == ref_points: 525 | ref_points = list(reversed(ref_points)) 526 | colors = list(reversed(colors)) 527 | 528 | if value < ref_points[0]: 529 | return colors[0] 530 | if value > ref_points[-1]: 531 | return colors[-1] 532 | 533 | for value_count in range(len(ref_points) - 1): 534 | value1, value2 = ref_points[value_count:value_count + 2] 535 | if value1 <= value <= value2: 536 | color1, color2 = colors[value_count:value_count + 2] 537 | return mix_two_colors(color1, color2, (value - value1) / (value2 - value1), mixing_order=mixing_order) 538 | 539 | 540 | def angle_of_np_vectors(v1, v2): 541 | """ Returns the angle in degree between vectors 'v1' and 'v2'::""" 542 | import numpy as np 543 | def unit_vector(vector): 544 | return vector / np.linalg.norm(vector) 545 | 546 | v1_u = unit_vector(v1) 547 | v2_u = unit_vector(v2) 548 | return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) / math.pi * 180 549 | 550 | 551 | def smiles_from_xyz(input_file): 552 | import subprocess 553 | babel_exe = r"C:\Program Files (x86)\OpenBabel-2.3.2\babel.exe" 554 | assert os.path.isfile(babel_exe), "OpenBabel not found." 555 | temp_file = r"D:\Gaussian\Temp\temp_xyz_file_for_smiles.smi" 556 | 557 | subprocess.call([babel_exe, '-ixyz', input_file, "-osmi", temp_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 558 | with open(temp_file) as temp_file: 559 | ret = temp_file.read().split() 560 | if ret: 561 | return (get_canonical_smiles(ret[0])) 562 | else: 563 | print("SMILES ERROR! Original str:", ret) 564 | 565 | 566 | def smiles_from_mol2(input_file): 567 | import subprocess 568 | babel_exe = r"C:\Program Files (x86)\OpenBabel-2.3.2\babel.exe" 569 | assert os.path.isfile(babel_exe), "OpenBabel not found." 570 | temp_file = r"D:\Gaussian\Temp\temp_xyz_file_for_smiles.smi" 571 | 572 | subprocess.call([babel_exe, '-imol2', input_file, "-osmi", temp_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 573 | with open(temp_file) as temp_file: 574 | ret = temp_file.read().split() 575 | if ret: 576 | return (get_canonical_smiles(ret[0])) 577 | else: 578 | print("SMILES ERROR! Original str:", ret) 579 | 580 | 581 | def get_bonds(filename, neighbor_list=False, add_bond="", bond_radii_factor=1.3): 582 | ''' 583 | 584 | :param filename: ALL file format supported by mogli 585 | :param neighbor_list: is neighbor_list=True, a dict of neighbor list of connection are returned, instead of the standard one {1:[3,4,5], 2:[3,6,7]} 586 | :param add_bond: a str with the format of "1-2,1-5", atom count start from 0, where a (single) bond will be added if they are not bonded before 587 | 588 | :return: a list of tuple of bonded atoms,no bond order information 589 | e.g. [(0, 1), (0, 2), (0, 13), (0, 26), (2, 3), (2, 4), (2, 5), (5, 6), (5, 9), (5, 10), (6, 7), (6, 8), (7, 13), (10, 11), (10, 12), (12, 13), (12, 38), (13, 14), (14, 15), (14, 16), (14, 20), (16, 17), (16, 18), (16, 19), (20, 21), (20, 22), (20, 23), (23, 24), (23, 25), (23, 26), (26, 27), (27, 28), (27, 32), (28, 29), (28, 30), (28, 31), (32, 33), (32, 34), (32, 35), (35, 36), (35, 37), (35, 38), (38, 39), (38, 40), (40, 41), (40, 45), (40, 46), (41, 42), (41, 43), (41, 44), (46, 47), (46, 48), (46, 49)] 590 | 591 | if neighbor_list is enabled: 592 | {0: [1, 3, 4], 1: [0, 2, 10], 2: [1], 3: [0], 4: [0, 5, 6], 5: [4], 6: [4, 7, 8], 7: [6], 8: [6, 9, 10], 9: [8], 10: [1, 8, 11], 11: [10, 12, 13, 14], 12: [11], 13: [11], 14: [11, 15], 15: [14, 16, 17, 49], 16: [15], 17: [15, 18, 19, 34], 18: [17], 19: [17, 20, 21, 22], 20: [19], 21: [19], 22: [19, 23, 24, 25], 23: [22], 24: [22], 25: [22, 26, 27, 28], 26: [25], 27: [25], 28: [25, 29, 30, 31], 29: [28], 30: [28], 31: [28, 32, 33, 34], 32: [31], 33: [31], 34: [17, 31, 35, 36], 35: [34, 49], 36: [34, 37, 38, 39], 37: [36], 38: [36], 39: [36, 40, 41, 42], 40: [39], 41: [39], 42: [39, 43, 47, 61], 43: [42, 44, 45, 46], 44: [43], 45: [43], 46: [43], 47: [42, 48, 49, 53], 48: [47], 49: [15, 35, 47, 50], 50: [49, 51], 51: [50, 52, 53], 52: [51], 53: [47, 51, 54, 55], 54: [53], 55: [53, 56, 60, 61], 56: [55, 57, 58, 59], 57: [56], 58: [56], 59: [56], 60: [55], 61: [42, 55, 62], 62: [61]} 593 | ''' 594 | 595 | # convert "1-2,1-5" to [(1,2),(1,5)] 596 | if not add_bond: 597 | add_bond = [] 598 | else: 599 | add_bond = add_bond.split(",") 600 | new_add_bond = [] 601 | for bond in add_bond: 602 | bond = bond.split('-') 603 | bond = [int(x) - 1 for x in bond] 604 | bond.sort() 605 | new_add_bond.append(bond) 606 | 607 | add_bond = new_add_bond 608 | 609 | import mogli 610 | import time 611 | molecules = mogli.read(filename) 612 | retry_attempts = 0 613 | while not molecules: 614 | print("Mogli reading error, retrying...") 615 | time.sleep(0.2) 616 | molecules = mogli.read(filename) 617 | retry_attempts += 1 618 | if retry_attempts > 5: 619 | break 620 | 621 | molecule = molecules[-1] 622 | molecule.calculate_bonds(param=bond_radii_factor) 623 | bonds = molecule.bonds 624 | bonds = [sorted(list(x)) for x in bonds.index_pairs] 625 | # print(bonds) 626 | 627 | for new_bond in add_bond: 628 | for existed_bond in bonds: 629 | if new_bond[0] == existed_bond[0] and new_bond[1] == existed_bond[1]: 630 | break 631 | else: 632 | bonds.append(new_bond) 633 | 634 | bonds = sorted([sorted(list(x)) for x in bonds]) 635 | # print(bonds) 636 | 637 | if neighbor_list: 638 | atom_count = len(molecule.atomic_numbers) 639 | ret = {} 640 | for atom in range(atom_count): 641 | bonding_to = [] 642 | for bond in bonds: 643 | if atom in bond: 644 | bonding_to.append(bond[0] if bond[0] != atom else bond[1]) 645 | ret[atom] = bonding_to 646 | return ret 647 | 648 | return bonds 649 | 650 | 651 | pass 652 | 653 | if __name__ == "__main__": 654 | pass -------------------------------------------------------------------------------- /Python_Lib/My_Lib_Create_Symlink.bat: -------------------------------------------------------------------------------- 1 | pushd %~dp0 2 | powershell -Command "New-Item -ItemType HardLink -Path .\My_Lib.py -Target ..\..\Python_Lib\My_Lib.py" 3 | pause -------------------------------------------------------------------------------- /Python_Lib/My_Lib_PyQt6.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | __author__ = 'LiYuanhe' 3 | 4 | # 5 | import os 6 | from PyQt6 import QtGui, QtCore, QtWidgets, uic 7 | from PyQt6.QtWidgets import QApplication 8 | import platform 9 | 10 | # import matplotlib 11 | # matplotlib.use("QtAgg") 12 | # from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as MpFigureCanvas 13 | # from matplotlib.backends.backend_qtagg import NavigationToolbar2QT as MpNavToolBar 14 | # from matplotlib import pyplot 15 | # import matplotlib.patches as patches 16 | # from matplotlib.figure import Figure as MpFigure 17 | # from matplotlib import pylab 18 | 19 | import sys 20 | import os 21 | import math 22 | import copy 23 | import shutil 24 | import re 25 | import time 26 | import random 27 | import traceback 28 | import pathlib 29 | 30 | Python_Lib_path = str(pathlib.Path(__file__).parent.resolve()) 31 | sys.path.append(Python_Lib_path) 32 | from My_Lib_Stock import * 33 | 34 | 35 | # 36 | # def set_Windows_scaling_factor_env_var(): 37 | # 38 | # # Sometimes, the scaling factor of PyQt is different from the Windows system scaling factor, reason unknown 39 | # # For example, on a 4K screen sets to 250% scaling on Windows, PyQt reads a default 300% scaling, 40 | # # causing everything to be too large, this function is to determine the ratio of the real DPI and the PyQt DPI 41 | # 42 | # import platform 43 | # if platform.system() == 'Windows': 44 | # import ctypes 45 | # try: 46 | # import win32api 47 | # MDT_EFFECTIVE_DPI = 0 48 | # monitor = win32api.EnumDisplayMonitors()[0] 49 | # dpiX,dpiY = ctypes.c_uint(),ctypes.c_uint() 50 | # ctypes.windll.shcore.GetDpiForMonitor(monitor[0].handle,MDT_EFFECTIVE_DPI,ctypes.byref(dpiX),ctypes.byref(dpiY)) 51 | # DPI_ratio_for_monitor = (dpiX.value+dpiY.value)/2/96 52 | # except Exception as e: 53 | # traceback.print_exc() 54 | # print(e) 55 | # DPI_ratio_for_monitor = 0 56 | # 57 | # DPI_ratio_for_device = ctypes.windll.shcore.GetScaleFactorForDevice(0) / 100 58 | # PyQt_scaling_ratio = QApplication.primaryScreen().devicePixelRatio() 59 | # print(f"Windows 10 High-DPI debug:",end=' ') 60 | # Windows_DPI_ratio = DPI_ratio_for_monitor if DPI_ratio_for_monitor else DPI_ratio_for_device 61 | # if DPI_ratio_for_monitor: 62 | # print("Using monitor DPI.") 63 | # ratio_of_ratio = DPI_ratio_for_monitor / PyQt_scaling_ratio 64 | # else: 65 | # print("Using device DPI.") 66 | # ratio_of_ratio = DPI_ratio_for_device / PyQt_scaling_ratio 67 | # 68 | # if ratio_of_ratio>1.05 or ratio_of_ratio<0.95: 69 | # use_ratio = "{:.2f}".format(ratio_of_ratio) 70 | # print(f"{DPI_ratio_for_monitor=}, {DPI_ratio_for_device=}, {PyQt_scaling_ratio=}") 71 | # print(f"Using GUI high-DPI ratio: {use_ratio}") 72 | # print("----------------------------------------------------------------------------") 73 | # os.environ["QT_SCALE_FACTOR"] = use_ratio 74 | # else: 75 | # print("Ratio of ratio near 1. Not scaling.") 76 | # 77 | # return Windows_DPI_ratio,PyQt_scaling_ratio 78 | # 79 | # 80 | def get_matplotlib_DPI_setting(Windows_DPI_ratio): 81 | matplotlib_DPI_setting = 60 82 | if platform.system() == 'Windows': 83 | matplotlib_DPI_setting = 60 / Windows_DPI_ratio 84 | if os.path.isfile("__matplotlib_DPI_Manual_Setting.txt"): 85 | matplotlib_DPI_manual_setting = open("__matplotlib_DPI_Manual_Setting.txt").read() 86 | if is_int(matplotlib_DPI_manual_setting): 87 | matplotlib_DPI_setting = matplotlib_DPI_manual_setting 88 | else: 89 | with open("__matplotlib_DPI_Manual_Setting.txt", 'w') as matplotlib_DPI_Manual_Setting_file: 90 | matplotlib_DPI_Manual_Setting_file.write("") 91 | matplotlib_DPI_setting = int(matplotlib_DPI_setting) 92 | print( 93 | f"\nMatplotlib DPI: {matplotlib_DPI_setting}. \n" 94 | f"Set an appropriate integer in __matplotlib_DPI_Manual_Setting.txt if the preview size doesn't match the output.\n") 95 | 96 | return matplotlib_DPI_setting 97 | 98 | 99 | def get_open_directories(): 100 | if not QApplication.instance(): 101 | QApplication(sys.argv) 102 | 103 | file_dialog = QtWidgets.QFileDialog() 104 | file_dialog.setFileMode(QtWidgets.QFileDialog.DirectoryOnly) 105 | file_dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, True) 106 | file_view = file_dialog.findChild(Qt.QListView, 'listView') 107 | 108 | # to make it possible to select multiple directories: 109 | if file_view: 110 | file_view.setSelectionMode(Qt.QAbstractItemView.MultiSelection) 111 | f_tree_view = file_dialog.findChild(Qt.QTreeView) 112 | if f_tree_view: 113 | f_tree_view.setSelectionMode(Qt.QAbstractItemView.MultiSelection) 114 | 115 | if file_dialog.exec(): 116 | return file_dialog.selectedFiles() 117 | 118 | return [] 119 | 120 | 121 | class Qt_Widget_Common_Functions: 122 | closing = QtCore.pyqtSignal() 123 | 124 | def center_the_widget(self, activate_window=True): 125 | frame_geometry = self.frameGeometry() 126 | screen_center = QtGui.QGuiApplication.primaryScreen().availableGeometry().center() 127 | frame_geometry.moveCenter(screen_center) 128 | self.move(frame_geometry.topLeft()) 129 | if activate_window: 130 | self.window().activateWindow() 131 | 132 | def closeEvent(self, event: QtGui.QCloseEvent): 133 | # print("Window {} closed".format(self)) 134 | self.closing.emit() 135 | if hasattr(super(), "closeEvent"): 136 | return super().closeEvent(event) 137 | 138 | def open_config_file(self): 139 | 140 | config_file = os.path.join(filename_class(sys.argv[0]).path, 'Config.ini') 141 | 142 | config_file_failure = False 143 | if not os.path.isfile(config_file): 144 | config_file_failure = True 145 | else: 146 | with open(config_file) as self.config_File: 147 | try: 148 | self.config = eval(self.config_File.read()) 149 | except Exception as e: 150 | traceback.print_exc() 151 | print(e) 152 | config_file_failure = True 153 | 154 | if config_file_failure: 155 | with open(config_file, 'w') as self.config_File: 156 | self.config_File.write('{}') 157 | 158 | with open(config_file) as self.config_File: 159 | self.config = eval(self.config_File.read()) 160 | 161 | def load_config(self, key, absence_return=""): 162 | if key in self.config: 163 | return self.config[key] 164 | else: 165 | self.config[key] = absence_return 166 | self.save_config() 167 | return absence_return 168 | 169 | def save_config(self): 170 | config_file = os.path.join(filename_class(sys.argv[0]).path, 'Config.ini') 171 | with open(config_file, 'w') as self.config_File: 172 | self.config_File.write(repr(self.config)) 173 | 174 | 175 | class Drag_Drop_TextEdit(QtWidgets.QTextEdit): 176 | drop_accepted_signal = QtCore.pyqtSignal(list) 177 | 178 | def __init__(self): 179 | super(self.__class__, self).__init__() 180 | self.setText(" Drop Area") 181 | self.setAcceptDrops(True) 182 | 183 | font = Qt.QFont() 184 | font.setFamily("arial") 185 | font.setPointSize(13) 186 | self.setFont(font) 187 | 188 | self.setAlignment(Qt.Qt.AlignCenter) 189 | 190 | def dropEvent(self, event): 191 | if event.mimeData().urls(): 192 | event.accept() 193 | self.drop_accepted_signal.emit([x.toLocalFile() for x in event.mimeData().urls()]) 194 | self.reset_dropEvent(event) 195 | 196 | def reset_dropEvent(self, event): 197 | mimeData = Qt.QMimeData() 198 | mimeData.setText("") 199 | dummyEvent = Qt.QDropEvent(event.posF(), event.possibleActions(), 200 | mimeData, event.mouseButtons(), event.keyboardModifiers()) 201 | 202 | super(self.__class__, self).dropEvent(dummyEvent) 203 | 204 | 205 | def default_signal_for_connection(signal): 206 | if isinstance(signal, QtWidgets.QPushButton) or isinstance(signal, QtWidgets.QToolButton) or isinstance(signal, QtWidgets.QRadioButton) or isinstance( 207 | signal, QtWidgets.QCheckBox): 208 | signal = signal.clicked 209 | elif isinstance(signal, QtWidgets.QLineEdit): 210 | signal = signal.textChanged 211 | elif isinstance(signal, QtWidgets.QDoubleSpinBox) or isinstance(signal, QtWidgets.QSpinBox): 212 | signal = signal.valueChanged 213 | return signal 214 | 215 | 216 | def disconnect_all(signal, slot): 217 | signal = default_signal_for_connection(signal) 218 | marker = False 219 | while not marker: 220 | try: 221 | signal.disconnect(slot) 222 | except Exception as e: # TODO: determine what's the specific exception? 223 | # traceback.print_exc() 224 | # print(e) 225 | marker = True 226 | 227 | 228 | def connect_once(signal, slot): 229 | signal = default_signal_for_connection(signal) 230 | disconnect_all(signal, slot) 231 | signal.connect(slot) 232 | 233 | 234 | def build_fileDialog_filter(allowed_appendix: list, tags=()): 235 | """ 236 | 237 | :param allowed_appendix: a list of list, each group shows together [[xlsx,log,out],[txt,com,gjf]] 238 | :param tags: list, tag for each group, default "" 239 | :return: a compiled filter ready for Qt.getOpenFileNames or other similar functions 240 | e.g. "Input File (*.gjf *.inp *.com *.sdf *.xyz)\n Output File (*.out *.log *.xlsx *.txt)" 241 | """ 242 | 243 | if not tags: 244 | tags = [""] * len(allowed_appendix) 245 | else: 246 | assert len(tags) == len(allowed_appendix) 247 | 248 | ret = "" 249 | for count, appendix_group in enumerate(allowed_appendix): 250 | ret += tags[count].strip() 251 | ret += "(*." 252 | ret += ' *.'.join(appendix_group) 253 | ret += ')' 254 | if count + 1 != len(allowed_appendix): 255 | ret += '\n' 256 | 257 | return ret 258 | 259 | 260 | def alert_UI(message="", title="", parent=None): 261 | # 旧版本的alert UI定义是alert_UI(parent=None,message="") 262 | if not isinstance(message, str) and isinstance(title, str) and parent is None: 263 | parent, message, title = message, title, "" 264 | elif not isinstance(message, str) and isinstance(title, str) and isinstance(parent, str): 265 | parent, message, title = message, title, parent 266 | print(message) 267 | if not QApplication.instance(): 268 | QApplication(sys.argv) 269 | if not title: 270 | title = message 271 | Qt.QMessageBox.critical(parent, title, message) 272 | 273 | 274 | def warning_UI(message="", parent=None): 275 | # 旧版本的alert UI定义是alert_UI(parent=None,message="") 276 | if not isinstance(message, str): 277 | message, parent = parent, message 278 | print(message) 279 | if not QApplication.instance(): 280 | QApplication(sys.argv) 281 | Qt.QMessageBox.warning(parent, message, message) 282 | 283 | 284 | def information_UI(message="", parent=None): 285 | # 旧版本的alert UI定义是alert_UI(parent=None,message="") 286 | 287 | if not isinstance(message, str): 288 | message, parent = parent, message 289 | print(message) 290 | if not QApplication.instance(): 291 | QApplication(sys.argv) 292 | Qt.QMessageBox.information(parent, message, message) 293 | 294 | 295 | def wait_confirmation_UI(parent=None, message=""): 296 | if not QApplication.instance(): 297 | QApplication(sys.argv) 298 | button = Qt.QMessageBox.warning(parent, message, message, Qt.QMessageBox.Ok | Qt.QMessageBox.Cancel) 299 | if button == Qt.QMessageBox.Ok: 300 | return True 301 | else: 302 | return False 303 | 304 | 305 | def get_open_file_UI(parent, start_path: str, allowed_appendix, title="No Title", tags=(), single=False): 306 | """ 307 | 308 | :param parent 309 | :param start_path: 310 | :param allowed_appendix: same as function (build_fileDialog_filter) 311 | but allow single str "txt" or single list ['txt','gjf'] as input, list of list is not necessary 312 | :param title: 313 | :param tags: 314 | :param single: 315 | :return: a list of files if not single, a single filepath if single 316 | """ 317 | 318 | if not QApplication.instance(): 319 | QApplication(sys.argv) 320 | 321 | if isinstance(allowed_appendix, str): # single str 322 | allowed_appendix = [[allowed_appendix]] 323 | if [x for x in allowed_appendix if isinstance(x, str)]: # single list not list of list 324 | allowed_appendix = [allowed_appendix] 325 | 326 | filename_filter_string = build_fileDialog_filter(allowed_appendix, tags) 327 | 328 | if single: 329 | ret = QtWidgets.QFileDialog.getOpenFileName(parent, title, start_path, filename_filter_string) 330 | if ret: # 上面返回 ('E:/My_Program/Python_Lib/elements_dict.txt', '(*.txt)') 331 | ret = ret[0] 332 | else: 333 | ret = QtWidgets.QFileDialog.getOpenFileNames(parent, title, start_path, filename_filter_string) 334 | if ret: # 上面返回 (['E:/My_Program/Python_Lib/elements_dict.txt'], '(*.txt)') 335 | ret = ret[0] 336 | 337 | return ret 338 | 339 | 340 | def show_pixmap(image_filename, graphicsView_object): 341 | # must call widget.show() holding the graphicsView, otherwise the View.size() will get a wrong (100,30) value 342 | if os.path.isfile(image_filename): 343 | pixmap = QtGui.QPixmap() 344 | pixmap.load(image_filename) 345 | 346 | print(graphicsView_object.size()) 347 | 348 | if pixmap.width() > graphicsView_object.width() or pixmap.height() > graphicsView_object.height(): 349 | pixmap = pixmap.scaled(graphicsView_object.size(), Qt.Qt.KeepAspectRatio, Qt.Qt.SmoothTransformation) 350 | else: 351 | pixmap = QtGui.QPixmap() 352 | 353 | graphicsPixmapItem = QtWidgets.QGraphicsPixmapItem(pixmap) 354 | graphicsScene = QtWidgets.QGraphicsScene() 355 | graphicsScene.addItem(graphicsPixmapItem) 356 | graphicsView_object.setScene(graphicsScene) 357 | 358 | 359 | def update_UI(): 360 | QtCore.QCoreApplication.processEvents() 361 | 362 | 363 | def exit_UI(): 364 | QtCore.QCoreApplication.instance().quit() 365 | 366 | 367 | def clear_layout(layout): 368 | while not layout.isEmpty(): 369 | layout.itemAt(0).widget().deleteLater() 370 | layout.removeItem(layout.itemAt(0)) 371 | 372 | 373 | def add_list_to_layout(layout, list_of_item): 374 | for item in list_of_item: 375 | if isinstance(item, Qt.QWidget): 376 | layout.addWidget(item) 377 | if isinstance(item, Qt.QLayout): 378 | layout.addLayout(item) 379 | 380 | 381 | def pyqt_ui_compile(filename): 382 | # 允许将.ui文件放在命名为UI的文件夹下,或程序目录下,但只输入文件名,而不必输入“UI/” 383 | 384 | if filename[:3] in ['UI\\', 'UI/']: 385 | filename = filename[3:] 386 | 387 | ui_filename = filename_class(filename).replace_append_to('ui') 388 | # print(os.path.abspath(ui_filename)) 389 | if not os.path.isfile(ui_filename): 390 | ui_filename = 'UI/' + ui_filename 391 | modify_log_filename = filename_class(ui_filename).replace_append_to('txt') 392 | py_file = filename_class(ui_filename).replace_append_to('py') 393 | 394 | modify_time = "" 395 | if os.path.isfile(modify_log_filename): 396 | with open(modify_log_filename) as modify_log_file: 397 | modify_time = modify_log_file.read() 398 | 399 | if modify_time != str(int(os.path.getmtime(ui_filename))): 400 | print("GUI MODIFIED:", ui_filename) 401 | with open(modify_log_filename, 'w') as modify_log_file: 402 | modify_log_file.write(str(int(os.path.getmtime(ui_filename)))) 403 | 404 | ui_File_Compile = open(py_file, 'w') 405 | uic.compileUi(ui_filename, ui_File_Compile) 406 | ui_File_Compile.close() 407 | with open(py_file, encoding='gbk') as ui_File_Compile_object: 408 | ui_File_Compile_content = ui_File_Compile_object.read() 409 | with open(py_file, 'w', encoding='utf-8') as ui_File_Compile_object: 410 | ui_File_Compile_object.write(ui_File_Compile_content) 411 | 412 | 413 | def wait_messageBox(message, title="Please Wait..."): 414 | if not QApplication.instance(): 415 | QApplication(sys.argv) 416 | 417 | message_box = Qt.QMessageBox() 418 | message_box.setWindowTitle(title) 419 | message_box.setText(message) 420 | 421 | return message_box 422 | -------------------------------------------------------------------------------- /Python_Lib/My_Lib_PyQt6_Create_Symlink.bat: -------------------------------------------------------------------------------- 1 | pushd %~dp0 2 | powershell -Command "New-Item -ItemType HardLink -Path .\My_Lib_PyQt6.py -Target ..\..\Python_Lib\My_Lib_PyQt6.py" 3 | pause -------------------------------------------------------------------------------- /Python_Lib/My_Lib_Stock_Create_Symlink.bat: -------------------------------------------------------------------------------- 1 | pushd %~dp0 2 | powershell -Command "New-Item -ItemType HardLink -Path .\My_Lib_Stock.py -Target ..\..\Python_Lib\My_Lib_Stock.py" 3 | pause -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Eyring Equation and Chemical Kinetics Calculator 2 | [](https://zenodo.org/badge/latestdoi/548741869) 3 | 4 | A simple program to solve the Eyring Equation and first/second order kinetics. 5 | 6 | [Download](https://github.com/liyuanhe211/Chemical_Kinetics_Calculator/releases/download/1.3/Chemical.Kinetics.Calculator.1.3.zip) 7 | 8 | ## 9 | ### Launch 10 | 11 | You can [download a release](https://github.com/liyuanhe211/Eyring_Eq/releases) for Windows 10/11 which includes the executable `Eyring Eq X.X.exe`. 12 | 13 | Alternatively, if you choose to set up your own environment: 14 | 15 | Get a Python environment (tested on Python 3.9). Launch a shell/cmd/PowerShell window from the cloned directory. Run: 16 | ``` 17 | pip install pipenv 18 | mkdir .venv 19 | pipenv sync 20 | pipenv run python Eyring_Eq.py 21 | ``` 22 | 23 | 24 | 25 | ## 26 | ### Background 27 | In literature, people often quote inexact rules like "21 kcal/mol at room temperature" when discussing calculated activation Gibbs free energies. They (sometimes including reviewers) might even ask for references to support these crude rules or ask for values at different conditions, which are difficult to find for the exact condition you need. In contrast, based on Eyring equation and first/second order kinetics (assuming the reaction is kinetically controlled), it's easy to calculate the reaction time, required temperatures, etc, exactly to our need. I created this simple program to automate these calculations. 28 | ## 29 | ### Usage 30 | 31 | To use the program, fill in the known values for the equations, and leave the unknown values blank. If the number of filled parameters is sufficient (and not excessive), the \[Calculate\] button will become available. Click it to get the values you left blank. 32 | 33 | For example, you can calculate: 34 | 35 | For a 21 kcal/mol unimolecular reaction to get a 98% conversion at 20 °C, you need 49 min. 36 | 37 |M-1·s-1
")) 553 | self.label.setText(_translate("Eyring_Eq", "ΔG≠
")) 554 | self.label_6.setText(_translate("Eyring_Eq", "kTST
")) 555 | self.conversion_lineEdit.setText(_translate("Eyring_Eq", "98")) 556 | self.conc1_unit_label.setText(_translate("Eyring_Eq", "mol/L")) 557 | self.label_4.setText(_translate("Eyring_Eq", "Rxn Time")) 558 | self.conv_label.setText(_translate("Eyring_Eq", "Conv.")) 559 | self.label_12.setText(_translate("Eyring_Eq", "%")) 560 | self.conc2_label.setText(_translate("Eyring_Eq", "Conc. B")) 561 | self.conc2_unit_label.setText(_translate("Eyring_Eq", "mol/L")) 562 | self.sigma_lineEdit.setText(_translate("Eyring_Eq", "1")) 563 | self.clear_G_pushButton.setText(_translate("Eyring_Eq", "×")) 564 | self.clear_sigma_pushButton.setText(_translate("Eyring_Eq", "×")) 565 | self.clear_k_pushButton.setText(_translate("Eyring_Eq", "×")) 566 | self.clear_T_pushButton.setText(_translate("Eyring_Eq", "×")) 567 | self.clear_conc1_pushButton.setText(_translate("Eyring_Eq", "×")) 568 | self.groupBox.setTitle(_translate("Eyring_Eq", "Reaction Type")) 569 | self.unimolecular_radioButton.setText(_translate("Eyring_Eq", "A → P")) 570 | self.bimolecular_AA_radioButton.setText(_translate("Eyring_Eq", "A + A → P")) 571 | self.bimolecular_AB_radioButton.setText(_translate("Eyring_Eq", "A + B → P")) 572 | self.bimolecular_A_Cat_radioButton.setText(_translate("Eyring_Eq", "A + Cat → P + Cat")) 573 | self.clear_conc2_pushButton.setText(_translate("Eyring_Eq", "×")) 574 | self.clear_t_pushButton.setText(_translate("Eyring_Eq", "×")) 575 | self.clear_conv_pushButton.setText(_translate("Eyring_Eq", "×")) 576 | self.energy_unit_comboBox.setCurrentText(_translate("Eyring_Eq", "kJ/mol")) 577 | self.energy_unit_comboBox.setItemText(0, _translate("Eyring_Eq", "kJ/mol")) 578 | self.energy_unit_comboBox.setItemText(1, _translate("Eyring_Eq", "kcal/mol")) 579 | self.energy_unit_comboBox.setItemText(2, _translate("Eyring_Eq", "eV")) 580 | self.time_unit_comboBox.setCurrentText(_translate("Eyring_Eq", "s")) 581 | self.time_unit_comboBox.setItemText(0, _translate("Eyring_Eq", "s")) 582 | self.time_unit_comboBox.setItemText(1, _translate("Eyring_Eq", "min")) 583 | self.time_unit_comboBox.setItemText(2, _translate("Eyring_Eq", "h")) 584 | self.time_unit_comboBox.setItemText(3, _translate("Eyring_Eq", "d")) 585 | self.time_unit_comboBox.setItemText(4, _translate("Eyring_Eq", "year")) 586 | self.calculate_pushButton.setText(_translate("Eyring_Eq", "Calculate")) 587 | self.calculate_pushButton.setShortcut(_translate("Eyring_Eq", "Ctrl+Shift+C")) 588 | self.recalc_pushButton.setText(_translate("Eyring_Eq", "Recalculate")) 589 | self.recalc_pushButton.setShortcut(_translate("Eyring_Eq", "Ctrl+Shift+V")) 590 | self.reset_all_pushButton.setText(_translate("Eyring_Eq", "Reset All")) 591 | self.reset_all_pushButton.setShortcut(_translate("Eyring_Eq", "Ctrl+Shift+R")) 592 | self.batch_pushButton.setText(_translate("Eyring_Eq", "Batch")) 593 | self.batch_pushButton.setShortcut(_translate("Eyring_Eq", "Ctrl+Shift+R")) 594 | self.status_label_2.setText(_translate("Eyring_Eq", "You can input any Python arithmetic expression, e.g. input 2E3*4.18 for 8360.
")) 595 | self.status_label_3.setText(_translate("Eyring_Eq", "If the [Calculate] button is not enabled, check your number of parameters.
")) 596 | self.status_label_5.setText(_translate("Eyring_Eq", "Shortcut: [Reset All] - Ctrl+Shift+R, [Calculate] - Ctrl+Shift+C, [Recalculate] - Ctrl+Shift+V
")) 597 | -------------------------------------------------------------------------------- /UI/Eyring_Eq.txt: -------------------------------------------------------------------------------- 1 | 1677509642 -------------------------------------------------------------------------------- /UI/Eyring_Eq.ui: -------------------------------------------------------------------------------- 1 | 2 |