forked from FOSSEE/Chemical-Simulator-GUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mainApp.py
355 lines (309 loc) · 13.2 KB
/
mainApp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
from functools import partial
from collections import defaultdict
import sys
import numpy as np
from OMChem.Flowsheet import Flowsheet
import pandas as pd
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QTextDocument ,QTextCursor ,QTextCharFormat ,QFont ,QPixmap
from PyQt5.uic import loadUiType
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QGraphicsProxyWidget, QGraphicsObject, QGraphicsEllipseItem ,QGraphicsPixmapItem,QApplication, QGraphicsView, QGraphicsScene, QHBoxLayout, QWidget, QLabel, QUndoStack
from PyQt5.QtGui import QBrush ,QTransform ,QMouseEvent
import PyQt5.QtGui as QtGui
import PyQt5.QtCore as QtCore
import PyQt5.QtWidgets as QtWidgets
from component_selector import *
from dockWidget import dockWidget
from Bin_Phase_env import *
from resDockWidget import resdockWidget
from UnitOperations import *
from Streams import *
import datetime
from container import Container
from Graphics import Graphics
import pickle
import threading
import os
import ctypes
import sys
ui,_ = loadUiType('main.ui')
'''
MainApp class is responsible for all the main App Ui operations
'''
class MainApp(QMainWindow,ui):
'''
Initializing the application
'''
def __init__(self):
QMainWindow.__init__(self)
# Loading and setting up style sheet
self.setupUi(self)
style = open('light.css','r')
style = style.read()
self.setStyleSheet(style)
# Initializing attributes
self.zoomcount = 0
self.thrd = None
# Creating instances of classes for the main app
self.Container = Container(self.textBrowser)
self.comp = componentSelector(self)
'''self.Container = self.graphics.getContainer(self.textBrowser)
self.comp = self.graphics.getComponentSelector()'''
# Setting up interactive canvas
'''self.scene = QGraphicsScene()
self.scene.setItemIndexMethod(QGraphicsScene.BspTreeIndex)
self.graphicsView.setScene(self.scene)
self.graphicsView.setMouseTracking(True)
self.graphicsView.keyPressEvent=self.deleteCall'''
self.graphics = Graphics()
self.scene = self.graphics.getScene()
self.graphicsView.setScene(self.scene)
self.graphicsView.setMouseTracking(True)
self.graphicsView.keyPressEvent=self.deleteCall
self.setDockNestingEnabled(True)
self.setCorner(Qt.BottomRightCorner, Qt.RightDockWidgetArea)
self.setCorner(Qt.BottomLeftCorner, Qt.LeftDockWidgetArea)
self.addDockWidget(Qt.BottomDockWidgetArea,self.dockWidget_2)
# Setting up undo stack
# self.undoStack = QUndoStack(self)
# Calling initialisation functions
self.buttonHandler()
self.menuBar()
self.comp.show()
'''
MenuBar function handels all the all the operations of
menu bar like new,zoom,comounds selector, simulation options.
'''
def menuBar(self):
self.actionSelect_compounds.triggered.connect(self.selectCompounds)
self.actionSelect_compounds.setShortcut('Ctrl+C')
self.actionZoomIn.triggered.connect(self.zoomin)
self.actionZoomIn.setShortcut('Ctrl++')
self.actionNew_Flowsheet.triggered.connect(self.new)
self.actionNew_Flowsheet.setShortcut('Ctrl+N')
self.actionZoomOut.triggered.connect(self.zoomout)
self.actionZoomOut.setShortcut('Ctrl+-')
self.actionResetZoom.triggered.connect(self.zoomReset)
self.actionResetZoom.setShortcut('Ctrl+R')
self.actionHelp.triggered.connect(self.help)
self.actionHelp.setShortcut('Ctrl+H')
self.actionSequential_mode.triggered.connect(partial(self.simulate,'SM'))
self.actionSequential_mode.setShortcut('Ctrl+M')
self.actionEquation_oriented.triggered.connect(partial(self.simulate,'EQN'))
self.actionEquation_oriented.setShortcut('Ctrl+E')
# self.actionUndo_2.triggered.connect(self.undoStack.undo)
# self.actionRedo.triggered.connect(self.undoStack.redo)
self.actionSave_2.triggered.connect(self.save)
self.actionSave_2.setShortcut('Ctrl+S')
self.actionOpen.triggered.connect(self.open)
self.actionOpen.setShortcut('Ctrl+O')
self.actionTerminate.triggered.connect(self.terminate)
self.actionTerminate.setShortcut('Ctrl+T')
self.actionBinary_Phase_Envelope.triggered.connect(self.BinPhaseEnv)
'''
Handles all the buttons of different components.
'''
def buttonHandler(self):
self.pushButton.clicked.connect(partial(self.component,'MaterialStream'))
self.pushButton_7.clicked.connect(partial(self.component,'Mixer'))
self.pushButton_14.clicked.connect(partial(self.component,'Pump'))
self.pushButton_26.clicked.connect(partial(self.component,'DistCol'))
self.pushButton_18.clicked.connect(partial(self.component,'ShortCol'))
self.pushButton_11.clicked.connect(partial(self.component,'Heater'))
self.pushButton_10.clicked.connect(partial(self.component,'Splitter'))
self.pushButton_9.clicked.connect(partial(self.component,'Flash'))
self.pushButton_25.clicked.connect(partial(self.component,'Valve'))
self.pushButton_12.clicked.connect(partial(self.component,'Cooler'))
self.pushButton_13.clicked.connect(partial(self.component,'CompSep'))
self.pushButton_15.clicked.connect(partial(self.component,'AdiabaticCompressor'))
self.pushButton_16.clicked.connect(partial(self.component,'AdiabaticExpander'))
'''
Displays help box
'''
def help(self):
msgBox = QMessageBox()
msgBox.setIcon(QMessageBox.Question)
msgBox.setTextFormat(Qt.RichText);
msgBox.setText("For any Help or Suggestion you can contact us at\n [email protected] or at <a href='https://www.fossee.in'>Visit fossee.in!</a>")
msgBox.setStandardButtons(QMessageBox.Ok)
msgBox.exec_()
def BinPhaseEnv(self):
#compounds = self.comp.getComp()
if len(self.comp.getComp())<2:
QMessageBox.about(self, 'Important', "Please select atleast 2 Compounds first")
self.comp.show()
#compunds = self.comp.getComp()
else:
self.bin_phase = Bin_Phase_env(self.comp)
self.bin_phase.show()
'''
Shows Compounds Selector Dialog
'''
def selectCompounds(self):
self.comp.show()
'''
Returns currenttime in a required particular format
'''
def currentTime(self):
now = datetime.datetime.now()
time = str(now.hour) + ":" + str(now.minute) + ":" +str(now.second)
return time
'''
Simulate function is responsible for the simulation
of the designed flowsheet in a particular mode
selected by the user.
'''
def simulate(self,mode):
self.thrd = threading.Thread(target=self.Container.simulate, args=(mode,))
self.thrd.start()
# self.Container.simulate(mode)
self.dockWidget_2.show()
self.res = resdockWidget(self.Container)
self.addDockWidget(Qt.LeftDockWidgetArea, self.res)
self.res.show()
def terminate(self):
os.chdir(self.Container.flowsheet.root_dir)
if self.thrd:
thread_id = self.thrd.ident
print('____________________Going to terminate simulation thread with Thread ID:',thread_id,'____________________')
print('____________________Going to terminate the new process created for omc____________________')
self.Container.flowsheet.process.terminate()
print('____________________New process created for omc is terminated.____________________')
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, ctypes.py_object(SystemExit))
self.textBrowser.append("<span style=\"color:red\">["+str(self.currentTime())+"]<b> Terminating the simulation </b></span>")
print('____________________Simulation thread terminated____________________')
if res > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
print('Exception raise (Thread termination) failure')
'''
Resets the zoom level to default scaling
'''
def zoomReset(self):
if(self.zoomcount>0):
for i in range(self.zoomcount):
self.zoomout()
elif(self.zoomcount<0):
for i in range(abs(self.zoomcount)):
self.zoomin()
'''
ZoomOut the canvas
'''
def zoomout(self):
self.graphicsView.scale(1.0/1.15,1.0/1.15)
self.zoomcount -=1
'''
ZoomIn the canvas
'''
def zoomin(self):
self.graphicsView.scale(1.15,1.15)
self.zoomcount +=1
'''
Instantiate a NodeItem object for selected type of
component and added that on canvas/flowsheeting area.
'''
def component(self,unitOpType):
if(self.comp.isCompSelected()):
self.type = unitOpType
if(self.type=="MaterialStream"):
self.obj = MaterialStream(CompNames=compound_selected)
else:
self.obj = eval(self.type)()
self.Container.addUnitOp(self.obj,self.scene,self.graphics)
else:
QMessageBox.about(self, 'Important', "Please Select Compounds first")
self.comp.show()
'''
New is used to delete all the existing work.
'''
def new(self):
l=self.scene.items()
compound_selected.clear()
self.comp.tableWidget.setRowCount(0)
self.delete(l)
self.textBrowser.append("<span>["+str(self.currentTime())+"] <b>New</b> flowsheet is created ... </span>")
self.comp.show()
'''
Handels all the operations which will happen when delete button is pressed.
'''
def deleteCall(self,event):
try:
if event.key() == QtCore.Qt.Key_Delete:
l=self.scene.selectedItems()
self.delete(l)
except Exception as e:
print(e)
'''
Deletes the selected item from the canvas and also the objects
created for that type.
'''
def delete(self,l):
# if isinstance(l,NodeItem):
# l = [l]
for item in l:
self.scene.removeItem(item)
if hasattr(item,'Input'):
for x in item.Input:
if x.newLine:
self.scene.removeItem(x.newLine)
del x.newLine
if x.otherLine:
self.scene.removeItem(x.otherLine)
del x.otherLine
if hasattr(item,'Output'):
for x in item.Output:
if x.newLine:
self.scene.removeItem(x.newLine)
del x.newLine
if x.otherLine:
self.scene.removeItem(x.otherLine)
del x.otherLine
if hasattr(item,'obj'):
self.Container.unitOp.remove(item.obj)
for k in list(self.Container.conn):
if item.obj==k:
del self.Container.conn[k]
elif item.obj in self.Container.conn[k]:
self.Container.conn[k].remove(item.obj)
self.textBrowser.append("<span style=\"color:blue\">["+str(self.currentTime())+"]<b> "+item.obj.name+" </b>is deleted .""</span>")
del item.obj
del item
'''
Function for saving the current canvas items and compound_selected
'''
def save(self):
def jdefault(o):
return o.__dict__
data = []
for i in self.Container.unitOp:
data.append(i)
data.append(self.comp.getComp())
fileFormat = 'sim'
initialPath = QDir.currentPath() + 'untitled.' + fileFormat
fileName, _ = QFileDialog.getSaveFileName(self, "Save As",
initialPath, "%s Files (*.%s);; All Files (*)" %
(fileFormat.upper(), fileFormat))
with open(fileName, 'wb') as f: #'saved_file.sim'
pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
'''
Function for loading previous saved canvas and simulation
***Not finished yet***
'''
def open(self):
fileFormat = 'sim'
initialPath = QDir.currentPath() + 'untitled.' + fileFormat
fileName, _ = QFileDialog.getOpenFileName(self, "Open As",
initialPath, "%s Files (*.%s);; All Files (*)" %
(fileFormat.upper(), fileFormat))
with open(fileName, 'rb') as f:
obj = pickle.load(f)
for i in obj:
print(i)
def main():
app = QApplication(sys.argv)
window = MainApp()
window.showMaximized()
app.exec()
if __name__ == '__main__':
main()