Skip to content

Instantly share code, notes, and snippets.

@DanWBR
Last active June 6, 2024 13:55
Show Gist options
  • Save DanWBR/c355fd5420d20d960f5d084a7142cde8 to your computer and use it in GitHub Desktop.
Save DanWBR/c355fd5420d20d960f5d084a7142cde8 to your computer and use it in GitHub Desktop.
Create, run and save a new DWSIM simulation in Python
import pythoncom
pythoncom.CoInitialize()
import clr
from System.IO import Directory, Path, File
from System import String, Environment
dwsimpath = "C:\\Users\\Daniel\\AppData\\Local\\DWSIM8\\"
clr.AddReference(dwsimpath + "CapeOpen.dll")
clr.AddReference(dwsimpath + "DWSIM.Automation.dll")
clr.AddReference(dwsimpath + "DWSIM.Interfaces.dll")
clr.AddReference(dwsimpath + "DWSIM.GlobalSettings.dll")
clr.AddReference(dwsimpath + "DWSIM.SharedClasses.dll")
clr.AddReference(dwsimpath + "DWSIM.Thermodynamics.dll")
clr.AddReference(dwsimpath + "DWSIM.Thermodynamics.ThermoC.dll")
clr.AddReference(dwsimpath + "DWSIM.UnitOperations.dll")
clr.AddReference(dwsimpath + "DWSIM.Inspector.dll")
clr.AddReference(dwsimpath + "System.Buffers.dll")
from DWSIM.Interfaces.Enums.GraphicObjects import ObjectType
from DWSIM.Thermodynamics import Streams, PropertyPackages
from DWSIM.UnitOperations import UnitOperations
from DWSIM.Automation import Automation3
from DWSIM.GlobalSettings import Settings
Directory.SetCurrentDirectory(dwsimpath)
# create automation manager
interf = Automation3()
sim = interf.CreateFlowsheet()
# add water
water = sim.AvailableCompounds["Water"]
sim.SelectedCompounds.Add(water.Name, water)
# create and connect objects
m1 = sim.AddObject(ObjectType.MaterialStream, 50, 50, "inlet")
m2 = sim.AddObject(ObjectType.MaterialStream, 150, 50, "outlet")
e1 = sim.AddObject(ObjectType.EnergyStream, 100, 50, "power")
h1 = sim.AddObject(ObjectType.Heater, 100, 50, "heater")
m1 = m1.GetAsObject()
m2 = m2.GetAsObject()
e1 = e1.GetAsObject()
h1 = h1.GetAsObject()
sim.ConnectObjects(m1.GraphicObject, h1.GraphicObject, -1, -1)
sim.ConnectObjects(h1.GraphicObject, m2.GraphicObject, -1, -1)
sim.ConnectObjects(e1.GraphicObject, h1.GraphicObject, -1, -1)
sim.AutoLayout()
# steam tables property package
stables = PropertyPackages.SteamTablesPropertyPackage()
sim.AddPropertyPackage(stables)
# set inlet stream temperature
# default properties: T = 298.15 K, P = 101325 Pa, Mass Flow = 1 kg/s
m1.SetTemperature(300.0) # K
m1.SetMassFlow(100.0) # kg/s
# set heater outlet temperature
h1.CalcMode = UnitOperations.Heater.CalculationMode.OutletTemperature
h1.OutletTemperature = 400 # K
# request a calculation
Settings.SolverMode = 0
errors = interf.CalculateFlowsheet2(sim)
print(String.Format("Heater Heat Load: {0} kW", h1.DeltaQ))
# save file
fileNameToSave = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "heatersample.dwxmz")
interf.SaveFlowsheet(sim, fileNameToSave, True)
# save the pfd to an image and display it
clr.AddReference(dwsimpath + "SkiaSharp.dll")
clr.AddReference("System.Drawing")
from SkiaSharp import SKBitmap, SKImage, SKCanvas, SKEncodedImageFormat
from System.IO import MemoryStream
from System.Drawing import Image
from System.Drawing.Imaging import ImageFormat
PFDSurface = sim.GetSurface()
bmp = SKBitmap(1024, 768)
canvas = SKCanvas(bmp)
canvas.Scale(1.0)
PFDSurface.UpdateCanvas(canvas)
d = SKImage.FromBitmap(bmp).Encode(SKEncodedImageFormat.Png, 100)
str = MemoryStream()
d.SaveTo(str)
image = Image.FromStream(str)
imgPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "pfd.png")
image.Save(imgPath, ImageFormat.Png)
str.Dispose()
canvas.Dispose()
bmp.Dispose()
from PIL import Image
im = Image.open(imgPath)
im.show()
@DanWBR
Copy link
Author

DanWBR commented Oct 26, 2022

Hello,

I'm trying to run this code using python 3.10 and DWSim 8, but I always have the following error :

m1.SetTemperature(300) # K AttributeError: 'ISimulationObject' object has no attribute 'SetTemperature'

Does anyone know how to fix this problem ?

Thank you in advance !

m1 = m1.GetAsObject()

@cassianeomart
Copy link

m1 = m1.GetAsObject()

That worked ! Thank you :)

@cassianeomart
Copy link

Hello,

I have another question, my code is working, but it does not solve the flowsheet (I've got a flowsheet without the solution). That is normal ? How can I fix it ? There is somewhere where I can get more information about the automation of DWSim using python ?

I'm working with a project where I would like to automate the DWSim simulation, to automatically get the simulation results. This results would be useful to an optimization code that would optimize the energetic integration of my system. I'm really new with this kind of programming, so I would really like to learn more about how the automation works with DWSim.

I thank you all in advance !

@yilong100
Copy link

@lordcommander1 the code can only run once through your local web server before the error comes up. If you want to run it multiple times, you will need to use multiprocessing. Let me know if you want more details

If anyone still has this problem, I can send the code that I wrote to fix this problem directly to you.

@cassianeomart
Copy link

@lordcommander1 the code can only run once through your local web server before the error comes up. If you want to run it multiple times, you will need to use multiprocessing. Let me know if you want more details

If anyone still has this problem, I can send the code that I wrote to fix this problem directly to you.

Hello, could you send me your code please ? Thank you in advance !

@DanWBR
Copy link
Author

DanWBR commented Oct 27, 2022

@cassianeomart use Automation3(), check the above code again, it was updated.

@ElnazAbb
Copy link

Hey,

I am using DWSIM 8 and Python 3.9

The code works until reaching "print(String.Format("Heater Heat Load: {0} kW", h1.DeltaQ))"
The error, that is giving out afterwards, is called: AttributeError: 'ISimulationObject' object has no attribute 'DeltaQ'

Did anyone have a similar problem and knows how to fix it?
Thanks a lot!

@DanWBR
Copy link
Author

DanWBR commented Nov 16, 2022

Hey,

I am using DWSIM 8 and Python 3.9

The code works until reaching "print(String.Format("Heater Heat Load: {0} kW", h1.DeltaQ))" The error, that is giving out afterwards, is called: AttributeError: 'ISimulationObject' object has no attribute 'DeltaQ'

Did anyone have a similar problem and knows how to fix it? Thanks a lot!

see lines 48-51

@ElnazAbb
Copy link

@DanWBR Thanks a lot! It works now!

@ElnazAbb
Copy link

Hey,
I can run the whole code, however the "Heater Heat Load" is still 0 kW. How can I achive the calculation of the deltaQ? Do I have to change the "Settings.SolverMode = 0" in line 78? Thanks again!

@DanWBR
Copy link
Author

DanWBR commented Nov 21, 2022

Hey, I can run the whole code, however the "Heater Heat Load" is still 0 kW. How can I achive the calculation of the deltaQ? Do I have to change the "Settings.SolverMode = 0" in line 78? Thanks again!

running DWSIM v8.3.1?

@ElnazAbb
Copy link

Hey, I can run the whole code, however the "Heater Heat Load" is still 0 kW. How can I achive the calculation of the deltaQ? Do I have to change the "Settings.SolverMode = 0" in line 78? Thanks again!

running DWSIM v8.3.1

no 8.3.0 but I think I just found the mistake: I imported Automation2 instead of 3.

@DanWBR
Copy link
Author

DanWBR commented Nov 21, 2022

Hey, I can run the whole code, however the "Heater Heat Load" is still 0 kW. How can I achive the calculation of the deltaQ? Do I have to change the "Settings.SolverMode = 0" in line 78? Thanks again!

running DWSIM v8.3.1

no 8.3.0 but I think I just found the mistake: I imported Automation2 instead of 3.

update to 8.3.1, it is better overall

@lordcommander1
Copy link

Hello all,
i have a question. Are there any function in the dwsim package for python, which get me the material composotion of a stream?
And are there any functions to detect, which stream go in/out a specific process unit?
Thank you in advance!

@VarunK21
Copy link

VarunK21 commented Dec 5, 2022

Hello all, just wanted to know that the above code only works in Windows OS as pythoncom is available only in Windows . Is there any substitute to the pythoncom library for MacOS to run this same code or if there is any other way to automate DWISM using python in MacOS . I will by highly obliged to hear suggestions and work arounds .
Thank you in advance !

@DanWBR
Copy link
Author

DanWBR commented Dec 5, 2022

Hello all, i have a question. Are there any function in the dwsim package for python, which get me the material composotion of a stream? And are there any functions to detect, which stream go in/out a specific process unit? Thank you in advance!

1 - You can use GetOverallComposition(), it will return the molar composition. There is also GetOverallMassComposition(): https://github.com/DanWBR/dwsim/blob/windows/DWSIM.Thermodynamics/MaterialStream/MaterialStream.vb#L1077

2 - Use GetConnectionPortsInfo(): https://github.com/DanWBR/dwsim/blob/windows/DWSIM.SharedClasses/BaseClass/SimulationObjectBaseClasses.vb#L1603

@DanWBR
Copy link
Author

DanWBR commented Dec 5, 2022

Hello all, just wanted to know that the above code only works in Windows OS as pythoncom is available only in Windows . Is there any substitute to the pythoncom library for MacOS to run this same code or if there is any other way to automate DWISM using python in MacOS . I will by highly obliged to hear suggestions and work arounds . Thank you in advance !

it works normally, you just have to remove the pythoncom lines.

@lordcommander1
Copy link

Hello all, i have a question. Are there any function in the dwsim package for python, which get me the material composotion of a stream? And are there any functions to detect, which stream go in/out a specific process unit? Thank you in advance!

1 - You can use GetOverallComposition(), it will return the molar composition. There is also GetOverallMassComposition(): https://github.com/DanWBR/dwsim/blob/windows/DWSIM.Thermodynamics/MaterialStream/MaterialStream.vb#L1077

2 - Use GetConnectionPortsInfo(): https://github.com/DanWBR/dwsim/blob/windows/DWSIM.SharedClasses/BaseClass/SimulationObjectBaseClasses.vb#L1603

Hello Daniel,
if i use GetOverallComposition() i just get a number.
If i use GetConnectionPortsInfo() it says:
AttributeError: 'HeatExchanger' object has no attribute 'GetConnectionPortsInfo'

@VarunK21
Copy link

VarunK21 commented Dec 6, 2022

Hello all, just wanted to know that the above code only works in Windows OS as pythoncom is available only in Windows . Is there any substitute to the pythoncom library for MacOS to run this same code or if there is any other way to automate DWISM using python in MacOS . I will by highly obliged to hear suggestions and work arounds . Thank you in advance !

it works normally, you just have to remove the pythoncom lines.

Hi sir thank you for such a quick reply , I tried the same but was not successful and have a few doubts regarding some things -

> Tried installing the clr module explicitly and importing it in the program but then while calling AddReference it throws an error stating that there is no attribute named AddReference in clr module . Looked for some solutions and saw that there is pythonnet which can be used directly as it has clr and Systems module inside it . 

> As I installed pythonnet module directly and tried using clr module it states that pythonnet has no module named clr . Tied clr_loader as well but it did not work even throwing an error that there is no module named AddReference in crl_loader . Looked for some solutions over the internet where they stated that may be in case you installed clr module , you could uninstall clr uninstall pythonnet and then again install pythonnet back as it has clr and System module inside it . But unfortunately it has not worked .

> Another problem is I downloaded the github repository from the link - https://github.com/DanWBR/dwsim on macOS

where I tried importing the modules written in lines 21 to 23 but I was unable to do so stating there are no required modules with respective names . So do I need to install any other repository for macOS or the same will work as this repository do have some modules missing like there is no Automation3 instead it has Automation inside the repository etc. So is there any updated repository or the same will work .

I know there have been a plenty of doubts from my end but I will be highly thankful and obliged to your suggestions and recommendations . Plus if any other folk has done the same exercise on macOS and was successful then they could share their possibilities as well .

@DanWBR
Copy link
Author

DanWBR commented Dec 6, 2022

Hello all, just wanted to know that the above code only works in Windows OS as pythoncom is available only in Windows . Is there any substitute to the pythoncom library for MacOS to run this same code or if there is any other way to automate DWISM using python in MacOS . I will by highly obliged to hear suggestions and work arounds . Thank you in advance !

it works normally, you just have to remove the pythoncom lines.

Hi sir thank you for such a quick reply , I tried the same but was not successful and have a few doubts regarding some things -

> Tried installing the clr module explicitly and importing it in the program but then while calling AddReference it throws an error stating that there is no attribute named AddReference in clr module . Looked for some solutions and saw that there is pythonnet which can be used directly as it has clr and Systems module inside it . 

> As I installed pythonnet module directly and tried using clr module it states that pythonnet has no module named clr . Tied clr_loader as well but it did not work even throwing an error that there is no module named AddReference in crl_loader . Looked for some solutions over the internet where they stated that may be in case you installed clr module , you could uninstall clr uninstall pythonnet and then again install pythonnet back as it has clr and System module inside it . But unfortunately it has not worked .

> Another problem is I downloaded the github repository from the link - https://github.com/DanWBR/dwsim on macOS

where I tried importing the modules written in lines 21 to 23 but I was unable to do so stating there are no required modules with respective names . So do I need to install any other repository for macOS or the same will work as this repository do have some modules missing like there is no Automation3 instead it has Automation inside the repository etc. So is there any updated repository or the same will work .

I know there have been a plenty of doubts from my end but I will be highly thankful and obliged to your suggestions and recommendations . Plus if any other folk has done the same exercise on macOS and was successful then they could share their possibilities as well .

@VarunK21 what are you trying to do? I mean, what is your main objective?

@VarunK21
Copy link

VarunK21 commented Dec 6, 2022

Hello all, just wanted to know that the above code only works in Windows OS as pythoncom is available only in Windows . Is there any substitute to the pythoncom library for MacOS to run this same code or if there is any other way to automate DWISM using python in MacOS . I will by highly obliged to hear suggestions and work arounds . Thank you in advance !

it works normally, you just have to remove the pythoncom lines.

Hi sir thank you for such a quick reply , I tried the same but was not successful and have a few doubts regarding some things -

> Tried installing the clr module explicitly and importing it in the program but then while calling AddReference it throws an error stating that there is no attribute named AddReference in clr module . Looked for some solutions and saw that there is pythonnet which can be used directly as it has clr and Systems module inside it . 

> As I installed pythonnet module directly and tried using clr module it states that pythonnet has no module named clr . Tied clr_loader as well but it did not work even throwing an error that there is no module named AddReference in crl_loader . Looked for some solutions over the internet where they stated that may be in case you installed clr module , you could uninstall clr uninstall pythonnet and then again install pythonnet back as it has clr and System module inside it . But unfortunately it has not worked .

> Another problem is I downloaded the github repository from the link - https://github.com/DanWBR/dwsim on macOS

where I tried importing the modules written in lines 21 to 23 but I was unable to do so stating there are no required modules with respective names . So do I need to install any other repository for macOS or the same will work as this repository do have some modules missing like there is no Automation3 instead it has Automation inside the repository etc. So is there any updated repository or the same will work .
I know there have been a plenty of doubts from my end but I will be highly thankful and obliged to your suggestions and recommendations . Plus if any other folk has done the same exercise on macOS and was successful then they could share their possibilities as well .

@VarunK21 what are you trying to do? I mean, what is your main objective?

I am trying to automate the simulation process so that instead of manually creating flowsheets everytime, I just pass a json file with connections given in the form of dictionaries i.e., pair value form between different equipments and store the results of certain parameters in csv file in the computer .

@DanWBR
Copy link
Author

DanWBR commented Dec 6, 2022

@VarunK21 on macOS you need to install pythonnet v2.x, not v3.x which uses with clr_loader.

Also, you need to download the DWSIM app bundle from the downloads page, and then change the path to DWSIM libraries inside the python script to something like this, assuming that you put DWSIM.app on the Desktop:

dwsimpath = "/Users/[username]/Desktop/DWSIM.app/Contents/MonoBundle"

@VarunK21
Copy link

VarunK21 commented Dec 8, 2022

@VarunK21 on macOS you need to install pythonnet v2.x, not v3.x which uses with clr_loader.

Also, you need to download the DWSIM app bundle from the downloads page, and then change the path to DWSIM libraries inside the python script to something like this, assuming that you put DWSIM.app on the Desktop:

dwsimpath = "/Users/[username]/Desktop/DWSIM.app/Contents/MonoBundle"

@DanWBR sir, thank you for the constant support . Tried doing the same as suggested by you i.e., installing pythonnet 2.x and then importing clr , was able to import almost all the modules from DWSIM but two modules named 'GlobalSettings' and 'Streams' are throwing errors rather the kernel is dying while importing these two . Could you suggest what could be the reasons and work around for the same .

@VarunK21
Copy link

Hi @DanWBR sir, please help with this error message while executing the code in macOS -

Error message -

*Assertion assembly.c:1939, condition 'is_ok (hook _error)' not met,
function:mono_assembly_invoke_load_hook_internal, (null)
assembly:/Users/manish.dighore/opt/anaconda3/lib/mono/4.5/mscorlib.dll type:ReflectionTypeLoadException member :
(null)

============================================
Native Crash Reporting

Got a abrt while executing native code . This usually indicates a fatal error in the mono runtime or one of the native libraries used by our
application .

Flowsheet initialization and everything else is working perfectly fine, the line where we call self.interf.CalculateFlowsheet2(self.Sim)
causes the above error .

@W1lfr3d99
Copy link

Hi all, can you share your results if any of you have successfully run the codes.

@ElnazAbb
Copy link

ElnazAbb commented Feb 7, 2023

Hi all, can you share your results if any of you have successfully run the codes.
My results:

Reactor Heat Load: -66.5 kW
Ethylene oxide conversion: 27.95%
Water conversion: 6.98%

@DanWBR
Copy link
Author

DanWBR commented Mar 30, 2023

Hi all, If I want to perform exactly this reaction with Arrhenius via the Script Manager, how do I specify the quantities of the reactants?

Is the following valid? => water is R1, ethylene oxide is R2 and ethylene glycol is P1

A = 0.5 E = 0.0 with k1=A*math.exp(E)

and then how do I specify the reaction r1?

thanks in advance

I guess that your question isn't related to this gist, is it?

@kookma
Copy link

kookma commented Apr 1, 2023

But yes, because I am trying to figure out how to work with the Script Manager and would like to run this reaction via the Script Manager as a test, since I know the results. Still have a few problems to handle Script Manager...

I think these questions can be asked in forum. There are several Q&A on Script Manager in forum answered by @DanWBR also you can find shared solution.

@morteza374
Copy link

Thank you for providing this code. I have a problem with mono compatibility (or maybe pythonnet compatibility) with my M2 macbook. So, I didn't succeed in running the code. when I use (import clr) i a get a long error including (OSError: cannot load library '/Library/Frameworks/Mono.framework/Versions/6.12.0/lib/libmonosgen-2.0.dylib':). i tried to fix the problem with (command export DYLD_LIBRARY_PATH="/Library/Frameworks/Mono.framework/Versions/6.12.0/lib:$DYLD_LIBRARY_PATH"
) switching to mono 6.8 and installing different versions of pythonnet. but, the problem is still there. Is there any solution to fix or bypass this problem?

@defencedog
Copy link

On tiny10 Win x64 I have python 10 through miniconda
Environment variables [System Path]:
C:\Users\ukhan\miniconda3\Scripts\;C:\Users\ukhan\miniconda3\Library\bin\;C:\Users\ukhan\miniconda3\; then u need conda install pythonnet pywin32 -y Everything works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment