Difference between revisions of "IronPython Script Snippets"

From DWSIM - Chemical Process Simulator
Jump to: navigation, search
(Created page with "= Script Manager Snippet 1: Create and Connect Objects = Assuming that you're running a simulation with defined compound(s) and property package(s), this will create and conn...")
 
 
(13 intermediate revisions by the same user not shown)
Line 1: Line 1:
= Script Manager Snippet 1: Create and Connect Objects =
+
= Create, connect and manipulate objects =
  
 
Assuming that you're running a simulation with defined compound(s) and property package(s), this will create and connect a cooler and its connections:
 
Assuming that you're running a simulation with defined compound(s) and property package(s), this will create and connect a cooler and its connections:
  
<script lang=python>
+
<source lang=python>
  
 
import clr
 
import clr
Line 24: Line 24:
 
Flowsheet.ConnectObjects(cooler.GraphicObject, heat_out.GraphicObject, 0, 0)
 
Flowsheet.ConnectObjects(cooler.GraphicObject, heat_out.GraphicObject, 0, 0)
  
 +
# get inlet properties
 +
inlet_properties = inlet.GetPhase('Overall').Properties
  
</script>
+
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))
 +
 
 +
</source>
 +
 
 +
= Getting a reference to a Compound in the simulation =
 +
 
 +
<source lang=python>
 +
 
 +
mycompound = Flowsheet.SelectedCompounds['Methane']
 +
 
 +
mycompound2 = Flowsheet.GetSimulationObject['MSTR-001'].Phases[0].Compounds['Methane']
 +
 
 +
</source>
 +
 
 +
'''mycompound''' and '''mycompound2''' are referencing the same object in memory.
 +
 
 +
= Executing a script from another tab/section =
 +
 
 +
<source lang=python>
 +
 
 +
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)
 +
 
 +
</source>
 +
 
 +
= Setting the properties of a Material Stream =
 +
 
 +
<source lang=python>
 +
 
 +
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
 +
 
 +
</source>
 +
 
 +
= Getting Surface Tension and Diffusion Coefficients from a Material Stream =
 +
 
 +
<source lang=python>
 +
 
 +
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"
 +
 
 +
</source>
 +
 
 +
= Create and Display a Two-Dimensional Plot (Classic UI) =
 +
 
 +
<source lang=python>
 +
 
 +
import clr
 +
 
 +
clr.AddReference("OxyPlot")
 +
clr.AddReference("OxyPlot.WindowsForms")
 +
clr.AddReference("System.Windows.Forms")
 +
clr.AddReference("DWSIM.ExtensionMethods.Eto")
 +
 
 +
import OxyPlot
 +
 
 +
from OxyPlot.WindowsForms import PlotView
 +
from System.Windows.Forms import *
 +
from DWSIM.UI.Shared import *
 +
from System import Array
 +
 
 +
from math import *
 +
x = [i * 0.1 for i in range(100)]
 +
 
 +
# generate and display a nice chart
 +
 
 +
# create a new Plot model
 +
 
 +
# http://dwsim.inforside.com.br/api_help5/html/T_DWSIM_UI_Shared_Common.htm
 +
# http://dwsim.inforside.com.br/api_help5/html/T_DWSIM_ExtensionMethods_OxyPlot.htm
 +
 
 +
chart1 = PlotView()
 +
chart1.Model = Common.CreatePlotModel(Array[float](x), Array[float]([sin(xi) for xi in x]), "Test", "", "x", "y")
 +
 
 +
# update the chart data view
 +
 
 +
chart1.Model.InvalidatePlot(True)
 +
 
 +
# setup and display the chart
 +
 
 +
form1 = Form()
 +
 
 +
chart1.Dock = DockStyle.Fill
 +
 
 +
form1.Controls.Add(chart1)
 +
form1.Invalidate()
 +
form1.ShowDialog()
 +
 
 +
</source>
 +
 
 +
= Manipulate a Splliter Block =
 +
 
 +
<source lang=python>
 +
 
 +
# assuming that you have a splitter named "SPLT-001" on your flowsheet, try the following:
 +
 
 +
splitter = SPLT_001
 +
 
 +
# print the current operation mode
 +
# http://dwsim.inforside.com.br/api_help57/html/P_DWSIM_UnitOperations_UnitOperations_Splitter_OperationMode.htm
 +
 
 +
print splitter.OperationMode
 +
 
 +
# ratios is an array which stores the relative amount for up to 3 streams.
 +
 
 +
print splitter.Ratios[0]
 +
print splitter.Ratios[1]
 +
print splitter.Ratios[2]
 +
 
 +
# the sum of the three values must be equal to 1 to preserve the mass balance.
 +
 
 +
sum = splitter.Ratios[0] + splitter.Ratios[1] + splitter.Ratios[2]
 +
 
 +
print sum
 +
 
 +
# DWSIM will use the ratios when the splitter is in SplitRatios operation mode.
 +
 
 +
# if calculation mode is StreamMassFlowSpec or StreamMoleFlowSpec, set the StreamFlowSpec
 +
# property to the mass (kg/s) or mole (mol/s) flow value, then DWSIM will calculate the value for
 +
# the second outlet stream to close the balance.
 +
 
 +
# if there are three outlet streams, you must set both StreamFlowSpec and Stream2FlowSpec.
 +
 
 +
</source>
 +
 
 +
= Copy PFR data profile (mole fractions) to Spreadsheet =
 +
 
 +
<source lang=python>
 +
 
 +
import clr
 +
import System
 +
 
 +
clr.AddReference('System.Core')
 +
clr.ImportExtensions(System.Linq)
 +
 
 +
reactor = Flowsheet.GetFlowsheetSimulationObject("REACTOR")
 +
 
 +
profile = reactor.points
 +
 
 +
cnames = reactor.ComponentConversions.Keys.ToArray()
 +
 
 +
n = cnames.Count
 +
 
 +
Spreadsheet.Worksheets[0].Cells["A1"].Data = "Reactor Length (m)"
 +
 
 +
for i in range(0, n-1):
 +
    Spreadsheet.Worksheets[0].Cells[0, i+1].Data = cnames[i]
 +
 
 +
j = 1
 +
for pointset in profile:
 +
    Spreadsheet.Worksheets[0].Cells[j, 0].Data = pointset[0]
 +
    tmols = 0
 +
    for i in range (1, n):
 +
        tmols += pointset[i]
 +
    for i in range (1, n):
 +
            Spreadsheet.Worksheets[0].Cells[j, i].Data = pointset[i] / tmols
 +
    j += 1
 +
 
 +
</source>
 +
 
 +
= Create Pseudocompounds from Bulk C7+ Assay Data / Export to JSON files =
 +
 
 +
<source lang=python>
 +
 
 +
import clr
 +
import System
 +
 
 +
clr.AddReference("DWSIM")
 +
clr.AddReference("System.Core")
 +
clr.AddReference("System.Windows.Forms")
 +
clr.ImportExtensions(System.Linq)
 +
clr.AddReference("DWSIM.Interfaces")
 +
clr.AddReference("DWSIM.SharedClasses")
 +
clr.AddReference("Newtonsoft.Json")
 +
 
 +
from System import *
 +
 
 +
from DWSIM import *
 +
from DWSIM import FormPCBulk
 +
 
 +
from DWSIM.Interfaces import *
 +
from DWSIM.Interfaces.Enums import*
 +
from DWSIM.Interfaces.Enums.GraphicObjects import *
 +
 
 +
from DWSIM.Thermodynamics import*
 +
from DWSIM.Thermodynamics.BaseClasses import *
 +
from DWSIM.Thermodynamics.PropertyPackages.Auxiliary import *
 +
from DWSIM.Thermodynamics.Utilities.PetroleumCharacterization import GenerateCompounds
 +
from DWSIM.Thermodynamics.Utilities.PetroleumCharacterization.Methods import *
 +
 
 +
from Newtonsoft.Json import JsonConvert, Formatting
 +
 
 +
# assay data from spreadsheet
 +
 
 +
names = ["NBP46", "NBP65", "NBP85", "NBP105", "NBP115"]
 +
relative_densities = [677.3/1000.0, 694.2/1000.0, 712.1/1000.0, 729.2/1000.0, 739.7/1000.0] # relative
 +
nbps = [46 + 273.15, 65 + 273.15, 85 + 273.15, 105 + 273.15, 115 + 273.15] # K
 +
 
 +
n = 5
 +
 
 +
# bulk c7+ pseudocompound creator settings
 +
 
 +
Tccorr = "Riazi-Daubert (1985)"
 +
Pccorr = "Riazi-Daubert (1985)"
 +
AFcorr = "Lee-Kesler (1976)"
 +
MWcorr = "Winn (1956)"
 +
adjustZR = True
 +
adjustAf = True
 +
 
 +
# initial values for MW, SG and NBP
 +
 
 +
mw0 = 65
 +
sg0 = 0.65
 +
nbp0 = 310
 +
 
 +
# pseudocompound generator
 +
 
 +
comps = GenerateCompounds()
 +
 
 +
for i in range(0, n):
 +
 
 +
    # will generate only 1 pseudocompound for each item on the list of assay data. Normally we generate from 7 to 10 pseudocompounds for each set of assay data (MW, SG and NBP)
 +
 
 +
    comp_results = comps.GenerateCompounds(names[i], 1, Tccorr, Pccorr, AFcorr, MWcorr, adjustAf, adjustZR, None, relative_densities[i], nbps[i], None, None, None, None, mw0, sg0, nbp0)
 +
 
 +
    comp_values = list(comp_results.Values)
 +
    comp_values[0].Name = names[i]
 +
    comp_values[0].ConstantProperties.Name = names[i]
 +
    comp_values[0].ComponentName = names[i]
 +
 
 +
    # save the compound to a JSON file, which can be loaded back on any simulation
 +
 
 +
    #System.IO.File.WriteAllText("C:\\Users\\[YOURUSERNAME]\\Desktop\\" + str(names[i]) + ".json", JsonConvert.SerializeObject(comp_values[0].ConstantProperties, Formatting.Indented))
 +
 
 +
    # the following is for calculation quality check only, not required but desired
 +
 
 +
    myassay = SharedClasses.Utilities.PetroleumCharacterization.Assay.Assay(0, relative_densities[i], nbps[i], 0, 0, 0, 0)
 +
    ms_check = Streams.MaterialStream("","")
 +
    ms_check.SetFlowsheet(Flowsheet)
 +
    ms_check.PropertyPackage = Flowsheet.PropertyPackages.Values.ToList()[0]
 +
 
 +
    c1 = Compound(names[i], names[i])
 +
    c1.ConstantProperties = comp_values[0].ConstantProperties
 +
   
 +
    ms_check.Phases[0].Compounds.Add(names[i], c1)
 +
 
 +
    c2 = Compound(names[i], names[i])
 +
    c2.ConstantProperties = comp_values[0].ConstantProperties
 +
   
 +
    ms_check.Phases[1].Compounds.Add(names[i], c2)
 +
 
 +
    c3 = Compound(names[i], names[i])
 +
    c3.ConstantProperties = comp_values[0].ConstantProperties
 +
   
 +
    ms_check.Phases[2].Compounds.Add(names[i], c3)
 +
 
 +
    c4 = Compound(names[i], names[i])
 +
    c4.ConstantProperties = comp_values[0].ConstantProperties
 +
 
 +
    ms_check.Phases[3].Compounds.Add(names[i], c4)
 +
 
 +
    c5 = Compound(names[i], names[i])
 +
    c5.ConstantProperties = comp_values[0].ConstantProperties
 +
   
 +
    ms_check.Phases[4].Compounds.Add(names[i], c5)
 +
 
 +
    c6 = Compound(names[i], names[i])
 +
    c6.ConstantProperties = comp_values[0].ConstantProperties
 +
   
 +
    ms_check.Phases[5].Compounds.Add(names[i], c6)
 +
 
 +
    c7 = Compound(names[i], names[i])
 +
    c7.ConstantProperties = comp_values[0].ConstantProperties
 +
   
 +
    ms_check.Phases[6].Compounds.Add(names[i], c7)
 +
 
 +
    c8 = Compound(names[i], names[i])
 +
    c8.ConstantProperties = comp_values[0].ConstantProperties
 +
   
 +
    ms_check.Phases[7].Compounds.Add(names[i], c8)
 +
 
 +
    ms_check.EqualizeOverallComposition()
 +
 
 +
    qc = QualityCheck(myassay, ms_check)
 +
    System.Windows.Forms.MessageBox.Show(str(names[i]) + " quality report:\n\n" + qc.GetQualityCheckReport())
 +
 
 +
</source>
 +
 
 +
= Other Snippets =
 +
 
 +
For more code snippets, go to [https://sourceforge.net/p/dwsim/discussion/scripting/ https://sourceforge.net/p/dwsim/discussion/scripting/].

Latest revision as of 13:20, 11 October 2019

Create, connect and manipulate objects

Assuming that you're running a simulation with defined compound(s) and property package(s), this will create and connect a cooler and its connections:


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))

Getting a reference to a Compound in the simulation


mycompound = Flowsheet.SelectedCompounds['Methane']

mycompound2 = Flowsheet.GetSimulationObject['MSTR-001'].Phases[0].Compounds['Methane']

mycompound and mycompound2 are referencing the same object in memory.

Executing a script from another tab/section


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)

Setting the properties of a Material Stream


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

Getting Surface Tension and Diffusion Coefficients from a Material Stream


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"

Create and Display a Two-Dimensional Plot (Classic UI)


import clr

clr.AddReference("OxyPlot")
clr.AddReference("OxyPlot.WindowsForms")
clr.AddReference("System.Windows.Forms")
clr.AddReference("DWSIM.ExtensionMethods.Eto")

import OxyPlot

from OxyPlot.WindowsForms import PlotView
from System.Windows.Forms import *
from DWSIM.UI.Shared import *
from System import Array

from math import * 
x = [i * 0.1 for i in range(100)]

# generate and display a nice chart

# create a new Plot model

# http://dwsim.inforside.com.br/api_help5/html/T_DWSIM_UI_Shared_Common.htm
# http://dwsim.inforside.com.br/api_help5/html/T_DWSIM_ExtensionMethods_OxyPlot.htm

chart1 = PlotView()
chart1.Model = Common.CreatePlotModel(Array[float](x), Array[float]([sin(xi) for xi in x]), "Test", "", "x", "y") 

# update the chart data view

chart1.Model.InvalidatePlot(True)

# setup and display the chart

form1 = Form()

chart1.Dock = DockStyle.Fill

form1.Controls.Add(chart1)
form1.Invalidate()
form1.ShowDialog()

Manipulate a Splliter Block


# assuming that you have a splitter named "SPLT-001" on your flowsheet, try the following:

splitter = SPLT_001

# print the current operation mode
# http://dwsim.inforside.com.br/api_help57/html/P_DWSIM_UnitOperations_UnitOperations_Splitter_OperationMode.htm

print splitter.OperationMode

# ratios is an array which stores the relative amount for up to 3 streams. 

print splitter.Ratios[0]
print splitter.Ratios[1]
print splitter.Ratios[2]

# the sum of the three values must be equal to 1 to preserve the mass balance.

sum = splitter.Ratios[0] + splitter.Ratios[1] + splitter.Ratios[2]

print sum

# DWSIM will use the ratios when the splitter is in SplitRatios operation mode.

# if calculation mode is StreamMassFlowSpec or StreamMoleFlowSpec, set the StreamFlowSpec 
# property to the mass (kg/s) or mole (mol/s) flow value, then DWSIM will calculate the value for
# the second outlet stream to close the balance.

# if there are three outlet streams, you must set both StreamFlowSpec and Stream2FlowSpec.

Copy PFR data profile (mole fractions) to Spreadsheet


import clr
import System

clr.AddReference('System.Core')
clr.ImportExtensions(System.Linq)

reactor = Flowsheet.GetFlowsheetSimulationObject("REACTOR")

profile = reactor.points

cnames = reactor.ComponentConversions.Keys.ToArray()

n = cnames.Count

Spreadsheet.Worksheets[0].Cells["A1"].Data = "Reactor Length (m)"

for i in range(0, n-1):
    Spreadsheet.Worksheets[0].Cells[0, i+1].Data = cnames[i]

j = 1
for pointset in profile:
    Spreadsheet.Worksheets[0].Cells[j, 0].Data = pointset[0]
    tmols = 0
    for i in range (1, n):
        tmols += pointset[i]
    for i in range (1, n):
            Spreadsheet.Worksheets[0].Cells[j, i].Data = pointset[i] / tmols
    j += 1

Create Pseudocompounds from Bulk C7+ Assay Data / Export to JSON files


import clr
import System

clr.AddReference("DWSIM")
clr.AddReference("System.Core")
clr.AddReference("System.Windows.Forms")
clr.ImportExtensions(System.Linq)
clr.AddReference("DWSIM.Interfaces")
clr.AddReference("DWSIM.SharedClasses")
clr.AddReference("Newtonsoft.Json")

from System import *

from DWSIM import *
from DWSIM import FormPCBulk

from DWSIM.Interfaces import *
from DWSIM.Interfaces.Enums import*
from DWSIM.Interfaces.Enums.GraphicObjects import *

from DWSIM.Thermodynamics import*
from DWSIM.Thermodynamics.BaseClasses import *
from DWSIM.Thermodynamics.PropertyPackages.Auxiliary import *
from DWSIM.Thermodynamics.Utilities.PetroleumCharacterization import GenerateCompounds
from DWSIM.Thermodynamics.Utilities.PetroleumCharacterization.Methods import *

from Newtonsoft.Json import JsonConvert, Formatting

# assay data from spreadsheet

names = ["NBP46", "NBP65", "NBP85", "NBP105", "NBP115"]
relative_densities = [677.3/1000.0, 694.2/1000.0, 712.1/1000.0, 729.2/1000.0, 739.7/1000.0] # relative
nbps = [46 + 273.15, 65 + 273.15, 85 + 273.15, 105 + 273.15, 115 + 273.15] # K

n = 5

# bulk c7+ pseudocompound creator settings

Tccorr = "Riazi-Daubert (1985)"
Pccorr = "Riazi-Daubert (1985)"
AFcorr = "Lee-Kesler (1976)"
MWcorr = "Winn (1956)"
adjustZR = True
adjustAf = True

# initial values for MW, SG and NBP

mw0 = 65
sg0 = 0.65
nbp0 = 310

# pseudocompound generator

comps = GenerateCompounds()

for i in range(0, n):

    # will generate only 1 pseudocompound for each item on the list of assay data. Normally we generate from 7 to 10 pseudocompounds for each set of assay data (MW, SG and NBP)

    comp_results = comps.GenerateCompounds(names[i], 1, Tccorr, Pccorr, AFcorr, MWcorr, adjustAf, adjustZR, None, relative_densities[i], nbps[i], None, None, None, None, mw0, sg0, nbp0)

    comp_values = list(comp_results.Values)
    comp_values[0].Name = names[i]
    comp_values[0].ConstantProperties.Name = names[i]
    comp_values[0].ComponentName = names[i]

    # save the compound to a JSON file, which can be loaded back on any simulation

    #System.IO.File.WriteAllText("C:\\Users\\[YOURUSERNAME]\\Desktop\\" + str(names[i]) + ".json", JsonConvert.SerializeObject(comp_values[0].ConstantProperties, Formatting.Indented))

    # the following is for calculation quality check only, not required but desired

    myassay = SharedClasses.Utilities.PetroleumCharacterization.Assay.Assay(0, relative_densities[i], nbps[i], 0, 0, 0, 0)
    ms_check = Streams.MaterialStream("","")
    ms_check.SetFlowsheet(Flowsheet)
    ms_check.PropertyPackage = Flowsheet.PropertyPackages.Values.ToList()[0]

    c1 = Compound(names[i], names[i])
    c1.ConstantProperties = comp_values[0].ConstantProperties
    
    ms_check.Phases[0].Compounds.Add(names[i], c1)

    c2 = Compound(names[i], names[i])
    c2.ConstantProperties = comp_values[0].ConstantProperties
    
    ms_check.Phases[1].Compounds.Add(names[i], c2)

    c3 = Compound(names[i], names[i])
    c3.ConstantProperties = comp_values[0].ConstantProperties
    
    ms_check.Phases[2].Compounds.Add(names[i], c3)

    c4 = Compound(names[i], names[i])
    c4.ConstantProperties = comp_values[0].ConstantProperties

    ms_check.Phases[3].Compounds.Add(names[i], c4)

    c5 = Compound(names[i], names[i])
    c5.ConstantProperties = comp_values[0].ConstantProperties
    
    ms_check.Phases[4].Compounds.Add(names[i], c5)

    c6 = Compound(names[i], names[i])
    c6.ConstantProperties = comp_values[0].ConstantProperties
    
    ms_check.Phases[5].Compounds.Add(names[i], c6)

    c7 = Compound(names[i], names[i])
    c7.ConstantProperties = comp_values[0].ConstantProperties
    
    ms_check.Phases[6].Compounds.Add(names[i], c7)

    c8 = Compound(names[i], names[i])
    c8.ConstantProperties = comp_values[0].ConstantProperties
    
    ms_check.Phases[7].Compounds.Add(names[i], c8)

    ms_check.EqualizeOverallComposition()

    qc = QualityCheck(myassay, ms_check)
    System.Windows.Forms.MessageBox.Show(str(names[i]) + " quality report:\n\n" + qc.GetQualityCheckReport())

Other Snippets

For more code snippets, go to https://sourceforge.net/p/dwsim/discussion/scripting/.


Comments