Skip to content

Python Script Unit Operation

Represents a Python Script Unit Operation that executes user-supplied Python code (IronPython or Python.NET) as part of the flowsheet calculation sequence.

DWSIM.UnitOperations.UnitOperations.CustomUO
Assembly DWSIM.UnitOperations.dll · Object ← BaseClass ← UnitOpBaseClass ← CustomUO

At a glance

Python Script Unit Operation in the example flowsheet

Port Index Connected in the example
Inlet, material 0 Feed
Inlet, material 1
Inlet, material 2
Inlet, energy 3
Inlet, material 4
Inlet, material 5
Inlet, material 6
Outlet, material 0 Product
Outlet, material 1
Outlet, material 2
Outlet, energy 3 Duty
Outlet, material 4
Outlet, material 5
Outlet, material 6

Example

This code runs on every build of this site, and the output below is what it printed.

    fs = (Flowsheet.Create("ScriptUOExample")
          .WithCompounds("N-hexane", "N-heptane")
          .WithPropertyPackage(PropertyPackages.PengRobinson))

    feed = (fs.AddMaterialStream("Feed")
            .At(Q.Celsius(25.0), Q.Bar(2.0))
            .SetCompoundMassFlow("N-hexane", 0.9)       # kg/s
            .SetCompoundMassFlow("N-heptane", 0.6))
    product = fs.AddMaterialStream("Product")
    duty = fs.AddEnergyStream("Duty")

    # The script runs in IronPython. ims1..ims6 and oms1..oms6 are the material streams on
    # ports 0-2 and 4-6, ies1 and oes1 the energy streams on port 3. Every input variable
    # becomes a script variable, and every number left in the script becomes an output.
    script = """
oms1.Assign(ims1)
oms1.SetTemperature(ims1.GetTemperature() + DeltaT)
oms1.SetFlashSpec("PT")
oms1.Calculate()
Q_kW = ims1.GetMassFlow() * (oms1.GetMassEnthalpy() - ims1.GetMassEnthalpy())
oes1.EnergyFlow = Q_kW
"""

    uo = (fs.AddUnitOperation(ObjectType.CustomUO, "SCRIPT-1")
          .ConnectFeed(feed, 0)
          .ConnectProduct(product, 0))
    # the duty leaves through outlet port 3
    uo.ConnectEnergyProduct(duty, 3)
    s = uo.Object.__implementation__             # the PythonScriptUO behind the generic builder
    s.ScriptText = script
    s.InputVariables["DeltaT"] = 40.0            # K

    fs.AutoLayout()
    fs.Solve()

    print(f"Outlet T          = {product.TemperatureK - 273.15:.2f} C")
    print(f"Duty (script)     = {s.OutputVariables['Q_kW']:.2f} kW")
    print(f"Energy stream     = {duty.Object.EnergyFlow:.2f} kW")
    print(f"Mean cp           = {s.OutputVariables['Q_kW'] / (1.5 * 40.0):.3f} kJ/(kg.K)")

Output

Outlet T          = 65.00 C
Duty (script)     = 135.84 kW
Energy stream     = 135.84 kW
Mean cp           = 2.264 kJ/(kg.K)

DWSIM 10.2.11.0, generated 2026-10-08.

Properties

IDs accepted by GetPropertyValue, SetPropertyValue, the sensitivity analysis, the optimizer, the Adjust block and dynamic events. Units are SI; pass another unit system to GetPropertyValue to get them converted.

ID Name Unit (SI) Input
DeltaT Temperature Difference yes
Q_kW result

Learn more

API members

Public members declared by this class. Inherited members are documented on the base classes.

Constructors

CustomUO(): Initializes a new default instance.

Initializes a new default instance.

public CustomUO()
Public Sub New()

CustomUO(string, string): Initializes a new instance with a name and description.

Initializes a new instance with a name and description.

Parameter Type Description
name String
description String
public CustomUO(string name, string description)
Public Sub New(name As String, description As String)

Properties

EmbeddedImageData: Gets or sets the Base-64 encoded embedded image data for a custom icon.

Gets or sets the Base-64 encoded embedded image data for a custom icon.

public string EmbeddedImageData { get; set; }
Public Property EmbeddedImageData As String

ExecutionEngine: Gets or sets the Python execution engine (IronPython or Python.NET).

Gets or sets the Python execution engine (IronPython or Python.NET).

public CustomUO.PythonExecutionEngine ExecutionEngine { get; set; }
Public Property ExecutionEngine As CustomUO.PythonExecutionEngine

FontName: Gets or sets the font name used in the script editor.

Gets or sets the font name used in the script editor.

public string FontName { get; set; }
Public Property FontName As String

FontSize: Gets or sets the font size used in the script editor.

Gets or sets the font size used in the script editor.

public int FontSize { get; set; }
Public Property FontSize As Integer

HasPropertiesForDynamicMode: Gets a value indicating this unit operation has no specific dynamic-mode properties.

Gets a value indicating this unit operation has no specific dynamic-mode properties.

public override bool HasPropertiesForDynamicMode { get; }
Public Overrides ReadOnly Property HasPropertiesForDynamicMode As Boolean

HighlightSpaces: Gets or sets whether spaces are highlighted in the script editor.

Gets or sets whether spaces are highlighted in the script editor.

public bool HighlightSpaces { get; set; }
Public Property HighlightSpaces As Boolean

HighlightTabs: Gets or sets whether tabs are highlighted in the script editor.

Gets or sets whether tabs are highlighted in the script editor.

public bool HighlightTabs { get; set; }
Public Property HighlightTabs As Boolean

Includes: Gets or sets the list of additional Python script files to include.

Gets or sets the list of additional Python script files to include.

public string[] Includes { get; set; }
Public Property Includes As String()

InputStringVariables: Gets or sets the dictionary of string-typed input variables exposed to the script.

Gets or sets the dictionary of string-typed input variables exposed to the script.

public Dictionary<string, string> InputStringVariables { get; set; }
Public Property InputStringVariables As Dictionary(Of String, String)

InputVariables: Gets or sets the dictionary of numeric input variables exposed to the script.

Gets or sets the dictionary of numeric input variables exposed to the script.

public Dictionary<string, double> InputVariables { get; set; }
Public Property InputVariables As Dictionary(Of String, Double)

MobileCompatible: Gets a value indicating whether this unit operation is compatible with mobile interfaces.

Gets a value indicating whether this unit operation is compatible with mobile interfaces.

public override bool MobileCompatible { get; }
Public Overrides ReadOnly Property MobileCompatible As Boolean

ObjectClass: Gets or sets the simulation object class category (UserModels).

Gets or sets the simulation object class category (UserModels).

public override SimulationObjectClass ObjectClass { get; set; }
Public Overrides Property ObjectClass As SimulationObjectClass

OutputVariables: Gets or sets the dictionary of numeric output variables produced by the script.

Gets or sets the dictionary of numeric output variables produced by the script.

public Dictionary<string, double> OutputVariables { get; set; }
Public Property OutputVariables As Dictionary(Of String, Double)

ScriptText: Gets or sets the Python script text to execute during calculation.

Gets or sets the Python script text to execute during calculation.

public string ScriptText { get; set; }
Public Property ScriptText As String

SupportsDynamicMode: Gets a value indicating this unit operation supports dynamic mode.

Gets a value indicating this unit operation supports dynamic mode.

public override bool SupportsDynamicMode { get; }
Public Overrides ReadOnly Property SupportsDynamicMode As Boolean

UseEmbeddedImage: Gets or sets whether the embedded image is used as the graphic object icon.

Gets or sets whether the embedded image is used as the graphic object icon.

public bool UseEmbeddedImage { get; set; }
Public Property UseEmbeddedImage As Boolean

Methods

Calculate(object): Executes the Python script, passing flowsheet objects and variables into the scope.

Executes the Python script, passing flowsheet objects and variables into the scope.

Parameter Type Description
args Object
public override void Calculate(object args = null)
Public Overrides Sub Calculate(args As Object = Nothing)

CloneXML(): Creates a deep copy via XML serialization.

Creates a deep copy via XML serialization.

public override object CloneXML()
Public Overrides Function CloneXML() As Object

CloseEditForm(): Closes and disposes the editing form.

Closes and disposes the editing form.

public override void CloseEditForm()
Public Overrides Sub CloseEditForm()

DeCalculate(): Clears all calculated results.

Clears all calculated results.

public override void DeCalculate()
Public Overrides Sub DeCalculate()

DisplayEditForm(): Opens or activates the editing form.

Opens or activates the editing form.

public override void DisplayEditForm()
Public Overrides Sub DisplayEditForm()

DisplayScriptEditorForm(): Opens the script editor window.

Opens the script editor window. Does nothing where the WinForms editors are not built.

public void DisplayScriptEditorForm()
Public Sub DisplayScriptEditorForm()

GetDisplayDescription(): Returns the localised display description.

Returns the localised display description.

public override string GetDisplayDescription()
Public Overrides Function GetDisplayDescription() As String

GetDisplayName(): Returns the localised display name.

Returns the localised display name.

public override string GetDisplayName()
Public Overrides Function GetDisplayName() As String

GetIconBitmapBytes(): Returns the icon bitmap as a byte array.

Returns the icon bitmap as a byte array.

public override byte[] GetIconBitmapBytes()
Public Overrides Function GetIconBitmapBytes() As Byte()

GetProperties(PropertyType): Returns an array of property identifiers for the specified property type.

Returns an array of property identifiers for the specified property type.

Parameter Type Description
proptype PropertyType
public override string[] GetProperties(PropertyType proptype)
Public Overrides Function GetProperties(proptype As PropertyType) As String()

GetPropertyUnit(string, IUnitsOfMeasure): Returns the unit string for the specified property.

Returns the unit string for the specified property.

Parameter Type Description
prop String
su IUnitsOfMeasure
public override string GetPropertyUnit(string prop, IUnitsOfMeasure su = null)
Public Overrides Function GetPropertyUnit(prop As String, su As IUnitsOfMeasure = Nothing) As String

GetPropertyValue(string, IUnitsOfMeasure): Returns the value of the specified property.

Returns the value of the specified property.

Parameter Type Description
prop String
su IUnitsOfMeasure
public override object GetPropertyValue(string prop, IUnitsOfMeasure su = null)
Public Overrides Function GetPropertyValue(prop As String, su As IUnitsOfMeasure = Nothing) As Object

GetReport(IUnitsOfMeasure, CultureInfo, string): Generates a plain-text report of the unit operation results.

Generates a plain-text report of the unit operation results.

Parameter Type Description
su IUnitsOfMeasure
ci CultureInfo
numberformat String
public override string GetReport(IUnitsOfMeasure su, CultureInfo ci, string numberformat)
Public Overrides Function GetReport(su As IUnitsOfMeasure, ci As CultureInfo, numberformat As String) As String

LoadData(List<XElement>): Restores the unit operation state from XML, including variable dictionaries.

Restores the unit operation state from XML, including variable dictionaries.

Parameter Type Description
data List<XElement>
public override bool LoadData(List<XElement> data)
Public Overrides Function LoadData(data As List(Of XElement)) As Boolean

RunDynamicModel(): Executes the script in dynamic simulation mode.

Executes the script in dynamic simulation mode.

public override void RunDynamicModel()
Public Overrides Sub RunDynamicModel()

SaveData(): Serializes the unit operation state to XML, including variable dictionaries.

Serializes the unit operation state to XML, including variable dictionaries.

public override List<XElement> SaveData()
Public Overrides Function SaveData() As List(Of XElement)

SetPropertyValue(string, object, IUnitsOfMeasure): Sets the value of the specified property.

Sets the value of the specified property.

Parameter Type Description
prop String
propval Object
su IUnitsOfMeasure
public override bool SetPropertyValue(string prop, object propval, IUnitsOfMeasure su = null)
Public Overrides Function SetPropertyValue(prop As String, propval As Object, su As IUnitsOfMeasure = Nothing) As Boolean

UpdateEditForm(): Refreshes the editing form with updated data.

Refreshes the editing form with updated data.

public override void UpdateEditForm()
Public Overrides Sub UpdateEditForm()

Validate(): Validates the unit operation configuration.

Validates the unit operation configuration.

public override void Validate()
Public Overrides Sub Validate()

Fields

f: The classic (WinForms) editor window open for this unit operation, if any.

The classic (WinForms) editor window open for this unit operation, if any. Not saved with the flowsheet.

public object f
Public f As Object

fs: Reserved handle for a script editor window; not assigned or read by the current code.

Reserved handle for a script editor window; not assigned or read by the current code. Not saved with the flowsheet.

public object fs
Public fs As Object

fsmono: Reserved handle for a script editor window on Mono; not assigned or read by the current code.

Reserved handle for a script editor window on Mono; not assigned or read by the current code. Not saved with the flowsheet.

public object fsmono
Public fsmono As Object