diff options
-rw-r--r-- | Graphics.py | 98 | ||||
-rw-r--r-- | OMChem/Flowsheet.py | 908 | ||||
-rw-r--r-- | OMChem/MatStm.py | 158 | ||||
-rw-r--r-- | OMChem/UnitOprns.py | 154 | ||||
-rw-r--r-- | container.py | 76 | ||||
-rw-r--r-- | helper.py | 316 | ||||
-rw-r--r-- | mainApp.py | 14 |
7 files changed, 1009 insertions, 715 deletions
diff --git a/Graphics.py b/Graphics.py index 4d0a5ea..3184019 100644 --- a/Graphics.py +++ b/Graphics.py @@ -4,10 +4,6 @@ import sys import numpy as np from OMChem.Flowsheet import Flowsheet from OMChem.MatStm import MatStm -from OMChem.Mixer import Mixer -from OMChem.Heater import Heater -from OMChem.Splitter import Splitter -from OMChem.ShortcutColumn import ShortcutColumn import pandas as pd from PyQt5.QtCore import * @@ -20,31 +16,31 @@ 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 componentSelector from component_selector import * from dockWidget import dockWidget from resDockWidget import resdockWidget -from helper import helperFunc + import datetime from container import Container + + class Graphics(QDialog): def __init__(self): QDialog.__init__(self) self.scene = QGraphicsScene() - self.scene.setItemIndexMethod(QGraphicsScene.BspTreeIndex) + self.scene.setItemIndexMethod(QGraphicsScene.BspTreeIndex) def getScene(self): return self.scene - '''def getContainer(self, textBrowser): - return Container(textBrowser) - def getComponentSelector(self): - return componentSelector(self)''' + return componentSelector(self) - def createNodeItem(self, conntype, container): - return NodeItem(conntype, container) + def createNodeItem(self,unitOpr): + return NodeItem(unitOpr) class NodeLine(QtWidgets.QGraphicsPathItem): def __init__(self, pointA, pointB , socket): @@ -140,12 +136,11 @@ class NodeLine(QtWidgets.QGraphicsPathItem): del self._pointB class NodeSocket(QtWidgets.QGraphicsItem): - def __init__(self, rect, parent, socketType,container): + def __init__(self, rect, parent, socketType): super(NodeSocket, self).__init__(parent) self.rect = rect self.type = socketType self.parent=parent - self.container=container self.newLine=None self.otherLine=None @@ -213,19 +208,26 @@ class NodeSocket(QtWidgets.QGraphicsItem): def mouseReleaseEvent(self, event): item = self.scene().itemAt(event.scenePos().toPoint(),QtGui.QTransform()) + stm = ['MatStm','EngStm'] item.otherLine=self.newLine if (self.type == 'op') and (item.type == 'in'): self.newLine.source = self self.newLine.target = item item.inLines.append(self.newLine) self.newLine.pointB = item.getCenter() - self.container.updateConn(self.newLine.source.parent.obj,self.newLine.target.parent.obj) + if self.newLine.source.parent.obj.type not in stm: + self.newLine.source.parent.obj.add_connection(0,self.newLine.target.parent.obj) + if self.newLine.target.parent.obj not in stm: + self.newLine.target.parent.obj.add_connection(1,self.newLine.source.parent.obj) elif (self.type =='in') and (item.type == 'op'): self.newLine.source = item self.newLine.target = self item.outLines.append(self.newLine) self.newLine.pointA = item.getCenter() - self.container.updateConn(self.newLine.source.parent.obj,self.newLine.target.parent.obj) + if self.newLine.source.parent.obj.type not in stm: + self.newLine.source.parent.obj.add_connection(0,self.newLine.target.parent.obj) + if self.newLine.target.parent.obj not in stm: + self.newLine.target.parent.obj.add_connection(1,self.newLine.source.parent.obj) else: self.scene().removeItem(self.newLine) if(self.newLine in self.inLines): @@ -242,34 +244,28 @@ class NodeSocket(QtWidgets.QGraphicsItem): return center class NodeItem(QtWidgets.QGraphicsItem): - def __init__(self,comptype,container): + def __init__(self,unitOpr): l = ['Mixer','Splitter'] super(NodeItem, self).__init__() - self.type = comptype - - # for creating unit operation objects without helper function - if (self.type == 'MatStm'): - self.obj = MatStm(CompNames=compound_selected) - elif (self.type == 'ShortCol'): # the only class that class name and type does not match - self.obj = ShortcutColumn() - else: - self.obj = eval(self.type)() + self.obj = unitOpr - #self.obj = myhelperFunc(self.type) - self.name = self.obj.getname() - self.pos = None + self.name = self.obj.name + self.type = self.obj.type self.setToolTip(self.name) - self.nin = self.obj.no_of_input - self.nop = self.obj.no_of_output - - self.container=container - self.container.addUnitOp(self.obj) - if(self.type not in l): + self.nin = self.obj.no_of_inputs + self.nop = self.obj.no_of_outputs + + self.dockWidget = None + + + + if(self.obj.type not in l): + self.dockWidget = dockWidget(self.obj.name,self.obj.type,self.obj) self.mainwindow= findMainWindow(self) - self.dockWidget=dockWidget(self.name,self.type,self.obj) self.mainwindow.addDockWidget(Qt.LeftDockWidgetArea, self.dockWidget) self.dockWidget.hide() + self.pic=QtGui.QPixmap("icons/"+self.type+".png") self.rect = QtCore.QRect(0,0,self.pic.width(),self.pic.height()) @@ -322,32 +318,31 @@ class NodeItem(QtWidgets.QGraphicsItem): def initializeSockets(self,type): if(self.type=="Flash" or self.type=="CompSep"): - Input = [NodeSocket(QtCore.QRect(-2.5+5.5,(self.rect.height()*x/(self.nin+1))-8,4,4), self, 'in',self.container) for x in range(1,self.nin+1) ] - Output = [NodeSocket(QtCore.QRect(self.rect.width()-7.5,(self.rect.height()*x*0.90/(self.nop+1))-4,4,4), self, 'op',self.container) for x in range(1,self.nop+1)] + Input = [NodeSocket(QtCore.QRect(-2.5+5.5,(self.rect.height()*x/(self.nin+1))-8,4,4), self, 'in') for x in range(1,self.nin+1) ] + Output = [NodeSocket(QtCore.QRect(self.rect.width()-7.5,(self.rect.height()*x*0.90/(self.nop+1))-4,4,4), self, 'op') for x in range(1,self.nop+1)] return Input,Output elif(self.type=="AdiaComp" or self.type=="AdiaExp" or self.type =="Mixer" or self.type =="Splitter" or self.type =="Valve" ): - Input = [NodeSocket(QtCore.QRect(-3.5,(self.rect.height()*x/(self.nin+1))-6,4,4), self, 'in',self.container) for x in range(1,self.nin+1) ] - Output = [NodeSocket(QtCore.QRect(self.rect.width()-2.5,(self.rect.height()*x/(self.nop+1))-6,4,4), self, 'op',self.container) for x in range(1,self.nop+1)] + Input = [NodeSocket(QtCore.QRect(-3.5,(self.rect.height()*x/(self.nin+1))-6,4,4), self, 'in') for x in range(1,self.nin+1) ] + Output = [NodeSocket(QtCore.QRect(self.rect.width()-2.5,(self.rect.height()*x/(self.nop+1))-6,4,4), self, 'op') for x in range(1,self.nop+1)] return Input,Output elif(self.type=="Cooler" or self.type=="Heater"): - Input = [NodeSocket(QtCore.QRect(3.5,(self.rect.height()*x/(self.nin+1))-4,4,4), self, 'in',self.container) for x in range(1,self.nin+1) ] - Output = [NodeSocket(QtCore.QRect(self.rect.width()-8.0,(self.rect.height()*x/(self.nop+1))-4,4,4), self, 'op',self.container) for x in range(1,self.nop+1)] + Input = [NodeSocket(QtCore.QRect(3.5,(self.rect.height()*x/(self.nin+1))-4,4,4), self, 'in') for x in range(1,self.nin+1) ] + Output = [NodeSocket(QtCore.QRect(self.rect.width()-8.0,(self.rect.height()*x/(self.nop+1))-4,4,4), self, 'op') for x in range(1,self.nop+1)] return Input,Output elif(self.type=="Pump"): - Input = [NodeSocket(QtCore.QRect(-2.5,(self.rect.height()*x/(self.nin+1))-10,4,4), self, 'in',self.container) for x in range(1,self.nin+1) ] - Output = [NodeSocket(QtCore.QRect(self.rect.width()-2.5,-2.5,4,4), self, 'op',self.container) for x in range(1,self.nop+1)] + Input = [NodeSocket(QtCore.QRect(-2.5,(self.rect.height()*x/(self.nin+1))-10,4,4), self, 'in') for x in range(1,self.nin+1) ] + Output = [NodeSocket(QtCore.QRect(self.rect.width()-2.5,-2.5,4,4), self, 'op') for x in range(1,self.nop+1)] return Input,Output elif(self.type=="DistCol" or self.type=="ShortCol"): - Input = [NodeSocket(QtCore.QRect(-2.5,(self.rect.height()*x/(self.nin+1))-12,5,5), self, 'in',self.container) for x in range(1,self.nin+1) ] - Output = [NodeSocket(QtCore.QRect(self.rect.width()-5.5,(self.rect.height()*1.44*x/(self.nop+1))-67,5,5), self, 'op',self.container) for x in range(1,self.nop+1)] + Input = [NodeSocket(QtCore.QRect(-2.5,(self.rect.height()*x/(self.nin+1))-12,5,5), self, 'in') for x in range(1,self.nin+1) ] + Output = [NodeSocket(QtCore.QRect(self.rect.width()-5.5,(self.rect.height()*1.44*x/(self.nop+1))-67,5,5), self, 'op') for x in range(1,self.nop+1)] return Input,Output elif(self.type=="MatStm"): - Input = [NodeSocket(QtCore.QRect(-2.5,(self.rect.height()*x/(self.nin+1))-1,4,4), self, 'in',self.container) for x in range(1,self.nin+1) ] - Output = [NodeSocket(QtCore.QRect(self.rect.width()-2.5,(self.rect.height()*x/(self.nin+1))-1,4,4), self, 'op',self.container) for x in range(1,self.nop+1)] + Input = [NodeSocket(QtCore.QRect(-2.5,(self.rect.height()*x/(self.nin+1))-1,4,4), self, 'in') for x in range(1,self.nin+1) ] + Output = [NodeSocket(QtCore.QRect(self.rect.width()-2.5,(self.rect.height()*x/(self.nin+1))-1,4,4), self, 'op') for x in range(1,self.nop+1)] return Input,Output def mouseMoveEvent(self, event): - #print(event.scenePos()) super(NodeItem, self).mouseMoveEvent(event) for output in self.Output: for line in output.outLines: @@ -357,10 +352,9 @@ class NodeItem(QtWidgets.QGraphicsItem): for line in input.inLines: line.pointA = line.source.getCenter() line.pointB = line.target.getCenter() - self.pos = event.scenePos() - + def mouseDoubleClickEvent(self, event): - self.setPos(event.scenePos().x()-250,event.scenePos().y()) + #self.setPos(event.scenePos().x()-250,event.scenePos().y()) self.dockWidget.show() def findMainWindow(self): diff --git a/OMChem/Flowsheet.py b/OMChem/Flowsheet.py index cfd9bae..6b6c9ad 100644 --- a/OMChem/Flowsheet.py +++ b/OMChem/Flowsheet.py @@ -6,454 +6,472 @@ from subprocess import Popen, PIPE import pandas as pd class Flowsheet(): - def __init__(self): - self.sim_name = 'Simulator' - self.sim_method = '' - self.UnitOpn = [] - self.data = [] - self.compounds = [] - self.interface = '' - self.omc_path = None - self.curr_path = os.getcwd() # Chemical-Simulator-GUI - self.sim_dir_path = os.path.join(self.curr_path, self.sim_name) # Chemical-Simulator-GUI/Simulator - self.Flomo_path = os.path.join(self.sim_dir_path,'Flowsheet.mo') - self.eqn_mos_path = os.path.join(self.sim_dir_path,'simulateEQN.mos') - self.sm_mos_path = os.path.join(self.sim_dir_path,'simulateSM.mos') - self.resdata = [] - self.stdout=None - self.stderr=None - - - def get_omc_path(self): - try: - self.omhome = os.environ.get('OPENMODELICAHOME') - if self.omhome is None: - self.omhome = os.path.split(os.path.split(os.path.realpath(spawn.find_executable("omc")))[0])[0] - elif os.path.exists('/opt/local/bin/omc'): - self.omhome = '/opt/local' - return os.path.join(self.omhome, 'bin', 'omc') - except BaseException: - print("The OpenModelica compiler is missing in the System path please install it" ) - raise - - def add_UnitOpn(self,unitop,flag): - f=(unitop,flag) - self.UnitOpn.append(f) - - def remove_UnitOpn(self,unitop): - self.UnitOpn.remove(unitop) - - def add_comp_list(self,comp): - self.compounds = comp - - def send_for_simulationEqn(self): - self.resdata = [] - self.omc_path = self.get_omc_path() - print(self.omc_path) - - if self.sim_method == 'Eqn': - simpath = self.eqn_mos_path - os.chdir(self.sim_dir_path) - - process = Popen([self.omc_path, '-s',simpath], stdout=PIPE, stderr=PIPE) - self.stdout, self.stderr = process.communicate() - #s = subprocess.check_output([self.omc_path, '-s',simpath]) - #print(s) - #print("############### StdOut ################") - print(self.stdout) - os.chdir(self.curr_path) - #os.system(self.omc_path + ' -s ' + simpath) - print("Hello") - if self.sim_method == 'Eqn': - print("hhhh") - csvpath = os.path.join(self.sim_dir_path,'Flowsheet_res.csv') - print("csvPath",csvpath) - with open (csvpath,'r') as resultFile: - self.resdata = [] - print("opened") - csvreader = csv.reader(resultFile,delimiter=',') - for row in csvreader: - print("124125") - self.resdata.append(row) - #self.ExtData() - - - def send_for_simulationSM(self,unitop): - - self.resdata = [] - self.omc_path = self.get_omc_path() - os.chdir(self.sim_dir_path) - #os.system(self.omc_path + ' -s ' + unitop.name+'.mos') - process = Popen([self.omc_path, '-s',unitop.name,'.mos'], stdout=PIPE, stderr=PIPE) - stdout, stderr = process.communicate() - #s = subprocess.check_output([self.omc_path, '-s',simpath]) - #print(s) - print("############### StdOut ################") - print(stdout) - self.resdata = [] - print('Simulating '+unitop.name+'...') - csvpath = os.path.join(self.sim_dir_path,unitop.name+'_res.csv') - with open(csvpath,'r') as resultFile: - csvreader = csv.reader(resultFile,delimiter=',') - for row in csvreader: - self.resdata.append(row) - self.ExtData() - - - - - - # if self.sim_method == 'SM': - # for unitop in self.UnitOpn: - # self.resdata = [] - # if unitop.type != 'MatStm': - # print 'Simulating '+unitop.name+'...' - # csvpath = os.path.join(self.sim_dir_path,unitop.name+'_res.csv') - # with open(csvpath,'r') as resultFile: - # csvreader = csv.reader(resultFile,delimiter=',') - # for row in csvreader: - # self.resdata.append(row) - # self.ExtData() - - - - - - # if self.interface == 'OMPython': - # omc = OMCSession() - # omc.sendExpression("loadModel(Modelica)") - # omc.sendExpression("loadFile(\"Simulator.mo\")") - # omc.sendExpression("loadFile(\"Flowsheet.mo\")") - # execsim = omc.sendExpression("simulate(Flowsheet, outputFormat=\"csv\", stopTime=1.0, numberOfIntervals=1)") - - # else: - # os.system(self.omc_path + ' -s ') - - def ExtData(self): - for unit in self.UnitOpn: - if unit[0].type == 'MatStm': + def __init__(self): + self.sim_name = 'Simulator' + self.sim_method = '' + self.UnitOpn = [] + self.data = [] + self.compounds = [] + self.interface = '' + self.omc_path = None + self.curr_path = os.getcwd() + self.sim_dir_path = os.path.join(self.curr_path, self.sim_name) + self.Flomo_path = os.path.join(self.sim_dir_path,'Flowsheet.mo') + self.eqn_mos_path = os.path.join(self.sim_dir_path,'simulateEQN.mos') + self.sm_mos_path = os.path.join(self.sim_dir_path,'simulateSM.mos') + self.resdata = [] + self.stdout=None + self.stderr=None + + + def get_omc_path(self): + try: + self.omhome = os.environ.get('OPENMODELICAHOME') + if self.omhome is None: + self.omhome = os.path.split(os.path.split(os.path.realpath(spawn.find_executable("omc")))[0])[0] + elif os.path.exists('/opt/local/bin/omc'): + self.omhome = '/opt/local' + elif os.path.exists('/usr/bin/omc'): + self.omhome = '/usr' + return os.path.join(self.omhome, 'bin', 'omc') + except BaseException: + print("The OpenModelica compiler is missing in the System path please install it" ) + raise + + def add_UnitOpn(self,unitop): + self.UnitOpn.append(unitop) + + def remove_UnitOpn(self,unitop): + self.UnitOpn.remove(unitop) + + def add_comp_list(self,comp): + self.compounds = comp + + + def send_for_simulationEqn(self): + self.resdata = [] + self.omc_path = self.get_omc_path() + print(self.omc_path) + + if self.sim_method == 'Eqn': + simpath = self.eqn_mos_path + os.chdir(self.sim_dir_path) + + process = Popen([self.omc_path, '-s',simpath], stdout=PIPE, stderr=PIPE) + self.stdout, self.stderr = process.communicate() + #s = subprocess.check_output([self.omc_path, '-s',simpath]) + #print(s) + #print("############### StdOut ################") + print(self.stdout) + os.chdir(self.curr_path) + #os.system(self.omc_path + ' -s ' + simpath) + print("Hello") + if self.sim_method == 'Eqn': + print("hhhh") + csvpath = os.path.join(self.sim_dir_path,'Flowsheet_res.csv') + print("csvPath",csvpath) + with open (csvpath,'r') as resultFile: + self.resdata = [] + print("opened") + csvreader = csv.reader(resultFile,delimiter=',') + for row in csvreader: + print("124125") + self.resdata.append(row) + #self.ExtData() + + + def send_for_simulationSM(self,unitop): + + self.resdata = [] + self.omc_path = self.get_omc_path() + os.chdir(self.sim_dir_path) + #os.system(self.omc_path + ' -s ' + unitop.name+'.mos') + process = Popen([self.omc_path, '-s',unitop.name,'.mos'], stdout=PIPE, stderr=PIPE) + stdout, stderr = process.communicate() + #s = subprocess.check_output([self.omc_path, '-s',simpath]) + #print(s) + print("############### StdOut ################") + print(stdout) + self.resdata = [] + print('Simulating '+unitop.name+'...') + csvpath = os.path.join(self.sim_dir_path,unitop.name+'_res.csv') + with open(csvpath,'r') as resultFile: + csvreader = csv.reader(resultFile,delimiter=',') + for row in csvreader: + self.resdata.append(row) + self.ExtData() + + + + + + # if self.sim_method == 'SM': + # for unitop in self.UnitOpn: + # self.resdata = [] + # if unitop.type != 'MatStm': + # print 'Simulating '+unitop.name+'...' + # csvpath = os.path.join(self.sim_dir_path,unitop.name+'_res.csv') + # with open(csvpath,'r') as resultFile: + # csvreader = csv.reader(resultFile,delimiter=',') + # for row in csvreader: + # self.resdata.append(row) + # self.ExtData() + + + + + + # if self.interface == 'OMPython': + # omc = OMCSession() + # omc.sendExpression("loadModel(Modelica)") + # omc.sendExpression("loadFile(\"Simulator.mo\")") + # omc.sendExpression("loadFile(\"Flowsheet.mo\")") + # execsim = omc.sendExpression("simulate(Flowsheet, outputFormat=\"csv\", stopTime=1.0, numberOfIntervals=1)") + + # else: + # os.system(self.omc_path + ' -s ') + + def ExtData(self): + for unit in self.UnitOpn: + if unit[0].type == 'MatStm': # - for key, value in unit[0].Prop.items(): - - - propertyname = unit[0].name + '.' + key - if propertyname in self.resdata[0]: - ind = self.resdata[0].index(propertyname) - resultval = str(self.resdata[-1][ind]) - #resultval = str(omc.sendExpression("val("+unit.name+ "." + value + ", 0.5)")) - print(resultval) - unit[0].Prop[key] = resultval - #print(unit[0].Prop) - # else: - # for v in value: - # propertyname = unit.name + '.' + v - # if propertyname in self.resdata[0]: - # ind = self.resdata[0].index(propertyname) - # resultval = str(self.resdata[-1][ind]) - # # resultval = str(omc.sendExpression("val("+unit.name+ "." + v + ", 0.5)")) - # unit.Prop[key][i] = resultval - # i = i + 1 - - # for key, value in unit.OMVapProp.iteritems(): - # i = 0 - - # if type(value) is str: - # propertyname = unit.name + '.' + value - # if propertyname in self.resdata[0]: - # ind = self.resdata[0].index(propertyname) - # resultval = str(self.resdata[-1][ind]) - # # resultval = str(omc.sendExpression("val("+unit.name+ "." + value + ", 0.5)")) - # unit.VapProp[key] = resultval - # else: - # for v in value: - # propertyname = unit.name + '.' + v - # if propertyname in self.resdata[0]: - # ind = self.resdata[0].index(propertyname) - # resultval = str(self.resdata[-1][ind]) - # # resultval = str(omc.sendExpression("val("+unit.name+ "." + v + ", 0.5)")) - # unit.VapProp[key][i] = resultval - # i = i + 1 - - - # for key, value in unit.OMLiqProp.iteritems(): - # i = 0 - - # if type(value) is str: - # propertyname = unit.name + '.' + value - # if propertyname in self.resdata[0]: - # ind = self.resdata[0].index(propertyname) - # resultval = str(self.resdata[-1][ind]) - # # resultval = str(omc.sendExpression("val("+unit.name+ "." + value + ", 0.5)")) - # unit.LiqProp[key] = resultval - # else: - # for v in value: - # propertyname = unit.name + '.' + v - # if propertyname in self.resdata[0]: - # ind = self.resdata[0].index(propertyname) - # resultval = str(self.resdata[-1][ind]) - # # resultval = str(omc.sendExpression("val("+unit.name+ "." + v + ", 0.5)")) - # unit.LiqProp[key][i] = resultval - # i = i + 1 - # for key, value in unit.OMVapProp.iteritems(): - # i = 0 - - # if type(value) is str: - # resultval = str(omc.sendExpression("val("+unit.name+ "." + value + ", 0.5)")) - # unit.VapProp[key] = resultval - # else: - # for v in value: - # resultval = str(omc.sendExpression("val("+unit.name+ "." + v + ", 0.5)")) - # unit.VapProp[key][i] = resultval - # i = i + 1 - - - # for key, value in unit.OMLiqProp.iteritems(): - # i = 0 - - # if type(value) is str: - # resultval = str(omc.sendExpression("val("+unit.name+ "." + value + ", 0.5)")) - # unit.LiqProp[key] = resultval - # else: - # for v in value: - # resultval = str(omc.sendExpression("val("+unit.name+ "." + v + ", 0.5)")) - # unit.LiqProp[key][i] = resultval - # i = i + 1 - - - - def simulateEQN(self): - self.data = [] - print("##################################################") - print("##################################################") - self.sim_method = 'Eqn' - self.data.append("model Flowsheet\n") - - for c in self.compounds: - ucase = c.title() - lcase = c.lower() - self.data.append("parameter Simulator.Files.Chemsep_Database." + ucase +' '+ ucase + "; \n") - - for unitop in self.UnitOpn: - self.data.append(unitop[0].OM_Flowsheet_Init(self.compounds)) - - self.data.append("equation\n") + for key, value in unit[0].Prop.items(): + + + propertyname = unit[0].name + '.' + key + if propertyname in self.resdata[0]: + ind = self.resdata[0].index(propertyname) + resultval = str(self.resdata[-1][ind]) + #resultval = str(omc.sendExpression("val("+unit.name+ "." + value + ", 0.5)")) + print(resultval) + unit[0].Prop[key] = resultval + #print(unit[0].Prop) + # else: + # for v in value: + # propertyname = unit.name + '.' + v + # if propertyname in self.resdata[0]: + # ind = self.resdata[0].index(propertyname) + # resultval = str(self.resdata[-1][ind]) + # # resultval = str(omc.sendExpression("val("+unit.name+ "." + v + ", 0.5)")) + # unit.Prop[key][i] = resultval + # i = i + 1 + + # for key, value in unit.OMVapProp.iteritems(): + # i = 0 + + # if type(value) is str: + # propertyname = unit.name + '.' + value + # if propertyname in self.resdata[0]: + # ind = self.resdata[0].index(propertyname) + # resultval = str(self.resdata[-1][ind]) + # # resultval = str(omc.sendExpression("val("+unit.name+ "." + value + ", 0.5)")) + # unit.VapProp[key] = resultval + # else: + # for v in value: + # propertyname = unit.name + '.' + v + # if propertyname in self.resdata[0]: + # ind = self.resdata[0].index(propertyname) + # resultval = str(self.resdata[-1][ind]) + # # resultval = str(omc.sendExpression("val("+unit.name+ "." + v + ", 0.5)")) + # unit.VapProp[key][i] = resultval + # i = i + 1 + + + # for key, value in unit.OMLiqProp.iteritems(): + # i = 0 + + # if type(value) is str: + # propertyname = unit.name + '.' + value + # if propertyname in self.resdata[0]: + # ind = self.resdata[0].index(propertyname) + # resultval = str(self.resdata[-1][ind]) + # # resultval = str(omc.sendExpression("val("+unit.name+ "." + value + ", 0.5)")) + # unit.LiqProp[key] = resultval + # else: + # for v in value: + # propertyname = unit.name + '.' + v + # if propertyname in self.resdata[0]: + # ind = self.resdata[0].index(propertyname) + # resultval = str(self.resdata[-1][ind]) + # # resultval = str(omc.sendExpression("val("+unit.name+ "." + v + ", 0.5)")) + # unit.LiqProp[key][i] = resultval + # i = i + 1 + # for key, value in unit.OMVapProp.iteritems(): + # i = 0 + + # if type(value) is str: + # resultval = str(omc.sendExpression("val("+unit.name+ "." + value + ", 0.5)")) + # unit.VapProp[key] = resultval + # else: + # for v in value: + # resultval = str(omc.sendExpression("val("+unit.name+ "." + v + ", 0.5)")) + # unit.VapProp[key][i] = resultval + # i = i + 1 + + + # for key, value in unit.OMLiqProp.iteritems(): + # i = 0 + + # if type(value) is str: + # resultval = str(omc.sendExpression("val("+unit.name+ "." + value + ", 0.5)")) + # unit.LiqProp[key] = resultval + # else: + # for v in value: + # resultval = str(omc.sendExpression("val("+unit.name+ "." + v + ", 0.5)")) + # unit.LiqProp[key][i] = resultval + # i = i + 1 + + + + def simulateEQN(self): + self.data = [] + print("##################################################") + print("##################################################") + self.sim_method = 'Eqn' + self.data.append("model Flowsheet\n") - for unitop in self.UnitOpn: - if unitop[1]==0: - - if unitop[0].type == 'MatStm': - self.data.append(unitop[0].OM_Flowsheet_Eqn(self.compounds,'Eqn')) - else: - self.data.append(unitop[0].OM_Flowsheet_Eqn(self.compounds)) - else: - pass - with open(self.Flomo_path, 'w') as txtfile: - for d in self.data: - txtfile.write(d) - txtfile.write('end Flowsheet;\n') - - with open(self.eqn_mos_path, 'w') as mosFile: - mosFile.write('loadModel(Modelica);\n') - mosFile.write("loadFile(\"Simulator\package.mo\");\n") - mosFile.write("loadFile(\"Flowsheet.mo\");\n") - mosFile.write("simulate(Flowsheet, outputFormat=\"csv\", stopTime=1.0, numberOfIntervals=1);\n") - - print('Initiating Simulation in Equation Oriented Mode') - - self.send_for_simulationEqn() - - - def simulateSM(self,ip,op): - self.sim_method = 'SM' - self.data = [] - self.resdata = [] - self.unit = [] - self.csvlist = [] - print("op list",op) - print("ip list",ip) - for i in ip: - common = ip[i] - print("common #############3",common) - print("*********** i *********",i) - for k,v in op.items(): - print("Print K",k) - if(set(v) & set(common)): - print("*****************common matstm***************") - if((i in self.unit) and (k in self.unit)): - print("both exist") - pass - elif(i in self.unit): - print("output exist") - self.unit.insert(self.unit.index(i),k) - elif(k in self.unit): - print("input exists") - self.unit.append(i) - else: - print("nothing exists") - self.unit.append(k) - self.unit.append(i) - print("##############################33") - print(self.unit) - print("################################11") - - for unitop in self.unit: - os.chdir(self.curr_path) - self.data = [] - if unitop.type not in ['MatStm','EngStm']: - inpstms = unitop.InputStms - outstms = unitop.OutputStms - - try: - engstms = unitop.EngStms - except: - engstms = None - - self.data.append("model "+unitop.name.lower()+'\n') - - for c in self.compounds: - ucase = c.title() - lcase = c.lower() - self.data.append("parameter Simulator.Files.Chemsep_Database." + ucase +' '+ ucase + "; \n") - - print("##############compounds added") - self.data.append(unitop.OM_Flowsheet_Init(self.compounds)) - - if type(outstms) is list: - for stm in outstms: - self.data.append(stm.OM_Flowsheet_Init(self.compounds)) - else: - self.data.append(outstms.OM_Flowsheet_Init(self.compounds)) - - - if engstms: - self.data.append(engstms.OM_Flowsheet_Init(self.compounds)) - - if type(inpstms) is list: - for stm in inpstms: - self.data.append(stm.OM_Flowsheet_Init(self.compounds)) - else: - self.data.append(inpstms.OM_Flowsheet_Init(self.compounds)) - - self.data.append('equation\n') - print("##################equation") - self.data.append(unitop.OM_Flowsheet_Eqn(self.compounds)) - ''' - if type(outstms) is list: - for stm in outstms: - #stm.GetEquationValues() - self.data.append(stm.OM_Flowsheet_Eqn(self.compounds,'SM')) - else: - #outstms.GetEquationValues() - self.data.append(outstms.OM_Flowsheet_Eqn(self.compounds,'SM')) + for c in self.compounds: + ucase = c.title() + lcase = c.lower() + self.data.append("parameter Simulator.Files.Chemsep_Database." + ucase +' '+ ucase + "; \n") + + for unitop in self.UnitOpn: + if unitop.type != 'MatStm': + self.data.append(unitop.send_to_flowsheet(self.compounds).OM_Flowsheet_Initialize(self.compounds)) + else: + self.data.append(unitop.OM_Flowsheet_Init(self.compounds)) + + + self.data.append("equation\n") + + self.outlist = [] + self.stm = ['MatStm','EngStm'] + for unitop in self.UnitOpn: + if unitop.type not in self.stm: + for j in unitop.OutputStms: + self.outlist.append(j) + print(j.name) + + + + for unitop in self.UnitOpn: + if unitop not in self.outlist: + + if unitop.type == 'MatStm': + self.data.append(unitop.OM_Flowsheet_Eqn(self.compounds,'Eqn')) + else: + self.data.append(unitop.send_to_flowsheet(self.compounds).OM_Flowsheet_Equation(self.compounds)) + else: + pass + with open(self.Flomo_path, 'w') as txtfile: + for d in self.data: + txtfile.write(str(d)) + txtfile.write('end Flowsheet;\n') + + with open(self.eqn_mos_path, 'w') as mosFile: + mosFile.write('loadModel(Modelica);\n') + mosFile.write("loadFile(\"Simulator/package.mo\");\n") + mosFile.write("loadFile(\"Flowsheet.mo\");\n") + mosFile.write("simulate(Flowsheet, outputFormat=\"csv\", stopTime=1.0, numberOfIntervals=1);\n") + + print('Initiating Simulation in Equation Oriented Mode') + + self.send_for_simulationEqn() + + + + + def simulateSM(self,ip,op): + self.sim_method = 'SM' + self.data = [] + self.resdata = [] + self.unit = [] + self.csvlist = [] + print("op list",op) + print("ip list",ip) + for i in ip: + common = ip[i] + print("common #############3",common) + print("*********** i *********",i) + for k,v in op.items(): + print("Print K",k) + if(set(v) & set(common)): + print("*****************common matstm***************") + if((i in self.unit) and (k in self.unit)): + print("both exist") + pass + elif(i in self.unit): + print("output exist") + self.unit.insert(self.unit.index(i),k) + elif(k in self.unit): + print("input exists") + self.unit.append(i) + else: + print("nothing exists") + self.unit.append(k) + self.unit.append(i) + print("##############################33") + print(self.unit) + print("################################11") + + for unitop in self.unit: + os.chdir(self.curr_path) + self.data = [] + if unitop.type not in ['MatStm','EngStm']: + inpstms = unitop.InputStms + outstms = unitop.OutputStms + + try: + engstms = unitop.EngStms + except: + engstms = None + + self.data.append("model "+unitop.name.lower()+'\n') + + for c in self.compounds: + ucase = c.title() + lcase = c.lower() + self.data.append("parameter Simulator.Files.Chemsep_Database." + ucase +' '+ ucase + "; \n") + + print("##############compounds added") + self.data.append(unitop.send_to_flowsheet(self.compounds).OM_Flowsheet_Initialize(self.compounds)) + + if type(outstms) is list: + for stm in outstms: + self.data.append(stm.send_to_flowsheet(self.compounds).OM_Flowsheet_Initialize(self.compounds)) + else: + self.data.append(outstms.send_to_flowsheet(self.compounds).OM_Flowsheet_Initialize(self.compounds)) + + + if engstms: + self.data.append(engstms.send_to_flowsheet(self.compounds).OM_Flowsheet_Initialize(self.compounds)) + + if type(inpstms) is list: + for stm in inpstms: + self.data.append(stm.send_to_flowsheet(self.compounds).OM_Flowsheet_Initialize(self.compounds)) + else: + self.data.append(inpstms.send_to_flowsheet(self.compounds).OM_Flowsheet_Initialize(self.compounds)) + + self.data.append('equation\n') + print("##################equation") + self.data.append(unitop.send_to_flowsheet(self.compounds).OM_Flowsheet_Equation(self.compounds)) + ''' + if type(outstms) is list: + for stm in outstms: + #stm.GetEquationValues() + self.data.append(stm.OM_Flowsheet_Eqn(self.compounds,'SM')) + else: + #outstms.GetEquationValues() + self.data.append(outstms.OM_Flowsheet_Eqn(self.compounds,'SM')) ''' - if type(inpstms) is list: - for stm in inpstms: - #stm.GetEquationValues() - self.data.append(stm.OM_Flowsheet_Eqn(self.compounds,'SM')) - else: - #inpstms.GetEquationValues() - self.data.append(inpstms.OM_Flowsheet_Eqn(self.compounds,'SM')) - - # os.chdir(self.sim_dir_path) - unitmofile = os.path.join(self.sim_dir_path,unitop.name.lower()+'.mo') - - with open(unitmofile,'w') as unitFile: - for d in self.data: - unitFile.write(d) - unitFile.write('end '+unitop.name.lower()+';\n') - - unitmosfile = os.path.join(self.sim_dir_path,unitop.name.lower()+'.mos') - with open(unitmosfile, 'w') as mosFile: - mosFile.write('loadModel(Modelica);\n') - mosFile.write("loadFile(\"Simulator\package.mo\");\n") - - mosFile.write("loadFile(\""+unitop.name.lower()+".mo\");\n") - mosFile.write("simulate("+unitop.name.lower()+", outputFormat=\"csv\", stopTime=1.0, numberOfIntervals=1);\n") - - print("Initiating simulation in Sequential Modular Mode") - #self.resdata = [] - self.omc_path = self.get_omc_path() - os.chdir(self.sim_dir_path) - #os.system(self.omc_path + ' -s ' + unitop[0].name.lower()+"SEQ"+'.mos') - print("SIM directory Path 1 ###",self.sim_dir_path) - sim = os.path.join(self.sim_dir_path,unitop.name.lower()+'.mos') - process = Popen([self.omc_path, '-s',sim], stdout=PIPE, stderr=PIPE) - self.stdout, self.stderr = process.communicate() - os.chdir(self.curr_path) - #s = subprocess.check_output([self.omc_path, '-s',simpath]) - #print(s) - print("############### StdOut ################") - print(self.stdout) - print("############### StdErr ################") - print(self.stderr) - print('Simulating '+unitop.name.lower()+'...') - csvpath = os.path.join(self.sim_dir_path,unitop.name.lower()+'_res.csv') - - self.csvlist.append(csvpath) - - with open(csvpath,'r') as resultFile: - csvreader = csv.reader(resultFile,delimiter=',') - for row in csvreader: - self.resdata.append(row) - - os.chdir(self.curr_path) - if type(inpstms) is list: - for stm in inpstms: - for key, value in stm.Prop.items(): - propertyname = stm.name + '.' + key - if propertyname in self.resdata[0]: - ind = self.resdata[0].index(propertyname) - resultval = str(self.resdata[-1][ind]) - stm.Prop[key] = resultval - - #print("input",stm.Prop[key]) - - - else: - for key, value in inpstms.Prop.items(): - propertyname = inpstms.name + '.' + key - if propertyname in self.resdata[0]: - ind = self.resdata[0].index(propertyname) - resultval = str(self.resdata[-1][ind]) - inpstms.Prop[key] = resultval - #print("input",inpstms.Prop[key]) - - if type(outstms) is list: - for stm in outstms: - for key, value in stm.Prop.items(): - propertyname = stm.name + '.' + key - if propertyname in self.resdata[0]: - ind = self.resdata[0].index(propertyname) - resultval = str(self.resdata[-1][ind]) - stm.Prop[key] = resultval - print("output key:",key,"value:",stm.Prop[key]) - else: - for key, value in outstms.Prop.items(): - propertyname = outstms.name + '.' + key - if propertyname in self.resdata[0]: - ind = self.resdata[0].index(propertyname) - resultval = str(self.resdata[-1][ind]) - outstms.Prop[key] = resultval - print("output key:",key,"value:",outstms.Prop[key]) - - - self.dataframes = [pd.read_csv(i) for i in self.csvlist] - os.chdir(self.sim_dir_path) - dffinal = pd.concat(self.dataframes,axis=1) - dffinal.to_csv('FlowsheetSEQ.csv',index=False) - self.resdata.clear() - with open(os.path.join(self.sim_dir_path+'/FlowsheetSEQ.csv'),'r') as resultFile: - csvreader = csv.reader(resultFile,delimiter=',') - for row in csvreader: - self.resdata.append(row) - - - - - - - - + if type(inpstms) is list: + for stm in inpstms: + #stm.GetEquationValues() + self.data.append(stm.send_to_flowsheet(self.compounds).OM_Flowsheet_Equation(self.compounds,'SM')) + else: + #inpstms.GetEquationValues() + self.data.append(inpstms.send_to_flowsheet(self.compounds).OM_Flowsheet_Equation(self.compounds,'SM')) + + # os.chdir(self.sim_dir_path) + unitmofile = os.path.join(self.sim_dir_path,unitop.name.lower()+'.mo') + + with open(unitmofile,'w') as unitFile: + for d in self.data: + unitFile.write(d) + unitFile.write('end '+unitop.name.lower()+';\n') + + unitmosfile = os.path.join(self.sim_dir_path,unitop.name.lower()+'.mos') + with open(unitmosfile, 'w') as mosFile: + mosFile.write('loadModel(Modelica);\n') + mosFile.write("loadFile(\"Simulator\package.mo\");\n") + + mosFile.write("loadFile(\""+unitop.name.lower()+".mo\");\n") + mosFile.write("simulate("+unitop.name.lower()+", outputFormat=\"csv\", stopTime=1.0, numberOfIntervals=1);\n") + + print("Initiating simulation in Sequential Modular Mode") + #self.resdata = [] + self.omc_path = self.get_omc_path() + os.chdir(self.sim_dir_path) + #os.system(self.omc_path + ' -s ' + unitop[0].name.lower()+"SEQ"+'.mos') + print("SIM directory Path 1 ###",self.sim_dir_path) + sim = os.path.join(self.sim_dir_path,unitop.name.lower()+'.mos') + process = Popen([self.omc_path, '-s',sim], stdout=PIPE, stderr=PIPE) + self.stdout, self.stderr = process.communicate() + os.chdir(self.curr_path) + #s = subprocess.check_output([self.omc_path, '-s',simpath]) + #print(s) + print("############### StdOut ################") + print(self.stdout) + print("############### StdErr ################") + print(self.stderr) + print('Simulating '+unitop.name.lower()+'...') + csvpath = os.path.join(self.sim_dir_path,unitop.name.lower()+'_res.csv') + + self.csvlist.append(csvpath) + + with open(csvpath,'r') as resultFile: + csvreader = csv.reader(resultFile,delimiter=',') + for row in csvreader: + self.resdata.append(row) + + os.chdir(self.curr_path) + if type(inpstms) is list: + for stm in inpstms: + for key, value in stm.Prop.items(): + propertyname = stm.name + '.' + key + if propertyname in self.resdata[0]: + ind = self.resdata[0].index(propertyname) + resultval = str(self.resdata[-1][ind]) + stm.Prop[key] = resultval + + #print("input",stm.Prop[key]) + + + else: + for key, value in inpstms.Prop.items(): + propertyname = inpstms.name + '.' + key + if propertyname in self.resdata[0]: + ind = self.resdata[0].index(propertyname) + resultval = str(self.resdata[-1][ind]) + inpstms.Prop[key] = resultval + #print("input",inpstms.Prop[key]) + + if type(outstms) is list: + for stm in outstms: + for key, value in stm.Prop.items(): + propertyname = stm.name + '.' + key + if propertyname in self.resdata[0]: + ind = self.resdata[0].index(propertyname) + resultval = str(self.resdata[-1][ind]) + stm.Prop[key] = resultval + print("output key:",key,"value:",stm.Prop[key]) + else: + for key, value in outstms.Prop.items(): + propertyname = outstms.name + '.' + key + if propertyname in self.resdata[0]: + ind = self.resdata[0].index(propertyname) + resultval = str(self.resdata[-1][ind]) + outstms.Prop[key] = resultval + print("output key:",key,"value:",outstms.Prop[key]) + + + self.dataframes = [pd.read_csv(i) for i in self.csvlist] + os.chdir(self.sim_dir_path) + dffinal = pd.concat(self.dataframes,axis=1) + dffinal.to_csv('FlowsheetSEQ.csv',index=False) + self.resdata.clear() + with open(os.path.join(self.sim_dir_path+'/FlowsheetSEQ.csv'),'r') as resultFile: + csvreader = csv.reader(resultFile,delimiter=',') + for row in csvreader: + self.resdata.append(row) + + + + + + + + diff --git a/OMChem/MatStm.py b/OMChem/MatStm.py index 7635fbe..69a6845 100644 --- a/OMChem/MatStm.py +++ b/OMChem/MatStm.py @@ -4,10 +4,9 @@ import sys from collections import defaultdict class MatStm(): - counter = 1 - def __init__(self,name ='MatStm',CompNames = [],Temperature=300,Pressure=101325,VapPhasMolFrac=None,VapPhasMasFrac=None,LiqPhasMolFrac=None,LiqPhasMasFrac=None,CompMolFrac = [1.0], CompMasFrac = [], MolFlow=100, MasFlow=None,**kwargs): - # self.name = name[0] - self.name = name + str(MatStm.counter) + counter = 1; + def __init__(self,CompNames = [],Temperature=300,Pressure=101325,VapPhasMolFrac=None,VapPhasMasFrac=None,LiqPhasMolFrac=None,LiqPhasMasFrac=None,CompMolFrac = [1.0], CompMasFrac = [], MolFlow=100, MasFlow=None,**kwargs): + self.name = 'MatStm' + str(MatStm.counter) self.type = 'MatStm' self.T = Temperature self.P = Pressure @@ -22,35 +21,20 @@ class MatStm(): self.MasFlow = MasFlow self.OM_data_init = '' self.OM_data_eqn = '' - # self.count = name[1] self.count = MatStm.counter self.thermoPackage ="Raoults_Law" self.mode1 = "P" self.mode1val = "" self.mode2 = "T" self.mode2val = "" - - # self.ValEntList = {"T":T," P":P," VapPhasMolFrac":vapPhasMolFrac," CompNames":CompNames," CompMolFrac[1]":CompMolFrac," CompMasFrac":CompMasFrac," MolFlow[1]":MolFlow," MasFlow[1]":MasFlow} - # self.OMProp = { - # 'Pressure': self.mode1, - # 'Temperature': self.mode2, - # 'Liquid Phase Mole Fraction': 'liqPhasMolFrac', - # 'Liquid Phase Mas Fraction': 'liqPhasMasFrac', - # 'Vapour Phase Mole Fraction': 'vapPhasMolFrac', - # 'Vapour Phase Mas Fraction': 'vapPhasMasFrac', - # 'Total Molar Flow': 'totMolFlo[1]', - # 'Total Mas Flow': 'totMasFlo[1]', - # 'Av. Molecular Weight': 'MW[1]', - # 'Comp Mole Fraction': ['compMolFrac[1,1]','compMolFrac[1,2]','compMolFrac[1,3]'], - # 'Comp Mas Fraction': ['compMasFrac[1,1]','compMasFrac[1,2]','compMasFrac[1,3]'], - # 'Comp Molar Flow': ['compMolFlo[1,1]','compMolFlo[1,2]','compMolFlo[1,3]'], - # 'Comp Mas Flow': ['compMasFlo[1,1]','compMasFlo[1,2]','compMasFlo[1,3]'], - # 'Molar Specific Heat': 'phasMolSpHeat[1]', - # 'Molar Enthalpy': 'phasMolEnth[1]', - # 'Molar Entropy': 'phasMolEntr[1]' - # } + self.no_of_inputs = 1 + self.no_of_outputs = 1 + self.x = 2500-30 + self.y = 2500-30 + MatStm.counter+=1 self.startDict = {} self.eqnDict = {} + self.Prop = { @@ -106,20 +90,11 @@ class MatStm(): 'totMasFlo[2]':None, 'totMolFlo[3]':None, 'totMasFlo[3]':None - } - - - # new - self.no_of_input = 1 - self.no_of_output = 1 - MatStm.counter += 1 - def getname(self): - return self.name + } def modesList(self): return ["PT","PH","PVF","TVF","PS"] - def paramgetter(self,mode): dict = {} if(mode=="PT"): @@ -144,7 +119,6 @@ class MatStm(): dict = {self.mode1:None,self.mode2:None,"CompMolFrac":None,"MolFlow":None,"thermoPackage":None} return dict - def paramsetter(self,dict): self.mode1val = dict[self.mode1] self.mode2val = dict[self.mode2] @@ -360,92 +334,7 @@ class MatStm(): print(e) print('error') - # self.OMVapProp = { - # 'Pressure': self.mode1, - # 'Temperature': self.mode2, - # 'Total Molar Flow': 'totMolFlo[3]', - # 'Total Mas Flow': 'totMasFlo[3]', - # 'Comp Mole Fraction': ['compMolFrac[3,1]','compMolFrac[3,2]','compMolFrac[3,3]'], - # 'Comp Mas Fraction': ['compMasFrac[3,1]','compMasFrac[3,2]','compMasFrac[3,3]'], - # 'Comp Molar Flow': ['compMolFlo[3,1]','compMolFlo[3,2]','compMolFlo[3,3]'], - # 'Comp Mas Flow': ['compMasFlo[3,1]','compMasFlo[3,2]','compMasFlo[3,3]'], - # 'Av. Molecular Weight': 'phasMolEnth[3]', - # 'Molar Specific Heat': 'phasMolSpHeat[3]', - # 'Molar Enthalpy': 'phasMolEnth[3]', - # 'Molar Entropy': 'phasMolEntr[3]'} - - - - # self.VapProp = { - # self.mode1:None, - # self.mode2:None, - # 'liqPhasMolFrac':None, - # 'liqPhasMasFrac':None, - # 'vapPhasMolFrac':None, - # 'vapPhasMasFrac':None, - # 'totMolFlo[3]':None, - # 'totMasFlo[3]':None, - # 'MW[1]':None, - # 'compMolFrac[3,1]':None, - # 'compMolFrac[3,2]':None, - # 'compMolFrac[3,3]':None, - # 'compMasFrac[3,1]':None, - # 'compMasFrac[3,2]':None, - # 'compMasFrac[3,3]'None, - # 'compMolFlo[3,1]':None, - # 'compMolFlo[3,2]':None, - # 'compMolFlo[3,3]':None, - # 'compMasFlo[3,1]':None, - # 'compMasFlo[3,2]':None, - # 'compMasFlo[3,3]':None, - # 'phasMolSpHeat[3]':None, - # 'phasMolEnth[3]':None, - # 'phasMolEntr[3]':None - # } - - - # self.OMLiqProp = { - # 'Pressure': self.mode1, - # 'Temperature': self.mode2, - # 'Total Molar Flow': 'totMolFlo[2]', - # 'Total Mas Flow': 'totMasFlo[2]', - # 'Comp Mole Fraction': ['compMolFrac[2,1]','compMolFrac[2,2]','compMolFrac[2,3]'], - # 'Comp Mas Fraction': ['compMasFrac[2,1]','compMasFrac[2,2]','compMasFrac[2,3]'], - # 'Comp Molar Flow': ['compMolFlo[2,1]','compMolFlo[2,2]','compMolFlo[2,3]'], - # 'Comp Mas Flow': ['compMasFlo[2,1]','compMasFlo[2,2]','compMasFlo[2,3]'], - # 'Av. Molecular Weight': 'MW[2]', - # 'Molar Specific Heat': 'phasMolSpHeat[2]', - # 'Molar Enthalpy': 'phasMolEnth[2]', - # 'Molar Entropy': 'phasMolEntr[2]'} - - - # self.LiqProp = { - # self.mode1:P, - # self.mode2:None, - # 'liqPhasMolFrac':None, - # 'liqPhasMasFrac':None, - # 'vapPhasMolFrac':None, - # 'vapPhasMasFrac':None, - # 'totMolFlo[2]':None, - # 'totMasFlo[2]':None, - # 'MW[1]':None, - # 'compMolFrac[2,1]':None, - # 'compMolFrac[2,2]':None, - # 'compMolFrac[2,3]':None, - # 'compMasFrac[2,1]':None, - # 'compMasFrac[2,2]':None, - # 'compMasFrac[2,3]'None, - # 'compMolFlo[2,1]':None, - # 'compMolFlo[2,2]':None, - # 'compMolFlo[2,3]':None, - # 'compMasFlo[2,1]':None, - # 'compMasFlo[2,2]':None, - # 'compMasFlo[2,3]':None, - # 'phasMolSpHeat[2]':None, - # 'phasMolEnth[2]':None, - # 'phasMolEntr[2]':None - # } - + def OM_Flowsheet_Init(self,addedcomp): self.OM_data_init = '' self.OM_data_init = self.OM_data_init + ("model ms"+str(self.count)+"\n") @@ -484,27 +373,4 @@ class MatStm(): self.OM_data_eqn = self.OM_data_eqn + self.name + '.'+ key + ' = ' + str(value) + ';\n' return self.OM_data_eqn - - # if self.P: - # self.OM_data_eqn = self.OM_data_eqn + (self.name + '.P=' + str(self.P) + ';\n') - # if self.T: - # self.OM_data_eqn = self.OM_data_eqn + (self.name + '.T=' + str(self.T) + ';\n') - # if self.VapPhasMolFrac: - # self.OM_data_eqn = self.OM_data_eqn + (self.name + '.vapPhasMolFrac=' + str(self.VapPhasMolFrac) + ';\n') - - - # if self.CompMolFrac != []: - # self.OM_data_eqn = self.OM_data_eqn + (self.name + ".compMolFrac[1,:] = {") - # mf = str(self.CompMolFrac).strip('[').strip(']') - # self.OM_data_eqn = self.OM_data_eqn + mf + ('};\n') - # if self.CompMasFrac != []: - # self.OM_data_eqn = self.OM_data_eqn + (self.name + ".compMasFrac[1,:] = {") - # Mf = str(self.CompMasFrac).strip('[').strip(']') - # self.OM_data_eqn = self.OM_data_eqn + Mf + ('};\n') - - # if self.MolFlow: - # self.OM_data_eqn = self.OM_data_eqn + (self.name + ".totMolFlo[1] = " + str(self.MolFlow) + ";\n") - # if self.MasFlow: - # self.OM_data_eqn = self.OM_data_eqn + (self.name + ".totMasFlo[1] = " + str(self.MasFlow) + ";\n") - - # return self.OM_data_eqn
\ No newline at end of file +
\ No newline at end of file diff --git a/OMChem/UnitOprns.py b/OMChem/UnitOprns.py new file mode 100644 index 0000000..90cd546 --- /dev/null +++ b/OMChem/UnitOprns.py @@ -0,0 +1,154 @@ +from OMChem.EngStm import EngStm +from collections import defaultdict + +class UnitOpr(): + + def __init__(self,name,counter,Type,parameters={},mode=None,modeVal=None,ThermoPackReq = False,thermoPack = None,extra=[], multidict=[],inputs=1,outputs=1): + self.OM_data_eqn = '' + self.OM_data_init = '' + self.InputStms = [] + self.OutputStms = [] + self.EngStms = EngStm(name='EngStm'+name) + self.name = name + self.mode = mode + self.modeVal = modeVal + self.thermoPack = thermoPack + self.extra = extra + self.type = Type + self.ForNaming = extra; + self.no_of_inputs = inputs + self.no_of_outputs = outputs + self.counter=counter + self.parameters = parameters + self.ThermoPackReq = ThermoPackReq + + + + + + + def connect(self,InputStms = [],OutputStms = []): + self.InputStms = InputStms + self.OutputStms = OutputStms + print('INPUT') + print(InputStms) + print('OUTPUT') + print(OutputStms) + + + + + def OM_Flowsheet_Initialize(self,addedcomp): + self.OM_data_init = '' + + if(self.ThermoPackReq): + if len(self.extra)>1: + for i in range(self.extra): + latest = '' + for j in range(self.extra[i]): + if self.extra[i][j]!='.': + latest += self.extra[i][j] + self.ForNaming[i] = latest + + + + if(self.ThermoPackReq): + if len(self.extra)==1: + for i in self.extra: + self.OM_data_init += ('model '+i+str(self.counter)+'\n') + self.OM_data_init += ('extends Simulator.Unit_Operations.'+i+';\n') + self.OM_data_init += ('extends Simulator.Files.Thermodynamic_Packages.'+self.thermoPack+';\n') + self.OM_data_init += ('end '+i+str(self.counter)+';\n') + + self.OM_data_init += i+str(self.counter) + ' ' + self.name + '(NOC = ' + str(len(addedcomp)) + + else: + for i in range(len(self.extra)): + if i!=(len(self.extra)-1): + self.OM_data_init += ('model '+self.ForNaming[i]+str(self.counter)+'\n') + self.OM_data_init += ('extends Simulator.Unit_Operations.'+self.extra[i]+';\n') + self.OM_data_init += ('extends Simulator.Files.Thermodynamic_Packages.'+self.thermoPack+';\n') + self.OM_data_init += ('end '+self.ForNaming[i]+str(self.counter)+';\n') + else: + self.OM_data_init += ('model '+self.ForNaming[i]+str(self.counter)+'\n') + self.OM_data_init += ('extends Simulator.Unit_Operations.'+self.extra[i]+';\n') + for j in range(len(self.extra)-1): + self.OM_data_init += (self.ForNaming[j] + str(self.counter) +' ' + self.ForNaming[j] + '#' + multidict[j] + ';\n') + + self.OM_data_init += ('end '+self.ForNaming[i]+str(self.counter)+';\n') + + self.OM_data_init += self.ForNaming[i] + str(self.counter) + ' ' + self.ForNaming + '(NOC = ' + str(len(addedcomp)) + + comp = str(addedcomp).strip('[').strip(']') + comp = comp.replace("'", "") + self.OM_data_init += ',comp = {' + comp + '}' + + + + for i in self.parameters: + self.OM_data_init += ', ' + self.OM_data_init += i[0] + ' = ' + str(i[1]) + self.OM_data_init += ');\n' + + else: + self.OM_data_init += 'Simulator.Unit_Operations.' + self.type + ' ' + self.name + '(NOC = ' + str(len(addedcomp)) + comp = str(addedcomp).strip('[').strip(']') + comp = comp.replace("'", "") + self.OM_data_init += ',comp = {' + comp + '}' + + for i in self.parameters: + self.OM_data_init += ', ' + self.OM_data_init += i[0] + ' = ' + str(i[1]) + + self.OM_data_init += ');\n' + + #print("HERE WE GO") + #print(self.OM_data_init) + + return self.OM_data_init + + + + + def OM_Flowsheet_Equation(self,addedcomp): + OM_data_eqn = '' + + if len(self.InputStms)>1: + strcount = 1 + for strm in self.InputStms: + self.OM_data_eqn += ('connect(' + strm.name + '.outlet,' + self.name + '.inlet[' + str(strcount) + ']);\n') + strcount += 1 + else: + self.OM_data_eqn += ('connect(' + self.name + '.inlet,' + self.InputStms[0].name + '.outlet);\n') + + if len(self.OutputStms)>1: + strcount = 1 + for strm in self.OutputStms: + self.OM_data_eqn += ('connect(' + strm.name + '.inlet,' + self.name + '.outlet[' + str(strcount) + ']);\n') + strcount += 1 + else: + self.OM_data_eqn += ('connect(' + self.name + '.outlet,' + self.OutputStms[0].name + '.inlet);\n') + + if self.mode: + self.OM_data_eqn += (self.name + '.' + self.mode + '=' + self.modeVal + ';\n') + + return self.OM_data_eqn + + + + + + + + + + + + + + + + + + + diff --git a/container.py b/container.py index 89fb897..dd3cf89 100644 --- a/container.py +++ b/container.py @@ -5,9 +5,22 @@ from OMChem.Heater import Heater from component_selector import * from collections import defaultdict from PyQt5.QtCore import * +from PyQt5.QtWidgets import * from PyQt5.QtGui import * +from PyQt5.uic import loadUiType +from PyQt5.QtCore import Qt +from PyQt5.QtWidgets import QGraphicsProxyWidget, QGraphicsObject, QGraphicsEllipseItem ,QGraphicsPixmapItem,QApplication, QGraphicsView, QGraphicsScene, QHBoxLayout, QWidget, QLabel +from PyQt5.QtGui import QBrush ,QTransform ,QMouseEvent +import PyQt5.QtCore as QtCore +import PyQt5.QtWidgets as QtWidgets +from dockWidget import dockWidget import datetime import itertools +import json +import pickle +import os +import sys + class Container(): def __init__(self,msgbrowser): self.unitOp = [] @@ -20,35 +33,20 @@ class Container(): self.msg.setText("") self.opl=[] self.result=[] + def currentTime(self): now = datetime.datetime.now() time = str(now.hour) + ":" + str(now.minute) + ":" +str(now.second) return time + + def updateConn(self,key,value): self.conn[key].append(value) self.msg.append("<span style=\"color:blue\">["+str(self.currentTime())+"]<b> "+key.name+" </b> output is connected to input of<b> "+value.name +" </b></span>") - - def addUnitOp(self,obj): - if(obj in self.unitOp): - pass - else: - self.unitOp.append(obj) - self.msg.append("<span style=\"color:blue\">["+str(self.currentTime())+"]<b> "+obj.name+" </b>is instantiated .""</span>") - - def fetchObject(self,name): - for i in self.unitOp: - if(i.name==name): - return i - - def addCompounds(self,comp): - self.compounds = comp - - def add_thermoPackage(self,thermo): - self.thermoPackage = thermo - + def connection(self): try: self.op.clear() @@ -71,6 +69,36 @@ class Container(): except Exception as e: print(e) + + def addUnitOp(self,obj,scene,graphics): + box = None + self.obj = obj + self.scene = scene + self.graphics = graphics + box = self.graphics.createNodeItem(self.obj) + self.scene.addItem(box) + box.setPos(2500-30, 2500-30) + + + if(obj in self.unitOp): + pass + else: + self.unitOp.append(obj) + + self.msg.append("<span style=\"color:blue\">["+str(self.currentTime())+"]<b> "+obj.name+" </b>is instantiated .""</span>") + + def fetchObject(self,name): + for i in self.unitOp: + if(i.name==name): + return i + def addCompounds(self,comp): + self.compounds = comp + + def add_thermoPackage(self,thermo): + self.thermoPackage = thermo + + + def msgBrowser(self,f): std = f.stdout.decode("utf-8") if(std): @@ -85,18 +113,18 @@ class Container(): self.msg.append("<span style=\"color:red\">"+stdout+"</span>") def simulate(self,mode): + print("SIMULATE") print(mode) self.compounds = compound_selected - self.connection() + #self.connection() f = Flowsheet() f.add_comp_list(self.compounds) print("######## connection master#########\n",self.conn) for i in self.unitOp : - if i in self.opl: print("here",i) - f.add_UnitOpn(i,1) - else: - f.add_UnitOpn(i,0) + f.add_UnitOpn(i) + + if mode=='SM': self.msg.append("<span>["+str(self.currentTime())+"] Simulating in <b>Sequential</b> mode ... </span>") f.simulateSM(self.ip,self.op) @@ -1,45 +1,283 @@ from OMChem.Flowsheet import Flowsheet from OMChem.MatStm import MatStm -from OMChem.Mixer import Mixer +from OMChem.UnitOprns import UnitOpr from OMChem.EngStm import EngStm -from OMChem.Heater import Heater -from OMChem.Flash import Flash -from OMChem.Splitter import Splitter -from OMChem.Valve import Valve -from OMChem.Cooler import Cooler -from OMChem.CompSep import CompSep -from OMChem.adiabatic_comp import AdiaComp -from OMChem.DistCol import DistCol -from OMChem.adiabatic_exp import AdiaExp -from OMChem.Pump import Pump -from OMChem.ShortcutColumn import ShortcutColumn +from Graphics import Graphics +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 +from PyQt5.QtGui import QBrush ,QTransform ,QMouseEvent +from PyQt5.QtGui import * +import PyQt5.QtCore as QtCore +import PyQt5.QtWidgets as QtWidgets from component_selector import * -def helperFunc(type,name1,count): - if(type=="Mixer"): - return Mixer(name=name1) - elif(type=="MatStm"): - return MatStm(name=(name1,count),CompNames=compound_selected) - elif(type=="Splitter"): - return Splitter(name=name1) - elif(type=="Flash"): - return Flash(name=(name1,count)) - elif(type=="Heater"): - return Heater(name=name1) - elif(type=="Valve"): - return Valve(name=name1) - elif(type=="Cooler"): - return Cooler(name=name1) - elif(type=="CompSep"): - return CompSep(name=name1) - elif(type=="AdiaComp"): - return AdiaComp(name=(name1,count)) - elif(type=="AdiaExp"): - return AdiaExp(name=(name1,count)) - elif(type=="DistCol"): - return DistCol(name=(name1,count)) - elif(type=="Pump"): - return Pump(name=name1) - elif(type=="ShortCol"): - return ShortcutColumn(name=(name1,count)) + +class HeaterClass(): + counter = 1; + + def __init__(self,name='Heater',pressDrop = None, eff = None): + self.OM_data_eqn = '' + self.OM_data_init = '' + self.InputStms = [] + self.OutputStms = [] + self.name = name + str(HeaterClass.counter) + self.mode = None + self.modeVal = None + self.type = 'Heater' + self.pressDrop = pressDrop + self.eff = eff + self.no_of_inputs = 1 + self.no_of_outputs = 1 + self.x = 2500-30 + self.y = 2500-30 + self.addedcomp = None + self.extra = None + HeaterClass.counter+=1 + + def modesList(self): + return ["heatAdd","outT","outVapPhasMolFrac","tempInc","enFlo"] + + def paramgetter(self,mode="heatAdd"): + self.mode = mode + dict = {"pressDrop":None,"eff":None,self.mode:None} + return dict + + def add_compounds(self,addedcomp): + self.addedcomp = addedcomp + + + + def paramsetter(self,dict): + + self.pressDrop = dict['pressDrop'] + self.eff = dict['eff'] + self.modeVal = dict[self.mode] + + def connect(self,InputStms,OutputStms): + self.InputStms = InputStms + self.OutputStms = OutputStms + + def add_connection(self,flag,UnitOpr): + if flag==1: + # Input stream if flag is 1 + self.InputStms.append(UnitOpr) + print("INPUT CONNECTION") + else : + print("OUTPUT CONNECTION") + self.OutputStms.append(UnitOpr) + + + + def send_to_flowsheet(self,addedcomp): + self.addedcomp = addedcomp + parameters = [['pressDrop',self.pressDrop],['eff',self.eff]] + Inst = UnitOpr(self.name,HeaterClass.counter,'Heater',parameters,self.mode,self.modeVal,False,None,self.extra,None,self.no_of_inputs,self.no_of_outputs) + Inst.connect(self.InputStms,self.OutputStms) + return Inst + + +class CoolerClass(): + counter = 1; + + def __init__(self,name='Cooler',pressDrop = None, eff = None): + self.OM_data_eqn = '' + self.OM_data_init = '' + self.InputStms = [] + self.OutputStms = [] + self.name = name + str(CoolerClass.counter) + self.mode = None + self.modeVal = None + self.type = 'Cooler' + self.pressDrop = pressDrop + self.eff = eff + self.no_of_inputs = 1 + self.no_of_outputs = 1 + self.x = 2500-30 + self.y = 2500-30 + self.addedcomp = None + self.extra = None + HeaterClass.counter+=1 + + def modesList(self): + return ["heatRem","outT","outVapPhasMolFrac","tempDrop","enFlo"] + + def paramgetter(self,mode="heatRem"): + self.mode = mode + dict = {"pressDrop":None,"eff":None,self.mode:None} + return dict + + def add_compounds(self,addedcomp): + self.addedcomp = addedcomp + + + + def paramsetter(self,dict): + + self.pressDrop = dict['pressDrop'] + self.eff = dict['eff'] + self.modeVal = dict[self.mode] + + def connect(self,InputStms,OutputStms): + self.InputStms = InputStms + self.OutputStms = OutputStms + + def add_connection(self,flag,UnitOpr): + if flag==1: + # Input stream if flag is 1 + self.InputStms.append(UnitOpr) + print("INPUT CONNECTION") + else : + print("OUTPUT CONNECTION") + self.OutputStms.append(UnitOpr) + + + + def send_to_flowsheet(self,addedcomp): + self.addedcomp = addedcomp + parameters = [['pressDrop',self.pressDrop],['eff',self.eff]] + Inst = UnitOpr(self.name,CoolerClass.counter,'Cooler',parameters,self.mode,self.modeVal,False,None,self.extra,None,self.no_of_inputs,self.no_of_outputs) + Inst.connect(self.InputStms,self.OutputStms) + return Inst + + + + +class AdiaCompClass(): + counter = 1; + + def __init__(self,name='AdiaComp', eff = None): + self.OM_data_eqn = '' + self.OM_data_init = '' + self.InputStms = [] + self.OutputStms = [] + self.name = name + str(AdiaCompClass.counter) + self.mode = None + self.modeVal = None + self.type = 'AdiaComp' + self.thermoPackage ="Raoults_Law" + #self.pressDrop = pressDrop + self.eff = eff + self.no_of_inputs = 1 + self.no_of_outputs = 1 + self.x = 2500-30 + self.y = 2500-30 + self.addedcomp = None + self.extra = ['Adiabatic_Compressor'] + AdiaCompClass.counter+=1 + + def modesList(self): + return ["pressInc","outP","reqPow"] + + def add_compounds(self,addedcomp): + self.addedcomp = addedcomp + + def paramgetter(self,mode="pressInc"): + self.mode = mode + dict = {"eff":None,self.mode:None,"thermoPackage":None} + return dict + + def paramsetter(self,dict): + + self.eff = dict['eff'] + self.modeVal = dict[self.mode] + + def add_connection(self,flag,UnitOpr): + if flag==1: + # Input stream if flag is 1 + self.InputStms.append(UnitOpr) + print("INPUT CONNECTION") + else : + print("OUTPUT CONNECTION") + self.OutputStms.append(UnitOpr) + + def connect(self,InputStms = None,OutputStms = None): + self.InputStms = InputStms + self.OutputStms = OutputStms + + def send_to_flowsheet(self,addedcomp): + self.addedcomp = addedcomp + parameters = [['eff',self.eff]] + Inst = UnitOpr(self.name,AdiaCompClass.counter,'AdiaComp',parameters,self.mode,self.modeVal,True,self.thermoPackage,self.extra,None,self.no_of_inputs,self.no_of_outputs) + Inst.connect(self.InputStms,self.OutputStms) + return Inst + +class AdiaExpClass(): + counter = 1; + + def __init__(self,name='AdiaExp', eff = None): + self.OM_data_eqn = '' + self.OM_data_init = '' + self.InputStms = [] + self.OutputStms = [] + self.name = name + str(AdiaExpClass.counter) + self.mode = None + self.modeVal = None + self.type = 'AdiaExp' + self.thermoPackage ="Raoults_Law" + #self.pressDrop = pressDrop + self.eff = eff + self.no_of_inputs = 1 + self.no_of_outputs = 1 + self.x = 2500-30 + self.y = 2500-30 + self.addedcomp = None + self.extra = ['Adiabatic_Expander'] + AdiaExpClass.counter+=1 + + def modesList(self): + return ["pressDrop","outP","genPow"] + + def add_compounds(self,addedcomp): + self.addedcomp = addedcomp + + def paramgetter(self,mode="pressDrop"): + self.mode = mode + dict = {"eff":None,self.mode:None,"thermoPackage":None} + return dict + + def paramsetter(self,dict): + + self.eff = dict['eff'] + self.modeVal = dict[self.mode] + + def add_connection(self,flag,UnitOpr): + if flag==1: + # Input stream if flag is 1 + self.InputStms.append(UnitOpr) + print("INPUT CONNECTION") + else : + print("OUTPUT CONNECTION") + self.OutputStms.append(UnitOpr) + + def connect(self,InputStms = None,OutputStms = None): + self.InputStms = InputStms + self.OutputStms = OutputStms + + def send_to_flowsheet(self,addedcomp): + self.addedcomp = addedcomp + parameters = [['eff',self.eff]] + Inst = UnitOpr(self.name,AdiaExpClass.counter,'AdiaExp',parameters,self.mode,self.modeVal,True,self.thermoPackage,self.extra,None,self.no_of_inputs,self.no_of_outputs) + Inst.connect(self.InputStms,self.OutputStms) + return Inst + + + + + + + + + +def helperFunc(type): + if(type=="MatStm"): + return MatStm(CompNames=compound_selected) + else: + return eval(type+"Class")() + + + @@ -27,6 +27,8 @@ import datetime from container import Container from Graphics import Graphics import pickle +import os +import sys ui,_ = loadUiType('main.ui') @@ -189,15 +191,9 @@ class MainApp(QMainWindow,ui): ''' def component(self,conntype): if(self.comp.isCompSelected()): - # box=None - #box = NodeItem(conntype,self.Container) # Returns the unit operation with NodeItem, NodeSocket initialized - box = self.graphics.createNodeItem(conntype, self.Container) - - # print(box) - # addNodeItem = AddNodeItemCommand(self,box) - # self.undoStack.push(addNodeItem) - self.scene.addItem(box) - box.setPos(2500-30, 2500-30) + self.type = conntype + self.obj = helperFunc(self.type) + self.Container.addUnitOp(self.obj,self.scene,self.graphics) else: QMessageBox.about(self, 'Important', "Please Select Compounds first") self.comp.show() |