Scripting Overview and Principles
Packages and Modules
The scripting API is delivered as a single Python “Package” named “apex”. This package includes a number of CAE domain specific Python “Modules”. Users are advised to import the apex package directly within their scripts rather than importing each module individually. The apex package is designed in such a way that importing an individual module will automatically cause all other modules to be imported.
Table 1 below identifies the modules included in the apex package and provides a brief description of each
|
Module |
Description |
|
apex |
Functions and Classes for Model, Assembly, Part entities, and their associated Collections. Also provides functions for Transform and Measure |
|
apex.attribute |
Functions and Classes for model attributes including Materials, Sections, BeamShapes, BeamSpans, PointMass, Ties etc. |
|
apex.catalog |
Functions and Classes |
|
apex.construct |
Functions and Classes for “construction geometry” objects including Sketch objects, Vectors, Point3D, Orientations and similar objects |
|
apex.environment |
Functions and Classes for Load, Constraint, Force, and Gravity objects |
|
apex.geometry |
Functions and Classes for Geometry and Topology entities including Solids, Surfaces, Curves, Points, Faces, Edges and Vertices. Also provides functions for geometry operations including vertex/edge drag, push/pull, defeature, stitch, mid-surface extraction, etc. |
|
apex.instrument |
Functions and Classes for Instrumentation objects including Point Sensors and Cross Section Force Sensors |
|
apex.mesh |
Functions and Classes for mesh entities including Solid, Hex, Surface and Bar meshes. Als provide function for mesh, node and element functions |
|
apex.session |
Functions and Classes for viewport visibility functions such as Show, Hide, Show All, Hide All, DisplayTopologyLines(), etc. |
|
apex.setting |
Functions and Classes to access Application Settings options |
|
apex.utility |
Functions and Classes for utilities including ProximitySearch |
Table 1 - apex module descriptions
Although it is sufficient to add a single “import apex” line to you Python script, this does require you to identify Classes and Functions in your script using the full package/module path.
Consider the following example,
import apex myPoint = apex.geometry.createPointXYZ(x = 0.0, y = 0, z = 0.0)
Fully qualifying createPointXYZ with apex.geometry can become tedious. To enable a more compact representation, you can simply import the geometry module or the even the createPointXYZ class directly.
Consider the following example,
import apex from apex.geometry import createPointXYZ myPoint = createPointXYZ(x=0.0, y=1.0, z=1.0).asPoint()
Using the additional import allows the createPointXYZ class to be referenced directly in your script and there is no need to include the package and module qualification.
A potential pitfall of this approach arises if two Classes or free Functions with the same name exist in different modules. All Apex Classes and Functions are designed to be uniquely named across all modules therefore the approach is quite safe for the Apex API, however if you use third party packages or libraries in your script you must ensure that these packages do not introduce any ambiguity into the name space.
Classes
Classes encapsulate the data and behavior of Application objects. Class names reflect the application object model presented above and Class naming uses the “Upper Camel Case” convention with the first letter always capitalized. Examples include,
- Model
- Part
- Assembly
- MeshDependentTie
Classes are implemented within Modules. The modules provided within the apex package have been presented previously and reflect familiar CAE simulation domains such as “geometry”, “mesh”, “environment”, “instrument” etc. It is usually easy to identify which module a particular class is implemented in simply by considering the simulation domain.
For example “SolidMesh”, “SurfaceMesh”, “Node” and “Element” are all defined within the “mesh” module and “Solid”, “Surface”, “Edge” and “Vertex” are defined within the “geometry” module.
Most Classes in the application scripting API inherit from a base “Entity” class. The “Entity” class provides methods and attributes to determine an object type and to support casting between application object types.
Object construction
Three patterns are provided for the creation of application objects. All application objects that inherit from the base Entity class are constructed using “factory” methods implemented as free functions on apex modules or as methods on application classes. Application classes that do NOT inherit from Entity use standard Python object creation semantics - myObj = myClass()
Module Free functions
Most modules provide a number of “create” methods to support creation of objects from the Classes that the module provides. For example the SolidMesh class is implemented in the apex.mesh module, therefore a free function, createSolidMesh() is provided by the apex.mesh module
my_solid_meshes = apex.mesh.createSolidMesh(target=<GeometryBodyCollection>,…)
The module level create functions usually support bulk creation of objects where applicable. In the above example, “target” is a Collection of geometry Solids enabling creation of multiple SolidMesh objects. To create a single SolidMesh, simply supply a single object in the target Collection
“Factory” methods on container classes
Objects that require user input to determine their position in the hierarchy can usually be created using a “factory” method on their parent. For example, Parts and Assemblies must ALWAYS be created as children of either the Model or an Assembly therefore both the Model and Assembly classes provide “create” methods for these objects. The example below shows how a new Part can be created as a child of an existing Assembly.
myPart = myAssembly.createPart(name = “My New Part”)
Native Python constructor
Apex objects such as the Point3D that do NOT inherit from the Entity class are constructed using standard Python constructor syntax. For example,
myPoint3D = Point3D(x=0.0, y=1.0, z=1.0)
Methods
Apex classes support methods to invoke the functionality or access the data provided by the class. The Apex scripting API does not support positional arguments and arguments must be defined using name-value pairs. The API supports the concept of optional method arguments allowing methods to be called with only the subset of required arguments supplied, for example
model.importGeometry(
geometryFileNames = _geometryFileNames,
importSolids = True, #defaults to True
importSurfaces = True, #defaults to True
importCurves = True, #defaults to True
importPoints = True, #defaults to True
importGeneralBodies = True, #defaults to True
importHiddenGeometry = False, #defaults to False
cleanOnImport = True, #defaults to True
sewOnImport = False #defaults to False
Is the same as
model.importGeometry(geometryFileNames = _geometryFileNames)
Redundant methods
The API supports redundant methods, usually for convenience. A common pattern that can lead to redundant methods arises when a Class defines a particular method that operates directly on a single instance of an object but that same operation can also be applied to multiple objects. The second case here is sometimes called a “bulk API” because it performs the same operation on multiple objects at the same time. This is almost always more efficient to use in your script (no need to define a looping construct) and the underlying implementation is usually more performant performant. Consider the following example,
apex.geometry.Solid.assignMaterial(material = myMaterial)
apex.attributes.assignMaterial(target = mySolidCollection, material = myMaterial)The first example shows the assignMaterial() method invoked on an instance of a geometry Solid class and assigns a material to the Solid object - only the material need be supplied as an argument since the target is implied to be the object upon which the method is called. The second is an example of a bulk API. Here the assignMaterial() method is implemented as a free function on the apex.attributes module and takes both a collection of geometry Solids and a Material as input, assigning the single Material to all of the Solids in the collection
Return types
All Apex methods return just a single value or object and do NOT returning tuples.
The return type can be any Python intrinsic or Apex type.
When a method needs to return multiple Apex objects of the same type (or objects with a common base class) it will return an Apex Collection of the appropriate type.
When a method needs to return multiple objects of the same type and these objects are Python intrinsic types, it will return a Python List.
When a method needs to return multiple values of heterogeneous types it will return a “ResultObject”. A ResultObject is a class from which the calling routine can subsequently recover the return data from properties of the ResultObject class. Each property of the ResultObject class can be of a different type. All ResultObjects are documented in the Apex scripting API and use a consistent naming convention – all ResultObject class names start with the string “ZResult”, followed by the method name with the first letter of the method name capitalized. For example the return type of the createSurfaceMesh() method is ZResultCreatSurfaceMesh.
NOTE : In the current Apex release some methods are not in compliance with the above definition. These methods will be brought into compliance in future Apex releases.
Exceptions
The Apex API uses exceptions to indicate errors. When a method encounters an error, the method will throw an exception and it is the responsibility of the calling function to catch and handle that exception. Apex methods do not return error codes and use exceptions exclusively for error handling
Properties
currentMeshSize = mySurfaceMesh.getMeshSize()
currentMeshSize = mySurfaceMesh.meshSize
mySurfaceMesh.update(meshSize = 8.0)
mySurfaceMesh.update(meshSize = 8.0, mappedMeshDominanceLevel = 5, elementMinEdgeLengthRatio = 0.2)
Collections
The Apex scripting API supports typed iterable Collections. Collections are high performance container data structures. In the current release, collections support a very modest subset of Python List functionality. Future releases of Apex will expand collection functionality to more closely match Python List functionality. Support for toList() and fromList() methods will also be added to enable convenient migration of data between Apex Collections and Python Lists.
Some examples of typed Apex collections are,
apex.mesh.NodeCollection, apex.geometry.SurfaceCollection, apex.PartCollectionApex Collections are scoped to the same module as the Object type that they collect, for example
apex.geometry.Solid
apex.geometry.SolidCollectionApex Collections support the inheritance defined in the Conceptual Data Model. This enables methods that return heterogeneous types that share a common base class to return a Collection of the base class types, for example,
mySurfaceAndFaceCollection = apex.geometry.GeometryCollection
apex.geometry.Surface and apex.geometry.Face are both specializations of apex.geometry.Geometry.
Collections in the current Apex release support,
- iteration
- appending new items
- clearing the collection
- slicing (standard Python slicing notation)
- copying
- accessing items ([] operator)
- combining ( ‘+’ operator)
For example,
entities = myPart.getEntities() # get EntityCollection
for entity in entities: # iterate EntityCollection
print entity.name #
n = entities.len() # length of collection
evenEntities = entities[0:n:2] # slice collection into new collection
entities[2] = myEntity # replace a collection item with another
print entities[2].name # access a particular collection item
newEntities = myParts + myBodies # combine collectionsObject retrieval
Many APIs operate on individual objects or collections of Apex objects, for example Nodes, Elements, Parts, Assemblies etc. Typed “get” methods are provided on most container objects (see the Conceptual Data model) to retrieve contained objects
Two main types of get methods
- Single object get methods return a single object
- Multi-object get methods return homogeneous collections of objects
The homogeneous collection may be a collection of objects with a common base class
Single object get()methods
If the object type is a First Class Apex object (See the Conceptual Data model)
- For example - Model, Assembly Part, Body Load, Constraint etc.
- First Class object get methods use a single string name argument as the key to find the object
- The name must be fully qualified, relative to the object from which the get method is being called
- The name is easy to relate to the Model because First Class objects are displayed in the Model Browser and the same names are used there
Example :
myPart = mYModel.getPart(name = "Assembly 1/Part 1")If the object type is a Sub-entity (aka Second Class object in the Conceptual Data model)
- For example - Node, Element, Cell, Face, Edge, Vertex etc.
- The get method uses a single Index or ID as the key
- Different methods are provided for the ID and index based methods, most APIs are duplicated.
getObject(index = IndexValue) naming style is used for the Index based methods
getObjectByID(id = IDValue) naming style is used for the ID based methods
- Index methods are preferred since they are faster and more efficient.
Example :
myNodes = myMesh.getNode(index = 21)
myOtherNodes = myMesh.getNodeByID(id = 465)
Multi-object get methods
Multiple object get methods take a single identifier argument of type Collection.
Each Collection contains either one or two keys from the following list of supported keys
- string - "path"
- [string] - "names"
- string - "ids"
- string - "indices"
path key
The path key is associated with a string type value that uniquely identifies one or more Apex first class objects. (See the Apex Conceptual Data Model where a series of hierarchical first class named object structures is visible)
- Uniquely identifies first class objects within the object hierarchies using a "\" separated name path.
- Supports wildcards as the last element in the path
- If used without any other key, will return the named first class object(s) that it identifies
Example :
Example : "path" : "MyProject/MyModel/Assembly 1/Part 2/Solid 1" names key
Has an associated [string] (List of strings) value that contains a list of object names.
The objects defined by "names" must exist within the scope defined by the associated path data
Example :
getSolids([
{"path" : " MyProject/MyModel/Assembly 1/Part 2",
"names" : ["Solid 3", "Solid 5" ] }
])This example will return an apex.geometry.SolidCollection containing two Solids.
Identifying multiple sub-entities
The ids and indices key are used to identify and return sub-entities from Geometry and mesh bodies.
Example :
myNodes = apex.getNodes([
{"path" : "MyProject/MyModel/Assembly 1/Part 2/Mesh 1"
"indices" : "1, 5, 1001, 60"}
])
Returns a NodeCollection of four nodes.
The pattern for IDs is exactly the same (use the ids key).
indices are much faster, and are preferred if you don't care about the IDs.
Both the ids and indices values are strings and can be run length encoded for compactness.
"ids" : "1-5000, 5002-5005, 5009, 50013, 60000-1000000"Integrating third party Python packages with Apex scripts
Apex currently supports execution of Python scripts that invoke Apex scripting methods using a Python interpreter that is delivered and integrated with Apex. The Python interpreter delivered with Apex Hawk is Python 3.5.1 (64 bit) and it is installed in the same location on your computer as the Apex application.
In order to execute Apex scripting API methods, Python scripts must be executed by the Python interpreter that is integrated with Apex, using the “Macro Play” capability. Macro play causes the Python interpreter to be invoked in the same process space as the Apex application executable. This architecture introduces some constraints on the usage of third party Python packages with Apex scripts,
- You will not see “python.exe” in the Windows task manager when Apex is executing a Python script – this is mostly a cosmetic issue
- Depending on your company’s IT policies you may or may not have write access to the Apex installation folder where the Apex Python interpreter is installed. This may make it difficult, or impossible, to install third party packages into the standard “Lib/site-packages” folder of the Apex Python installation
- Because the Python interpreter and the Apex executable are both executing in the same process space, Windows requires that any compiled code that may be used to support third party Python packages must use the same Microsoft VC++ runtime as Apex. Note that Apex delivers and installs only a basic Python interpreter and does not deliver or install any third party Python packages. Strictly, the requirement is that all code running in a single Windows process space must use the same VC++ runtime. Since packages such as numpy, pandas, h5py, vtk and most other scientific Python packages rely on compiled code, it is a requirement that to be compatible with the Apex script execution environment, the versions of these packages that are installed must have been,
- compiled and linked with the VC++ 14.0 runtime (Visual Studio 2015 supports this version)
- must be compatible with Python 3.5.1.
- In order to provide a controlled environment for the Apex executable, Apex modifies its runtime environment prior to starting. Specifically, Apex modifies the Windows PATH and PYTHONPATH environment variables. Note that Apex only modifies these environment variables for the process in which it is running – no other processes are impacted. Since third party Python packages typically rely on both of these environment variables, and the Apex Python interpreter inherits the modified environment, settings in these environment variable that may have been made to ensure correct execution of the third party packages outside of Apex will NOT be available when these packages are invoked by the Apex integrated Python interpreter.
The following process is recommended to reliably integrate third party Python packages with Apex Hawk,
- Ensure that the third party Python packages that you intend to use with Apex are compatible with both Python 3.5.1 64 bit AND the Windows VC++ 14.0 Runtime. It is possible, but not straightforward, to determine VC++ runtime version for .dlls using the free to download ”depends.exe” package. A simpler approach though, is to download and install Anaconda 3.4.2.0. Anaconda provides extensive scientific Python packages and ensures that all packages within a given Anaconda version are compatible. Anaconda 3.4.2.0 includes Python 3.5.1 and all of the compiled code in the included packages has been compiled and linked using the Microsoft VC++ 14.0 runtime. After downloading an installing this version of Anaconda you will have a working version of Pythin 3.5.1 64 bit and access to most of the 3rd party Python packages you are likely to need. It is required that you know the location on your computer where Anaconda was installed.
- When authoring a script that will be executed by the Apex Macro/Play capability, add the following lines prior to importing any third party packages or modules
import apex import os import sys os.environ['PATH'] = 'xyz_dllpath' + ';' + os.environ['PATH'] sys.path.insert(0, 'xyz_pypath') import xyz
where,
- ‘xyz_dllpath’ is the path to the .dlls in your Anacond installation – usually “<ANACONDA_3_4_2_0\Library\bin
- ‘xyz_pypath’ is the path to the Python Packages/Modules in your Anaconda installation – usually “<ANACONDA_3_4_2_0\Lib\site-packages
Limitations
Although the above procedure is known to work well, some limitations still exist. If the Apex executable has been linked with a compiled code library and that same library library (same .dll name) is ALSO required by a Python package, there is currently no way for that Python package to execute within the Apex script execution environment. We are currently aware of just one Python package that meets these requirements – h5py. The h5py Python package provides Python bindings to the hdf5 libraries.
This limitation will be removed in a future release of Apex, however there is no know workaround for the Apex Hawk release.
- Log in to post comments
