File size: 33,381 Bytes
b1b3bae |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 |
<?xml version="1.0" encoding="UTF-8"?>
<root>
<row>
<A>Name</A>
<B>Category1</B>
<C>Category2</C>
<D>Scope</D>
<E>Snippet</E>
</row>
<row>
<A>Hello World</A>
<B>IronPython</B>
<C>Basics</C>
<D>Flowsheet/User Model</D>
<E>print "Hello World!"</E>
</row>
<row>
<A>Multi-Line Statements</A>
<B>IronPython</B>
<C>Basics</C>
<D>Flowsheet/User Model</D>
<E>def add(a, b):
return a + b
x = add(3, 2)
print x
y = add("Iron", "Python")
print y</E>
</row>
<row>
<A>Using the standard .NET libraries</A>
<B>IronPython</B>
<C>.NET Integration</C>
<D>Flowsheet/User Model</D>
<E>import System
dir(System.Environment)
print System.Environment.OSVersion
print System.Environment.CommandLine</E>
</row>
<row>
<A>Imports content of a class</A>
<B>IronPython</B>
<C>.NET Integration</C>
<D>Flowsheet/User Model</D>
<E>from System.Math import *
print dir()
print Sin(PI/2)</E>
</row>
<row>
<A>Working with .NET classes</A>
<B>IronPython</B>
<C>.NET Integration</C>
<D>Flowsheet/User Model</D>
<E>from System.Collections import *
h = Hashtable()
print dir(h)
h["a"] = "IronPython"
h["b"] = "Tutorial"
print h["a"]
for e in h: print (e.Key + ": " + e.Value)</E>
</row>
<row>
<A>Initializing collections with Python lists</A>
<B>IronPython</B>
<C>.NET Integration</C>
<D>Flowsheet/User Model</D>
<E>from System.Collections import *
l = ArrayList([1,2,3])
for i in l: print i
s = Stack((1,2,3))
while s.Count: s.Pop()</E>
</row>
<row>
<A>Using Generics</A>
<B>IronPython</B>
<C>.NET Integration</C>
<D>Flowsheet/User Model</D>
<E>from System.Collections.Generic import *
l = List[str]()
l.Add("Hello")
l.Add("Hi")
for i in l: print i</E>
</row>
<row>
<A>Loading .NET libraries</A>
<B>IronPython</B>
<C>.NET Integration</C>
<D>Flowsheet/User Model</D>
<E>import clr
clr.AddReference("System.Xml")
from System.Xml import *
print dir()</E>
</row>
<row>
<A>Loading the Mapack library</A>
<B>IronPython</B>
<C>.NET Integration</C>
<D>Flowsheet/User Model</D>
<E>import clr
clr.AddReference("Mapack")
from Mapack import *
print dir()
m = Matrix(2, 2, 1.2)
n = Matrix(2,1)
n[0,0] = 4
print m
print n
print m * n
print n.Transpose() * m
print m * 3</E>
</row>
<row>
<A>Get Current Directory</A>
<B>IronPython</B>
<C>Using Python Standard Library</C>
<D>Flowsheet/User Model</D>
<E>from System.IO import Directory, Path
lpath = Path.Combine(Directory.GetCurrentDirectory(), "Lib")
import sys
sys.path.append(lpath)
import os
print os.getcwd()</E>
</row>
<row>
<A>Get Current Directory</A>
<B>IronPython</B>
<C>.NET Integration</C>
<D>Flowsheet/User Model</D>
<E>from System.IO import Directory
print Directory.GetCurrentDirectory()</E>
</row>
<row>
<A>Using Windows.Forms</A>
<B>IronPython</B>
<C>Advanced</C>
<D>Flowsheet/User Model</D>
<E>import clr
clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
from System.Windows.Forms import *
from System.Drawing import *
f = Form()
f.Text = "My First Interactive Application"
def click(f, a):
l = Label(Text = "Hello")
l.Location = a.Location
f.Controls.Add(l)
f.Click += click
f.Show()</E>
</row>
<row>
<A>Use Word for Spell Checking</A>
<B>IronPython</B>
<C>Advanced</C>
<D>Flowsheet/User Model</D>
<E># Import clr module and add a reference to the Word COM interop assembly. Also, import System so that we can use a special value from it later.
import clr
clr.AddReferenceByPartialName("Microsoft.Office.Interop.Word")
from Microsoft.Office.Interop.Word import ApplicationClass
import System
# Start an instance of Word as a COM server running. You won't see it show up since it is hidden, but you can see it in the Windows Task Manager by typing ctrl-shift-escape and looking
# for the WINWORD.EXE process.
w = ApplicationClass()
# Define the following function to check the spelling. We have to build up an argument list so that we can supply the 12 optional arguments we do not care about (System.Type.Missing).
# We get the answer by taking the first (at index zero) of a few return values (out parameters in COM interop). Remember to indent the lines of the function's body extra spaces, and you
# have to hit an extra return or enter to complete the function's definition.
def check_word (word):
args = [word] + [System.Type.Missing]*12
return w.CheckSpelling(*args)
print check_word("foo")
print check_word("food")
# You can try that out on a couple of words, but now lets define a function that will suggest corrections for us. First, we need to add a document so that we can call GetSpellingSuggestions(),
# which gives a nice error message if you try to call it with no documents opened.
w.Documents.Add(*[System.Type.Missing]*4)
# The function we'll define builds an argument list just like check_word() did to supply several unneeded optional arguments. The first result of several return values from GetSpellingSuggestions()
# is a collection of items, each of which is a correction suggestion. We use a Python list comprehension to iterate through the COM collection object and call the Name property on each item object
# in the collection. Each item's Name property is a string that Word is suggesting as a correct spelling.
def suggestions (word):
args = [word] + [System.Type.Missing]*13
res_objects = w.GetSpellingSuggestions(*args)
return [x.Name for x in res_objects]
print suggestions("foo")
print suggestions("food")
# Now, let's shut down Word.
w.Quit(*[System.Type.Missing]*3)</E>
</row>
<row>
<A>Create, connect and manipulate objects</A>
<B>DWSIM</B>
<C>Advanced</C>
<D>Flowsheet</D>
<E>import clr
clr.AddReference('DWSIM.Interfaces')
from DWSIM import Interfaces
cooler = Flowsheet.AddObject(Interfaces.Enums.GraphicObjects.ObjectType.Cooler, 100, 100, 'COOLER-001')
heat_out = Flowsheet.AddObject(Interfaces.Enums.GraphicObjects.ObjectType.EnergyStream, 130, 150, 'HEAT_OUT')
inlet = Flowsheet.AddObject(Interfaces.Enums.GraphicObjects.ObjectType.MaterialStream, 50, 100, 'INLET')
outlet = Flowsheet.AddObject(Interfaces.Enums.GraphicObjects.ObjectType.MaterialStream, 150, 100, 'OUTLET')
cooler.GraphicObject.CreateConnectors(1, 1)
inlet.GraphicObject.CreateConnectors(1, 1)
outlet.GraphicObject.CreateConnectors(1, 1)
heat_out.GraphicObject.CreateConnectors(1, 1)
Flowsheet.ConnectObjects(inlet.GraphicObject, cooler.GraphicObject, 0, 0)
Flowsheet.ConnectObjects(cooler.GraphicObject, outlet.GraphicObject, 0, 0)
Flowsheet.ConnectObjects(cooler.GraphicObject, heat_out.GraphicObject, 0, 0)
# get inlet properties
inlet_properties = inlet.GetPhase('Overall').Properties
inlet_properties.temperature = 400 # K
inlet_properties.pressure = 1000000 # Pa
inlet_properties.massflow = 30 # kg/s
# the following will define all compound mole fractions to the same value so the sum is equal to 1
inlet.EqualizeOverallComposition()
# set the cooler's outlet temperature to 300 K
# http://dwsim.inforside.com.br/api_help57/html/T_DWSIM_UnitOperations_UnitOperations_Cooler.htm
cooler.OutletTemperature = 300
# set the cooler's calculation mode to 'outlet temperature'
# http://dwsim.inforside.com.br/api_help57/html/T_DWSIM_UnitOperations_UnitOperations_Cooler_CalculationMode.htm
clr.AddReference('DWSIM.UnitOperations')
from DWSIM import UnitOperations
cooler.CalcMode = UnitOperations.UnitOperations.Cooler.CalculationMode.OutletTemperature
#calculate the flowsheet
Flowsheet.RequestCalculation(None, False)
#get the outlet stream temperature and cooler's temperature decrease
deltat = cooler.DeltaT
heat_flow = heat_out.EnergyFlow
print('Cooler Temperature Drop (K):'+ str(deltat))
print('Heat Flow (kW): ' + str(heat_flow))</E>
</row>
<row>
<A>Getting a reference to a Compound in the simulation</A>
<B>DWSIM</B>
<C>Advanced</C>
<D>Flowsheet/User Model</D>
<E>mycompound = Flowsheet.SelectedCompounds['Methane']
mycompound2 = Flowsheet.GetSimulationObject['MSTR-001'].Phases[0].Compounds['Methane']</E>
</row>
<row>
<A>Executing a script from another tab/section</A>
<B>DWSIM</B>
<C>Advanced</C>
<D>Flowsheet</D>
<E>import clr
import System
from System import *
clr.AddReference('System.Core')
clr.ImportExtensions(System.Linq)
# get the script text from "Functions" using LINQ
source = Flowsheet.Scripts.Values.Where(lambda x: x.Title == 'Functions').FirstOrDefault().ScriptText.replace('\r', '')
# execute the script
exec(source)</E>
</row>
<row>
<A>Setting the properties of a Material Stream</A>
<B>DWSIM</B>
<C>Advanced</C>
<D>Flowsheet/User Model</D>
<E>ms1 = Flowsheet.GetFlowsheetSimulationObject('MSTR-001')
overall = ms1.GetPhase('Overall')
overall.Properties.temperature = 200 # set temperature to 200 K
overall.Properties.pressure = 101325 # set pressure to 101325 Pa
overall.Properties.massflow = 14 # set mass flow to 14 kg/s</E>
</row>
<row>
<A>Getting Surface Tension and Diffusion Coefficients from a Material Stream</A>
<B>DWSIM</B>
<C>Advanced</C>
<D>Flowsheet/User Model</D>
<E>import clr
import System
# get feed's interfacial tension - method 1
mixphase = feed.GetPhase("Mixture")
sftens = mixphase.Properties.surfaceTension
print str(sftens) + " N/m"
# get feed's interfacial tension - method 2
sftens2 = clr.Reference[System.Object]()
feed.GetTwoPhaseProp("surfacetension", None, "", sftens2)
print str(sftens2.Value[0]) + " N/m"
# diffusion coefficients
phase = feed.GetPhase("Vapor")
compound = phase.Compounds["Methane"]
difc = compound.DiffusionCoefficient
print str(difc) + " m2/s"</E>
</row>
<row>
<A>Override Mixer Model</A>
<B>DWSIM</B>
<C>Model Customization</C>
<D>Flowsheet</D>
<E># for more details, go to https://dwsim.org/wiki/index.php?title=Model_Customization
import clr
clr.AddReference('DWSIM.MathOps')
clr.AddReference('DWSIM.UnitOperations')
clr.AddReference('DWSIM.Interfaces')
from DWSIM import *
from DWSIM.Thermodynamics.Streams import *
from DWSIM.UnitOperations import *
from DWSIM.MathOps.MathEx import *
from System import *
from System.Collections.Generic import *
# gets the mixer object
mixer = Flowsheet.GetFlowsheetSimulationObject('MIX-004')
def CalcMixer():
ms = MaterialStream()
P = 0.0
W = 0.0
H = 0.0
i = 1
for cp in mixer.GraphicObject.InputConnectors:
if cp.IsAttached:
ms = Flowsheet.SimulationObjects[cp.AttachedConnector.AttachedFrom.Name]
ms.Validate()
if mixer.PressureCalculation == UnitOperations.Mixer.PressureBehavior.Minimum:
print '[' + mixer.GraphicObject.Tag + '] ' + 'Mixer Mode: Outlet Pressure = Minimum Inlet Pressure'
if ms.Phases[0].Properties.pressure < P:
P = ms.Phases[0].Properties.pressure
elif P == 0.0:
P = ms.Phases[0].Properties.pressure
elif mixer.PressureCalculation == UnitOperations.Mixer.PressureBehavior.Maximum:
print '[' + mixer.GraphicObject.Tag + '] ' + 'Mixer Mode: Outlet Pressure = Maximum Inlet Pressure'
if ms.Phases[0].Properties.pressure > P:
P = ms.Phases[0].Properties.pressure
elif P == 0:
P = ms.Phases[0].Properties.pressure
else:
print '[' + mixer.GraphicObject.Tag + '] ' + 'Mixer Mode: Outlet Pressure = Inlet Average'
P += ms.Phases[0].Properties.pressure
i += 1
We = ms.Phases[0].Properties.massflow
W += We
if not Double.IsNaN(ms.Phases[0].Properties.enthalpy): H += We * ms.Phases[0].Properties.enthalpy
if W != 0.0:
Hs = H / W
else:
Hs = 0.0
if mixer.PressureCalculation == UnitOperations.Mixer.PressureBehavior.Average: P = P / (i - 1)
print '[' + mixer.GraphicObject.Tag + '] ' + 'Mixture Pressure (Pa): ' + str(P)
print '[' + mixer.GraphicObject.Tag + '] ' + 'Mixture Mass Flow (kg/s): ' + str(W)
print '[' + mixer.GraphicObject.Tag + '] ' + 'Mixture Enthalpy (kJ/kg): ' + str(Hs)
T = 0.0
n = Flowsheet.SelectedCompounds.Count
Vw = Dictionary[String, Double]()
for cp in mixer.GraphicObject.InputConnectors:
if cp.IsAttached:
ms = Flowsheet.SimulationObjects[cp.AttachedConnector.AttachedFrom.Name]
for comp in ms.Phases[0].Compounds.Values:
if not Vw.ContainsKey(comp.Name):
Vw.Add(comp.Name, 0)
Vw[comp.Name] += comp.MassFraction * ms.Phases[0].Properties.massflow
if W != 0.0: T += ms.Phases[0].Properties.massflow / W * ms.Phases[0].Properties.temperature
if W == 0.0: T = 273.15
print '[' + mixer.GraphicObject.Tag + '] ' + 'Mixture Temperature Estimate (K): ' + str(T)
omstr = Flowsheet.SimulationObjects[mixer.GraphicObject.OutputConnectors[0].AttachedConnector.AttachedTo.Name]
omstr.Clear()
omstr.ClearAllProps()
if W != 0.0: omstr.Phases[0].Properties.enthalpy = Hs
omstr.Phases[0].Properties.pressure = P
omstr.Phases[0].Properties.massflow = W
omstr.Phases[0].Properties.molarfraction = 1
omstr.Phases[0].Properties.massfraction = 1
for comp in omstr.Phases[0].Compounds.Values:
if W != 0.0: comp.MassFraction = Vw[comp.Name] / W
mass_div_mm = 0.0
for sub1 in omstr.Phases[0].Compounds.Values:
mass_div_mm += sub1.MassFraction / sub1.ConstantProperties.Molar_Weight
for sub1 in omstr.Phases[0].Compounds.Values:
if W != 0.0:
sub1.MoleFraction = sub1.MassFraction / sub1.ConstantProperties.Molar_Weight / mass_div_mm
else:
sub1.MoleFraction = 0.0
print '[' + mixer.GraphicObject.Tag + '] ' + sub1.Name + ' outlet molar fraction: ' + str(sub1.MoleFraction)
omstr.Phases[0].Properties.temperature = T
omstr.SpecType = Interfaces.Enums.StreamSpec.Pressure_and_Enthalpy
print '[' + mixer.GraphicObject.Tag + '] ' + 'Outlet Stream variables set successfully.'
return None
mixer.OverrideCalculationRoutine = True
mixer.CalculationRoutineOverride = CalcMixer</E>
</row>
<row>
<A>Override Property Package Fugacity Coefficients Calculation</A>
<B>DWSIM</B>
<C>Model Customization</C>
<D>Flowsheet</D>
<E># for more details, go to https://dwsim.org/wiki/index.php?title=Model_Customization
import clr
clr.AddReference('DWSIM.MathOps')
from DWSIM import *
from DWSIM.MathOps.MathEx import *
from DWSIM.Thermodynamics.PropertyPackages import *
from System import *
# gets the first Property Package added to the the simulation
pp = Flowsheet.PropertyPackagesArray[0]
def calcroots(coeffs):
# auxiliary function
# calculates the roots of of a cubic polynomial and returns only the real ones
a = coeffs[0]
b = coeffs[1]
c = coeffs[2]
d = coeffs[3]
# uses DWSIM's internal 'CalcRoots' function to calculate roots
# https://github.com/DanWBR/dwsim5/blob/windows/DWSIM.Math/MATRIX2.vb#L29
res = PolySolve.CalcRoots(a, b, c, d)
roots = [[0] * 2 for i in range(3)]
roots[0][0] = res[0, 0]
roots[0][1] = res[0, 1]
roots[1][0] = res[1, 0]
roots[1][1] = res[1, 1]
roots[2][0] = res[2, 0]
roots[2][1] = res[2, 1]
# orders the roots
if roots[0][0] > roots[1][0]:
tv = roots[1][0]
roots[1][0] = roots[0][0]
roots[0][0] = tv
tv2 = roots[1][1]
roots[1][1] = roots[0][1]
roots[0][1] = tv2
if roots[0][0] > roots[2][0]:
tv = roots[2][0]
roots[2][0] = roots[0][0]
roots[0][0] = tv
tv2 = roots[2][1]
roots[2][1] = roots[0][1]
roots[0][1] = tv2
if roots[1][0] > roots[2][0]:
tv = roots[2][0]
roots[2][0] = roots[1][0]
roots[1][0] = tv
tv2 = roots[2][1]
roots[2][1] = roots[1][1]
roots[1][1] = tv2
validroots = []
if roots[0][1] == 0 and roots[0][0] > 0.0: validroots.append(roots[0][0])
if roots[1][1] == 0 and roots[1][0] > 0.0: validroots.append(roots[1][0])
if roots[2][1] == 0 and roots[2][0] > 0.0: validroots.append(roots[2][0])
# returns only valid real roots
return validroots
def fugcoeff(Vz, T, P, state):
# calculates fugacity coefficients using PR EOS
# Vx = composition vector in molar fractions
# T = temperature in K
# P = Pressure in Pa
# state = mixture state (Liquid, Vapor or Solid)
R = 8.314
n = len(Vz)
Tc = pp.RET_VTC() # critical temperatures
Pc = pp.RET_VPC() # critical pressures
w = pp.RET_VW() # acentric factors
alpha = [0] * n
ai = [0] * n
bi = [0] * n
for i in range(n):
alpha[i] = (1 + (0.37464 + 1.54226 * w[i] - 0.26992 * w[i] ** 2) * (1 - (T / Tc[i]) ** 0.5)) ** 2
ai[i] = 0.45724 * alpha[i] * R ** 2 * Tc[i] ** 2 / Pc[i]
bi[i] = 0.0778 * R * Tc[i] / Pc[i]
a = [[0] * n for i in range(n)]
# get binary interaction parameters (BIPs/kijs) from PR Property Package
kij = [[0] * n for i in range(n)]
vkij = pp.RET_VKij()
for i in range(n):
for j in range(n):
kij[i][j] = vkij[i, j]
a[i][j] = (ai[i] * ai[j]) ** 0.5 * (1 - kij[i][j]) # <- default mixing rule for amix
amix = 0.0
bmix = 0.0
amix2 = [0] * n
for i in range(n):
for j in range(n):
amix += Vz[i] * Vz[j] * a[i][j] # <- default mixing rule for amix
amix2[i] += Vz[j] * a[j][i]
for i in range(n):
bmix += Vz[i] * bi[i] # <- default mixing rule - no interaction parameters for bmix
AG = amix * P / (R * T) ** 2
BG = bmix * P / (R * T)
coeff = [0] * 4
coeff[0] = 1
coeff[1] = BG - 1
coeff[2] = AG - 3 * BG ** 2 - 2 * BG
coeff[3] = -AG * BG + BG ** 2 + BG ** 3
roots = calcroots(coeff) # <- get the real roots of the cubic equation
# compressibility factor = cubic equation's root
if state == State.Liquid:
# liquid
Z = min(roots)
else:
# vapor
Z = max(roots)
# gets a special zeroed vector from the property package because DWSIM requires a
# .NET array as the returning value, not a Python one
fugcoeff = pp.RET_NullVector()
for i in range(n):
t1 = bi[i] * (Z - 1) / bmix
t2 = -Math.Log(Z - BG)
t3 = AG * (2 * amix2[i] / amix - bi[i] / bmix)
t4 = Math.Log((Z + (1 + 2 ** 0.5) * BG) / (Z + (1 - 2 ** 0.5) * BG))
t5 = 2 * 2 ** 0.5 * BG
fugcoeff[i] = Math.Exp(t1 + t2 - (t3 * t4 / t5))
# returns calculated fugacity coefficients
print 'calculated fugacities = ' + str(fugcoeff) + ' (' + str(state) + ')'
return fugcoeff
# activate fugacity calculation override on PR Property Package
pp.OverrideKvalFugCoeff = True
# set the function that calculates the fugacity coefficient
pp.KvalFugacityCoefficientOverride = fugcoeff</E>
</row>
<row>
<A>Override Property Package Enthalpy Calculation</A>
<B>DWSIM</B>
<C>Model Customization</C>
<D>Flowsheet</D>
<E># for more details, go to https://dwsim.org/wiki/index.php?title=Model_Customization
import clr
clr.AddReference('DWSIM.MathOps')
from DWSIM import *
from DWSIM.MathOps.MathEx import *
from DWSIM.Thermodynamics.PropertyPackages import *
from System import *
# gets the first Property Package added to the the simulation
pp = Flowsheet.PropertyPackagesArray[0]
def calcroots(coeffs):
# auxiliary function
# calculates the roots of of a cubic polynomial and returns only the real ones
a = coeffs[0]
b = coeffs[1]
c = coeffs[2]
d = coeffs[3]
# uses DWSIM's internal 'CalcRoots' function to calculate roots
# https://github.com/DanWBR/dwsim5/blob/windows/DWSIM.Math/MATRIX2.vb#L29
res = PolySolve.CalcRoots(a, b, c, d)
roots = [[0] * 2 for i in range(3)]
roots[0][0] = res[0, 0]
roots[0][1] = res[0, 1]
roots[1][0] = res[1, 0]
roots[1][1] = res[1, 1]
roots[2][0] = res[2, 0]
roots[2][1] = res[2, 1]
# orders the roots
if roots[0][0] > roots[1][0]:
tv = roots[1][0]
roots[1][0] = roots[0][0]
roots[0][0] = tv
tv2 = roots[1][1]
roots[1][1] = roots[0][1]
roots[0][1] = tv2
if roots[0][0] > roots[2][0]:
tv = roots[2][0]
roots[2][0] = roots[0][0]
roots[0][0] = tv
tv2 = roots[2][1]
roots[2][1] = roots[0][1]
roots[0][1] = tv2
if roots[1][0] > roots[2][0]:
tv = roots[2][0]
roots[2][0] = roots[1][0]
roots[1][0] = tv
tv2 = roots[2][1]
roots[2][1] = roots[1][1]
roots[1][1] = tv2
validroots = []
if roots[0][1] == 0 and roots[0][0] > 0.0: validroots.append(roots[0][0])
if roots[1][1] == 0 and roots[1][0] > 0.0: validroots.append(roots[1][0])
if roots[2][1] == 0 and roots[2][0] > 0.0: validroots.append(roots[2][0])
# returns only valid real roots
return validroots
def enthalpy(Vz, T, P, state):
# calculates enthalpy using PR EOS
# Vx = composition vector in molar fractions
# T = temperature in K
# P = Pressure in Pa
# state = mixture state (Liquid, Vapor or Solid)
# ideal gas enthalpy contribution
Hid = pp.RET_Hid(298.15, T, Vz)
R = 8.314
n = len(Vz)
Tc = pp.RET_VTC() # critical temperatures
Pc = pp.RET_VPC() # critical pressures
w = pp.RET_VW() # acentric factors
alpha = [0] * n
ai = [0] * n
bi = [0] * n
ci = [0] * n
for i in range(n):
alpha[i] = (1 + (0.37464 + 1.54226 * w[i] - 0.26992 * w[i] ** 2) * (1 - (T / Tc[i]) ** 0.5)) ** 2
ai[i] = 0.45724 * alpha[i] * R ** 2 * Tc[i] ** 2 / Pc[i]
bi[i] = 0.0778 * R * Tc[i] / Pc[i]
ci[i] = 0.37464 + 1.54226 * w[i] - 0.26992 * w[i] ** 2
a = [[0] * n for i in range(n)]
# get binary interaction parameters (BIPs/kijs) from PR Property Package
kij = [[0] * n for i in range(n)]
vkij = pp.RET_VKij()
for i in range(n):
for j in range(n):
kij[i][j] = vkij[i, j]
a[i][j] = (ai[i] * ai[j]) ** 0.5 * (1 - kij[i][j]) # <- default mixing rule for amix
amix = 0.0
bmix = 0.0
amix2 = [0] * n
for i in range(n):
for j in range(n):
amix += Vz[i] * Vz[j] * a[i][j] # <- default mixing rule for amix
amix2[i] += Vz[j] * a[j][i]
for i in range(n):
bmix += Vz[i] * bi[i] # <- default mixing rule - no interaction parameters for bmix
AG = amix * P / (R * T) ** 2
BG = bmix * P / (R * T)
coeff = [0] * 4
coeff[0] = 1
coeff[1] = BG - 1
coeff[2] = AG - 3 * BG ** 2 - 2 * BG
coeff[3] = -AG * BG + BG ** 2 + BG ** 3
roots = calcroots(coeff) # <- get the real roots of the cubic equation
# compressibility factor = cubic equation's root
if state == State.Liquid:
# liquid
Z = min(roots)
else:
# vapor
Z = max(roots)
# amix temperature derivative
dadT1 = -8.314 / 2 * (0.45724 / T) ** 0.5
dadT2 = 0.0#
for i in range(n):
j = 0
for j in range(n):
dadT2 += Vz[i] * Vz[j] * (1 - kij[i][j]) * (ci[j] * (ai[i] * Tc[j] / Pc[j]) ** 0.5 + ci[i] * (ai[j] * Tc[i] / Pc[i]) ** 0.5)
dadT = dadT1 * dadT2
uu = 2
ww = -1
DAres = amix / (bmix * (uu ** 2 - 4 * ww) ** 0.5) * Math.Log((2 * Z + BG * (uu - (uu ** 2 - 4 * ww) ** 0.5)) / (2 * Z + BG * (uu + (uu ** 2 - 4 * ww) ** 0.5))) - R * T * Math.Log((Z - BG) / Z) - R * T * Math.Log(Z)
DSres = R * Math.Log((Z - BG) / Z) + R * Math.Log(Z) - 1 / (8 ** 0.5 * bmix) * dadT * Math.Log((2 * Z + BG * (2 - 8 ** 0.5)) / (2 * Z + BG * (2 + 8 ** 0.5)))
DHres = DAres + T * (DSres) + R * T * (Z - 1)
# mixture molar weight (MW)
MW = pp.AUX_MMM(Vz)
print 'calculated enthalpy = ' + str(Hid + DHres/ MW) + ' kJ/kg (' + str(state) + ')'
return Hid + DHres / MW # kJ/kg
# activate enthalpy calculation override on PR Property Package
pp.OverrideEnthalpyCalculation = True
# set the function that calculates the enthalpy
pp.EnthalpyCalculationOverride = enthalpy</E>
</row>
<row>
<A>Add a New Property to a Valve Object</A>
<B>DWSIM</B>
<C>Dynamic Properties</C>
<D>Flowsheet</D>
<E># The Dynamic Properties feature in DWSIM allows you to add new properties to flowsheet objects, which will persist between simulation file saving/opening cycles.
# These properties can be used by scripts to perform additional calculations, or even override the actual models.
# For instance, you can add a new property to a valve object on the flowsheet called "Cv", setting a value for it for later use on an additional calculation step:
valve = Flowsheet.GetFlowsheetSimulationObject("FV-01")
valve.ExtraProperties.Cv = 3102.78
props = valve.ExtraProperties
# Cv = 11.6 Q (SG / dp)^0.5
# dp = SG/(Cv/11.6Q)^2
# where
# q = water flow (m3/hr)
# SG = specific gravity (1 for water)
# dp = pressure drop (kPa)
DP = valve.DeltaP / 1000
SG = inlet.Phases[0].Properties.density / 1000
Q = props.Cv / 11.6 / (SG/DP) ** 0.5 / 60 / 60 # m3/s</E>
</row>
<row>
<A>Create an Excel Spreadsheet</A>
<B>IronPython</B>
<C>Advanced</C>
<D>Flowsheet</D>
<E>import clr
import sys
clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c')
from Microsoft.Office.Interop import Excel
ex = Excel.ApplicationClass()
ex.Visible = False
ex.DisplayAlerts = True
workbook = ex.Workbooks.Add()
workbook.Worksheets.Add()
ws1 = workbook.Worksheets[1]
ws1.UsedRange.Cells[1, 1].Value2 = "time"
ws1.UsedRange.Cells[1, 2].Value2 = "source_level"
ws1.UsedRange.Cells[1, 3].Value2 = "sink_level"
ws1.UsedRange.Cells[1, 4].Value2 = "hot_water_flow"
ws1.UsedRange.Cells[1, 5].Value2 = "hot_water_temp"
ws1.UsedRange.Cells[1, 6].Value2 = "cooling_water_flow"
ws1.UsedRange.Cells[1, 7].Value2 = "cooling_water_temp"
ws1.UsedRange.Cells[1, 8].Value2 = "valve_opening"
ex.Visible = True</E>
</row>
<row>
<A>Get Feed Stream Properties</A>
<B>DWSIM</B>
<C>Basics</C>
<D>User Model</D>
<E>import math
from System import Array
# Set the feed stream
feed = ims1
# Get temperature and pressure of the feed
# Notice that the values returned are one-element vectors, not scalars
T = feed.GetProp("temperature", "Overall", None, "", "") # K
P = feed.GetProp("pressure", "Overall", None, "", "") # Pa
# Get the number of components in the feed stream
n = int(feed.GetNumCompounds())
# Get compound IDs in the feed stream
ids = feed.ComponentIds</E>
</row>
<row>
<A>Set Product Stream Properties</A>
<B>DWSIM</B>
<C>Basics</C>
<D>User Model</D>
<E># Set properties in the overflow stream (T, P, xmo, xwo, to)
# CAPE-OPEN's "SetProp" function expects you to provide a vector containing
# the property values, even if it is only one value that you're trying to set.
# Notice the "[]" enclosure around the qt variable in the last SetProp call.
overflow = oms1
overflow.Clear()
overflow.SetProp("temperature", "Overall", None, "", "", T) # K
overflow.SetProp("pressure", "Overall", None, "", "", P) # Pa</E>
</row>
<row>
<A>Calculate Equilibrium, Get and Set Properties</A>
<B>DWSIM</B>
<C>Advanced</C>
<D>User Model</D>
<E>import math
from System import Array
# Set the streams
inlet1 = ims1
inlet2 = ims2
inlet3 = ims3
outlet1 = oms1
outlet2 = oms2
outlet3 = oms3
# Get streams' enthalpies and mass flows, set specified outlet temperatures
if inlet1 <> None:
mixphase = inlet1.GetPhase("Mixture")
Hin1 = mixphase.Properties.enthalpy
Win1 = mixphase.Properties.massflow
outlet1.CopyFromMaterial(inlet1)
else:
Hin1 = 0.0
Win1 = 0.0
if inlet2 <> None:
mixphase = inlet2.GetPhase("Mixture")
Hin2 = mixphase.Properties.enthalpy
Win2 = mixphase.Properties.massflow
outlet2.CopyFromMaterial(inlet2)
outlet2.GetPhase("Mixture").Properties.temperature = 20 + 273.15
else:
Hin2 = 0.0
Win2 = 0.0
if inlet3 <> None:
Hin3 = mixphase.Properties.enthalpy
Win3 = mixphase.Properties.massflow
outlet3.CopyFromMaterial(inlet3)
outlet3.GetPhase("Mixture").Properties.temperature = 13 + 273.15
else:
Hin3 = 0.0
Win3 = 0.0
if outlet2 <> None:
outlet2.CalcEquilibrium("TP",None)
Hout2 = outlet2.GetPhase("Mixture").Properties.enthalpy
else:
Hout2 = 0.0
if outlet3 <> None:
outlet3.CalcEquilibrium("TP",None)
Hout3 = outlet3.GetPhase("Mixture").Properties.enthalpy
else:
Hout3 = 0.0</E>
</row>
<row>
<A>Calculate PH Flash</A>
<B>DWSIM</B>
<C>Advanced</C>
<D>User Model</D>
<E> outlet1.GetPhase("Mixture").Properties.enthalpy = 0.0 # kJ/kg
# calculate outlet temperature
outlet1.CalcEquilibrium("PH",None)
print outlet1.GetPhase("Mixture").Properties.temperature</E>
</row>
<row>
<A>Get Ideal Gas Heat Capacity from a Compound</A>
<B>DWSIM</B>
<C>Basics</C>
<D>Flowsheet/User Model</D>
<E>compIds = ['Argon']
props = ['idealgasheatcapacity']
values = feed.GetTDependentProperty(props, 298.15, compIds, None)
Flowsheet.ShowMessage(str(values[0]), 0, "")</E>
</row>
<row>
<A>Clone a Material Stream</A>
<B>DWSIM</B>
<C>Basics</C>
<D>Flowsheet/User Model</D>
<E>oms1 = ims1.Duplicate()</E>
</row>
<row>
<A>Copy Properties between Material Streams</A>
<B>DWSIM</B>
<C>Basics</C>
<D>Flowsheet/User Model</D>
<E>i_solid = Flowsheet.GetFlowsheetSimulationObject('i_solid')
o_solid = Flowsheet.GetFlowsheetSimulationObject('o_solid')
o_solid.Assign(i_solid)</E>
</row>
<row>
<A>Working with the CoolProp library</A>
<B>DWSIM</B>
<C>Basics</C>
<D>Flowsheet/User Model</D>
<E>import clr
clr.AddReference("DWSIM.Thermodynamics.CoolPropInterface")
import CoolProp
tcrit = CoolProp.Props1SI("Water", "TCRIT")
print tcrit</E>
</row>
<row>
<A>Calculate Latent Heat of Vaporization</A>
<B>DWSIM</B>
<C>Advanced</C>
<D>Flowsheet/User Model</D>
<E>import clr
import System
import DWSIM
from System import *
clr.AddReference("System.Core")
clr.ImportExtensions(System.Linq)
ms = Flowsheet.GetFlowsheetSimulationObject("MSTR-000")
pp = ms.PropertyPackage
pp.CurrentMaterialStream = ms
# get mixture composition
Vz = ms.Phases[0].Compounds.Values.Select(lambda x: x.MoleFraction).Cast[Double]().ToArray()
# get temperature
T = ms.Phases[0].Properties.temperature
# get pressure
P = ms.Phases[0].Properties.pressure
# calculate mixture enthalpy as vapor
hv = pp.DW_CalcEnthalpy(Vz, T, P, DWSIM.Thermodynamics.PropertyPackages.State.Vapor)
# calculate mixture enthalpy as liquid
hl = pp.DW_CalcEnthalpy(Vz, T, P, DWSIM.Thermodynamics.PropertyPackages.State.Liquid)
# enthalpy of vaporization
hvap = hv-hl
# kJ/kg
print str(hvap) </E>
</row>
<row>
<A>Get the Critical Temperature of a Compound</A>
<B>DWSIM</B>
<C>Basics</C>
<D>Flowsheet/User Model</D>
<E>air_stream = Flowsheet.GetFlowsheetSimulationObject('MSTR-000')
air_compound = air_stream.GetPhase('Mixture').Compounds['Air']
crit_temp = air_compound.ConstantProperties.Critical_Temperature
print crit_temp</E>
</row>
</root> |