Connecting to a Third-Party Solver

This section discusses how to add a connection to a third-party solver, or the ability to launch an external process from the Mechanical system instead of launching the ANSYS solver. The example used in this section is defined in the extension ExtSolver1, which was written to demonstrate the ability to connect to a very simple solver. This solver distributes the values assigned at boundaries inside the structure. This example is for demonstration purposes only.

Third-Party Solver Connection Extension

The XML extension definition file ExtSolver1.xml follows. The extension ExtSolver1 adds a third-party solver in a project.

 <extension version="1" name="ExtSolver1">

  <script src="[ext.Folder]\main.py" />

  <interface context="Mechanical">
    
    <images>[ext.Folder]\images</images>

    <callbacks>
      <onload>Load</onload>
      <onsave>Save</onsave>
    </callbacks>

    <toolbar name="ExtSolver1" caption="ExtSolver1">
      <entry name="Values Load" icon="tload">
        <callbacks>
          <onclick>CreateValuesLoad</onclick>
        </callbacks>
      </entry>
    </toolbar>

  </interface>

  <simdata context="Project|Mechanical">

    <solver name="Solver1" version="1" caption="Solver1" icon="result" analysis="Static" physics="Structural">

      <callbacks>
        <onsolve>Solve</onsolve>
        <getsteps>GetSteps</getsteps>
        <getreader>GetReader</getreader>
      </callbacks>

      <property name="MaxIter" caption="Max. Iterations" control="integer" default="10" />

    </solver>

  </simdata>

  <simdata context="Mechanical">

    <load name="Values" version="1" caption="Values" icon="tload" issupport="false" isload="true" color="#0000FF">

      <callbacks>
        <getsolvecommands>WriteInitialValues</getsolvecommands>
        <getnodalvaluesfordisplay>NodeValues</getnodalvaluesfordisplay>
      </callbacks>

      <property name="Geometry" control="scoping" />
      <property name="Expression" caption="Expression" control="text" />

    </load>

  </simdata>

</extension>

As with the loads and results features, the solver definition must be encapsulated within a <simdata> block. In this example, the attribute context is Project|Mechanical. When Project is specified, the solver appears as a system in the Workbench Toolbox.

 


Note:  Custom solver-based systems support general data transfer to their Model, Setup, and Solution tasks. For an explanation of general data transfer, see Defining Task-Level General Data Transfer.


In ExtSolver1.xml, the <solver> block specifies the definition for the third-party solver. This block has some mandatory attributes:

  • name: Internal name of the solver

  • version: Version of the solver

  • caption: Display name of the solver

  • analysis: Analysis type addressed by the solver. For compatibility reasons, this attribute must be set to Static, but this does not prevent you from integrating any type of third-party solver.

  • physics: Physics type addressed by the solver. This attribute must be set to Structural, even though it has no real impact on what the solver computes.

You must define the callback <onsolve>. This callback is invoked when the product launches the solver, thereby taking the object solver as an argument.

You can define a set of properties, which appear in the Details view of the analysis. In this example, a simple property is created to define the maximum number of iterations to be performed by the solver. The default value is 10.

As shown in the previous figure, a new system for the third-party solver ExtSolver1 is added to the Toolbox. Each third-party solver is added into a new category, identified by the caption of the extension. The system is named by the caption of the solver.

The system related to the third-party solver is equivalent to one standard system that can be created with the ANSYS solver. The components that build this new system remain the same. You can add the new system related to the solver to the Project Schematic just as you do for any other system.

The script main.py follows. The solver code is located in a separate script, solver.py, which is placed in the same folder as main.py. The second line of the script main.py is import solver. This technique of importing another script supports reuse and maintainability. The script in solver.py defines the class SolverEngine.

import os
import solver
    
def CreateValuesLoad(analysis):
    analysis.CreateLoadObject("Values")

initValues = {}
sol = None
solbystep = SerializableDictionary[int,dict]()
values = {}
steps = []
res = [0.]
dScal = [0.]
dVec = [0., 0., 0.]

def WriteInitialValues(load,filename):
    global initValues    
    propEx = load.Properties["Expression"]
    exp = propEx.Value
    if exp=="": 
        return None
    vexp = compile(exp,'','eval')
    values = []
    propGeo = load.Properties["Geometry"]
    refIds = propGeo.Value.Ids
    mesh = load.Analysis.MeshData
    for refId in refIds:
        meshRegion = mesh.MeshRegionById(refId)
        nodeIds = meshRegion.NodeIds
        for nodeId in nodeIds:
            node = mesh.NodeById(nodeId)
            x = node.X
            y = node.Y
            z = node.Z
            v = 0.
            try:
                v = eval(vexp)
                v = float(v)
            finally:
                initValues.Add(nodeId,v)

def NodeValues(load,nodeIds):
    propEx = load.Properties["Expression"]
    exp = propEx.Value
    if exp=="": 
        return None
    try:
        vexp = compile(exp,'','eval')
    except: 
        return None
    values = []
    mesh = load.Analysis.MeshData
    for id in nodeIds:
        node = mesh.NodeById(id)
        x = node.X
        y = node.Y
        z = node.Z
        v = 0.
        try:
            v = eval(vexp)
            v = float(v)
        finally:
            values.Add(v)
    return values

def Solve(s):
    global steps
    global initValues
    global sol
    global solbystep
    global values
    
    solbystep = SerializableDictionary[int,dict]()
    solbystepTmp = {}
    
    f = open("solve.out","w")
    f.write("SolverEngine version 1.0\n\n\n")
    try:
    
        maxIter = int(s.Properties["MaxIter"].Value)
        f.write("Max. iteration : %d\n" % (maxIter))
    
        mesh = s.Analysis.MeshData
        
        numEdges = 0
        geo = ExtAPI.DataModel.GeoData
        nodeIds = []
        for asm in geo.Assemblies:
            for part in asm.Parts:
                for body in part.Bodies:
                    for edge in body.Edges:
                        numEdges = numEdges + 1
                        ids = mesh.MeshRegionById(edge.Id).NodeIds
                        nodeIds.extend(ids)
        steps = []
        stepsTmp = []
        f.write("Num. edges : %d\n" % (numEdges))
        sol = solver.SolverEngine(mesh,initValues,nodeIds)
        initValues = sol.Run(maxIter,f,stepsTmp,solbystepTmp)
        nodeIds = mesh.NodeIds
        sol = solver.SolverEngine(mesh,initValues,nodeIds)
        values = sol.Run(maxIter,f,steps,solbystep)
    
        initValues = {}
    
    except StandardError, e:
        f.write("Error:\n");
        f.write(e.message+"\n");
        f.close()
        return False

    f.close()
    
    return True

def GetSteps(solver):
    global steps
    return steps


def Save(folder):
    global solbystep
    fm = System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
    try:
        stream = System.IO.StreamWriter(os.path.join(folder,"sol.res"),False)
    except:
        return
    try:
        fm.Serialize(stream.BaseStream,solbystep)
    finally:
        stream.Close()
    
def Load(folder):
    global solbystep
    if folder==None:
        return
    fm = System.Runtime.Serialization.Formatters.Binary.BinaryFormatter()
    try:
        stream = System.IO.StreamReader(os.path.join(folder,"sol.res"))
    except:
        return
    try:
        solbystep = fm.Deserialize(stream.BaseStream)
    finally:
        stream.Close()

class ExtSolver1Reader(ResultReaderBase):
    def __init__(self,infos):
        self.infos = infos
        self.step = 1

    def get_CurrentStep(self):
        return self.step

    def set_CurrentStep(self,step):
        self.step = step

    def StepValues(self):
        global steps
        return steps

    def ResultNames(self):
        return ["U","VALUES"]

    def GetResultLocation(self,resultName):
        return "node"

    def GetResultType(self,resultName):
        if resultName=="U":
            return "vector"
        return "scalar"

    def ComponentNames(self,resultName):
        if resultName=="U":
            return ["X","Y","Z"]
        else:
            return ["VALUES"]

    def ComponentUnit(self,resultName,componentName):
        if resultName=="U":
            return "Length"
        return "Temperature"

    def GetValues(self,resultName,entityId):
        global values
        global solbystep
        global dVec
        global dScal
        if resultName=="U":
            values = solbystep[self.step]
            dVec[0] = 0.
            dVec[1] = 0.
            dVec[2] = 0.
            try:
                dVec[0] = values[entityId]
            finally:
                return dVec
        else:
            values = solbystep[self.step]
            try:
                dScal[0] = values[entityId]
                return dScal
            except:
                return None

def GetReader(solver):
    return ["ExtSolver1Reader"]

The function Solve is associated with the callback <onsolve>. This function creates a file solve.out, which is read interactively by the product and stored in the solution information.

By default, the product launches the resolution directly into the working directory, so it is not necessary to set the folder in which the file solve.out must be created.

The callback function must return True or False to specify if the solve has succeeded or failed.

Currently, it is not possible to return progress information.

Post Processing

You can create a result reader to expose results.

To do that, you create a class that implements the interface ICustomResultReader. The following methods need to be implemented. For each method, the expected results that must be returned are described.

GetCurrentStep(self)

This method must return the current step number.

SetCurrentStep(self,stepInfo)

This method is called each time the current step number is changed.

GetStepValues(self)

This method must return a lost of double values that represents the time steps or frequencies.

GetResultNames(self)

This method must return a list of strings that represents the result names available for the reader.

GetResultLocation(self,resultName)

This method must return the location type of the result identified by the name resultName. The possible values are node, element, and elemnode.

GetResultType(self,resultName)

This method must return the type of the result identified by the name resultName. The possible values are scalar, vector, and tensor.

GetComponentNames(self,resultName)

This method must return a list of strings that represents the list of available components available for the result identified by the name resultName.

GetComponentUnit(self,resultName,componentName)

This method must return the unit name related to the result's component identified by the result name resultName and the component name componentName.

GetValues(self,resultName,collector)

This method must return a list of double values for each component associated with the result identified by the name resultName.

To specify a dedicated reader, add the callback <getreader> in the solver definition. This callback returns a list of strings, where the first is the name of the reader class and the remainder represents parameters given to the constructor of the class when the reader is instanced by ACT. Any result exposed in the method ResultNames() is available in Mechanical's Results worksheet.

If the name of the result matches a standard result name (like "U"), Workbench applies the same treatment for this result as it does for a standard one. So, if the result is named "U", Workbench uses this result to draw the deformed model.

In the extension Extsolver1, the reader declares one single scalar nodal result “VALUES". No deformation is considered.

Load and Save Data

It is possible to use the callbacks <onload> and <onsave> in the <interface> block to load and save data associated with the third-party solver. As previously discussed, the extension Extsolver1 uses these callbacks to save and load the computed results. This means that the results are still available if the user closes and reopens the system Solver1.

The callbacks <onload> and <onsave> take in argument the name of the working directory.

The following figure shows the analysis settings object associated with the external solver.

 

The next figure shows the boundary condition object associated with the external solver.

 

During the resolution, solution information is interactively displayed. Two types of output are derived from the resolution. The following figure shows the solution information associated with the external solver.

 

The next figure shows the postprocessing associated with the external solver.

 


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