Maxwell Scripting Guide
Maxwell Scripting Guide
Release 2024 R1
ANSYS, Inc. January 2024
Southpointe
2600 Ansys Drive ANSYS, Inc. and
Canonsburg, PA 15317 ANSYS Europe,
[email protected] Ltd. are UL
https://www.ansys.com registered ISO
9001:2015 com-
(T) 724-746-3304 panies.
(F) 724-514-9494
Maxwell Scripting Guide
2
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Table of Contents
Table of Contents Contents-1
1 - Introduction to Scripting 1-1
Scripting Help Conventions 1-1
Variable Types 1-2
Introduction to VBScript 1-2
Simple and Composite Names 1-3
VBScript Variables 1-3
Declaring Variables 1-3
Declaring Variables in Python 1-4
Variable Naming Conventions 1-4
Scope and Lifetime of Variables 1-4
Array Variables 1-4
VBScript Operators 1-5
Operator Precedence 1-6
Arithmetic Operators 1-6
Comparison Operators 1-7
Logical Operators 1-7
Controlling Program Execution 1-8
Using If...Then...Else 1-8
Using Select Case 1-8
Looping Through Code 1-9
Using a For...Next Loop 1-9
Using a Do Loop 1-9
Repeating Statements While a Condition is True 1-9
Repeating a Statement Until a Condition Becomes True 1-9
VBScript Procedures 1-10
Function Procedures 1-10
Sub Procedures 1-10
Contents-1
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-2
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-3
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Structures 1-39
Return Values for UDM and UDP Functions 1-40
Constants 1-40
Methods 1-40
Output Parameters 1-40
Comparison with C function: 1-41
'List Size' Parameters 1-41
Comparison with C function: 1-42
Added Parameters 1-43
Developing a UDM/UDP 1-44
Creation 1-44
Location 1-44
Organize 1-44
Edit/Reload 1-45
UDPExtension 1-45
Import 1-45
Main class: UDPExtension 1-45
IUDPExtension methods 1-45
Mandatory methods. 1-45
GetLengthParameterUnits() 1-45
GetPrimitiveTypeInfo() 1-45
GetPrimitiveParametersDefinition2() 1-45
AreParameterValuesValid2(errorMsg, udpParams) 1-46
CreatePrimitive2(funcLib, udpParams) 1-46
Optional methods 1-46
GetPrimitiveParameters() 1-46
GetRegisteredFaceNames() 1-46
GetRegisteredEdgeNames() 1-46
GetRegisteredVertexNames() 1-46
MapParametersDefinitionVersions2(oldVersion, oldUDPParams) 1-47
Contents-4
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
GetOldPrimitiveParametersDefinition2(version ) 1-47
Example UDP 1-47
UDMExtension 1-47
Import 1-47
Main class: UDMExtension 1-48
IUDMExtension methods 1-48
Mandatory methods. 1-48
GetInfo() 1-48
IsAttachedToExternalEditor() 1-48
CreateInstance(funcLib) 1-48
GetUnits(instanceId) 1-48
ReleaseInstance(instanceId) 1-49
GetAttribNameForEntityId() 1-49
GetAttribNameForPartId() 1-49
Optional methods 1-49
GetInstanceSourceInfo(instanceId) 1-50
ShouldAttachDefinitionFilesToProject() 1-50
Example UDM 1-50
UDMFunctionLibrary 1-51
Functions list: 1-52
UDM/UDP Functions 1-53
Return Values for Each UDM and UDP Function 1-53
UDP/UDM Structures and Constants 1-56
UDP/UDM Structures 1-56
List of structures 1-57
UDP/UDM Constants 1-63
Enum constants: 1-63
UDP Python Example 1-65
Introduction to CPython 1-70
Creating an External Script 1-70
Contents-5
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-6
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-7
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
GetDefinitionManager 2-41
GetDependentFiles 2-42
GetDesign 2-42
GetEDBHandle 2-43
GetLegacyName 2-43
GetName [Project] 2-44
GetPath 2-45
GetTopDesignList 2-46
InsertDesign 2-46
InsertDesignWithWorkflow 2-47
InsertToolObject 2-49
Paste (Project Object) 2-49
Redo [Project Level] 2-50
Rename 2-50
RestoreProjectArchive 2-51
Save 2-52
SaveAs 2-53
SaveAsStandAloneProject 2-55
SaveProjectArchive 2-56
SetActiveDefinitionEditor 2-57
SetActiveDesign 2-58
SimulateAll 2-58
Undo [Project] 2-59
UpdateDefinitions 2-60
3 - Application Object Script Commands 3-1
GetAppDesktop 3-2
GetApp 3-2
4 - Desktop Object Script Commands 4-1
AddMessage 4-5
ClearMessages 4-7
Contents-8
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
CloseAllWindows 4-11
CloseProject 4-11
CloseProjectNoForce 4-12
Count 4-13
DeleteProject 4-14
EnableAutoSave 4-15
ExportOptionsFiles 4-16
GetActiveProject 4-16
GetAutoSaveEnabled 4-17
GetBuildDateTimeString 4-18
GetCustomMenuSet 4-19
GetDefaultUnit 4-19
GetDesigns 4-22
GetDesktopConfiguration 4-23
GetDistributedAnalysisMachines 4-23
GetDistributedAnalysisMachinesForDesignType 4-24
GetExeDir 4-25
GetGDIObjectCount 4-26
GetLibraryDirectory 4-26
GetLocalizationHelper 4-28
GetMessages 4-28
GetName [Desktop] 4-30
GetPersonalLibDirectory 4-31
GetProcessID 4-32
GetProjects 4-32
GetProjectDirectory 4-33
GetProjectList 4-34
GetSchematicEnvironment 4-35
GetScriptingToolsHelper 4-35
GetSysLibDirectory 4-36
Contents-9
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
GetTempDirectory 4-37
GetUserLibDirectory 4-38
GetVersion 4-38
ImportANF 4-39
ImportAutoCAD 4-40
ImportGDSII 4-41
ImportODB 4-42
LaunchJobMonitor 4-43
NewProject 4-44
OpenAndConvertProject 4-45
OpenMultipleProjects 4-46
OpenProject 4-47
OpenProjectWithConversion 4-47
Paste (Project Object) 4-48
Paste (Project Object) 4-48
PauseRecording 4-49
PauseScript 4-50
Print 4-50
QuitApplication 4-51
RefreshJobMonitor 4-52
ResetLogging 4-53
RestoreProjectArchive 4-54
RestoreWindow 4-55
ResumeRecording 4-55
RunACTWizardScript 4-56
RunProgram 4-56
RunScript 4-57
RunScriptWithArguments 4-59
SelectScheduler 4-60
SetActiveProject 4-62
Contents-10
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
SetActiveProjectByPath 4-63
SetCustomMenuSet 4-63
SetDesktopConfiguration 4-65
SetLibraryDirectory 4-66
SetProjectDirectory 4-66
SetSchematicEnvironment 4-67
SetTempDirectory 4-68
ShowDockingWindow 4-69
Sleep 4-69
SubmitJob 4-70
TileWindows 4-71
Desktop Commands For Registry Values 4-72
DoesRegistryValueExist 4-73
GetRegistryInt 4-74
GetRegistryString 4-75
SetRegistryFromFile 4-76
SetRegistryInt 4-76
SetRegistryString 4-77
5 - Running Instances Manager Script Commands 5-1
GetAllRunningInstances 5-1
GetRunningInstanceByProcessID 5-2
GetRunningInstancesMgr 5-2
6 - Property Script Commands 6-1
Object Script Property Function Summary 6-3
Object Path 6-3
Property Object 6-4
Project Object 6-5
Design Object 6-6
3D Modeler Object 6-7
Variable Object 6-7
Contents-11
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-12
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
ExportConvergence 7-24
ExportElementBasedHarmonicForce 7-25
ExportHarmonicTransientForce 7-26
ExportMeshStats 7-28
ExportProfile 7-28
GetConfigurableData 7-29
GetData 7-30
GetDesignValidationInfo 7-30
GetGeometryMode 7-31
GetManagedFilesPath 7-32
GetModule 7-33
GetName 7-34
GetNominalVariation 7-35
GetNoteText 7-35
GetPostProcessingVariables 7-36
GetSelections [Design] 7-37
GetSolutionType 7-37
GetVariationVariableValue 7-37
InitializeSystemCoupling 7-38
Is2D 7-39
Is3D 7-39
Redo [Design] 7-40
RenameDesignInstance 7-41
ResetToTimeZero 7-41
SetActiveEditor 7-42
SetConductivityThreshold 7-43
SetDesignSettings [Maxwell] 7-43
SetFastTransformationForLayoutComponent 7-57
SetObjectAttributesForLayoutComponent 7-58
SetObjectDeformation 7-60
Contents-13
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
SetObjectTemperature 7-63
SetShowAllLayoutComponents 7-65
SetShowLayoutForLayoutComponent 7-65
SetSolutionType (Maxwell) 7-66
Solve 7-67
StopSimLink 7-67
RunToolkit 7-68
Undo [Design] 7-70
ValidateDesign 7-70
ValidateLink 7-71
8 - 3D Modeler Editor Script Commands 8-1
Conventions Used in this Chapter: 8-1
<AttributesArray> 8-1
<SelectionsArray> 8-2
Draw Menu Commands 8-4
Create3DComponent 8-6
CreateBondwire 8-10
CreateBox 8-14
CreateCircle 8-16
CreateCone 8-19
CreateCutplane 8-22
CreateCylinder 8-24
CreateEllipse 8-26
CreateEquationCurve 8-29
CreateEquationSurface 8-33
CreateHelix 8-36
CreatePoint 8-38
CreateUserDefinedPart 8-40
CreatePolyline 8-47
CreateRectangle 8-53
Contents-14
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
CreateRegion 8-55
CreateRegularPolyhedron 8-59
CreateRegularPolygon 8-62
CreateSphere 8-65
CreateSpiral 8-67
CreateTorus 8-69
CreateUserDefinedModel 8-72
CreateUserDefinedPart 8-79
Edit3DComponent 8-87
[Beta] EditNativeComponentDefinition [Maxwell] 8-89
EditPolyline 8-92
Get3DComponentParameters 8-97
Get3DComponentDefinitionNames 8-97
Get3DComponentInstanceNames 8-98
Get3DComponentMaterialNames 8-99
Get3DComponentMaterialProperties 8-99
Insert3DComponent 8-100
InsertNativeComponent [Layout Component to Maxwell with CS] 8-101
InsertPolylineSegment 8-105
SweepAlongPath 8-107
SweepAlongVector 8-109
SweepAroundAxis 8-112
SweepFacesAlongNormal 8-114
SweepFacesAlongNormalWithAttributes 8-116
UpdateComponentDefinition 8-119
Edit Menu Commands 8-120
Copy 8-120
DeletePolylinePoint 8-121
DuplicateAlongLine 8-122
DuplicateAroundAxis 8-125
Contents-15
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
DuplicateMirror 8-128
Mirror 8-131
Move 8-133
OffsetFaces 8-134
Paste (Model Editor) 8-136
Rotate 8-137
Scale 8-138
Modeler Menu Commands 8-140
AssignMaterial 8-142
Chamfer 8-145
Connect 8-147
CoverLines 8-148
CoverSurfaces 8-149
CreateEntityList 8-150
CreateFaceCS 8-152
CreateGroup 8-157
CreateObjectCS 8-158
CreateObjectFromEdges 8-165
CreateObjectFromFaces 8-166
CreateRelativeCS 8-168
DeleteEmptyGroups 8-170
DeleteLastOperation 8-171
DetachFaces 8-172
EditEntityList 8-173
EditFaceCS 8-175
EditObjectCS 8-181
EditRelativeCS 8-188
Export 8-190
ExportModelImageToFile 8-192
Fillet 8-196
Contents-16
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
FlattenGroup 8-198
GenerateHistory 8-199
HealObject 8-200
GetActiveCoordinateSystem 8-204
GetCoordinateSystems 8-205
Import 8-206
ImportDXF [Modeler] 8-209
ImportGDSII [Modeler] 8-213
Intersect 8-217
MoveCStoEnd 8-218
MoveEntityToGroup 8-219
MoveFaces 8-220
ProjectSheet 8-223
PurgeHistory 8-224
Section 8-225
SeparateBody 8-226
SetModelUnits 8-227
SetWCS 8-229
ShowWindow 8-230
Split 8-230
Subtract 8-233
SweepFacesAlongNormal 8-235
ThickenSheet 8-236
UncoverFaces 8-238
Unite 8-240
Ungroup 8-241
WrapSheet 8-242
Other oEditor Commands 8-243
AddDefinitionFromBlock 8-246
AddDefinitionFromLibFile 8-251
Contents-17
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
AddViewOrientation 8-255
BreakUDMConnection 8-262
ChangeProperty 8-263
Delete 8-270
GetBodyNamesByPosition 8-271
GetEdgeByPosition 8-272
GetEdgeIDsFromFace 8-274
GetEdgeIDsFromObject 8-275
GetFaceArea 8-275
GetFaceCenter 8-276
GetFaceByPosition 8-277
GetFaceIDs 8-278
GetGeometryModelerMode 8-279
GetModelBoundingBox 8-280
GetObjectIDByName 8-280
GetObjectName 8-281
GetObjectNameByFaceID 8-281
GetObjectsByMaterial 8-282
GetObjectsInGroup 8-283
GetMatchedObjectName 8-284
GetModelUnits 8-285
GetNumObjects 8-285
GetSelections [Model Editor] 8-286
GetUserPosition 8-287
GetVertexIDsFromEdge 8-287
GetVertexIDsFromFace 8-288
GetVertexIDsFromObject 8-289
GetVertexPosition 8-289
OpenExternalEditor 8-290
PageSetup 8-291
Contents-18
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
RenamePart 8-293
9 - Output Variable Script Commands 9-1
CreateOutputVariable (Maxwell) 9-1
DeleteOutputVariable 9-3
DoesOutputVariableExist 9-3
EditOutputVariable 9-4
GetOutputVariableValue 9-6
10 - Reporter Editor Script Commands 10-1
AddCartesianLimitLine 10-4
AddCartesianXMarker 10-6
AddCartesianYMarker 10-7
AddDeltaMarker 10-8
AddMarker 10-9
AddNote 10-10
AddTraceCharacteristics 10-12
AddTraces 10-13
ChangeProperty[ReportSetup] 10-16
ClearAllMarkers 10-20
ClearAllTraceCharacteristics 10-20
CopyTracesData 10-21
CopyReportsData 10-22
CopyReportDefinitions 10-23
CopyTraceDefinitions 10-23
CreateReportFromFile 10-24
CreateReport (Maxwell) 10-25
CreateReportFromTemplate 10-35
CreateReportOfAllQuantities 10-36
DeleteMarker 10-37
DeleteAllReports 10-38
DeleteReports 10-39
Contents-19
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
DeleteTraces 10-39
ExportImageToFile [Reporter] 10-40
ExportPlotImageToFile 10-41
ExportReport 10-43
ExportToFile 10-44
ExportToFile [Reporter] 10-46
ExportMarkerTable 10-47
FFTOnReport 10-47
GetAllReportNames 10-48
GetAllCategories 10-49
GetAllQuantities 10-50
GetAvailableDisplayTypes 10-51
GetAvailableReportTypes 10-52
GetAvailableSolutions 10-52
GetDataExpressions 10-53
GetDataUnits 10-54
GetDesignVariableNames 10-55
GetDesignVariableUnits 10-56
GetDesignVariableValue 10-57
GetDesignVariationKey 10-58
GetDisplayType (Maxwell) 10-59
GetImagDataValues 10-59
GetPerQuantityPrimarySweepValues 10-60
GetPropertyValue 10-61
GetRealDataValues 10-63
GetReportTraceNames 10-64
GetSolutionContexts 10-65
GetSolutionDataPerVariation 10-66
GetSweepNames 10-68
GetSweepUnits 10-69
Contents-20
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
GetSweepValues 10-70
GroupPlotCurvesByGroupingStrategy 10-71
ImportIntoReport 10-72
IsDataComplex 10-72
IsPerQuantityPrimarySweep 10-73
MovePlotCurvesToGroup 10-74
MovePlotCurvesToNewGroup 10-75
PasteReports 10-76
PasteTraces 10-77
Release Data 10-78
RenameReport 10-79
RenameTrace 10-79
ResetPlotSettings 10-80
SavePlotSettingsAsDefault 10-81
UpdateAllReports 10-82
UpdateReports 10-82
UpdateTraces 10-83
UpdateTracesContextAndSweeps 10-86
UnGroupPlotCurvesInGroup 10-88
11 - Boundary and Excitation Module Script Commands in Maxwell 11-1
General Commands Recognized by the Boundary/Excitations Module 11-2
AddAssignmentToBoundary 11-3
DeleteAllBoundaries 11-4
DeleteAllExcitations 11-5
DeleteBoundaries 11-5
GetBoundaryAssignment 11-6
GetBoundaries 11-7
GetBoundariesOfType 11-7
GetCoreLossEffect 11-8
GetCoreLossEffectOnField 11-9
Contents-21
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
GetDisplacementCurrent 11-9
GetEddyEffect 11-9
GetExcitations 11-10
GetExcitationsOfType 11-11
GetNumBoundaries 11-11
GetNumBoundariesOfType 11-12
GetNumExcitations 11-13
GetNumExcitationsOfType 11-13
ReassignBoundary 11-14
RemoveAssignmentFromBoundary 11-15
RenameBoundary 11-16
ReprioritizeBoundaries 11-17
Script Commands for Creating and Modifying Boundaries in Maxwell 11-18
AssignCylindricalHField 11-19
AssignDependent (2D) 11-20
AssignDependent (3D) 11-21
AssignFluxTangential 11-23
AssignImpedance (Maxwell) 11-23
AssignIndependent (Maxwell) 11-24
AssignInsulating 11-26
AssignRadiation (Maxwell) 11-26
AssignResistiveSheet 11-27
For 3D Magnetostatic, Eddy Current, and Transient designs 11-28
AssignSymmetry (Maxwell) 11-29
AssignTangentialHField 11-29
AssignThinLayer 11-30
AssignTouching 11-34
AssignVectorPotential 11-35
AssignZeroTangentialHField 11-36
EditCylindricalHField 11-36
Contents-22
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-23
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
AssignVoltageDropGroup 11-61
AssignVoltageGroup 11-61
AssignVolumeChargeDensity 11-62
AssignWindingGroup 11-62
EditCharge 11-63
EditCoilTerminal 11-64
EditCurrent 11-64
EditCurrentDensity 11-65
EditCurrentDensityTerminal 11-65
EditExternalCircuit 11-66
EditFloating 11-66
EditSink 11-66
EditVoltage 11-67
EditVoltageAPhi 11-68
EditVoltageDrop 11-69
EditVolumeChargeDensity 11-70
EditWindingGroup 11-70
SetCoreLoss 11-70
SetEddyEffect 11-71
SetMagnetizationCompute 11-72
SetMinimumTimeStep 11-73
ShowWindow 11-74
12 - Mesh Operations Module Script Commands 12-1
General Commands Recognized by the Mesh Operations Module 12-2
DeleteOp 12-2
GetOperationNames 12-3
RenameOp 12-3
Script Commands for Creating and Modifying Mesh Operations 12-4
AssignCylindricalGapOp 12-5
AssignDensityControlOp 12-8
Contents-24
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
AssignEdgeCutLayerOp 12-11
AssignLengthOp 12-12
AssignModelResolutionOp 12-15
AssignSkinDepthLayerSetting 12-17
AssignSkinDepthOp 12-18
AssignTrueSurfOp 12-19
EditCylindricalGapOp 12-22
EditDensityControlOp 12-24
EditEdgeCutLayerOp 12-26
EditLengthOp 12-27
EditModelResolutionOp 12-30
EditSkinDepthOp 12-31
EditTrueSurfOp 12-33
InitialMeshSettings 12-35
13 - Analysis Setup Module Script Commands 13-1
ClearLinkedData (Module) 13-2
CopySetup 13-2
DeleteSetups 13-3
EditSetup [Maxwell] 13-4
VB Example: 3D ElectricTransient EditSetup: 13-8
VB Example: 3D Transient EditSetup: 13-8
VB Example: 3D ACConduction EditSetup: 13-9
VB Example: 2D DCConduction EditSetup: 13-9
VB Example: 2D Transient EditSetup: 13-10
Python Example: Transient EditSetup: 13-11
ExportCircuit 13-12
ExportIcepak 13-17
ExportSolnData 13-17
GetSetupCount 13-19
GetSetups 13-19
Contents-25
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
GetSweepCount 13-20
GetSweeps 13-21
InsertSetup [Maxwell] 13-21
Example: 3D Magnetostatic solve setup: 13-24
Python Example: 3D EddyCurrent solve setup: 13-25
VB Example:3D EddyCurrent solve setup: 13-27
Example: 3D Transient solve setup: 13-29
Example: 3D Electrostatic solve setup 13-30
Example:3D DCConduction solve setup 13-30
Example: 3D ElectroDCConduction solve setup 13-31
Example: 3D ElectricTransient solve setup 13-31
VB Example: 3D ACConduction solve setup 13-31
Python Example:3D ACConduction solve setup 13-32
Example:2D Magnetostatic solve setup 13-33
Example:2D EddyCurrent solve setup 13-34
Example: 2D Transient solve setup 13-34
Example: 2D Electrostatic solve setup: 13-36
Example: 2D ACConduction solve setup: 13-36
Example: 2D DCConduction solve setup: 13-36
PasteSetup 13-37
PasteSweep 13-37
RenameSetup 13-38
ResetAllToTimeZero 13-38
ResetSetupToTimeZero 13-39
RevertAllToInitial 13-39
RevertAllToInitialTemperature 13-40
RevertSetupToInitial 13-41
RevertSetupToInitialTemperature 13-41
14 - Optimetrics Module Script Commands 14-1
General Commands Recognized by the Optimetrics Module 14-6
Contents-26
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
CopySetup 14-7
DeleteSetups [Optimetrics] 14-8
DistributedAnalyzeSetup 14-8
ExportDXConfigFile 14-9
ExportOptimetricsProfile 14-10
ExportOptimetricsResult 14-11
ExportParametricResults 14-12
GetSetupNames [Optimetrics] 14-13
GetSetupNamesByType [Optimetrics] 14-13
ImportSetup 14-14
PasteSetup [Optimetrics] 14-16
RenameSetup [Optimetrics] 14-16
SolveSetup [Optimetrics] 14-17
SolveAllSetup 14-18
Parametric Script Commands 14-18
EditSetup [Parametric] 14-19
ExportParametricSetupTable 14-19
GenerateVariationData [Parametric] 14-20
InsertSetup [Parametric] 14-21
Optimization Script Commands 14-28
EditSetup [Optimization] 14-28
InsertSetup [Optimization] 14-35
Sensitivity Script Commands 14-43
EditSetup [Sensitivity] 14-43
InsertSetup [Sensitivity] 14-50
Statistical Script Commands 14-54
EditSetup [Statistical] 14-54
InsertSetup [Statistical] 14-57
15 - Solutions Module Script Commands 15-1
DeleteSolutionVariation 15-1
Contents-27
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
GetValidISolutionList 15-2
16 - Field Overlays Module Script Commands 16-1
AddMarkerToPlot 16-2
CreateFieldPlot 16-4
Maxwell Field Line Trace Plot Examples 16-26
DeleteFieldPlot 16-36
EditSurfaceMeshSummaryData 16-36
ExportPlotImageWithViewToFile [Reporter] 16-40
ExportSurfaceMeshSummary 16-42
GetFieldPlotNames 16-43
ModifyFieldPlot 16-43
ModifyInceptionParameters 16-46
RenameFieldPlot 16-47
RenamePlotFolder 16-48
SetFieldPlotSettings 16-49
SetPlotFolderSettings 16-52
SetPlotsViewSolutionContext 16-57
UpdateAllFieldsPlots 16-58
UpdateQuantityFieldsPlots 16-59
17 - Fields Calculator Script Commands 17-1
AddNamedExpression 17-2
AddNamedExpr 17-3
CalcOp 17-4
CalcRead(deprecated) 17-4
CalculatorRead 17-5
CalcStack 17-6
CalculatorWrite 17-7
ChangeGeomSettings 17-8
ClcEval 17-9
ClcMaterial 17-10
Contents-28
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
ClearAllNamedExpr 17-11
CopyNamedExprToStack 17-11
DeleteNamedExpr 17-12
EnterComplex 17-13
EnterComplexVector 17-13
EnterLine 17-14
EnterPoint 17-15
EnterQty 17-16
EnterScalar 17-16
EnterScalarFunc 17-17
EnterSurf 17-18
EnterVector 17-18
EnterVectorFunc 17-19
EnterVol 17-20
ExportOnGrid [Fields Calculator] 17-20
ExportToFile [Fields Calculator] 17-23
GetTopEntryValue 17-26
LoadNamedExpressions 17-27
SaveNamedExpressions 17-28
18 - Motion Setup Script Commands A
DeleteMotionSetup A
ReassignMoving B
Commands to Create and Edit the Band B
AssignBand B
EditMotionSetup E
GetMotionSetupNames G
Other Commands Recognized By the ModelSetup Module G
GetSymmetryMultiplier H
SetSymmetryMultiplier H
19 - Parameter Setup Script Commands 19-1
Contents-29
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-30
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
UpdateAllDocuments 20-10
UpdateDocument 20-11
ViewHtmlDocument 20-12
ViewPdfDocument 20-13
Explication of a Sample UDD Script 20-13
Example Python Script: Defining a Document 20-15
21 - User Defined Solutions Commands 21-1
CreateUserDefinedSolution 21-1
DeleteUserDefinedSolutions 21-3
EditUserDefinedSolution 21-4
22 - Network Data Explorer Script Commands 22-1
AddDiffPair 22-4
Cascade (SPISim) 22-5
ClearDiffPairs 22-6
Clone 22-7
Close 22-8
Combine (SPISim) 22-9
Deembed (SPISim) 22-10
DeembedBack (SPISim) 22-11
DeembedFront (SPISim) 22-13
DisableDiffPairs 22-14
EnableDiffPairs 22-15
ExportCitiFile 22-16
ExportMatlab 22-18
ExportSpreadsheet 22-20
ExportTouchstone 22-22
ExportTouchstone2 22-24
Extract (SPISim) 22-27
GetFrequencies 22-28
GetFrequencyCount 22-29
Contents-31
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
GetName 22-30
GetPortCount 22-30
GetPortNumber 22-31
GetPostProcSettings 22-32
GetVariation 22-33
HasSameData 22-34
LoadSolution 22-36
Open 22-37
Rename (SPISim) 22-38
Renormalize (SPISim) 22-39
Reorder 22-41
Reorder (SPISim) 22-42
Reset 22-43
SetAllPortImpedances 22-44
SetPortDeembedDistance 22-45
SetPortImpedance 22-46
SetPostProcSettings 22-47
Smooth 22-48
Stretch (SPISim) 22-49
Terminate 22-51
23 - CompInstance Script Commands 23-1
Callback Scripting Using CompInstance Object 23-1
CompInstance Functions 23-2
GetComponentName 23-2
GetInstanceID [Component Instance] 23-3
GetInstanceName [Component Instance] 23-4
GetParentDesign 23-4
GetPropHost 23-5
GetPropServerName 23-5
24 - Schematic Scripting 24-1
Contents-32
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-33
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-34
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-35
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-36
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-37
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-38
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-39
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-40
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-41
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
Contents-42
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
1 - Introduction to Scripting
Using scripts is a fast, effective way to accomplish tasks you want to repeat. When you execute a
script, the commands in the script are performed in the order in which they appear.
Electronics Desktop can record scripts in VBScript or IronPython, and can run external scripts
written in VBScript, IronPython, CPython, or JavaScript. Additionally, it contains an IronPython
command shell for executing scripts.
When running Ansys Electronics Desktop from the command line, scripts can be written in any
language that provides Microsoft COM methods.
The following sections contain more information about scripting:
l Scripting Help Conventions – explains the layout of the scripting help.
l Introduction to VBscript – provides a broad overview of VBscript
l Introduction to IronPython – provides a broad overview of IronPython.
l Introduction to C-Python – provides guidance on using C-Python for Ansys Electronics
Desktop scripts.
l Ansys Electronics Desktop Scripting – details instructions and tips for running, recording,
and working with scripts in Electronics Desktop.
l PyAEDT (Beta) – a Python library that interacts directly with the AEDT API to make script-
ing simpler for the end user.
Parameters
[List of arguments taken by the script command, if any. Includes argument
types and brief descriptions.]
Return Value [The script's return value, if any.]
Python Syn- [Correct syntax for the command in Python. Arguments are enclosed in angle
tax brackets (<>).]
Python [Sample script]
Example
Variable Types
The following data types are used throughout the help:
l <string> – use within quotation marks.
l <bool> – boolean value; should be set to either True or False.
l <int> – an integer. For example, 1.
l <double> – a double precision value. For example, 1.2.
l <array> – in VBscript, an array; in IronPython, a list contained in square brackets.
l <value> – can be an integer, string, or VBscript variable, depending on context.
Introduction to VBScript
Ansys Electronics Desktop can use Microsoft® Visual Basic® Scripting (VBScript) to record mac-
ros. VBScript is based on the Microsoft Visual Basic programming language.
This chapter provides an overview of key VBScript components.
Simple and Composite Names
VBScript Variables
VBScript Operators
Controlling Program Execution
Looping Through Code
VBScript Procedures
Converting Between Data Types
Including Scripts
Aborting Scripts
Interacting with a Script
Recommended VBScript References
Sample HFSS Script
Sample Circuit Script
Sample Q3D Script
For more details about VBScript, please see the Recommended VBScript References section at
the end of this chapter.
Simple and Composite Names
Components, symbols, footprints, models, and padstacks possess either "simple" names or
"composite" names. Composite names are used to distinguish items from libraries that may pos-
sess the same simple name. A composite name is created by combining an item’s library name
with its simple name. Composite names for definitions are unique, but simple names are not.
l Composite names are used by definition manager script commands to uniquely identify
script definitions.
l Materials and scripts do not have composite names, so project definitions for these items
must possess a unique simple name.
l The format of a composite name is LibraryName:SimpleDefinitionName. For example, the
composite name for the component "CAP_ in" the system library Nexxim Circuit Ele-
ments\Capacitors is "Nexxim Circuit Elements\Capacitors:CAP_in."
l The format of a composite name in a project is OriginLibraryName:SimpleDefinitionName.
For example, the composite name for the project component "CAP_" that was originally
from the system library Nexxim Circuit Elements\Capacitors is "Nexxim Circuit Ele-
ments\Capacitors:CAP_".
l Not all definitions in a project have a library of origin. Newly added definitions do not have
a library of origin, and project definitions whose names are changed do not have a library
of origin (even if they did before the name change). As a result, the composite name for
items without a library of origin is the item’s simple name itself. For example, the com-
posite name for the project component "CAP_" that came from a system library and was
renamed to "MyCAP_" is "MyCAP_".
To construct a composite name, select Tools > Edit Configured Libraries > Components to
open the Edit Libraries dialog box. The subnames used to construct a composite name can be
found in the Name and Origin columns that correspond to a particular component. The Origin
column contains the library portion of the composite name, while the Name column contains the
simple portion of the composite name.
VBScript Variables
A VBScript variable is a placeholder representing information that may change during the time
your script is running. Variables are useful because they let you assign a short and easy to
remember name to each piece of data you plan to use. Use a variable name in a script to view or
modify its value.
Declaring Variables
To declare variables explicitly in a script, use the Dim, Public, or Private statements. For
example:
Dim box_xsize
After declaring a variable, you can assign information to it. For example:
box_xsize = "3mm"
You can declare multiple variables by separating each variable name with a comma. For
example:
Dim Top, Bottom, Left, Right
You can also declare a variable implicitly by simply using its name in your script. Doing so is not
generally a good practice because you could misspell the variable name in one or more places,
causing unexpected results when your script is run. For that reason, the Option Explicit state-
ment is available to require explicit declaration of all variables. The Option Explicit statement
should be the first statement in your script.
Declaring Variables in Python
Python does not require you to declare variables before you assign a value to them.
You can directly assign information to it. For example:
box_xsize = "3mm"
Variable Naming Conventions
You should use names that are short but intuitive and easy to remember. Use the following con-
ventions for naming variables in VBScript:
l Begin with an alphabetic character.
l Cannot contain an embedded period.
l Must not exceed 255 characters.
l Must be unique in the scope in which it is declared.
l Do not use VBScript keywords.
All arrays in VBScript are zero-based, so the array above actually contains 3 elements. You
assign data to each of the array’s elements using an index into the array. Data can be assigned
to the elements of an array as follows:
Primitives(0) = "Box1"
Primitives(1) = "Cone1"
Primitives(2) = "Cylinder1"
Similarly, the data can be retrieved from any element using an index into a particular array ele-
ment. For example:
one_prim = Primitives(1)
You can also use the Array function to assign an array of elements to a variable. For example:
Dim Primitives
Primitives = Array ("Box1", "cone1", "Cylinder1")
Note:
When using the Array function, do not use parentheses on the variable when it is
declared. For example, use Dim myarray, not Dim myarray().
If you do not know the size of the array at declaration or the size changes during the time your
script is running, you can use dynamic arrays. They are declared without size or number of
dimensions inside the parentheses. For example:
Dim FirstArray()
ReDim SecondArray()
To use a dynamic array, you must subsequently use ReDim to determine the number of dimen-
sions and the size of each dimension. You can also use the Preserve keyword to preserve the
contents of the array as the resizing takes place.
ReDim FirstArray(25)
ReDim Preserve FirstArray(30)
VBScript Operators
VBScript provides operators, which are grouped into these categories: arithmetic operators,
comparison operators, and logical operators.
Please see the online VBScript User’s Guide for more details.
Operator Precedence
When several operations occur in an expression, each part is evaluated and resolved in a pre-
determined order, called operator precedence. You can use parentheses to override the order of
precedence and force some parts of an expression to be evaluated before others. Operations
within parentheses are always performed before those outside the parentheses. Within par-
entheses, however, standard operator precedence is maintained.
When an expression contains operators from more than one category, they are evaluated in the
following order:
1. Arithmetic Operators
2. String Concatenation Operator (&)
3. Comparison Operators
4. Logical Operators
Arithmetic operators within a single expression are evaluated in the following order of pre-
cedence:
1. Exponentiation (^)
2. Multiplication and Division (*,/): These two operators are of equal precedence and are eval-
uated in the left-to-right order in which they appear within the expression.
3. Integer Division (\)
4. Modulus Arithmetic (Mod)
5. Addition and Subtraction (+,-): These two operators are of equal precedence and are eval-
uated in the order in which they appear within the expression.
If the same arithmetic operator appears multiple times within a single expression, they are eval-
uated in the left-to-right order in which they appear.
Comparison operators all have equal precedence and are evaluated in the left-to-right order in
which they appear within the expression.
Logical operators all have equal precedence and are evaluated in the left-to-right order in which
they appear within the expression.
Arithmetic Operators
Following is a list of VBScript’s arithmetic operators:
Symbol Description
^ Exponentiation
- Unary negation
* Multiplication
/ Division
\ Integer division
Mod Modulus arithmetic
+ Addition
- Subtraction
Note:
For the order of precedence for these operators, see Operator Precedence.
Comparison Operators
Following is a list of VBScript’s comparison operators:
Symbol Description
= Equality
<> Inequality
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
Is Object equivalence
Note:
All comparison operators have the same precedence. When multiple comparisons
exist in a single expression, evaluate them in the left-to-right order in which they
appear.
Logical Operators
Following is a list of VBScript’s logical operators:
Symbol Description
Not Logical negation
And Logical conjunction
Or Logical disjunction
Xor Logical exclusion
Note:
All logical operators have the same precedence. When multiple logical operators exist
in a single expression, evaluate them in the left-to-right order in which they appear.
Using If...Then...Else
Following is an example that demonstrates the If...Then...Else conditional statement:
If obj = "Box1" Then
<statements to execute>
ElseIf obj = "Cylinder1" Then
<statements to execute>
Else
<statements to execute>
End If
Using Select Case
Following is an example that demonstrates the Select Case conditional statement:
Select Case primitive_name
Case "Box1"
<statements to execute>
Case "Cylinder1"
<statements to execute>
Case Else
<statements to execute>
End Select
Looping Through Code
Looping allows you to run a group of statements repeatedly. There are two types of loops:
l For...Next: Uses a counter to run statements a specified number of times.
l Do...Loop: Loops while or until a condition is True.
When using conditional statements that test for zero voltage/current, it is important to note that a
real voltage or current should not be trusted to be exactly zero, even when it should be. Typ-
ically, the voltage or current is often on the order of 'epsilon' (1e-16) or smaller; hence, it is
nonzero in value.
Using a For...Next Loop
The For...Next type of loop allows you to run a group of statements repeatedly. It uses a counter
to run statements a specified number of times. Following is an example that demonstrates the
For...Next loop:
For variable = start To end
<statements to execute>
Next
You can exit early from a For...Next loop with the Exit For statement.
Using a Do Loop
You can use Do...Loop statements to run a block of statements until (or while) a condition is
true.
Repeating Statements While a Condition is True
Use the While keyword to check a condition in a Do...Loop statement. The syntax is as follows:
Do While condition
<statements to execute>
Loop
Repeating a Statement Until a Condition Becomes True
Following is the syntax:
Do Until condition
<statements to execute>
Loop
You can exit early from a loop by using the Exit For statement.
VBScript Procedures
In VBScript, there are two kinds of procedures, Sub and Function. These procedures are called
by name, they can receive arguments, and each performs a specific task with a group of
VBScript statements. If there is no argument, then the Sub or Function statement must include
an empty set of parentheses.
Function Procedures
A Function returns a value by assigning a value to its name in one or more statements. Following
is the syntax of a Function:
Function FunctionName([arguments])
<Function statements>
End Function
Sub Procedures
A Sub procedure is like a function procedure, except that it does not return a value through its
name. Following is the syntax of a Sub:
Sub ProcedureName([arguments])
<Procedure statements>
End Sub
Converting Between Data Types
To convert data from one subtype to another, use the following VBScript functions:
Including Scripts
You can include one script within another using the following command:
#include "<scriptfilename>"
Where scriptfilename is the full path name to a file that contains script text, or is the name of a
script in the project library or script library (listed in the project window under the Defin-
itions/Scripts directory).
The command works for VBScript, JScript, and for the following:
l Scripts in the project library that are run by right-clicking the script icon in the project win-
dow and choosing Run Script
l Scripts in files that are external are run by choosing Tools> Run Script
l Scripts that are specified as callbacks in the Property dialog box
l Scripts that are run to draw parameterized footprints in layout
An include command can be placed anywhere in a script, but for readability it is recommended
that commands be placed at the beginning of a file. The same script can be included multiple
times without error, and circular inclusions will be ignored.
Aborting Scripts
You can abort a script that is running in the desktop simply by pressing the ESC key. Ter-
minating a script in this manner works for each of the following:
l Scripts in the project library that are run by right-clicking the script icon in the project win-
dow and choosing Run Script.
l Scripts in files that are external can be run by choosing Tools > Run Script.
l Scripts that are specified as callbacks in the Property dialog box.
l Scripts that are run to draw parameterized footprints in layout.
The MsgBox function shows a message and returns a number based on the button the user
presses. For example:
Introduction to IronPython
IronPython is an implementation of the Python programming language targeting the .NET
runtime. What this means in practical terms is that IronPython uses the Python programming lan-
guage syntax and standard python libraries and can additionally use .NET classes and objects
to give one the best of both worlds. This usage of .NET classes is fairly seamless in that a class
defined in a .NET assembly can be used as a base class of a python class.
Scope
Functioning as a tutorial on Python or IronPython is way out of the scope of this document.
There are several excellent resources online that do a very good job in that regard. This doc-
ument only attempts to provide a limited introduction to IronPython as used to script Ansys EM
products.
This document is also not a tutorial on the scripting of Ansys EM products. It complements the
existing scripting guide (available from a product's Help menu) and provides a pythonic inter-
pretation of that information. The reader might have to refer to either the scripting guide or recor-
ded samples of VBScript to follow some of the sections.
Python compatibility
The version of IronPython in use is 2.7 and built on the .NET framework version 4.0: this version
targets Python 2.7 language compatibility. While most python files will execute under
IronPython with no changes, python libraries that make use of extensions written in the C pro-
gramming language (NumPy or SciPy for instance), are not expected to work under IronPython.
In such cases, it might be possible to locate .NET implementation of such libraries or explore the
use of IronClad.
(http://code.google.com/p/ironclad/).
Advantages of IronPython
The advantages that IronPython use provides are significant:
l Python has a large eco-system with plenty of supporting libraries, Visual IDEs and debug-
gers. It is actively developed and enhanced.
l IronPython, in addition, has access to the entire .NET eco system. This allows us, for
instance, to create a modern GUI using the System.Windows.Forms assembly from
IronPython code and call any other .NET assembly for that matter.
l The use of IronPython's technologies enables the ability to interactively script Desktop
(feature in development). This allows better discovery of the scripting APIs as well as dir-
ectly programming to the scripting API in python, a language more tractable and platform
independent compared with VBScript.
l The Python syntax of dictionaries is somewhat easier to read and write when supplying
arguments to the scripting methods.
This document describes IronPython briefly and then goes on to describe the desktop provided
IronPython scripting console and scripting with IronPython. You can open an IronPython Com-
mand Window by clicking Tools > Open Command Window.
The document assumes that you know how desktop scripting works using VBScript or Javas-
cript.
Introduction to IronPython
IronPython Mini Cookbook
Translating Script Commands from VBScript to IronPython
Scripting Using Iron Python
Standalone IronPython and Desktop IronPython
IronPython Examples
Creating User Defined Primitives and User Defined Models in Python Scripts
Introduction to IronPython
IronPython is an implementation of the Python programming language targeting the .NET
runtime. What this means in practical terms is that IronPython uses the Python programming lan-
guage syntax and standard python libraries and can additionally use .NET classes and objects
to give one the best of both worlds. This usage of .NET classes is fairly seamless in that a class
defined in a .NET assembly can be used as a base class of a python class.
Scope
Functioning as a tutorial on Python or IronPython is way out of the scope of this document.
There are several excellent resources online that do a very good job in that regard. This doc-
ument only attempts to provide a limited introduction to IronPython as used to script Ansys EM
products.
This document is also not a tutorial on the scripting of Ansys EM products. It complements the
existing scripting guide (available from a product's Help menu) and provides a pythonic inter-
pretation of that information. The reader might have to refer to either the scripting guide or recor-
ded samples of VBScript to follow some of the sections.
Python compatibility
The version of IronPython in use is 2.7 and built on the .NET framework version 4.0: this version
targets Python 2.7 language compatibility. While most python files will execute under
IronPython with no changes, python libraries that make use of extensions written in the C pro-
gramming language (NumPy or SciPy for instance), are not expected to work under IronPython.
In such cases, it might be possible to locate .NET implementation of such libraries or explore the
use of IronClad.
(http://code.google.com/p/ironclad/).
Advantages of IronPython
The advantages that IronPython use provides are significant:
l Python has a large eco-system with plenty of supporting libraries, Visual IDEs and debug-
gers. It is actively developed and enhanced.
l IronPython, in addition, has access to the entire .NET eco system. This allows us, for
instance, to create a modern GUI using the System.Windows.Forms assembly from
IronPython code and call any other .NET assembly for that matter.
l The use of IronPython's technologies enables the ability to interactively script Desktop
(feature in development). This allows better discovery of the scripting APIs as well as dir-
ectly programming to the scripting API in python, a language more tractable and platform
independent compared with VBScript.
l The Python syntax of dictionaries is somewhat easier to read and write when supplying
arguments to the scripting methods.
This document describes IronPython briefly and then goes on to describe the desktop provided
IronPython scripting console and scripting with IronPython. You can open an IronPython Com-
mand Window by clicking Tools > Open Command Window.
The document assumes that you know how desktop scripting works using VBScript or Javas-
cript.
Introduction to IronPython
IronPython Mini Cookbook
Translating Script Commands from VBScript to IronPython
Scripting Using Iron Python
Standalone IronPython and Desktop IronPython
IronPython Examples
Creating User Defined Primitives and User Defined Models in Python Scripts
IronPython Mini Cookbook
This topic presents simple counterparts between IronPython and VBScript. It does not provide a
full tutorial on IronPython syntax. Because IronPython is a Python implementation, you can con-
sult Python documentation for additional information.
Comments
VBScript IronPython
Comments start with a single quote: Comments start with a hash:
' comment # comment
Assigning/Creating Variables
VBScript IronPython
Declare with a Dim: No Set syntax. Simply create and assign:
Dim doc doc = app.GetActiveProject()
Assignment then needs a Set instruction:
Set doc = app.GetActiveProject()
Create Lists/Arrays
VBScript IronPython
Declare as array of String with 11 indices, Declare an empty array:
from 0 through 10:
myEmptyArray = []
Dim myArray(0 to 10) as String
Declare an array and initialize it with 5 ints:
myArray(0) = "Hello"
myInitedArray = [ 1, 2, 3, 4, 5]
myArray(1) = "bye"
Python lists can have items of any type and
Declare an array with no size: there is no pre-declaration. Declare an array
and init with mixed types:
Dim array2() as String
mixed = ["hello", 1 ,2 ["nested"]]
Re-dimension an array once size is known:
Append to an array:
ReDim array2(0 to 2) as String
mixed.append( 3.5 )
array2(0) = "this"
array2(1) = "also"
Create Dictionaries/Maps
VBScript IronPython
Declare with a Dim: An IronPython dictionary is a collection of
name value pairs. Just like arrays, there is no
Dim dict restriction on the keys or the values. For pur-
Use the CreateObject function with ProgID poses of Ansys EM scripting, however, all
Scripting.Dictionary: keys must be strings
Boolean Values
VBScript IronPython
Boolean literals are in lower case: The first letter is capitalized:
true True
false False
VBScript IronPython
Use CInt, CDbl, CBool, CLng to convert the Use integer() or float() or double() functions to
string representation to the number rep- cast a string CONTAINING the string rep-
resentation. Use IsNumber to check before resentation of whatever you are casting to:
conversion:
strInt = "3"
Dim nStr = "100"
intVal = int(strVal)
Dim n = CInt(nStr)
floatVal = float(strVal)
Use CStr to convert a number to its string rep-
resentation: Invoke the str() function with the int/float values
as needed. You can alternately use the string
Dim v, vStr formatting method listed below:
v = 100 strVal = str(42)
vStr = CStr(v) strVal = str(42.345)
String Formatting/Concatenation
VBScript IronPython
String concatenation uses the & operator: If you have two strings, you can always con-
catenate them using the '+' operator:
Dim allStr, str1
str1 = "hello"
str1 = " how are you"
str2 = "world"
allStr = "Hello " & " There" & str1
str12 = str1 + " " + str2
There seems to be no direct string formatting
function in VBScript. Ssing string con- If you have different types (for instance a string
catenation or using Replace are the two built-in and an int), you must use the string formatting
options: commands. When formatting multiple argu-
ments, they must be entered as a tuple ( item1,
Dim fmt = "{1} climbs stalk {2}" item2, ):
Dim str = Replace(fmt, "{1}", "jack") num = 10
str = Replace(str, "{2"}, 10) str3 = "%s climbs stalk %d" % ("jack", num)
str4 = "%d stalks" % num
VBScript IronPython
Dim myArray(0 to 2) as String vals = [1, 3, 3.456]
myArray(0) = "alpha"
myArray(1) = "bravo" def process(val):
myArray(2) = "charlie" return 2*val
VBScript IronPython
To loop over a range, specify start, end, and for i in range(0, 10):
step:
print i
For i = 0 To 10 Step 1
Print i
Next
Related Topics:
Indentation in IronPython
Methods in IronPython
Introduction to IronPython
IronPython Samples
Indentation in IronPython
Python is a language where white space (spaces and tabs) is syntactically significant. You must
understand the basics of indentation before scripting in python.
Any statement that introduces a block of code should be written so that every line of the block
has the same indent (leading spaces or tabs) and the indent should be at least one more than
the indent of the introducing statement.
Note:
Indenting Functions
Each line that belongs to the body of this function should have an indent that is more than the
indent used by the if statement.
def multInt(a,b):
If a%2 == 0:
return (a * b) + 100
else:
return (a * b) + 1000
Methods in IronPython
Finding Methods
Once you know a function name, you can get more help on it using the built-in help method.
Related Topics
Introduction to IronPython
Translating Script commands from VBScript to IronPython
Scripting Using Iron Python: Putting it all Together
IronPython Samples
Translating Script Commands from VBScript to IronPython
This topic briefly describes scripting methods and arguments via VBScript samples. The dis-
tinctions made here are significant and useful when translating scripts written in VBScript to
IronPython.
Related Topics
Script Method Argument
VBscript Method Call Types
Converting VBScript Function calls to IronPython Syntax
Introduction to IronPython
IronPython Mini Cookbook
Scripting Using Iron Python
IronPython Samples
Script Method Argument
Script method calls in VBscript generally take the form:
objectName .methodName ( arg1, arg2, ...)
The function call syntax is a standard followed by several programming languages. However,
the argument types in VBScript objects used for product scripting are restricted to the following:
l Primitive Types
l Named Arrays
l Named Functions
Primitive Types
Primitive types are the standard bool, int, float, double, and string.
Named Arrays
Named arrays are a special construct used very commonly and can be found in many recorded
script samples.
A named array begins with Array("NAME:someName" followed by a collection of comma sep-
arated values which can be:
l Primitive values
l Arrays of primitive values
l Additional named arrays
l Keys, in the form "keyName:=" followed by a primitive value or function
Named Functions
Named functions are arrays which start with Array( and do not have a leading "NAME:name"
item. They are always introduced by a key and can contain comma separated values of the
following type:
l A primitive value
l A key (of the form "keyName:=") followed by
o A primitive value
o Another function (nested function)
Related Topics
Translating Script commands from VBScript to IronPython
VBScript Method Call Types
VBScript method calls fall into two categories and the distinction between the two results in syn-
tax differences. These syntax differences are significant when converting VBScript to
IronPython.
VBScript Functions
In VBScript terminology, functions return values. The syntax for this is one shared with prac-
tically all programming languages:
Set oDesktop = oAnsoftApp.GetAppDesktop()
Set oProject = oDesktop.NewProject
Note:
If there are arguments, the method name is always followed by an argument list
enclosed in parentheses. If the argument list is empty, as shown above for the NewPro-
ject call, the parentheses can be omitted.
VBScript Sub-Routines
VBScript subroutines are those that do not have any return value. VBScript allows these to be
written without any parentheses even if they have a non-empty argument list.
oModule.CreateReport "XY Plot1", "Standard", "XY Plot", "optimtee
: optimtee", _
Array("Domain:=", "Sweep"), Array("Freq:=", Array("All"), "off-
set:=",_
Array("0uin")), Array("X Component:=", "Freq", "Y Component:=", _
Array("dB20(S(1,1))", "dB20(S(1,2))", "dB20(S(1,3))", _
"dB20(S(2,1))", "dB20(S(2,2))", "dB20(S(2,3))", "dB20(S(3,1))",
"dB20(S(3,2))", "dB20(S(3,3))")), Array()
Related Topics
Translating Script commands from VBScript to IronPython
Converting VBScript Function calls to IronPython Syntax
When used for scripting, IronPython function names are always followed by parentheses.
So:
l If you see a VBScript snippet that looks like a VBScript subroutine, remember to add par-
entheses.
l If you see a VBScript function that has no arguments and no parentheses, remember to
add them around an empty argument list.
The parentheses change is the only one to keep in mind when converting VBScript function calls
syntax to IronPython.
Return Values
VBscript return values are sometimes assigned via the Set declaration. IronPython return values
are simple assignment (See: Iron Python Mini Cookbook).
Primitive Method Arguments
While it is generally not allowed to replace arrays and nested arrays with Python dictionaries, in
the case where the named array consists entirely of key value pairs, you can use a dictionary
and avoid typing the trailing := symbols after the keys. This further aids readability of the script.
l If all key value pairs
l Remove the trailing := after each key
l Replace the , after the key with a :
l If the named array is the top level argument, ensure that the NAME:name is present and is
split into NAME : name as a key value pair
l Enclose the converted array in a { } pair to declare the dictionary.
[ "NAME:name",
"key1:=" , 1,
"key2:=" , 2,
["NAME:name2", "R:=", 255]
]
Sample Script: Named array with nested named array in array syntax
The above named array with a nested named array (after conversion to IronPython as named
array) can be converted to a dictionary as well. The dictionary can take any of the following forms
{ "NAME" : "name",
"key1" : 1,
"key2" : 2,
"name2" : ["NAME:name2", "R:=", 255]
}
Sample Script: Named array with nested named array as mixed dictionary + array
{ "NAME" : "name",
"key1" : 1,
"key2" : 2,
"name2" : {"R" : 255}
}
Sample Script: Named array with nested named array in all dictionary syntax
{ "NAME" : "name",
"key1" : 1,
"key2" : 2,
"name2" : {
"NAME" : "name2",
"R" : 255
}
}
Function Blocks
Function blocks in VBScript argument syntax are represented as arrays without the "NAME:.."
field. However, functions are always introduced by a key in a parent structure. Function blocks
can therefore never exist as a top-level argument. They are only found as the value pairs inside
a named array or inside another function block.
Important:
Function blocks and their items cannot be converted to dictionaries even though they
might be composed entirely of key value pairs.
The reason for this is the need to main the user-entered order. Every item in a function block is
expect to be transmitted to the script method in exactly the same order as typed out and this is
impossible to achieve when a dictionary is used (as the keys get reordered according to the dic-
tionary's internal tree/key sorting scheme).
When you see a function block, simply replace the Array( ) delimiters with python array delim-
iters [ ]
Scripting Using Iron Python
If you have existing VBScript/Javascript scripts use existing scripts them as much as possible by
either embedding the test into the IronPython script or invoking them.
Translating a script in VBScript to IronPython
Read the chapter on translation and study the samples in that chapter as well as those in the
appendix. For python syntax and the differences, the mini-cookbook chapter will also be useful.
Writing an IronPython script from scratch
Read through the scripting guide available from the product's help menu and translate the
VBScript methods described to IronPython using the information provided in the chapter on
translation. Studying the samples in the document will also prove helpful.
For python syntax and the differences, the mini-cookbook chapter will also be useful.
IronPython Script Execution Environment
Scripting using Embedded VBScript or JavaScript
Scripting with IronPython
Related Topics
Introduction to IronPython
IronPython Mini-cookbook
Translating Script commands from VBScript to IronPython
Appendix: IronPython Samples
IronPython Script Execution Environment
Scripts written in IronPython are executed by desktop in four different ways:
l Tools > Open Command Window, to open the IronPython Command Window:
l Tools > Run Script menu item, select "IronPython" from the file type drop-down list.
l Launch the product with a script argument.
o Maxwell -runscript someScript.py to keep Maxwell GUI open after completing script
execution.
o Maxwell -features=beta -ng -runscriptandexit someScript.py to run Maxwell in a
non-graphical mode and exit after script completion. Note that this is a beta feature.
l Register an IronPython script as an external tool using the Tools > External Tools menu
item.
When desktop executes a script, it does so in an execution environment setup with predefined
variables and functions. These predefined variables and functions are how the script
communicates with the desktop, and they come in four flavors addressed in the following sub-
topics:
Script Argument for IronPython
Script Argument for IronPython
When scripts are launched using the Tools > Run Script menu item, the dialog that pops up
allows the user to specify arguments.
Related Topics
IronPython Script Execution Environment
Scripting using Embedded VBScript or JavaScript
Since script recording is still done in VBScript and users are expected to have a significant col-
lection of VBScript or JavaScript assets, it is useful to continue to use existing script files and
snippets even when scripting in IronPython. The various Run<*>Command methods have been
designed for this purpose.
For instance: one can create a parameterized cone in HFSS by executing the following
IronPython script from the Tools > Run Script menu.
# assign the VBScript snippet obtained from a script recording from
HFSS to
# coneScript and replace the BottomRadius recorded value with botRa-
dius
coneScript = """Dim oAnsoftApp
Dim oDesktop
Dim oProject
Dim oDesign
Dim oEditor
Dim oModule
Set oAnsoftApp = CreateObject("Ansoft.ElectronicsDesktop")
Set oDesktop = oAnsoftApp.GetAppDesktop()
oDesktop.RestoreWindow
Set oProject = oDesktop.GetActiveProject()
oProject.InsertDesign "HFSS", "HFSSPyTestDesign", "DrivenModal", ""
Set oDesign = oProject.SetActiveDesign("HFSSPyTestDesign")
Set oEditor = oDesign.SetActiveEditor("3D Modeler")
oEditor.CreateCone Array("NAME:ConeParameters", _
"XCenter:=", "0mm", "YCenter:=", "0mm", "ZCenter:=", "0mm",_
"WhichAxis:=", "Z", "Height:=", "2mm", _
"BottomRadius:=", "3mm", _
"TopRadius:=", "0mm"), Array("NAME:Attributes", "Name:=", _
"Cone1", "Flags:=", "", "Color:=", "(132 132 193)", "Trans-
parency:=", 0, _
"PartCoordinateSystem:=", "Global", "UDMId:=", "", "Mater-
ialValue:=", _
"" & Chr(34) & "vacuum" & Chr(34) & "", "SolveInside:=", _
true)
"""
SetScriptingLanguageToVBScript()
RunScriptCommand(coneScript)
Sample Script 11: Hybrid VBScript + IronPython scripting: parameterized Cone Creation
Even though recorded VBScript is used for scripting, the incremental functionality that is
provided using IronPython is the ability to write a GUI using IronPython/.NET, collect information
from the user and then modify or generate the VBScript commands to actually script the Ansys
EM desktop. This GUI functionality is cross platform and a significant positive. The following
example demonstrates a contrived use of a .NET window form to display the argument supplied
to the IronPython script (via the ScriptArgument variable).
clr.AddReference("System.Windows.Forms")
_button = Button()
_button.Text = "Close"
_button.Dock = DockStyle.Bottom
_button.Click += self._buttonPressed
self.Controls.Add(self._label)
self.Controls.Add(_button)
def _buttonPressed(self,sender,args):
self.Close()
#----------------------------------------------------
# Main script code
#----------------------------------------------------
#display the ScriptArgument variable as the text label
# in the form.
gui = ShowPropertiesForm("Sample Form", ScriptArgument)
Related Topics
IronPython Script Execution Environment
Scripting with IronPython
While this section talks about directly interacting with the script objects, note that you can
execute VBScript or Javascript at any point using any of the available Run*Command functions.
using your existing script assets in this fashion and mixing with IronPython code for new func-
tionality as needed is a viable and option.
Access to the application scripting objects is provided via the predefined oDesktop object (as lis-
ted in Script Objects). Interacting with the script objects is very natural, method calls are made
just like in VBScript except that the argument syntax is somewhat simplified to follow natural
Python syntax. All primitive types (string, integer, double) map to the natural primitive types in
python. The only differences from the VBScript syntax are seen when specifying array type argu-
ments. The differences are described in earlier chapters.
Note:
The typical VBScript calls to obtain the registered COM scripting interface via
CreateObject calls and then obtain the oDesktop object from it using the GetAp-
pDesktop() is not needed (or even supported on all platforms). Since all scripting
occurs in the context of a running workbench, the available Desktop object is always
provided and expected to be used directly.
Scripting using the IronPython scripting API is very much like scripting with VBScript except that
l Any argument is supplied via the built in ScriptArgument variable
l The oDesktop object is always available
l The scripting method names are identical to the ones used with VBScript
l Method calls, while the name is the same have to adhere to the rule of ensuring trailing
parentheses irrespective of whether the function returns anything or has any arguments.
l Any compound/block arguments should be translated to the appropriate IronPython array
or dictionary syntax.
The samples section lists a collection of pure IronPython snippets: these, along with the various
script snippets listed in this document should serve as a guide and reference.
Related Topics
IronPython Script Execution Environment
Standalone IronPython and Desktop IronPython
Standalone IronPython
In general, it is easier to run a script directly from Electronics Desktop. Standalone IronPython
does not implement all the functionality available when a script is run from Electronics Desktop.
It only implements full support for COM functions.
Running Standalone IronPython
Standalone IronPython uses COM to get the handle to the AnsysEDT app. To run standalone
IronPython, you’ll need to call the IronPython interpreter ipy64.exe.
It is located in:
\\<AnsysEDTInstallationPath>\common\IronPython\ipy64.exe
For example, to run myScript.py, type the following in the command line:
"C:\Program Files\AnsysEM\v241\Win64\common\IronPython\ipy64.exe"
"<filePath>\myScript.py"
You can set the interpreter to be the default program when double-clicking the .py script. You
can use any recorded script as the basis for a standalone script and simply add an installation-
internal path to the python module search path (as shown below) and end the script with a new
shutdown call.
Using a Recorded Script
A python script recorded in AnsysEDT already has the required lines to be run as a standalone,
except for the first two lines (path settings) and the final Shutdown() call. See the example
script below.
Creating an External Script
When creating a script outside of Electronics Desktop, the following lines should be included at
the beginning of your script:
l import sys
l sys.path.append("<InstallationPath>")
# Adds the Electronics Desktop installation path to the list of directories Python searches
for modules and files.
l sys.path.append("<InstallationPath>/PythonFiles/DesktopPlugin")
l import ScriptEnv
# This imports ScriptEnv.py from the installation path specified above. ScriptEnv.py per-
forms an operating system check and defines functions used in Electronics Desktop
scripts. See the annotations in the ScriptEnv.py file for more information.
l ScriptEnv.Initialize("Ansoft.ElectronicsDesktop")
or ScriptEnv.InitializeNew(NonGraphical=True)
# Initialize and InitializeNew are functions within ScriptEnv.py. The first option
launches Electronics Desktop. The second allows you to run a script without launching
Electronics Desktop. See the annotations in the ScriptEnv.py file for more information.
l ScriptEnv.Shutdown()
# This stops ScriptEnv.py. If you are running multiple scripts, include this only at the end of
the last script.
Example Script
import sys
sys.path.append(r"C:\Program Files\AnsysEM\v241\Win64")
sys.path.append(r"C:\Program Files\An-
sysEM\v241\Win64\PythonFiles\DesktopPlugin")
import ScriptEnv
ScriptEnv.Initialize("Ansoft.ElectronicsDesktop")
oDesktop.RestoreWindow()
oProject = oDesktop.NewProject()
oProject.InsertDesign("HFSS", "HFSSDesign1", "DrivenModal", "")
oDesign = oProject.SetActiveDesign("HFSSDesign1")
oEditor = oDesign.SetActiveEditor("3D Modeler")
oEditor.CreateRectangle(
[
"NAME:RectangleParameters",
"IsCovered:= ", True,
"XStart:= ", "-0.2mm",
"YStart:= ", "-3mm",
"ZStart:= ", "0mm",
"Width:= ", "0.8mm",
"Height:= ", "1.2mm",
"WhichAxis:= ", "Z"
],
[
"NAME:Attributes",
"Name:= ", "Rectangle1",
Change property
The following snippets show how a change property command (in this case, to change the color
of a cone) looks in VBScript and its two possible IronPython variants.
oEditor.ChangeProperty Array("NAME:AllTabs", Array("NAME:Geo-
metry3DAttributeTab",_
Array("NAME:PropServers", "Cone1"), _
Array("NAME:ChangedProps", _
Array("NAME:Color", "R:=", 255, "G:=", 255, "B:=", 0))))
Sample Script 13: ChangeProperty command to change color of a cone in VBScript
oEditor.ChangeProperty(
["NAME:AllTabs",
["NAME:Geometry3DAttributeTab",
["NAME:PropServers", "Cone1"],
["NAME:ChangedProps",
["NAME:Color", "R:=", 0, "G:=", 0, "B:=", 64]
]
]
])
Sample Script 14: ChangeProperty command to change color of cone using Python
arrays
Any time there are named arrays composed purely of key-value pairs, they can always be rep-
resented using a Python dictionary, irrespective of the nesting of said named array.
oEditor.ChangeProperty(
["NAME:AllTabs",
["NAME:Geometry3DAttributeTab",
["NAME:PropServers", "Cone1"],
["NAME:ChangedProps",
{
"NAME":"Color",
"R" : 0,
"G" : 64,
"B" : 0
}]]
])
Sample Script 15: ChangeProperty command to change the color of a cone using
Python arrays and dictionaries
Most scripting tasks using IronPython are expected to be formatted as the following example.
One starts with the predefined oDesktop object and drills down to the design, editors, modules
etc and issues any required commands on the object while formatting the script command argu-
ments in natural python syntax.
oProject = oDesktop.GetActiveProject()
oDesign = oProject.InsertDesign("HFSS","Random","DrivenModal","")
oEditor = oDesign.SetActiveEditor("3D Modeler")
oEditor.CreateCone(
{
"NAME" : "ConeParameters",
"XCenter" : "0mm",
"YCenter" : "0mm",
"ZCenter" : "0mm",
"WhichAxis" : "Z",
"Height" : "2mm",
"BottomRadius" : "1.56204993518133mm",
"TopRadius" : "0mm"
},
{
"NAME" : "Attributes",
"Name" : "Cone1",
"Flags" : "",
"Color" : "(132 132 193)",
"Transparency" : 0,
"PartCoordinateSystem": "Global",
"UDMId" : "",
"MaterialValue" : "\"vacuum\"",
"SolveInside" : True
}
)
Sample Script 16: IronPython script to create a cone
Create geometry and then create a grid from it using copy/paste/move
The following script demonstrates slightly more advanced use of scripting and the use of return
values from script methods. It creates a 5x5 grid of cones and also demonstrates the adding of
information messages to the application's message window.
oProject = oDesktop.GetActiveProject()
oDesign = oProject.InsertDesign("HFSS","Hersheys Kis-
ses","DrivenModal","")
oEditor = oDesign.SetActiveEditor("3D Modeler")
coneBotRad = "1.5mm"
oEditor.CreateCone(
{
"NAME" : "ConeParameters",
"XCenter" : "0mm",
"YCenter" : "0mm",
"ZCenter" : "0mm",
"WhichAxis" : "Z",
"Height" : "2mm",
"BottomRadius": coneBotRad,
"TopRadius" : "0mm"
},
{
"NAME" : "Attributes",
"Name" : firstConeName,
"Flags" : "",
"Color" : "(132 132 193)",
"Transparency" : 0,
"PartCoordinateSystem": "Global",
"UDMId" : "",
"MaterialValue" : "\"vacuum\"",
"SolveInside" : True
}
)
# position
if x == 0 and y == 0:
continue
# copy first
oEditor.Copy(
{
"NAME" : "Selections",
"Selections" : firstConeName
}
)
Related Topics
Introduction to IronPython
IronPython Mini-cookbook
Translating Script commands from VBScript to IronPython
Scripting Using Iron Python: Putting it all Together
Creating User Defined Primitives and User Defined Models in Python
Scripts
You can create User Defined Primitives and User Defined Models in Python scripts (based on
the IronPython implementation).
Advantages Compared to C++
l No need to create and build project; all you need to do is create a Python script
l Python script is platform independent
l Scripts can inherit functionality from existing scripts
l Garbage collector - no need to free memory
l Easy debugging
Changes compared to C
Though methods, constants and structures are kept as close to the C implementation as pos-
sible, some changes had to be made to make code Python-compatible.
Structures
l Structure instances are created using the supplied constructors and members are
accessed using the provided access methods.
For a complete list of structures and examples please see UDP/UDM Structures.
Return Values for UDM and UDP Functions
For information on return values for each UDM and UDP function, see the Return Values sec-
tion.
Constants
Enumeration/Enum constants have almost the same names as in C but the enum must be qual-
ified by the type. Additionally, redundant "UDP", "UDM" or type prefixes have been removed.
This allows for better human-readability.
# Example of specifying the LengthUnit enum by qualifying it
# with the type of the enum: UnitType
unitType = UnitType.LengthUnit
For a complete list of enum constants please see UDP/UDM Constants.
Methods
l If there is more than one out variable, the function will return a Python tuple with all output
parameters in the specified order. If function has a return value, it must always be the first
in the tuple.
# one output parameter; return value is ignored
udmDefinition = udmFunctionLibrary.GetDefinition()
C Python
bool getDefinition(UDMDefinition* udmDefinition = udmFunctionLibrary.GetDefinition()
udmDefinition,
void* callbackData );
(Note: callbackData is omitted in py interface)
l If function has input 'List' parameter and input 'list size' parameter, 'list size' parameter will
be omitted.
l If function has output 'List' parameter and output 'list size' parameter, 'list size' parameter
will be omitted.
l If function has output 'List' parameter and input 'list size' parameter, 'list size' parameter
won't be omitted as it's needed for memory allocation in the corresponding C++ function
from the UDP/UDM function library.
Example:
# input list, input list size
lret = udpFunctionLibrary.Unite(objectIds)
C Python
bool getAllFaces( long partId, faceIds = udmFunc-
tionLibrary.GetAllFaces(partId)
long* numFaces,
long** faceIds,
void* callbackData);
(ignore numFaces as redundant: fol-
ded into faceIds,
where numFaces and faceIds are output parameters return value is omitted: folded into the
and numFaces is the size of faceId. faceIds is None check
callbackData is omitted)
long unite( long numObjects, lret = udpFunctionLibrary.Unite
(objectIds)
long* objectIds,
void* callbackData);
C Python
and numObjects is the size of objectIds. callbackData is omitted)
long detachFaces( long nSize, (lret, partIdList) = udpFunc-
tionLibrary.DetachFaces(nSize,
long* faceIds, faceIds)
long* partIds,
void* callbackData);
Added Parameters
C Python
long duplicateAlongLine( (lret, cloneIds) = udmFunctionLibrary.DuplicateAlongLine(partId,
long partId, transVec, nClones, cloneIdsSize)
UDPVector transVector,
int nClones,
long* nClones, (callbackData is omitted
void* callbackData); cloneIdsSize is a new parameter)
long duplicateAroundAxis( (lret, cloneIds) = udmFunctionLibrary.DuplicateAroundAxis
(partId, axis, angle, nClones, cloneIdsSize)
long partId,
UDPCoordinateSystemAxis
axis,
C Python
double angle, (callbackData is omitted
int nClones, cloneIdsSize is a new parameter)
long* nClones,
void* callbackData);
Developing a UDM/UDP
Creation
To create a User Defined Primitive in Python you write a Python script that implements UDPEx-
tension class. To create a User Defined Model in Python you write a Python script that imple-
ments UDMExtension class (see links for full description).
Location
The scripts are located the same way the C based UDM/UDP are. They are expected to be
under the UserDefinedParts or UserDefinedModels sub-directories of one of the library folders
(SysLib, UserLib or PersonalLib). They will then appear under the appropriate menu items:
Draw > User Defined Primitives for UDP or Draw > User Defined Model for UDM.
The sub-directories structure created in one of the specified directory will be displayed in the
UDP/UDM menu.
Keep in mind that there is no difference between the menu display for C and Python imple-
mentations of UDM or UDP - only the file names without extensions are displayed
Organize
"Lib" sub-directory is a special directory. The contents of this directory is not shown in the menu.
In the "Lib" directory you can create Python scripts with base classes and utilities to be used in
UDP/UDM Python scripts. All the Lib directories upstream of a script (till the UserDefinedModels
or UserDefinedPrimitives) are included in the Python search path and this allows for easy import
of helper modules in such directories.
To use UDM data structures, constants, and/or classes in your Lib sub-directory scripts you
have to add import statement to the scripts:
For UDM:extension:
from UDM import *
For UDP:extension:
from UDP import *
Edit/Reload
Python is a scripting language, so if you have errors in your script, you will see them at the time
you try to run the script. The errors will be displayed in the Message Manager Window. If you
need more information, you might be able to get it from log files. See: Debug Logging.
You can always change your script, call Update Menu command from Draw > User Defined
Model > menu or Draw > User Defined Primitives > menu and run the script again. If you
delete script you might want to restart the application instead of calling Update Menu.
UDPExtension
Import
You do not have to add import statements for the predefined classes, structures, and constants -
it is done for you and all data types described in this document can be used in your Python script.
However you have to add import statements to your helper scripts in your Lib sub-directory.
from UDP import *
You must write a class derived from IUDPExtension with a mandatory name UDPExtension:
class UDPExtension(IUDPExtension):
The class should implement IUDPextension methods described below.
IUDPExtension methods
All methods are same as the methods in the C UDP implementation. The changes to the meth-
ods signatures are just to conform to the Python style.
Mandatory methods.
These methods must be implemented in the UDP Python script as methods of UDPExtension
class.
GetLengthParameterUnits()
l returns string.
GetPrimitiveTypeInfo()
l returns UDPPrimitiveTypeInfo.
GetPrimitiveParametersDefinition2()
AreParameterValuesValid2(errorMsg, udpParams)
CreatePrimitive2(funcLib, udpParams)
Optional methods
GetPrimitiveParameters()
GetRegisteredFaceNames()
GetRegisteredEdgeNames()
GetRegisteredVertexNames()
ProjectParametersOnToValidPlane2(currentUDPParams, projectedUDPParams)
l currentUDPParams is a list of UDPParam
l projectedUDPParams is a list of UDPParam
l returns True on success, False on failure.
MapParametersDefinitionVersions2(oldVersion, oldUDPParams)
l oldVersion is a string
l oldUDPParamsis a list of UDPParam
l returns Python list of UDPParam or NULL
GetOldPrimitiveParametersDefinition2(version )
l version is a string
l returns a list of UDPPrimitiveParameterDefinition2 or None on failure.
Example UDP
import sys
class UDPExtension(IUDPExtension):
def GetLengthParameterUnits(self):
return "mm"
def GetPrimitiveTypeInfo(self)
typeInfo = UDPPrimitiveTypeInfo(
name = "SampleUDP",
purpose = "example",
company="Ansys",
date="12.21.12",
version = "1.0")
return typeInfo
...
...
UDMExtension
Import
You do not have to add import statements for the predefined classes and structures - it is done
for you, and all data types described in this document can be used in your Python script.
However you have to add import statements to your helper scripts in your Lib sun-directory.
You must write a class derived from IUDMExtension with a mandatory name UDMExtension:
class UDMExtension(IUDMExtension):
The class should implement IUDMExtension methods described below.
IUDMExtension methods
All methods are the same as the methods in the C UDM implementation. The changes to the
methods signatures are just to conform to the Python style.
Mandatory methods.
These methods must be implemented in the UDM Python script as methods of UDMExtension
class.
GetInfo()
IsAttachedToExternalEditor()
CreateInstance(funcLib)
l funcLib is UDMFunctionLibrary
l returns UDMParameters.
GetUnits(instanceId)
l instanceId is a long
l returns string containing units for the instance.
l updatedParams: UDM script can change the UDM parameters it receives. Updated para-
meters need to be sent back to desktop. If the UDM script is not going to change any of
the parameters that it received, it needs to copy udmInParams to updatedParams.
l refreshModifiedPartsOnly is a boolean
Supporting this flag is optional. For UDMs where the refresh performance is not an issue,
it is recommended to ignore this flag and update all parts every time.
This flag can be used to optimize performance of Refresh method when the model created
by UDM is large. If the UDM consists of multiple parts, and new parameters change only a
few parts amongst them, UDM script can only modify parts that are changed by the new
parameters.
l nonEditedPartRefIds: If RefreshModifiedPartsOnly is true and the UDM script supports
partial update, Refresh method needs to return ids of parts that are unchanged.
ReleaseInstance(instanceId)
l instanceId is a long
l This should release any resources assigned to this particular instance of UDM.
l returns True on success, False on failure.
GetAttribNameForEntityId()
l Returns string that acts as a the name of the attribute containing entity IDs.
l For example, it can return a unique string such as "ATTRIB_XACIS_ID"
l Python UDMs should implement this method.
GetAttribNameForPartId()
l Returns string that acts as a the name of the attribute containing entity IDs.
l For example, it can return a unique string such as "ATTRIB_XACIS_ID" (Can be same as
GetAttribNameForEntityId())
l Python UDMs should implement this method.
Optional methods
These methods have default implementations (default is to return NULL or FALSE depending on
the return type) but can be overridden by the user as needed as methods of UDMExtension
class.
DialogForDefinitionOptionsAndParams(self, defData, optData, params):
l instanceId is a long
l returns string containing source information of UDM instance. It is used to create initial
name for UDM instance.
ShouldAttachDefinitionFilesToProject()
class UDMExtension(IUDMExtension):
def IsAttachedToExternalEditor(self):
return False
def GetInfo(self)
udmInfo = UDMInfo(
name = "SampleUDM",
purpose = "udm example",
company="Ansys",
date="12.21.12",
version = "1.0")
return udmInfo
...
...
UDMFunctionLibrary
UDMFunctionLibrary implements IUDMFunctionLib interface. The IUDMFunctionLib object is
passed as a parameter to Python script in the following functions
l CreateInstance
l Refresh
You can call any of the functions from the functions list (shown below).
partRefId = udmFunctionLib.GetPartRefId(partId)
For example sample code that calls GetBoundingBox in Python script can look like this:
partId = 10
exact = True
udpPosition = UDPPosition(0,0,0)
if bret:
udpPosition.X = udpPositionLow.X
As you can see udpPositionLow and udpPositionHigh output parameters are defined in the call
to GetBoundingBox function. There is no need to define them before the function call.
Functions list:
In addition to the above functions all functions defined in the UDPFunctionLib are available in the
IUDMFunctionLib and can be called directly exactly the same way as the IUDMFunctionLib func-
tions.
Example:
udmFunctionLib.CreateCircle(center,radius,ratio,isCovered)
UDM/UDP Functions
Return Values for Each UDM and UDP Function
ID – ID of created Object
SI – Success Indicator. Identifies whether or not operation was successful.
Functions list:
UDP/UDM Structures
Instead of containing arrays of data, the structures contain single fields where each field
corresponds to an item in a different array from the original C API. The structure objects
thus constructed are added to the Python list. Alternately the Python list can be initialized
using the structure objects.
udmParamList = [
UDMParameter(
"cubeSizeName", UnitType.LengthUnit,
UDPParam(ParamDataType.Double, cubeSize),
ParamPropType.Value,
ParamPropFlag.MustBeReal),
UDMParameter(
"cubeDistanceName", UnitType.LengthUnit,
UDPParam(ParamDataType.Double, cubeDistance),
ParamPropType.Value,
ParamPropFlag.MustBeReal),
UDMParameter("numCubesName", UnitType.LengthUnit,
UDPParam(ParamDataType.Int, numCubes),
ParamPropType.Number,
ParamPropFlag.MustBeInt]
l UDPParam
l UDPParamData
Data field in UDPParam is now an object - the same for all types of data used - as Python
can work with any type of data.
UDPParamData is obsolete, thus not implemented. Be sure to set proper data type to
UDPParam.DataType when setting UDPParam.Data.
Example:
nCubes = nCubesParam.Data
distanceParam = UDPParam()
distanceParam.setDouble(10.5)
doubleDistance = distanceParam.Data * 2
l UDP3x3Matrix
The structure is not implemented. Use size 9 Python List of doubles instead.
Example:
List of structures
You can use constructors to create a structure. You can also modify fields - directly or by
provided methods.
Example:
pos1 = UDPPosition(1,2,3)
pos2 = UDPPosition(x=1,y=10,z=0)
pos2.Z = pos1.Z
udpParam = UDPParam(ParamDataType.Double,1)
value = udpParam.Data
methods:
setInt(int val)
setBool(bool val)
setString(string val)
setDouble(double val)
UDP/UDM Constants
##############################################################
# Class Implementation
##############################################################
class UDPExtension(IUDPExtension):
def CreatePrimitive2(self, func_lib, param_values):
"""
Inbuilt function that is called to generate a UDP after suc-
cessful validation
:param func_lib: drawing inbuilt class, see in Help: UDMFunc-
tionLibrary
:param param_values: list of udp parameter values (user
input) generated by UDP Core
:return: None
"""
param_dict = self.get_param_dict(param_values)
start_point = UDPPosition(0, 0, 0)
box = func_lib.CreateBox(start_point, [
param_dict["x_size"],
param_dict["y_size"],
param_dict["z_size"]
])
edges = [func_lib.GetEdgeIDFromPosition(UDPPosition(point
[0], point[1], point[2])) for point in points]
def GetPrimitiveTypeInfo(self):
return primitive_info
def GetLengthParameterUnits(self):
return length_units
def GetPrimitiveParametersDefinition2(self):
return primitive_param_definitions
# Custom Functions
def get_param_value_by_name(self, param_values, param_name):
"""
Function to get a value of a single parameter accessing it
by name
:param param_values: list of udp parameter values (user
input) generated by UDP Core
:param param_name: name of the parameter as specified in
definition list
:return: Value of the parameter or None if parameter does
not exist
"""
param_dict = self.get_param_dict(param_values)
value = param_dict.get(param_name, None)
return value
"""
udm_param_def = self.GetPrimitiveParametersDefinition2()
param_dict = {}
for i, param in enumerate(udm_param_def):
param_value = param_values[i].Data
if str(param.PropType) != "Menu":
param_dict[param.Name] = param_value
else:
param_dict[param.Name] = param_value.replace('"',
'').split(",")[0]
return param_dict
Introduction to CPython
An Ansys Electronics Desktop 2024R1 feature allows CPython to be used for standalone script-
ing, as an alternative to IronPython, to:
l Launch Ansys Electronics Desktop (InitializeNew)
l Connect with a running instance of Ansys Electronics Desktop (Initialize)
l Execute Ansys Electronics Desktop script functions
One advantage of CPython is the large set of libraries and tools that are available. See below for
instructions on modifying a script so that it can be launched with CPython interpreters.
CPython Script Engine and ansysedt process are comunicated using GRPC, the ansysedt pro-
cess started as GRPC server, the Script Script Engine acted as the GRPC clinet.
Important:
Connect() to an opened project in remote machine needs to use a share network path.
Connect Functions:
1. Connect(projectPath)
Example:
import sys
sys.path.append(r"<InstallationPath>/PythonFiles/DesktopPlugin")
import ScriptEnv
ScriptEnv.Connect(r”c:\myProjects\Project1.aedt”)
oProject = oDesktop.GetActiveProject()
print(oProject.GetName())
Note:
InitializeNew() will always launch a new instance of Electronics Desktop. Please use Ini-
tialize() to connect to an existing instance. See below.
-grpcsrv Flag
This flag will launch the application in a mode where the executable serves as a scripting server
that can be used for CPython scripting in conjunction with the CPython stand alone scripting
instructions that were mentioned earlier. The
-ng flag can be combined with -grpcsrv.
On Windows:
ansysedt.exe -grpcsrv <optional port number>.
On Linux:
ansysedt -grpcsrv <optional port number>.
If the port number is omitted, the default of 50051 will be used.
With -grpcsrv, a message will be displayed in the Messages window indicating that the server
was started. If the requested port is in use by another application, starting the sever may fail.
Related Topics:
Consult the following for details about script commands recognized by oDesktop:
l Desktop Object Script Commands.
oProject
The oProject object corresponds to one project open in Electronics Desktop. It is used to
manipulate the project and its data. Its data includes variables, material definitions, and one or
more designs.
In Iron Python, for example:
oProject = oDesktop.GetActiveProject()
In VBscript, for example:
Set oProject = oDesktop.GetActiveProject()
Consult the following for details about script commands recognized by oProject:
l Project Object Script Commands
oDesign
The oDesign object corresponds to a design in the project. This object is used to manipulate
the design and its data, including variables, modules, and editors.
In Iron Python, for example:
oDesign = oProject.GetActiveDesign()
In VBscript, for example:
Set oDesign = oProject.GetActiveDesign()
Consult the following for details about script commands recognized by oDesign:
l Design Object Script Commands
l Output Variable Script Commands
l Reporter Editor Script Commands
oEditor
The oEditor object corresponds to an editor, such as the 3D Modeler, Layout, or Schematic
editor. This object is used to add and modify data in the editor.
In Iron Python, for example:
oEditor = oDesign.SetActiveEditor('3D Modeler')
In VBscript, for example:
Set oEditor = oDesign.SetActiveEditor("3D Modeler")
Consult the following for details about script commands recognized by oEditor:
Important:
There is no Reporter Editor object for oEditor. Reporter Editor commands are
executed by oDesign.
oModule
The oModule object corresponds to a module in the design. Modules are used to handle a set of
related functionalities.
In IronPython, for example:
oModule = oDesign.GetModule('BoundarySetup')
In VBscript, for example:
Set oModule = oDesign.GetModule("BoundarySetup")
Consult the following for details about script commands recognized by oModule:
l Analysis Module Script Commands
l Boundary and Excitation Module Script Commands
l Field Overlays Module Script Commands
l Mesh Operations Module Script Commands
l Optimetrics Module Script Commands
l Radiation Module Script Commands
l Reduce Matrix Module Script Commands
l Solutions Module Script Commands
1. Click Tools > Run Script, or select the Automation tab and click the Run Script icon:
2. Use the file browser to locate the script file (*.vbs, *.py, or *.js).
3. If desired, type script arguments in the Script Arguments field:
You can access script arguments using the AnsoftScriptHost.arguments collection from
VBScript. This is a standard COM collection.
4. Click Open.
While script execution is in progress, the Run Script button transforms into a Stop Script
button. Click Stop Script to stop the script execution.
To temporarily pause a running script, click Pause Script. This button transforms into a
Resume Script button, which you can click to resume script execution.
In Iron Python, the command line parameter following -scriptargs is passed without modi-
fication as a single string in the ScriptArgument python variable.
In VBscript, the command line parameter following -scriptargs is split into multiple strings
and converted to a VBscript collection which is accessible via the AnsoftScript.Arguments
collection. To access these arguments, for example:
msgbox AnsoftScript.Arguments(0) // Returns 'hello'
msgbox AnsoftScript.Arguments(1) // Returns 'there'
For more information about running a script from the command line, consult the Maxwell help
topic "Running Maxwell from the Command Line".
Direct Launch
If you run a script directly from the command line without launching Electronics Desktop, script
arguments will be in the WSH.arguments collection instead of the AnsoftScriptHost.ar-
guments collection. The following script ensures the arguments are accessed regardless of the
collection in which they reside:
on error resume next
dim args
Set args = AnsoftScript.arguments
if(IsEmpty(args)) then
Set args = WSH.arguments
End if
on error goto 0
// At this point, args has the arguments regardless of col-
lection
msgbox "Count is " & args.Count
for i = 0 to args.Count - 1
msgbox args(i)
next
Recording a Script
Electronics Desktop can record a script based on UI actions and save this script in either
IronPython (*.py) or VBscript (*.vbs) format.
Scripts can be saved to an external file, or to the project.
Important:
When you record a script, every subsequent action you take is recorded. You must
manually stop recording.
1. Click Tools > Record Script to File, or select the Automation tab and click the Record
Script icon:
The Record Script button transforms into a Stop Recording button, and Electronics
Desktop begins recording your actions.
1. Click Tools > Record Script to Project, or select the Automation tab and use the
Record Script drop-down menu to select Record Script to Project.
2. Enter a name for the script in the text box, then click OK.
3. Perform the steps you want to record.
4. When you have finished, click Stop Recording, or select Tools > Stop Script Record-
ing.
The recorded script is saved to scriptname.vbs in the Scripts library and can be accessed
from the Project Manager. See: Working with Project Scripts.
Individual scripts appear in this folder. Right-click a script to edit or run it:
You can also run project scripts from the Automation tab by selecting Run Script > Project
Scripts > [Script Name].
Note:
Project scripts are stored in the project scripts library. Refer to the topic "Managing
Library Contents" for information on working with libraries.
If the full path to the script is not specified, Electronics Desktop searches for the specified script
in the following locations, in order:
Each of the library directories can be specified in Electronics Desktop under Tools > Options
> General Options, on the Project Options tab.
Electronics Desktop Scripting Conventions
A number of scripting conventions exist for Electronics Desktop regarding syntax, arguments,
and numerical values.
Consult the following topics:
l Named Arguments
l Setting Numerical Values
l Event Callback Scripting
Named Arguments
Many Electronics Desktop script commands use named arguments. The names can appear in
three ways:
For example:
For example:
For example:
..., Array("NAME:Attributes",...),...
In the first and second examples, the name is formatted as "<Name>:=". This signals to Elec-
tronics Desktop that this is a name for the next argument in the script command. In the third
example, the name is formatted as "NAME:<name>" and is the first element of the array.
The names are used both to identify what the data means to you and to inform Electronics
Desktop which data is being given. The names must be included or the script will not play back
correctly. However, if you are writing a script, you do not need to pass in every piece of data that
the command can take. For example, if you are modifying a boundary, the script will be recorded
to include every piece of data needed for the boundary, whether or not it was modified. If you are
writing a script by hand, you can add only the data that changed and omit anything that you do
not want to change. Electronics Desktop will use the names to determine which data you
provided.
VBscript Example
For example, when editing an impedance boundary, Electronics Desktop records the EditIm-
pedance command as follows in VBscript:
oModule.EditImpedance "Imped1", Array("NAME:Imped1",
"Resistance:=", "100", "Reactance:=", "50",
"InfGroundPlane:=", false)
If you only wish to change the resistance, you can leave out the other data arguments when
manually writing a script:
oModule.EditImpedance "Imped1", Array("NAME:Imped1",
"Resistance:=", "100")
IronPython Example
When editing a port excitation, Electronics Desktop records the Edit command as follows
in IronPython:
oModule.Edit("Port1",
["NAME:Port1",
["NAME:Properties",
"PortSolver:=", "true",
"Phase:=", "0deg",
"Magnitude:=", "2mA",
"Impedance:=", "50Ohm",
"Theta:=", "0deg",
"Phi:=", "0deg",
"PostProcess:=", "false",
"Renormalize:=", "50Ohm + 0i Ohm",
"Deembed:=", "0mm",
"RefToGround:=", "false"
],
"Type:=", "EdgePort",
"IsGapSource:=", true,
"UpperProbe:=", false,
"LayoutObject:=", "Port1",
"Pin:=", "",
"ReferencePort:=", ""
]
)
If you only wish to change the magnitude, you can leave out the other data arguments when
manually writing a script:
oModule.Edit("Port1",
["NAME:Port1",
["Magnitude:=", "1mA"]
]
)
Setting Numerical Values
For script arguments that expect a number, the following options are possible:
l Pass in the number directly.
In IronPython:
oModule.EditVoltage('Voltage1', ['NAME:Voltage1',
'Voltage:=', 3.5])
In VBscript:
In IronPython:
oModule.EditVoltage('Voltage1', ['NAME:Voltage1',
'Voltage:=', '3.5V'])
In VBscript:
In IronPython:
var = 3.5
oModule.EditVoltage('Voltage1', ['NAME:Voltage1',
'Voltage:=', var]
In VBscript:
dim var
var = "3.5V"
Scripts Vis-
Callback ible from the Functions Callable
Event Event Call- from the Visible Script
back Script
Place Com- CompInstance CompInstance.GetParentDesign() — Returns a oDesign item
ponent that can be used to call Design functions.
Object-Oriented Scripting
There are five basic functions in object-oriented scripting for retrieving and setting properties:
1. GetChildNames()
2. GetChildObjects()
3. GetPropNames()
4. GetPropValue()
5. SetPropValue()
At a high level, use GetChildNames() to determine what object instances exist for a given object. An example is shown below to
demonstrate for an AEDT Project shown that has two Designs.
If you open the Command Window that allows for executing python code, you first define the Project Object, oProject, and the Design
Object, oDesign, as shown:
Once the objects have been defined, you can use GetChildNames() to learn what object instances exist for each. As an example,
observe the Child Names of oProject, and you see a list of the Designs in the AEDT Project, per the GUI.
As another example, retrieve the names of the Object Instances available in oDesign, to see the various objects associated with a
Design setup:
These names are what you would expect based on the Project Manager Layout:
In the Project Manager above, any object that has the ‘+’ symbol is populated with children that you can query. Once you know the
name of the object you want, you can instance it via the GetChildObject() command. This defines the instance to the desired object.
As an example, set an instance for the Excitations:
You now have an object, oExcitations defined to be the oDesign Child Object ‘Excitations’. What does this mean? If you expand the
Excitations dialogue in the Project Manager, you expect that the Child Names of this object would be the names of the Excitations as
defined, in this case six ports:
There is clear logic to the Object Child Names as the children of the oExcitations object as the ports that have been defined in HFSS.
Looking at the Project tree can help you to conceive and retrieve desired information.
Expand the first port to see its expected Child Object, its Terminal, in the Project Manager Window:
Through scripting, first define the Port Object (in this example, oPort) using the ‘GetChildObject()’ command for the first port, ‘BAW_
module1_SE1.’ Then determine its Object Child Name, the terminal definition:
As the use and logic for GetChildNames() and GetChildObject() have been demonstrated, you can now explore the properties of each
of these objects, if they exist. The function to determine what properties exist is GetPropNames(). Use this to determine what prop-
erties exist to be retrieved or modified for a given object. The properties available are readily identifiable in the Property window, by
default located beneath the Project Manager window. For example, if you select a given port object, ‘BAW_module1_SE1’ the Prop-
erty window populates as shown:
If you execute the GetPropNames() function on the previously defined object, oPort, you see the same Property Names as available
in the Properties window:
Once you identify the desired object and you know the desired property, you can access the value via GetPropValue(). For example, if
you want to retrieve the name of the object oPort:
To change the value of the property, use the SetPropValue() function. The arguments for this function are (‘Property Name’,’New
Value’). For example, to change the name of the port to ‘Bob’:
This function returns a Boolean ‘True’ if successful. The Project Manager window updates accordingly:
This approach for retrieving and setting properties is general and can be used for many aspects of an Ansys Electronics Desktop sim-
ulation. This Object-Oriented method of property identification and modification operates only on existing objects. Object-Oriented
scripting cannot create new instances; you must revert to the functions in a given Module to do that. Not all Children of a given object
may be accessible via the GetChildNames() command just yet. An example is given for Material property modification later in this App
Note. However, if you need specific objects you can reference details in the Scripting Help or reach out to an Application Engineer.
All materials with a Project Definition, or assigned to an object, in the Project are accessible. For example, assume you want to see the
conductivity of ‘copper.’ Follow the same flow as in the previous section:
The Material Property of interest is "Bulk Conductivity." So you create a "Cond" object to store the value and use the GetPropValue
function to obtain in. Then name the Cond object to see the value:
Retrieving Variables
Retrieving defined variables in a Design or Project is a common effort for automation. There are two types of variables, Design and
Project. Project variables are preceded with a ‘$’ symbol and are retrieved in the Project object as it is globally defined to all Designs.
Design variables do not have any preceding symbols and are retrieved in the Design object as their scope is limited to a given Design.
The following example demonstrates the retrieval of Project Variable names and values, and then Design variable names and val-
ues.:
GetSolutionData API
Many users want to use scripts to extract solution data from Ansys Electronics Desktop for custom Post Processing. Scripting includes
a new method to do this without having to export data to a file and then re-import it for use in a script. The new function is accessible
via the “ReportSetup” Module. The function call is “GetSolutionDataPerVariation()”. A code snippet to extract Terminal S Parameter
data is shown:
The above code shows how you can extract the Dependent and Independent data to variables for easy manipulation. For more inform-
ation on other functions available for this, see GetSolutionDataPerVariation.
Summary
Scripting has been advancing in Ansys Electronics Desktop to better allow you to customize and automate their repetitive or complex
simulations. The ability to easily retrieve and set property values via the Object-Oriented scripting allows for ease or both writing and
reading. The ability to extract solution data within a script execution is a new functionality that markedly enables more advanced post
processing.
Object oriented property scripting presents an easy to use, intuitive and object oriented representation of the data model. The frame-
work supports query of objects and their properties including the edits of the data model in an object oriented fashion. With the new
scripting framework, data exposure is intuitive and provides maximum coverage.
Each exposed script object supports the following COM functions:
l GetName
o Return name of the object as text string
o e.g. name of a design, solve setup, boundary, etc
l GetChildTypes
o An object can have different types of children.
o Return array of text string. Can be empty if the object’s children are NOT categorized into different types.
For example, a design object has 3 children types. The following examples show how the commands run in the Tools > Open
Command Window for IronPython.
>>> design.GetChildTypes()
['Module', 'Editor', ‘Design Data’]
l GetChildNames
o Input: [String – Type]. Default = “Module” and “Editor” for design script object. ‘All’ for other script objects.
o Return an array of immediate children’s names, of a given type if specified
>>> design.GetChildNames("module")
['Boundaries', 'Excitations', 'Optimetrics', 'Results']
l GetChildObject
o Input: String -- Object path. The path may include multiple generations.
o Return the child object if found
For example,
>>> d = project.GetChildObject("hfss")
>>> d.GetChildObject("3d modeler").GetChildNames()
['Box1', 'Box1_1', 'Box1_1_1']
>>> project.GetChildObject("hfss/3d modeler").GetChildNames()
['Box1', 'Box1_1', 'Box1_1_1']
l GetPropNames
o Input: [BOOL - IncludeReadOnly] -- default to true
o Return an array of the object’s properties
For example,
>>> geom = project.GetChildObject("hfss/3d modeler").GetChildObject("Box1")
>>> geom.GetPropNames()
['Name', 'Material', 'Material/SIValue', 'Material/EvaluatedValue', 'Solve Inside', 'Ori-
entation', 'Orientation/Choices', 'Model', 'Group', 'Display Wireframe', 'Material Appearance',
'Color', 'Color/Red', 'Color/Green', 'Color/Blue', 'Transparent']
l GetPropValue
o Input: String – Property Path. The path may include multiple generations.
o Return the property value as VARIANT
For example,
>>> geom.GetPropValue("material")
'"vacuum"’
>>> geom.GetPropValue("xsize")
'3mm'
>>> op.GetPropValue("attach to original object")
False
l • SetPropValue
o Input: String – Property Path. The path may include multiple generations.
o Input: String – Data. New value of the property.
o Return -- True if property data is updated successfully. False if failed to assign the new value.
For example,
>>> geom.SetPropValue("model", False)
>>> boxcmd.SetPropValue("ysize", "4mm")
l GetPropEvaluatedValue (<PropName>)
For example,
oVar = oDesign.GetChildObject(" Variables/var")
oVar.GetPropEvaluatedValue()
l GetPropSIValue (<PropName>
For example,
oCreateBox = oDesign.GetChildObject("3D Modeler/Box1/CreateBox:1")
oCreateBox.GetPropValue("xSize")
return "length / 2"
oCreateBox.GetPropEvaluatedValue("xSize")
return '0.4mm'
oCreateBox.GetPropSIValue("xSize")
return 0.0004
HFSS 3D Layout
l Boundaries, Excitations, Circuit Elements, Analysis, Radiation, Field Overlays, Optimetrics, Results
Maxwell 3D/2D
l Boundaries, Excitations, Analysis, Field Overlays, Optimetrics, Results
RMxprt
l Analysis, Field Overlays, Optimetrics, Results
Q3D
l Boundaries, Nets, Analysis, Optimetrics,
Q2D
l Boundaries, Conductors, Analysis, Field Overlays, Optimetrics,
Icepak
l Thermal, Monitor, Mesh, Analysis, Field Overlays, Optimetrics, Results
Mechanical
l Boundaries, Excitations, Analysis, Field Overlays, Optimetrics, Results
Circuit
l Optimetrics, Results
Circuit Netlist
l Results
EMIT
l Coupling
Simplorer/Twin Builder
l Analysis, Optimetrics, Results
3D component encapsulation
These script interfaces are compliant with encapsulation. For example,
Related Topics
Example: GetPropNames and GetPropValues for Layered Impedance Boundary Script
Some Material Properties like Relatively Permittivity may have values assigned as BH Curves or Tensors, as discussed in the Assign-
ing Materials chapter of the online help.
A new Toolkit allows you to select materials from the Granta materials gateway, such that project materials will automatically be added
when you select a material from the gateway, and that the gateway itself is easily accessed from the materials.
True
>>> omat.GetPropNames()
['Coordinate System Type', 'Coordinate System Type/Choices', 'Relative Permeability Type',
'Relative Permeability Type/Choices', 'Relative Permeability', 'Relative Permeability/SIValue',
'Relative Permeability/EvaluatedValue', 'Bulk Conductivity Type', 'Bulk Conductivity
Type/Choices', 'Bulk Conductivity', 'Bulk Conductivity/SIValue', 'Bulk Con-
ductivity/EvaluatedValue', 'Magnetic Coercivity Type', 'Magnetic Coercivity Magnitude', 'Mag-
netic Coercivity Magnitude/SIValue', 'Magnetic Coercivity Magnitude/EvaluatedValue', 'Magnetic
Coercivity Components', 'Magnetic Coercivity Components/Component1', 'Magnetic Coercivity Com-
ponents/Component2', 'Magnetic Coercivity Components/Component3', 'Composition', 'Com-
position/Choices', '- Stacking Factor Type', '- Stacking Factor', '- Stacking Factor/SIValue',
'- Stacking Factor/EvaluatedValue', '- Stacking Direction', '- Stacking Direction/Choices',
"Young's Modulus Type", "Young's Modulus Type/Choices", "Young's Modulus", "Young's Mod-
ulus/SIValue", "Young's Modulus/EvaluatedValue", "Poisson's Ratio Type", "Poisson's Ratio
Type/Choices", "Poisson's Ratio", "Poisson's Ratio/SIValue", "Poisson's Ratio/EvaluatedValue"]
>>> omat.SetPropValue("Magnetic Coercivity Components/Component2", 2)
True
>>> omat.GetPropValue("Magnetic Coercivity Components")
['Component1:=', '2', 'Component2:=', '2', 'Component3:=', '0']
AddMaterial
AnalyzeAll
ChangeProperty
ClearMessages
CloneMaterial
Close
CopyDesign
CutDesign
DeleteDesign
DeleteToolObject
EditMaterial
ExportMaterial
GetActiveDesign
GetArrayVariables
GetChildNames [Project]
GetChildObject [Project]
GetChildTypes [Project]
GetConfigurableData
GetDefinitionManager
GetDependentFiles
GetDesign
GetDesign
GetDesigns
GetEDBHandle
GetLegacyName
GetName [Project]
GetObjPath [Project]
GetPath
GetPropEvaluatedValue
GetPropNames [Project]
GetPropSIValue
GetPropValue [Project]
GetProperties
GetPropertyValue
GetTopDesignList
GetVariableValue
GetVariables
InsertDesign
InsertDesign (PlanarEM)
InsertDesignWithWorkflow
InsertToolObject
AnalyzeAll [project]
Runs the project-level script command from the script, which simulates all solution setups and Optimetrics setups for all design
instances in the project. The UI waits until simulation is finished before continuing with the script.
VB Syntax AnalyzeAll
VB Example oProject.AnalyzeAll
ClearMessages
Clears information in the Messages window.
Note:
Additional options are available when using the Desktop-level ClearMessages command.
UI Access N/A
Parameters None.
VB Syntax ClearMessages
VB Example oProject.ClearMessages
Close
Closes the active project.
Warning:
UI Access N/A
Parameters None.
Return Value None.
VB Syntax Close
VB Example oProject.Close
CopyDesign
Copies a specified design.
CutDesign
Cuts a design from the active project. The design is stored in memory and can be pasted.
Warning:
This is a legacy command that is no longer supported and should not be used as it may have unintended effects on solved
designs.
DeleteDesign
Deletes a specified design in the project.
DeleteToolObject
Note:
This command is for internal Ansys use only.
UI Access N/A
GetActiveDesign
Returns the design in the active project
UI Access N/A
Parameters None.
Return Value Object of the active design.
VB Syntax GetActiveDesign
VB Example Set oDesign = oProject.GetActiveDesign
GetConfigurableData (Project)
Note:
This command is for internal Ansys use only.
GetDefinitionManager
Gets the DefinitionManager object.
UI Access N/A
Parameters None.
Return Value DefinitionManager object.
VB Syntax GetDefinitionManager
VB Example Set oDefinitionManager = oProject.GetDefinitionManager
GetDependentFiles
Provides a list of the external files referenced in the project, including characteristic (for example, MDX) and coupled project files.
UI Access N/A
Parameters None.
Return Value List of referenced files.
VB Syntax GetDependentFiles
VB Example files = oProject.GetDependentFiles
GetDesign
Use: Returns the specified design.
Command: None
Syntax: GetDesign <DesignName>
Return Value: The specified design.
Parameters: <DesignName>
Type: <string>
Name of the design to return.
VB Example: Set oDesign = oProject.GetDesign ("Maxwell3DDesign1")
GetEDBHandle
Returns the EDB handle for the project.
Important:
UI Access N/A
Parameters None.
Return Value String indicating the EDB handle for the project.
VB Syntax GetEDBHandle
VB Example oProject.GetEDBHandle
GetLegacyName
Obtains the legacy name of a project.
Note:
This command is for internal Ansys use only.
UI Access N/A
Parameters None.
Return Value String containing the legacy project name.
VB Syntax GetLegacyName
VB Example oProject.GetLegacyName
GetName [Project]
Obtains the project name
UI Access N/A
Parameters None.
Return Value String containing the project name, not including the path or extension.
VB Syntax GetName
VB Example oProject.GetName
GetPath
Returns the location of the project on disk.
UI Access N/A
Parameters None.
Return Value String containing the path to the project, not including the project name.
VB Syntax GetPath
VB Example oProject.GetPath
GetTopDesignList
Returns a list of top-level design names.
UI Access N/A
Parameters None.
Return Value List of strings containing name of top-level designs.
VB Syntax GetTopDesignList
VB Example oProject.GetTopDesignList
InsertDesign
Inserts a new design in the project. For Maxwell scripts, the last argument will always be empty.
UI Access Project > [Insert Maxwell 3D Design / Insert Maxwell 2D Design / Insert RMxprt Design].
InsertDesignWithWorkflow
Inserts a design with a named workflow and returns an IDispatch string.
UI Access N/A
InsertToolObject
Note:
This command is for internal Ansys use only.
VB Syntax Paste
VB Example oProject.Paste
VB Syntax Redo
VB Example oProject.Redo
Rename
Renames the project and saves it. Similar to SaveAs().
RestoreProjectArchive
Restores a previously archived project to a specified path.
Save
Saves the active project.
VB Syntax Save
VB Example oProject.Save
SaveAs
Saves the project under a new name. Requires a full path.
Note:
This script takes two parameters for non-schematic/layout designs and four parameters for schematic/layout designs.
oProject.SaveAs('D:/projects/project1.aedt', True)
Pytho- ----
n oProject.SaveAs('D:/Projects/Project1.aedt', True, 'ef_overwrite', ['NAME:Over-
Exam- rideActions', ['NAME:ef_copy_no_overwrite', ['NAME:Files',
ple
'$PROJECTDIR/circuit_models.inc']], ['NAME:ef_make_path_absolute', ['NAME:Files',
'$PROJECTDIR/SL_6s.sp']]])
Important:
The DefaultAction is applied to all files that are NOT explicitly listed in the OverrideActions array. Those in the Over-
rideActions array are separate arrays for actions that are different from the default action; those actions are applied to the
files listed in the same array:
l If OverrideActions are not specified, DefaultAction is applied to ALL files in project directory.
SaveAsStandAloneProject
Saves the project as a standalone copy.
Note:
This script is not supported when the application is being controlled by Ansys Workbench.
UI Access N/A
SaveProjectArchive
Saves the active project as an archive to the specified file path.
SetActiveDefinitionEditor
Obtains a specified definition editor.
UI Access N/A
oProject.SetActiveDefinitionEditor "SymbolEditor",_
VB Example
"Simplorer Elements\Basic Elements\Circuit\Passive Elements:R"
SetActiveDesign
Sets a design to be the active design.
UI Access N/A
SimulateAll
Simulates all solution setups and Optimetrics setups for all design instances in the project. Script processing only continues when all
analyses are finished.
UI Access N/A
Parameters None.
Return Value None.
VB Syntax SimulateAll
VB Example oProject.SimulateAll
Undo [Project]
Cancels the last project-level command.
VB Syntax Undo
VB Example oProject.Undo
UpdateDefinitions
Updates all definitions. The Messages window reports when definitions are updated, or warns when definitions cannot be found.
UI Access Tools > Project Tools > Update Definitions. Click Select All, then Update.
Parameters None.
Return Value None.
VB Syntax UpdateDefinitions
VB Example oProject.UpdateDefinitions
The following deprecated commands are no longer supported and produce an error if used.
l GetDesiredRamMBLimit (deprecated)
l GetHPCLicenseType (deprecated)
l GetMaximumRamMBLimit (deprecated)
l GetMPISpawnCmd(deprecated)
l GetMPIVendor (deprecated)
l GetNumberOfProcessors (deprecated)
l GetUseHPCForMP (deprecated)
l SetDesiredRamMBLimit (deprecated)
l SetHPCLicenseType (deprecated)
l SetMaximumRamMBLimit (deprecated)
l SetMPISpawnCmd (deprecated)
l SetMPIVendor (deprecated)
l SetNumberOfProcessors (deprecated)
l SetUseHPCForMP (deprecated)
GetAppDesktop
GetAppDesktop is a function of oAnsoftApp. This function does not take an input and it returns an object. The object is assigned to the
variable oDesktop.
UI Access NA
VB Syntax GetAppDesktop()
VB Example Set oDesktop = oAnsoftApp.GetAppDesktop()
GetApp
Obtains the product application object.
UI Access NA
VB Syntax GetApp(<productname>)
Dim oHFSSApp
VB Example
oHFSSApp = oAnsoftApp.GetApp("HFSS")
3-4
Ansys Electromagnetics Suite 2024 R1 - © ANSYS, Inc. All rights reserved. - Contains proprietary and confidential
information of ANSYS, Inc. and its subsidiaries and affiliates.
Maxwell Scripting Guide
GetActiveScheduler
GetActiveSchedulerInfo
GetAutoSaveEnabled
GetBuildDateTimeString
GetCustomMenuSet
GetDefaultUnit
GetDesktopConfiguration
GetDistributedAnalysisMachines
GetDistributedAnalysisMachinesForDesignType
GetExeDir
GetFullGeometry
GetGDIObjectCount
GetGrpcServerPort
GetHashcode
GetIsGrpcServer
GetIsNongraphical
GetLibraryDirectory
GetLocalizationHelper
GetMessages
GetMonitorData
GetPersonalLibDirectory
GetProcessID
GetProjectDirectory
GetProjectList
GetProjects
GetRegistryInt
GetRegistryString
GetRunningInstancesMgr
GetSchematicEnvironment
GetScriptingToolsHelper
GetSysLibDirectory
GetTempDirectory
GetTool
GetUserLibDirectory
GetVersion
IsFeatureEnabled
KeepDesktopResponsive
LaunchJobMonitor
NewProject
OpenAndConvertProject
OpenMultipleProjects
OpenProject
OpenProjectWithConversion
PageSetup
PauseRecording
PauseScript
Print
QuitApplication
RefreshJobMonitor
RefreshToolkitUI
ResetLogging
RestoreProjectArchive
RestoreWindow
ResumeRecording
RunACTWizardScript
RunProgram
RunScript
RunScriptWithArguments
SelectScheduler
SetActiveProject
SetActiveProjectByPath
SetCustomMenuSet
SetDesktopConfiguration
SetLibraryDirectory
SetProjectDirectory
SetRegistryFromFile
SetRegistryInt
SetRegistryString
SetSchematicEnvironment
SetTempDirectory
ShowDockingWindow
Sleep
StopSimulations
SubmitJob
TileWindows
WaitForSimulationsToBeDone
Related Topics:
AddMessage
Add a message with severity and context to message window.
UI Access N/A
ClearMessages
For a specified project and design, this command clears all messages in a specified severity range. The user-specified integral sever-
ity level is interpreted as:
0 => info, 1 => warning, 2 => error, and 3 => fatal error.
The ClearMessages function accepts four input arguments. The first two specifies project and design, respectively. This function
clears messages in the range specified by the third (interpreted as start severity) and fourth (interpreted as stop severity) arguments.
The fourth argument has a default value of 0. The last two arguments need not be specified in any given order, i.e., they can indicate
either ascending or descendingtrend. The function clears all messages having severity level within this specified range. The start and
stop severity need not be specified in any given order (i.e., they can indicate either ascending or descending severity).
UI Access In Message Manager, right-click and select Clear messages for [ProjectName]...
<stopSeverity> Integer Optional. User-specified stop severity level until which messages will be
cleared.
l 0 = informational
l 1 = warning
l 2 = error
l 3 = fatal error
sages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor", "Maxwell3DDesign1", 0,
1)
# startSeverity = 0 and stopSeverity = 2; clears all the Info, Warning, and Error
messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor", "Maxwell3DDesign1", 0,
2)
# startSeverity = 0 and stopSeverity = 3; clears all the Info, Warning, Error,
and Fatal messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor", "Maxwell3DDesign1", 0,
3)
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",2)
# startSeverity = 2 and stopSeverity = 2; clears all the Error messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",2, 2)
# startSeverity = 2 and stopSeverity = 3; clears all the Error and Fatal messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",2, 3)
# startSeverity = 2 and stopSeverity = 0; clears all the Info, Warning, and Error
messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",2, 0)
# startSeverity = 3; clears all the Info, Warning, Error, and Fatal messages;
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",3)
# startSeverity = 3 and stopSeverity = 3; clears all the Fatal error messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",3, 3)
# startSeverity = 3 and stopSeverity = 0; clears all the Info, Warning, Error,
and Fatal messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",3, 0)
CloseAllWindows
Closes all MDI child windows on the desktop.
VB Syntax CloseAllWindows
VB Example oDesktop.CloseAllWindows
CloseProject
Closes a specified project. Changes to the project are not saved. Save the project using the Project command Save or Save As
before closing to save changes.
CloseProjectNoForce
Use: Close a named project currently open in the Desktop, unless a simulation is running. Changes to the project will not be saved.
Save the project using the Project command Save or Save As before closing to save changes. To determine if the project has been
closed, use GetProjectList and see if the named project is present.
oDesktop.CloseProjectNoForce("MyProject")
Python Example
Count
Gets the total number of queried projects or designs obtained by GetProjects() and GetDesigns() commands.
UI Access N/A
Parameters None.
Return Value Integer
VB Syntax Count
Dim oAnsoftApp
Dim oDesktop
VB Example Dim oProject
Dim oDesign
Dim oEditor
Dim oModule
Dim oProjects
Set oAnsoftApp = CreateObject("Ansoft.ElectronicsDesktop")
Set oDesktop = oAnsoftApp.GetAppDesktop()
oDesktop.RestoreWindow
Dim projects
set projects = oDesktop.GetProjects()
for i = 0 to projects.Count - 1
msgbox projects(i).GetName()
dim designs
set designs = projects(i).GetDesigns()
for j = 0 to designs.Count - 1
msgbox designs(j).GetName()
next
next
DeleteProject
Deletes a project from disk.
EnableAutoSave
Enable or disable autosave feature.
UI Access N/A
ExportOptionsFiles
Copies the options config files to the DestinationDirectory.
GetActiveProject
Obtains the project currently active in the Desktop, as an object.
Note:
UI Access N/A
Parameters None.
Return Value Object: the project that is currently active in the desktop.
VB Syntax GetActiveProject
VB Example Set oProject = oDesktop.GetActiveProject
GetAutoSaveEnabled
Checks whether the autosave feature is enabled.
UI Access N/A
Parameters None.
Integer:
Return Value
l 1 – Autosave is enabled.
VB Syntax GetAutoSaveEnabled
VB Example Enabled = oDesktop.GetAutoSaveEnabled()
GetBuildDateTimeString
Returns a string representing the build date and time of the product;
UI Access N/A
Parameters None.
String build date and time, in the format: year-month-day hour:minute:second.
Return Value
Example: 2019-01-18 21:59:33
VB Syntax GetBuildDateTimeString
VB Example dnt = oDesktop.GetBuildDateTimeString
GetCustomMenuSet
Returns the name of the current selected menu set in Tools > Options > General Options > General > Desktop Configuration.
UI Access N/A
Parameters None.
Return Value String containing current menu set. For example, 'Default', 'EM', ‘Twin Builder’.
VB Syntax GetCustomMenuSet
VB Example Set oProject = oDesktop.GetCustomMenuSet
GetDefaultUnit
Returns the default unit for a physical quantity.
UI Access Tools > Options > General Options > Default Units. Note that this menu only displays units that can be
changed, while the script can be used to view additional default units.
l "MagneticReluctance"
l "Mass"
l "MassFlowRate"
l "MomentInertia"
l "Power"
l "Pressure"
l "PressureCoefficient"
l "Resistance"
l "SaturateMagnetization" (Magnetic Inductance)
l "Speed"
l "Temperature"
l "Time"
l "Torque"
l "Voltage"
l "VoltageChangeRate"
l "Volume"
l "VolumeFlowPerPressureRoot"
l "VolumeFlowRate"
Return Value String containing the default unit (for example, "mm").
GetDesigns
Obtains all designs in the current project.
UI Access N/A
Parameters None.
Return Value List of objects for all designs in the project.
VB Syntax GetDesigns
VB Example oProject.GetDesigns
GetDesktopConfiguration
Returns the name of the current selected configuration in Tools > Options > General Options > General > Desktop Configuration.
UI Access N/A
Parameters None.
Return Value String containing current Desktop configuration. For example, 'All', ‘Twin Builder’.
VB Syntax GetDesktopConfiguration
VB Example Set oProject = oDesktop.GetDesktopConfiguration
GetDistributedAnalysisMachines
Gets a list of machines used for distributed analysis. You can iterate through the list using standard VBScript methods.
UI Access N/A
Parameters None.
Return Value Returns a collection of names of machines used for distributed analysis.
VB Syntax GetDistributedAnalysisMachines
VB Example oDesktop.GetDistributedAnalysisMachines()
GetDistributedAnalysisMachinesForDesignType
To obtain a list of the machines set up for analysis of the specified design type.
UI Access NA
GetExeDir
Returns the path where the executable is located.
UI Access N/A
Parameters None.
String path where executable is located.
Return Value
Example: 'C:/Program Files/AnsysEM/v241/Win64/'
VB Syntax GetExeDir
VB Example oDesktop.GetExeDir
GetGDIObjectCount
Note:
This command is for internal Ansys use only.
VB Syntax GetGDIObjectCount()
VB Example oDesktop.GetGDIObjectCount()
GetLibraryDirectory
Get the path to the SysLib directory.
UI Access NA
String
Return Value
The path to the SysLib directory.
VB Syntax GetLibraryDirectory
VB Example MsgBox oDesktop.GetLibraryDirectory
VB Example:
------------------------------------------------------
message box returns the path in this example
------------------------------------------------------
Dim oAnsoftApp
Dim oDesktop
Dim oProject
Dim oDesign
Dim oEditor
Dim oModule
Set oAnsoftApp = CreateObject("Ansoft.ElectronicsDesktop")
Set oDesktop = oAnsoftApp.GetAppDesktop()
oDesktop.RestoreWindow
libdir = oDesktop.GetLibraryDirectory
msgbox(oDesktop.GetLibraryDirectory())
GetLocalizationHelper
Note:
This command is for internal Ansys use only.
UI Access NA
Object
Return Value
Localization helper object, such as "IDispatch(ILocalizationHelper)"
VB Syntax GetLocalizationHelper
VB Example oDesktop.GetLocalizationHelper()
GetMessages
Get the messages from a specified project and design.
UI Access NA
GetName [Desktop]
Gets names of queried projects or designs obtained by GetProjects() and GetDesigns() commands. See the example query.
UI Access N/A
Parameters N-
o-
Return Value String containing name.
n-
e-
.
VB Syntax GetName()
--------------------------------------------------------------
In this example, message box returns project name. projects(0) is the first of
the several projects. Similarly projects(1) displays name of second project
VB Example ----------------------------------------------------------------
Dim oAnsoftApp
Dim oDesktop
Dim oProject
Dim oDesign
Dim oEditor
Dim oModule
Dim oProjects
Set oAnsoftApp = CreateObject("Ansoft.ElectronicsDesktop")
Set oDesktop = oAnsoftApp.GetAppDesktop()
oDesktop.RestoreWindow
set projects = oDesktop.GetProjects()
project_name = projects(0).GetName()
msgbox(project_name)
GetPersonalLibDirectory
Get the path to the PersonalLib directory.
UI Access N/A
Parameters None.
Return Value String path to the PersonalLib directory.
VB Syntax GetPersonalLibDirectory
VB Example oDesktop.GetPersonalLibDirectory
GetProcessID
Returns the process ID of ansysedt.exe.
UI Access N/A
Parameters None.
Return Value Integer process ID of ansysedt.exe. For example, 12716.
VB Syntax GetProcessID
VB Example oDesktop.GetProcessID
GetProjects
Returns a list of all the projects that are currently open in Electronics Desktop. Once you have the projects, you can iterate through
them using standard VBScript methods.
UI Access N/A
Parameters None.
Return Value Returns a collection containing objects for all open projects in Electronics Desktop.
VB Syntax GetProjects
VB Example oDesktop.GetProjects
GetProjectDirectory
Gets the path to the Project directory.
UI Access N/A
Parameters None.
Return Value String path to the Project directory.
VB Syntax GetProjectDirectory
VB Example oDesktop.GetProjectDirectory
GetProjectList
Returns a list of all projects that are open in Electronics Desktop.
UI Access N/A
Parameters None.
Return Value Array of strings containing the names of all open projects in Electronics Desktop.
VB Syntax GetProjectList
VB Example list_of_projects = oDesktop.GetProjectList
GetSchematicEnvironment
Returns the name of the current schematic environment set in Tools > Options > General Options > General > Desktop Con-
figuration.
UI Access N/A
Parameters None.
Integer representing a schematic environment:
l 0 = Circuit
Return Value
l 1 = Twin Builder
l 2 = Maxwell Circuit
VB Syntax GetSchematicEnvironment
VB Example Set oProject = oDesktop.GetSchematicEnvironment
GetScriptingToolsHelper
Note:
This command is for internal Ansys use only.
UI Access NA
Object
Return Value
ScriptingTools helper object
VB Syntax GetScriptingToolsHelper
VB Example oDesktop.GetScriptingToolsHelper()
GetSysLibDirectory
Get the path to the SysLib directory.
UI Access N/A
Parameters None.
Return Value String path to the SysLib directory.
VB Syntax GetSysLibDirectory
VB Example oDesktop.GetSysLibDirectory
GetTempDirectory
Gets the path to the Temp directory.
UI Access N/A
Parameters None.
Return Value String path to the Temp directory.
VB Syntax GetTempDirectory
VB Example oDesktop.GetTempDirectory
GetUserLibDirectory
Gets the path to the UserLib directory.
UI Access N/A
Parameters None.
Return Value Stringpath to the UserLib directory.
VB Syntax GetUserLibDirectory
VB Example oDesktop.GetUserLibDirectory
GetVersion
Returns a string representing the version.
UI Access N/A
Parameters None.
Return Value String containing version of the product.
VB Syntax GetVersion()
VB Example oDesktop.GetVersion
ImportANF
Imports an ANF file into a new project. For older ANFv2 files, use ImportANFv2.
ImportAutoCAD
Imports an AutoCAD file into a new project.
ImportGDSII
Imports a GDSII file into a new project.
<propertyFileName> String Optional. Full path to property mapping file. Pass empty string if none.
ImportODB
Imports an ODB++ file into a new project.
LaunchJobMonitor
Use: For use in starting job monitoring. This brings up the Monitor Job dialog box.
VB Syntax LaunchJobMonitor()
VB Example oDesktop.LaunchJobMonitor("C:\\projects\\basic.aedt")
NewProject
Creates a new project. The new project becomes the active project.
VB Syntax NewProject
VB Example Set oProject = oDesktop.NewProject
OpenAndConvertProject
Opens a legacy project and converts or copies it to .aedt format.
Return Value An object reference to the newly opened project which has the .aedt extension
Warning: If project file/results with the same name and .aedt extension already exist in the same directory, they will be overwritten.
OpenMultipleProjects
Opens all files of a specified type in a specified directory.
UI Access N/A
OpenProject
Opens a specified project.
OpenProjectWithConversion
Note:
This command is for internal Ansys use only.
VB Syntax Paste
VB Example oProject.Paste
VB Syntax Paste
VB Example oProject.Paste
PauseRecording
Temporarily stop script recording.
UI Access NA
VB Syntax PauseRecording
VB Example oDesktop.PauseRecording
PauseScript
Pause the execution of the script and pop up a message to the user. The script execution will not resume until the user chooses.
Print
Prints the contents of the active view window.
VB Syntax Print
VB Example oDesktop.Print
QuitApplication
Exits the desktop.
VB Syntax QuitApplication
VB Example oDesktop.QuitApplication
RefreshJobMonitor
For use in monitoring a job.
VB Syntax RefreshJobMonitor
VB Example oDesktop.RefreshJobMonitor
ResetLogging
Redirects simulation log file to a specified directory and log level.
UI Access N/A
RestoreProjectArchive
Restores a previously archived project to a specified path.
RestoreWindow
Restores a minimized Desktop window.
UI Access N/A
Parameters None.
Return Value None.
VB Syntax RestoreWindow
VB Example oDesktop.RestoreWindow
ResumeRecording
Resume recording a script.
UI Access N/A
Parameters None.
Return Value None
VB Syntax ResumeRecording
VB Example oDesktop.ResumeRecording
RunACTWizardScript
Note:
This command is for internal Ansys use only.
RunProgram
Runs an external program.
UI Access NA
RunScript
Launches another script from within the script currently being executed.
This is the PersonalLib subdirectory in the project directory. The project dir-
ectory can be specified in the General Options dialog box (click Tools>Op-
tions>General Options to open this dialog box) under the Project Options
tab.
This is the userlib subdirectory in the library directory. The library directory can
be spec-ified in the General Options dialog box (click Tools>Op-
tions>General Options to open this dialog box) under the Project Options
tab.
This is the syslib subdirectory in the library directory. The library directory can
be speci-fied in the General Options dialog box (click Tools>Op-
tions>General Options to open this dialog box) under the Project Options
tab.
Long
Return Value
the return code for the script method.
RunScriptWithArguments
Similar to RunScript, launch another script from within the currently executing script, but with arguments.
UI Access NA
Long
Return Value
the return code for the script method.
SelectScheduler
Selects the scheduler used for batch job submission. It tries non-graphical selection of the scheduler, attempting to get version inform-
ation from the scheduler in order to check for successful selection. If unable to get the information, it displays the Select Scheduler
window and waits for the user to complete the settings.