IronPython Script

The IronPython script is referenced by the XML extension definition file. It defines the functions that are used by the extension and the actions that are performed during each step of the wizard. The XML file can reference multiple scripts.

ANSYS journaling and scripting commands can be used inside callbacks. You can write the commands manually or edit commands obtained from a session journal file, either from the temporary journal stored in your folder %TEMP% or from a journal generated by using the Record Journal menu option.

Example: IronPython Script for a Project Wizard

To demonstrate how an IronPython script is used in a wizard, this topic uses the same Project Wizard extension as the previous section.

The XML extension definition file references the script main.py:

geoSystem = None
dsSystem = None
fluentSystem = None 

def EmptyAction(step):
    pass

def InitTabularData(step):
    table = step.Properties["TableB"]
    for i in range(1, 10):
        table.AddRow()
        table.Properties["Integer"].Value = i
        table.Properties["FileOpen"].Value = "super"
        table.Properties["Number"].Value = 45.21
        table.Properties["ReadOnly"].Value = 777
        table.Properties["myselect"].Properties["TestStr"].Value = 777
        table.Properties["myselect"].Properties["Number B"].Value = 777
        table.SaveActiveRow()

def CreateGeometry(step):
    global geoSystem
    template1 = GetTemplate(TemplateName="Geometry")
    geoSystem = template1.CreateSystem()
    geometry1 = geoSystem.GetContainer(ComponentName="Geometry")
    geometry1.SetFile(FilePath=step.Properties["definition/filename"].Value)

def DeleteGeometry(step):
    global geoSystem
    geoSystem.Delete()
    
def RefreshMechanical(step):
    tree = step.UserInterface.GetComponent("Tree")
    root = tree.CreateTreeNode("Root")
    node1 = tree.CreateTreeNode("Node1")
    node2 = tree.CreateTreeNode("Node2")
    node3 = tree.CreateTreeNode("Node3")
    root.Values.Add(node1)
    root.Values.Add(node2)
    node2.Values.Add(node1)
    node2.Values.Add(node3)
    root.Values.Add(node3)
    tree.SetTreeRoot(root)
    chart = step.UserInterface.GetComponent("Chart")
    chart.Plot([1,2,3,4,5],[10,4,12,13,8],"b","Line1")
    chart.Plot([1,2,3,4,5],[5,12,7,8,11],"r","Line2")

def CreateMechanical(step):
    global dsSystem, geoSystem
    template2 = GetTemplate(
        TemplateName="Static Structural",
        Solver="ANSYS")
    geometryComponent1 = geoSystem.GetComponent(Name="Geometry")
    dsSystem = template2.CreateSystem(
        ComponentsToShare=[geometryComponent1],
        Position="Right",
        RelativeTo=geoSystem)
    if step.Properties["name"].Value=="error":
        raise UserErrorMessageException("Invalid system name. Please try again.")
    dsSystem.DisplayText = step.Properties["name"].Value

def DeleteMechanical(step):
    global dsSystem
    dsSystem.Delete()

def CreateFluent(step):
    global dsSystem, fluentSystem
    template3 = GetTemplate(TemplateName="Fluid Flow")
    geometryComponent2 = dsSystem.GetComponent(Name="Geometry")
    solutionComponent1 = dsSystem.GetComponent(Name="Solution")
    componentTemplate1 = GetComponentTemplate(Name="CFDPostTemplate")
    fluentSystem = template3.CreateSystem(
        ComponentsToShare=[geometryComponent2],
        DataTransferFrom=[Set(FromComponent=solutionComponent1, TransferName=None, 
ToComponentTemplate=componentTemplate1)],
        Position="Right",
        RelativeTo=dsSystem)
    if step.Properties["name"].Value=="error":
        raise Exception("Invalid system name. Please try again.")
    fluentSystem.DisplayText = step.Properties["name"].Value

def CreateDialog(step):
    comp = step.UserInterface.Panel.CreateOKCancelDialog("MyDialog", "MyTitle", 400, 150)
    comp.SetOkButton("Ok")
    comp.SetMessage("My own message")
    comp.SetCallback(cbDialog)
    prop = step.Properties["nextstep"]
    prop.Options.Clear()
    s = step.NextStep
    val = s.Caption
    while s!=None:
        prop.Options.Add(s.Caption)
        s = s.NextStep
    prop.Value = val

def cbDialog(sender, args):
    dialog = CurrentWizard.CurrentStep.UserInterface.GetComponent("MyDialog").Hide()

def ValidateDialog(step, prop):
    dialog = step.UserInterface.GetComponent("MyDialog")
    dialog.Show()

def worker(step):
    progressDialog = step.UserInterface.GetComponent("Progress")
    progress = progressDialog.GetFirstOrDefaultComponent()
    progress.Reset()
    stopped = progress.UpdateProgress("Start progress...", 0, True)
    progressDialog.Show()
    for i in range(100):
        System.Threading.Thread.Sleep(100)
        stopped = progress.UpdateProgress("Start progress...", i+1, True)
        if stopped:
            break
    progressDialog.Hide()
    
def ValidateDialogProgress(step, prop):
    thread = System.Threading.Thread(System.Threading.ParameterizedThreadStart(worker))
    thread.Start(step)
    
def ValidateNextStep(step, prop):
    prop = step.Properties["nextstep"]
    s = step.NextStep
    v = False
    while s!=None:
        if prop.Value==s.Caption:
            v = True
        s.IsEnabled = v
        s = s.NextStep
    steps = step.UserInterface.GetComponent("Steps")
    steps.UpdateData()
    steps.Refresh()

def RefreshReport(step):
    report = step.UserInterface.GetComponent("Report")
    report.SetHtmlContent(System.IO.Path.Combine(ExtAPI.Extension.InstallDir,"help","report.html"))
    report.Refresh()
    
def EmptyReset(step):
    pass
    
def LogReport(step):
    ExtAPI.Log.WriteMessage("Report:")
    for s in step.Wizard.Steps.Values:
        ExtAPI.Log.WriteMessage("Step "+s.Caption)
        for prop in s.AllProperties:
            ExtAPI.Log.WriteMessage(prop.Caption+": "+prop.DisplayString)

import random
import math

def RefreshCharts(step):
    graph = step.UserInterface.GetComponent("Graph")
    graph.Title("Line Bar Graph")
    graph.ShowLegend(False)
    graph.Plot([-1, 0, 1, 2, 3, 4],  [0.5, -0.5, 0.5, -0.5, 0.5, 0.5], key="Variable A", color='g')
    graph.Bar([-1, 0, 1, 2, 3, 4],  [10, 20, 30, 10, 5, 20], key="Variable B")

    graphB = step.UserInterface.GetComponent("GraphB")
    graphB.Title("Plot Graph")
    graphB.YTickFormat("0.2f")

    xValues = []
    yValues = []
    for i in range(0, 100):
        xValues.append(i)
        yValues.append(abs(math.sin(i*0.2))*i/100.0)
    graphB.Plot(xValues, yValues, key="y = a*sin(bx)", color="c")
    graphB.Plot(xValues, yValues, key="y = x", color="m")

    xValues = []
    yValues = []
    for i in range(0, 100):
        xValues.append(i)
        yValues.append(i/100.0)
    graphB.Plot(xValues, yValues, key="y = x", color="m")

    graphB.Plot([0, 10, 20, 30, 100], [0.2, 0.2, 0.2, 0.3, 0.3], key="Smth", color="r")
    graphB.Plot([0, 10, 20, 30, 100], [0.2, 0.1, 0.3, 0.5, 0.7], key="Smth", color="r")
    graphB.Plot([0, 10, 20, 30, 100], [0.2, 0.2, 0.2, 0.3, 0.3])

    graphC = step.UserInterface.GetComponent("GraphC")
    graphC.Title("Pie Graph")
    graphC.Pie([1, 2, 3])
    graphC.Pie([20, 30, 5, 15, 12], [0, "Banana", 2, 3, "42"])

    graphD = step.UserInterface.GetComponent("GraphD")
    graphD.Title("Bar Graph")
    graphD.Bar(["Banana"], [70], key="key")
    graphD.Bar([0, "Banana", 2, 3, 4], [20, 30, 5, 15, 12], key="key")

    graphE = step.UserInterface.GetComponent("GraphE")
    graphE.Title("Bubble Graph")
    graphE.XTickFormat("f")
    graphE.YTickFormat("f")
    keys = ["one", "two", "three", "four", "five"]
    colors = ["#BB3333", "#33BB33", "#3333BB", "#BBBB33", "#BB33BB"]
    for c in range(0, 5):
        xValues = []
        yValues = []
        sizeValues = []
        for i in range(0, (c+1)*20):
            rad = random.randrange(c+1, c+2) + (random.random()*2-1)
            angle = random.random() * 2 * math.pi
            xValues.append(math.cos(angle) * rad)
            yValues.append(math.sin(angle) * rad)
            sizeValues.append(random.random() * 2.0 + 0.5)
        graphE.Bubble(xValues, yValues, sizeValues, key=keys[c], color=colors[c])

def CreateStaticStructural(step):
    template1 = GetTemplate(
        TemplateName="Static Structural",
        Solver="ANSYS")
    system1 = template1.CreateSystem()
    system1.DisplayText = "toto"

    nextStep = step.NextStep
    if nextStep!=None:
        nextStep.SystemName = system1.Name
        nextStep.ComponentName = "Geometry"
    nextStep = nextStep.NextStep
    if nextStep!=None:
        nextStep.SystemName = system1.Name
        nextStep.ComponentName = "Geometry"
    nextStep = nextStep.NextStep
    if nextStep!=None:
        nextStep.SystemName = system1.Name
        nextStep.ComponentName = "Geometry"
    nextStep = nextStep.NextStep
    if nextStep!=None:
        nextStep.SystemName = system1.Name
        nextStep.ComponentName = "Geometry"
    nextStep = nextStep.NextStep
    if nextStep!=None:
        nextStep.SystemName = system1.Name
        nextStep.ComponentName = "Model"
    nextStep = nextStep.NextStep
    if nextStep!=None:
        nextStep.SystemName = system1.Name
        nextStep.ComponentName = "Model"

def OnSelectContext(step, prop):
    firstDMStep = step.NextStep
    secondDMStep = firstDMStep.NextStep
    firstSCStep = secondDMStep.NextStep
    secondSCStep = firstSCStep.NextStep

    firstGeoStep = step.NextStep
    if prop.Value == "DesignModeler":
        firstDMStep.IsEnabled = True
        secondDMStep.IsEnabled = True
        firstSCStep.IsEnabled = False
        secondSCStep.IsEnabled = False
    elif prop.Value == "SpaceClaim":
        firstDMStep.IsEnabled = False
        secondDMStep.IsEnabled = False
        firstSCStep.IsEnabled = True
        secondSCStep.IsEnabled = True

    panel = step.UserInterface.Panel.GetComponent("Steps")
    panel.UpdateData()
    panel.Refresh()


def RefreshResultsProject(step):
    step.Properties["Res"].Value = ExtAPI.Extension.Attributes["result"]
    panel = step.UserInterface.Panel.GetComponent("Properties")
    panel.UpdateData()
    panel.Refresh()

This script defines all functions executed by callbacks in the XML file. Each step defined in the XML file can include multiple actions.

  • Step 1 (Geometry): The callback <onupdate> executes the function EmptyAction. The callback <onreset> executes the function DeleteGeometry. The callback <oninit> executes the function InitTabularData.

  • Step 2 (Mechanical): The callback <onupdate> executes the function EmptyAction. The callback <onreset> executes the function DeleteMechanical.

  • Step 3 (Fluent): The callback <onrefresh> executes the function CreateDialog. The callback <onupdate> executes the function EmptyAction. The callback <onreset> executes the function EmptyReset.

  • Step 4 (ReportView): The callback <onrefresh> executes the function RefreshReport. The callback <onreset> executes the function EmptyReset.

  • Step 5 (CustomStep): The callback <onrefresh> executes the funcrtion RefreshMechanical. The callback <onupdate> executes the funcion LogReport. The callback <onreset> executes the function EmptyReset.

  • Step 6 (Charts): The callback <onrefresh> executes the function RefreshCharts.

Functions executed by callbacks within property definitions are also defined.


Note:  For a mixed wizard, the definition of the first step executed in the Project tab specifies the ANSYS products and component names from which subsequent steps are executed. For instance, in the following excerpted code, multiple actions are defined. These actions are called by the steps in the XML file.

…
def action1(step):

    template1 = GetTemplate( TemplateName="Static Structural", Solver="ANSYS")
    system1 = template1.CreateSystem()
    geometry1 = system1.GetContainer(ComponentName="Geometry")
    geometry1.SetFile(FilePath=step.Properties["filename"].Value)

    nextStep = step.NextStep
    if nextStep!=None:
        nextStep.SystemName = system1.Name
        nextStep.ComponentName = "Geometry"

    thirdStep = step.Wizard.Steps["Step3"]
    if thirdStep!=None:
        thirdStep.SystemName = system1.Name
        thirdStep.ComponentName = "Model"
…


Release 18.2 - © ANSYS, Inc. All rights reserved.