Skip to content

Instantly share code, notes, and snippets.

@DanWBR
Last active March 19, 2024 09:04
Show Gist options
  • Save DanWBR/3cb00f7ca112e6bbeca3e986890cef7f to your computer and use it in GitHub Desktop.
Save DanWBR/3cb00f7ca112e6bbeca3e986890cef7f to your computer and use it in GitHub Desktop.
Using DWSIM Standalone Thermodynamics Library in Python with Python.NET (Low-Level Flash API + CAPE-OPEN-style calls)
import clr
from System.IO import Directory, Path, File
from System import String, Double, Array, Reflection, Exception
dtlpath = "C:\\Users\\Daniel\\Source\\Repos\\DanWBR\\dwsim6\\DistPackages\\DTL\\"
clr.AddReference(dtlpath + "DWSIM.Thermodynamics.StandaloneLibrary.dll")
from DWSIM.Thermodynamics import Streams, PropertyPackages, CalculatorInterface
import CapeOpen
dtlc = CalculatorInterface.Calculator()
print(String.Format("DTL version: {0}", Reflection.Assembly.GetAssembly(dtlc.GetType()).GetName().Version))
print()
dtlc.Initialize()
nrtl = PropertyPackages.NRTLPropertyPackage(True)
dtlc.TransferCompounds(nrtl)
T = 355.0 #K
P = 101325.0 #Pa
compprops = dtlc.GetCompoundConstPropList()
print("Ethanol constant properties:\n")
for prop in compprops:
pval = dtlc.GetCompoundConstProp("Ethanol", prop)
print(prop + "\t" + pval)
print()
compprops = dtlc.GetCompoundPDepPropList()
print()
print("Ethanol pressure-dependent properties at P = " + str(P) + " Pa:\n")
for prop in compprops:
pval = dtlc.GetCompoundPDepProp("Ethanol", prop, P)
print(prop + "\t" + pval)
print()
compprops = dtlc.GetCompoundTDepPropList()
print()
print("Ethanol temperature-dependent properties at T = " + str(T) + " K:\n")
for prop in compprops:
pval = dtlc.GetCompoundTDepProp("Ethanol", prop, T)
print(prop + "\t" + pval)
print()
print()
print("Water/Ethanol Interaction Parameters for NRTL model:")
print()
# uncheck this if you have a CUDA or OpenCL device to use
# dtlc.EnableGPUProcessing()
# dtlc.InitComputeDevice(Cudafy.eLanguage.Cuda, 0)
ip = dtlc.GetInteractionParameterSet("NRTL", "Water", "Ethanol")
print("A12 = " + str(ip.Parameters["A12"]) + " cal/mol")
print("A21 = " + str(ip.Parameters["A21"]) + " cal/mol")
print("alpha = " + str(ip.Parameters["alpha"]))
print("PT Flash of an equimolar mixture of Water and Ethanol at T = " + str(T) + " K and P = " + str(P) + " Pa:" + "\n")
print("Using NRTL model for equilibrim calculations.")
print()
carray = Array[String](["Water", "Ethanol"])
comparray = Array[Double]([0.5, 0.5])
result2 = dtlc.PTFlash(nrtl, 0, P, T, carray, comparray)
print()
print("Flash calculation results:")
print()
for i in range(0, result2.GetLength(0)):
if (i == 0):
line = "Phase Name" + "\t"
elif (i == 1):
line = "Phase Mole Fraction in Mixture" + "\t"
elif (i == 2):
line = "Water Mole Fraction in Phase" + "\t"
elif (i == 3):
line = "Ethanol Mole Fraction in Phase" + "\t"
else:
line = ""
for j in range(0, result2.GetLength(1)):
line += str(result2[i, j])
print(line)
print()
print("Vapor Phase Mixture Properties at T = " + str(T) + " K and P = " + str(P) + " Pa:" + "\n")
vcarray = Array[Double]([float(result2[2, 0]), float(result2[3, 0])])
compphaseprops = dtlc.GetPropList()
for prop in compphaseprops:
try:
values = dtlc.CalcProp(nrtl, prop, "Mole", "Vapor", carray, T, P, vcarray)
line = ""
for i in range(0, values.Length):
line += str(values[i]) + "\t"
print(prop + "\t" + line)
except CapeOpen.CapeThrmPropertyNotAvailableException as e:
print(prop + "\t" + "Property Not Available")
except CapeOpen.CapeComputationException as e:
print(prop + "\t" + "Error Calculating Property")
except Exception as e:
print(prop + "\t" + e.Message)
print()
print("Liquid Phase Mixture Properties at T = " + str(T) + " K and P = " + str(P) + " Pa:" + "\n")
lcarray = Array[Double]([float(result2[2, 1]), float(result2[3, 1])])
for prop in compphaseprops:
try:
values = dtlc.CalcProp(nrtl, prop, "Mole", "Liquid", carray, T, P, lcarray)
line = ""
for i in range(0, values.Length):
line += str(values[i]) + "\t"
print(prop + "\t" + line)
except CapeOpen.CapeThrmPropertyNotAvailableException as e:
print(prop + "\t" + "Property Not Available")
except CapeOpen.CapeComputationException as e:
print(prop + "\t" + "Error Calculating Property")
except Exception as e:
print(prop + "\t" + e.Message)
@DanWBR
Copy link
Author

DanWBR commented Nov 6, 2020

Output:

DTL version: 6.3.7615.25480

Ethanol constant properties:

molecularweight 46.06844
criticaltemperature 513.92
criticalpressure 6148000
criticalvolume 0.000167
criticalcompressibilityfactor 0.24
acentricfactor 0.649
normalboilingpoint 351.8
idealgasgibbsfreeenergyofformationat25c -167850
idealgasenthalpyofformationat25c -234950
casregistrynumber 64-17-5
chemicalformula CH3CH2OH

Ethanol pressure-dependent properties at P = 101325.0 Pa:

boilingPointTemperature 351.805508295451

Ethanol temperature-dependent properties at T = 355.0 K:

heatOfVaporization 38573.9812218718
idealGasEnthalpy 3963.42097966534
idealGasEntropy 12.1445881310132
idealGasHeatCapacity 74.1528517567789
vaporPressure 114643.641285918
viscosityOfLiquid 0.000415880191836046
heatCapacityOfLiquid 140.587682621749
heatCapacityOfSolid 393.25216949475
thermalConductivityOfLiquid 0.155686475774892
thermalConductivityOfVapor 0.0208222194538193
viscosityOfVapor 1.05252376595578E-05

Water/Ethanol Interaction Parameters for NRTL model:

A12 = -57.9601 cal/mol
A21 = 1241.7396 cal/mol
alpha = 0.2937
PT Flash of an equimolar mixture of Water and Ethanol at T = 355.0 K and P = 101325.0 Pa:

Using NRTL model for equilibrim calculations.

Flash calculation results:

Phase Name VaporLiquidLiquid2Solid
Phase Mole Fraction in Mixture 0.75394111086200380.246058889137996230.00.0
Water Mole Fraction in Phase 0.42619163611621660.72617160800178180.00.0
Ethanol Mole Fraction in Phase 0.57380836388378340.27382839199821820.00.0

Vapor Phase Mixture Properties at T = 355.0 K and P = 101325.0 Pa:

molecularWeight 34.112417841370004
compressibilityFactor 0.9824551902352248
isothermalCompressibility 1.004810282017654e-05
bulkModulus 99521.27460240605
jouleThomsonCoefficient -7.841775013334011e-10
speedOfSound 291.51613264392233
volume 0.0291287441401431
density 34.33035063883421
viscosity 1.1513126534743293e-05
thermalConductivity 0.021650321376846367
heatCapacityCp 58.81682885071911
heatCapacityCv 49.50710942803439
enthalpy 2861.866676599058
entropy 16.689284485320474
internalEnergy -2489.41485912609
helmholtzEnergy -2494.5063042277866
gibbsEnergy -2.6320721496932244
fugacity 43183.86752947565 58141.13247052435
fugacityCoefficient 1.0 1.0
activityCoefficient 1.9828563891576885 0.8838257304415011
logFugacityCoefficient 0.0 0.0

Liquid Phase Mixture Properties at T = 355.0 K and P = 101325.0 Pa:

molecularWeight 25.697031693268734
compressibilityFactor 0.0008766413845747492
isothermalCompressibility 2.4880526857839656e-10
bulkModulus 4019207493.9317775
jouleThomsonCoefficient -1.1776211724429323e-10
speedOfSound 2124.6732098940583
volume 2.886202619111463e-05
density 34647.60212530943
viscosity 0.0003613479151163817
thermalConductivity 0.31811296341961254
heatCapacityCp 115.17204228581757
heatCapacityCv 58.17724684054671
enthalpy -39195.573698182
entropy -102.33294978082874
internalEnergy -63.275156080624164
helmholtzEnergy -8.260560375194403
gibbsEnergy -4.342289807686878
fugacity 43175.77117881436 58186.72262136402
fugacityCoefficient 0.5867920566604414 2.0971466819024656
activityCoefficient 1.1635243786561367 1.853512197975417
logFugacityCoefficient -0.5330847695117467 0.7405776979248467

@kookma
Copy link

kookma commented Nov 6, 2020

Thanks Daniel. I will check this and come back to you!

@kookma
Copy link

kookma commented Nov 7, 2020

What is: dtlpath = "C:\Users\Daniel\Source\Repos\DanWBR\dwsim6\DistPackages\DTL\"?
Should we set it to point to dwsim6 installation dir?

There is no DistPackages\dtl in my installation folder: D:\DWSIM6

@DanWBR
Copy link
Author

DanWBR commented Nov 7, 2020

What is: dtlpath = "C:\Users\Daniel\Source\Repos\DanWBR\dwsim6\DistPackages\DTL"?
Should we set it to point to dwsim6 installation dir?

There is no DistPackages\dtl in my installation folder: D:\DWSIM6

It is the path to the DTL file in your computer.

@kookma
Copy link

kookma commented Nov 7, 2020

So, I have to install Standalone Thermodynamics Library! I have not it on my laptop.
More question: Having Python 3.9 installed + PythonNet (https://pypi.org/project/pythonnet/) should be enough to run the code or I need more tools?

@DanWBR
Copy link
Author

DanWBR commented Nov 7, 2020

The library is just a single DLL file, no need to install. Just extract to a folder and get the folder path and put it on the script as dtlpath.

@kookma
Copy link

kookma commented Nov 7, 2020

Thank you Daniel!

@andr1976
Copy link

andr1976 commented Nov 8, 2020

One some instances (choice of Proppack/Flashalg) I get the follwoing exception:

Unhandled Exception: System.DllNotFoundException: Unable to load DLL 'Ipopt39': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
at Cureos.Numerics.Ipopt.FreeIpoptProblem(IntPtr ipopt_problem)
at Cureos.Numerics.Ipopt.Dispose(Boolean disposing) in C:\Users\Daniel\source\repos\DanWBR\dwsim6\DWSIM.Math.DotNumerics\LinearAlgebra\CSLapack\dscal.cs:line 0
at Cureos.Numerics.Ipopt.Finalize() in C:\Users\Daniel\source\repos\DanWBR\dwsim6\DWSIM.Math.DotNumerics\LinearAlgebra\CSLapack\dscal.cs:line 0

Ifs some path to a required DLL hardtyped somewhere?

@DanWBR
Copy link
Author

DanWBR commented Nov 8, 2020

Forgot to include IPOPT. Download it and put the DLLs on the same folder.

@lnix05
Copy link

lnix05 commented Sep 11, 2023

Hi Daniel,
Trying to execute this code I get the following error:

NullReferenceException Traceback (most recent call last)
in
35 print("Ethanol constant properties:\n")
36 for prop in compprops:
---> 37 pval = dtlc.GetCompoundConstProp("Ethanol", prop)
38 print(prop + "\t" + pval)
39

NullReferenceException: Object reference not set to an instance of an object.
at DWSIM.Thermodynamics.Streams.MaterialStream.get_PropertyPackage() in C:\Users\Daniel\source\repos\DanWBR\dwsim\DWSIM.Thermodynamics\MaterialStream\MaterialStream.vb:line 279
at DWSIM.Thermodynamics.Streams.MaterialStream.GetCompoundConstant(Object props, Object compIds) in C:\Users\Daniel\source\repos\DanWBR\dwsim\DWSIM.Thermodynamics\MaterialStream\MaterialStream.vb:line 4233
at DWSIM.Thermodynamics.CalculatorInterface.Calculator.GetCompoundConstProp(String compound, String prop) in C:\Users\Daniel\source\repos\DanWBR\dwsim\DWSIM.Thermodynamics\Interfaces\Thermodynamics.vb:line 541

Any idea on what might be causing it?

@wangyexiang
Copy link

Dear Sir, have you resolved this issue? @lnix05

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