0% found this document useful (0 votes)
227 views1,696 pages

Maxwell Scripting Guide

The Maxwell Scripting Guide for ANSYS Electromagnetics Suite 2024 R1 provides comprehensive information on scripting using VBScript and IronPython, including variable types, control structures, and procedures. It covers the integration of user-defined models and primitives, along with examples and best practices for scripting within the ANSYS environment. The document also includes legal disclaimers and trademark information relevant to the software and its usage.

Uploaded by

mansattha.m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
227 views1,696 pages

Maxwell Scripting Guide

The Maxwell Scripting Guide for ANSYS Electromagnetics Suite 2024 R1 provides comprehensive information on scripting using VBScript and IronPython, including variable types, control structures, and procedures. It covers the integration of user-defined models and primitives, along with examples and best practices for scripting within the ANSYS environment. The document also includes legal disclaimers and trademark information relevant to the software and its usage.

Uploaded by

mansattha.m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1696

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

Copyright and Trademark Information


© 1986-2024 ANSYS, Inc. Unauthorized use, distribution or duplication is prohibited.
ANSYS, Ansys Workbench, AUTODYN, CFX, FLUENT and any and all ANSYS, Inc. brand,
product, service and feature names, logos and slogans are registered trademarks or trademarks
of ANSYS, Inc. or its subsidiaries located in the United States or other countries. ICEM CFD is a
trademark used by ANSYS, Inc. under license. All other brand, product, service and feature
names or trademarks are the property of their respective owners. FLEXlm and FLEXnet are
trademarks of Flexera Software LLC.
Disclaimer Notice
THIS ANSYS SOFTWARE PRODUCT AND PROGRAM DOCUMENTATION INCLUDE TRADE
SECRETS AND ARE CONFIDENTIAL AND PROPRIETARY PRODUCTS OF ANSYS, INC.,
ITS SUBSIDIARIES, OR LICENSORS. The software products and documentation are furnished
by ANSYS, Inc., its subsidiaries, or affiliates under a software license agreement that contains
provisions concerning non-disclosure, copying, length and nature of use, compliance with export-
ing laws, warranties, disclaimers, limitations of liability, and remedies, and other provisions. The
software products and documentation may be used, disclosed, transferred, or copied only in
accordance with the terms and conditions of that software license agreement.
ANSYS, Inc. and ANSYS Europe, Ltd. are UL registered ISO 9001: 2015 companies.
U.S. Government Rights
For U.S. Government users, except as specifically granted by the ANSYS, Inc. software license
agreement, the use, duplication, or disclosure by the United States Government is subject to
restrictions stated in the ANSYS, Inc. software license agreement and FAR 12.212 (for non-
DOD licenses).
Third-PartySoftware
See the legal information in the product help files for the complete Legal Notice for Ansys pro-
prietary software and third-party software. If you are unable to access the Legal Notice, please
contact ANSYS, Inc.

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

Converting Between Data Types 1-10


Including Scripts 1-10
Aborting Scripts 1-11
Interacting with a Script 1-11
Recommended VBScript References 1-12
Introduction to IronPython 1-12
Scope 1-12
Python compatibility 1-12
Advantages of IronPython 1-12
Introduction to IronPython 1-14
Scope 1-14
Python compatibility 1-14
Advantages of IronPython 1-14
IronPython Mini Cookbook 1-15
Comments 1-15
Assigning/Creating Variables 1-16
Create Lists/Arrays 1-16
Create Dictionaries/Maps 1-17
Boolean Values 1-17
Converting Numbers to Strings and Vice Versa 1-17
String Formatting/Concatenation 1-18
Looping over Lists 1-18
Looping over a Range 1-18
Indentation in IronPython 1-19
Indenting Functions 1-19
Indenting If Conditions 1-19
Methods in IronPython 1-20
Finding Methods 1-20
Help 1-20
Translating Script Commands from VBScript to IronPython 1-20

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

Script Method Argument 1-20


Primitive Types 1-21
Named Arrays 1-21
Named Functions 1-21
VBScript Method Call Types 1-21
Converting VBScript Function calls to IronPython Syntax 1-22
Return Values 1-23
Primitive Method Arguments 1-23
Named Array Arguments 1-23
Named Array Values with All Key Value Pairs 1-23
Named Arrays with Nested Named Arrays 1-24
Function Blocks 1-25
Scripting Using Iron Python 1-25
Translating a script in VBScript to IronPython 1-25
Writing an IronPython script from scratch 1-25
IronPython Script Execution Environment 1-26
Script Argument for IronPython 1-27
Scripting using Embedded VBScript or JavaScript 1-27
Scripting with IronPython 1-30
Standalone IronPython 1-31
Running Standalone IronPython 1-31
Using a Recorded Script 1-32
Creating an External Script 1-32
Example Script 1-33
IronPython Samples 1-34
Change property 1-34
Create a Cone using IronPython 1-35
Creating User Defined Primitives and User Defined Models in Python Scripts 1-39
Advantages Compared to C++ 1-39
Changes compared to C 1-39

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

Start ansysedt as GRPC server 1-71


Connect Functions: 1-72
Example: 1-72
Launching Electronics Desktop 1-72
Connecting with a Running Instance of Electronics Desktop 1-73
Closing Electronics Desktop/Ending the Script 1-73
-grpcsrv Flag 1-73
Ansys Electronics Desktop Scripting 1-74
Overview of Electronics Desktop Scripting Objects 1-74
oAnsoftApp 1-75
oDesktop 1-75
oProject 1-76
oDesign 1-76
oEditor 1-76
oModule 1-77
Example Script Opening 1-77
GetActiveProject and GetActiveDesign for Wider Use 1-78
Running a Script 1-78
Within Electronics Desktop 1-78
From the Command Line 1-79
Direct Launch 1-80
Recording a Script 1-80
Recording a Script to File 1-81
Recording a Script to a Project 1-81
Working with Project Scripts 1-82
Executing a Script from Within a Script 1-83
Electronics Desktop Scripting Conventions 1-84
Named Arguments 1-84
VBscript Example 1-85
IronPython Example 1-85

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

Setting Numerical Values 1-86


Event Callback Scripting 1-87
2 - Object-Oriented Property Scripting 2-1
Object-Oriented Scripting 2-1
Material Properties and Examples 2-9
Body Properties and Modification 2-11
Retrieving Variables 2-11
Retrieve Datasets and Values 2-12
GetSolutionData API 2-14
Summary 2-14
Additional Details Specific to AEDT Solvers 2-18
Additional details on Boundaries/Excitations 2-20
3D component encapsulation 2-21
Additional details on Solve setup 2-22
Materials Scripting Support 2-23
Object Oriented Scripting for Materials 2-27
Examples showing change to material property type: 2-28
Examples showing change to a vector component value 2-28
Change choice property value 2-29
Change choice property value 2-30
Project Object Script Commands 2-31
AnalyzeAll [project] 2-34
ClearMessages 2-35
Close 2-36
CopyDesign 2-37
CutDesign 2-37
DeleteDesign 2-38
DeleteToolObject 2-39
GetActiveDesign 2-40
GetConfigurableData (Project) 2-41

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

Optimetrics Module Object: 6-9


Optimetrics Setup Object 6-9
ReportSetup(Results) Module Object: 6-10
ReportSetup(Results) Module Child Objects: 6-11
Radiation Module Object: 6-12
Radiation Module Child Objects: 6-12
Conventions Used in this Chapter 6-13
GetArrayVariables 6-26
GetProperties 6-26
GetPropertyValue 6-28
GetVariables 6-30
GetVariableValue 6-30
SetPropertyValue 6-31
SetVariableValue 6-33
7 - Design Object Script Commands 7-1
ApplyMeshOps 7-5
Analyze 7-6
AnalyzeAll (Maxwell menu) 7-6
AnalyzeDistributed 7-7
ClearLinkedData (Design) 7-8
ConfigureFluentConductivityCoupling 7-8
ConstructVariationString 7-9
CreateParametricCircuit 7-10
Create3DDesign [Maxwell] 7-11
DeleteFieldVariation 7-12
DeleteFullVariation 7-13
DeleteLinkedDataVariation 7-13
DeleteVariation 7-14
EditNotes 7-14
EnableHarmonicForceCalculation 7-15

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

EditDependent (Maxwell) 11-37


EditFluxTangential 11-37
EditImpedance (Maxwell) 11-38
EditIndependent (Maxwell) 11-39
EditInsulating 11-39
EditRadiation (Maxwell) 11-40
EditResistiveSheet 11-40
EditSymmetry 11-42
EditTangentialHField 11-43
EditThinLayer 11-43
EditTouching 11-46
EditVectorPotential 11-47
EditZeroTangentialHField 11-48
Script Commands for Creating and Modifying Excitations in Maxwell 11-48
AddTerminalsToWinding 11-50
AssignCharge 11-50
AssignCoilGroup 11-51
AssignCoilTerminal 11-52
AssignCoilTerminalGroup 11-53
AssignCurrent 11-54
AssignCurrentDensity 11-55
AssignCurrentDensityGroup 11-56
AssignCurrentDensityTerminal 11-57
AssignCurrentDensityTerminalGroup 11-57
AssignCurrentGroup 11-57
AssignFloating 11-58
AssignSink (Maxwell) 11-58
AssignVoltage (Maxwell) 11-59
AssignVoltageAPhi 11-59
AssignVoltageDrop 11-61

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

General Parameter Setup Script Commands 19-1


Commands to Create and Edit Parameters 19-2
AddReduceOp 19-2
AssignForce 19-4
[Beta] AssignLayoutForce 19-5
AssignMatrix 19-7
AssignTorque 19-9
DeleteAllParameters 19-10
DeleteParameters 19-10
DeleteReduceMatrix 19-11
DeleteReduceOp 19-11
EditForce 19-12
[Beta] EditLayoutForce 19-12
EditMatrix 19-15
EditReduceOp 19-15
EditTorque 19-16
ReassignParameter 19-16
RenameParameter 19-17
RenameReduceMatrix 19-17
RenameReduceOp 19-18
20 - User Defined Document Script Commands 20-1
AddDocument 20-1
DeleteAllDocuments 20-4
DeleteDocument 20-5
EditDocument 20-5
GetDocumentDefinitionNames 20-7
GetDocumentNames 20-8
RenameDocument 20-8
SaveHtmlDocumentAs 20-9
SavePdfDocumentAs 20-10

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

Method Format 24-2


Editor Scripting IDs 24-4
Format of IDs for different schematic objects: 24-4
Format for Components 24-5
Create Method List 24-6
CreateArc (Schematic Editor) 24-7
CreateCircle (Schematic Editor) 24-10
CreateComponent (Schematic Editor) 24-13
CreateGlobalPort (Schematic Editor) 24-15
CreateGround (Schematic Editor) 24-19
CreateLine (Schematic Editor) 24-22
CreatePagePort (Schematic Editor) 24-25
CreateIPort (Schematic Editor) 24-28
CreatePolygon (Schematic Editor) 24-31
CreateRectangle (Schematic Editor) 24-34
CreateText (Schematic Editor) 24-38
CreateWire (Schematic Editor) 24-42
General Method List 24-45
Activate (Schematic Editor) 24-47
AddPinGrounds (Schematic Editor) 24-48
AddPinIPorts (Schematic Editor) 24-51
AddPinPageConnectors (Schematic Editor) 24-52
AlignHorizontal (Schematic Editor) 24-53
AlignVertical (Schematic Editor) 24-54
BringToFront (Schematic Editor) 24-55
CloseEditor (Schematic Editor) 24-57
Copy (Schematic Editor) 24-57
CopyData [Schematic Editor] 24-58
CopySubdesign [Schematic Editor] 24-59
CreatePage (Schematic Editor) 24-60

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

Cut (Schematic Editor) 24-61


DeactivateOpen (Schematic Editor) 24-62
DeactivateShort (Schematic Editor) 24-63
Delete (Schematic Editor) 24-64
DeletePage (Schematic Editor) 24-65
ElectricRuleCheck (Schematic Editor) 24-66
ExportImage (Schematic Editor) 24-67
ExportNetlist 24-68
FindElements (Schematic Editor) 24-69
FitToBorder [Schematic Editor] 24-71
GridSetup (Schematic Editor) 24-72
FlipHorizontal (Schematic Editor) 24-75
FlipVertical (Schematic Editor) 24-76
Move (Schematic Editor) 24-78
NameNets (Schematic Editor) 24-79
PageBorders (Schematic Editor) 24-81
Pan (Schematic Editor) 24-81
Paste (Schematic Editor) 24-83
PasteData [Schematic Editor] 24-84
PasteDesign (Schematic Editor) 24-85
PushExcitations 24-87
Rotate (Schematic Editor) 24-90
SelectAll (Schematic Editor) 24-92
SelectPage (Schematic Editor) 24-93
SetPageData [Schematic Editor] 24-94
SendToBack 24-97
ShowVariableBlock (Schematic Editor) 24-98
SortComponents (Schematic Editor) 24-98
Wire (Schematic Editor) 24-99
ZoomArea (Schematic Editor) 24-100

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

ZoomIn (Schematic Editor) 24-101


ZoomOut (Schematic Editor) 24-102
ZoomPrevious (Schematic Editor) 24-103
ZoomToFit (Schematic Editor) 24-104
Property Method List 24-105
ChangeProperty (Schematic Editor) 24-105
GetEvaluatedPropertyValue (Schematic Editor) 24-106
GetProperties (Schematic Editor) 24-107
GetPropertyAttribute [Schematic Editor] 24-109
GetPropertyValue (Schematic Editor) 24-110
SetPropertyValue (Schematic Editor) 24-111
Information Method List 24-112
GetAllPorts 24-113
GetCompInstanceFromRefDes (Schematic Editor) 24-113
GetComponentInfo (Schematic Editor) 24-114
GetComponentPins (Schematic Editor) 24-116
GetComponentPinInfo (Schematic Editor) 24-117
GetComponentPinLocation [Schematic Editor] 24-118
GetEditorName (Schematic Editor) 24-119
GetNetConnections (Schematic Editor) 24-120
GetNumPages [Schematic Editor] 24-121
GetPortInfo (Schematic Editor) 24-122
GetSelections (Schematic Editor) 24-123
GetSignals (Schematic Editor) 24-124
GetWireConnections (Schematic Editor) 24-126
GetWireInfo (Schematic Editor) 24-128
GetWireSegments (Schematic Editor) 24-130
25 - Definition Manager Script Commands 25-1
AddMaterial (Maxwell) 25-2
Additional Properties for Nonlinear Property Type 25-6

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

Additional Properties for Vector Property Type 25-7


Additional Examples 25-8
CloneMaterial 25-12
ComputeCoreLossCoefficients 25-13
DoesMaterialExist 25-15
EditMaterial (Maxwell) 25-16
Example: Nonlinear Conductivity 25-16
Example using a Thermal Modifier for Electrical Steel Core Loss properties 25-17
Example: Set oProject = oDesktop.SetActiveProject("example_magnetostatic") 25-20
VB Example (Young's Modulus and Poisson's Ratio): 25-21
Additional Python Examples 25-22
Python Example (Young's Modulus and Poisson's Ratio): 25-22
Example: Magnetostrictive stress and deformation with full magnetostriction matrix
[3x3] 25-23
Python Example: Core Loss Y Parameter for Electrical Steel (Simple Property) 25-26
Python Example: Core Loss Y Parameter for Electrical Steel (Anisotropic Property) 25-28
Additional VB Examples 25-30
Example:Set oAnsoftApp = CreateObject("Ansoft.ElectronicsDesktop") 25-30
Example:Litz Wire 25-32
Example: Thermal Modifier 25-32
Example: B-P Curve Core Loss Model 25-34
GetProjextMaterialNames 25-36
ExportMaterial 25-37
RemoveMaterial 25-38
RemoveUnusedDefinitions 25-39
Component Manager Script Commands 25-40
Add [component manager] 25-41
AddDynamicNPortData [component manager] 25-60
AddNPortData [component manager] 25-63
AddSolverOnDemandModel 25-69

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

ClearSolutionCache [component manager] 25-69


Edit [component manager] 25-69
EditSolverOnDemandModel 25-96
EditWithComps [component manager] 25-96
Export [component manager] 25-108
GetData [component manager] 25-109
GetNames [component manager] 25-110
GetNPortData [component manager] 25-111
GetSolverOnDemandData 25-114
GetSolverOnDemandModelList 25-114
IsUsed [component manager] 25-115
Remove [component manager] 25-115
RemoveSolverOnDemandModel 25-117
RemoveUnused [component manager] 25-117
Update Dynamic Link [component manager] 25-118
Material Manager Script Commands 25-119
GetData [material manager] 25-119
GetNames [material manager] 25-120
GetProperties [material manager] 25-121
IsUsed [material manager] 25-122
RemoveUnused [material manager] 25-123
Model Manager Script Commands 25-123
Add [model manager] 25-124
ConvertToDynamic 25-135
ConvertToParametric 25-135
Edit [deprecated] 25-135
EditWithComps [model manager] 25-136
Export [model manager] 25-147
GetData [model manager] 25-148
GetNames [model manager] 25-149

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

IsUsed [model manager] 25-150


Remove [model manager] 25-151
RemoveUnused [model manager] 25-152
Network Data Explorer Manager Script Commands 25-153
ExportFullWaveSpice 25-153
ExportNetworkData 25-155
ExportNMFData 25-158
Symbol Manager Script Commands 25-158
Add [symbol manager] 25-159
BringToFront [symbol manager] 25-169
Edit [deprecated] 25-170
EditWithComps [symbol manager] 25-170
Export [symbol manager] 25-181
GetData [symbol manager] 25-182
GetNames [symbol manager] 25-183
IsUsed [symbol manager] 25-184
Remove [symbol manager] 25-184
RemoveUnused [symbol manager] 25-185
Add [footprint manager] 25-186
Edit [footprint manager] 25-209
EditWithComps [footprint manager] 25-209
Export [footprint manager] 25-227
GetData [footprint manager] 25-228
GetNames [footprint manager] 25-228
IsUsed [footprint manager] 25-229
Remove [footprint manager] 25-229
RemoveUnused [footprint manager] 25-231
Add [padstack manager] 25-231
Edit [padstack manager] 25-238
EditWithComps [padstack manager] 25-245

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

Export [padstack manager] 25-252


GetData [padstack manager] 25-253
GetNames [padstack manager] 25-254
IsUsed [padstack manager] 25-254
Remove [padstack manager] 25-255
RemoveUnused [padstack manager] 25-256
Script and Library Scripts 25-257
AddScript 25-257
EditScript 25-258
ExportScript 25-259
RemoveScript 25-260
ModifyLibraries 25-261
26 - Definition Editor Script Commands 26-1
Symbol Editor Scripts 26-1
AddLevel (Symbol Editor) 26-3
AlignHorizontal (Symbol Editor) 26-4
AlignVertical (Symbol Editor) 26-5
BringToFront (Symbol Editor) 26-6
ChangeProperty (Symbol Editor) 26-6
CloseEditor (Symbol Editor) 26-19
Copy (Symbol Editor) 26-20
CreateArc (Symbol Editor) 26-20
CreateCircle (Symbol Editor) 26-21
CreateImage (Symbol Editor) 26-22
CreateLine (Symbol Editor) 26-23
CreatePin (Symbol Editor) 26-24
CreatePolygon (Symbol Editor) 26-25
CreateRectangle (Symbol Editor) 26-26
CreateText (Symbol Editor) 26-27
Cut (Symbol Editor) 26-27

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

Delete (Symbol Editor) 26-28


DisplayPinNames (Symbol Editor) 26-29
ExportFile (Symbol Editor) 26-29
FlipHorizontal (Symbol Editor) 26-30
FlipVertical (Symbol Editor) 26-31
GetProperties (Symbol Editor) 26-31
GetPropertyValue (Symbol Editor) 26-32
GetVisibleLevels (Symbol Editor) 26-32
GridSetup (Symbol Editor) 26-33
Move (Symbol Editor) 26-34
Pan (Symbol Editor) 26-35
Paste (Symbol Editor) 26-35
Redo (Symbol Editor) 26-36
RemoveLevels (Symbol Editor) 26-37
RemovePort (Symbol Editor) 26-37
Rotate (Symbol Editor) 26-38
Save (Symbol Editor) 26-39
SelectAll (Symbol Editor) 26-39
SendToBack (Symbol Editor) 26-40
SetActivelLevel (Symbol Editor) 26-40
SetInitialLevels (Symbol Editor) 26-41
SetPropertyValue (Symbol Editor) 26-42
SetVisibleLevels (Symbol Editor) 26-42
ToggleLevel (Symbol Editor) 26-43
Undo (Symbol Editor) 26-44
ZoomArea (Symbol Editor) 26-45
ZoomIn (Symbol Editor) 26-46
ZoomOut (Symbol Editor) 26-46
ZoomPrevious (Symbol Editor) 26-47
ZoomToFit (Symbol Editor) 26-47

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

27 - Core Global Script Context Commands 27-1


AddErrorMessage 27-1
AddFatalMessage 27-2
AddInfoMessage 27-2
AddWarningMessage 27-3
LogDebug 27-3
LogError 27-4
28 - Example Scripts 28-1
VBScript Example Scripts 28-1
Variable Helix Script 28-1
Data Export Script 28-5
IronPython Example Scripts 28-8
BH Coordinates Python Script 28-8
Script Contents 28-9
Posco_BH_Curve.tab Contents 28-11
Equation Based Curve Python Script 28-13
Index Index-1

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.

Scripting Help Conventions


The majority of this guide lists individual script commands using the following format.
[ScriptName]
[Description of script use.]

UI Access [UI commands corresponding to the script command, if any.]

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

Introduction to Scripting 1-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

[Correct syntax for the command in VBscript. Arguments are enclosed in


VB Syntax
angle brackets (<>)
VB Example [Sample script]

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

Introduction to Scripting 1-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

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:

Introduction to Scripting 1-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

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.

Scope and Lifetime of Variables


Variables at the script level are available to all procedures within the script. At the procedure
level, variables are available only within the procedure. It has local scope and is a procedure-
level variable.
The lifetime of a variable depends on how long it exists. The script-level variables exist from
declaration until the end of the script. A procedure-level variable exists only as long as you are in
the procedure and is destroyed when the procedure exits.
Array Variables
Create an array variable when you want to assign more than one related value to a single vari-
able. An array variable contains a series of values. For example:
Dim Primitives(2)

Introduction to Scripting 1-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

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.

Introduction to Scripting 1-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

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

Introduction to Scripting 1-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

\ 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

Introduction to Scripting 1-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

Eqv Logical equivalence


Imp Logical implication

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.

Controlling Program Execution


You can use conditional statements to control the flow of a script. There are two types of con-
ditional statements in VBScript:
l If...Then...Else
l Select Case

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>

Introduction to Scripting 1-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

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.

Introduction to Scripting 1-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

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:

CStr Syntax: CStr(variablename).


Converts variablename to a string. For example, it can be used to convert the number
2.5 to the string "2.5".
CBool Syntax: CBool(variablename).
Converts variablename to a boolean. If variablename is 0 or "0", CBool returns False.
Otherwise it returns True.
CDbl Syntax: CDbl(variablename).
Converts variablename to a double precision number. For example, it can be used to
convert the string "2.5" to the number 2.5.
CInt Syntax: CInt(variablename).
Converts variablename to an integer.

Including Scripts
You can include one script within another using the following command:

Introduction to Scripting 1-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

#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.

Interacting with a Script


VBScript provides two functions that enable you to interact with a script while it is running:
the InputBox function and the MsgBox function.
The InputBox function displays a dialog box with an input field. The value that is typed into the
input field is returned. For example:
Dim users_string
users_string = InputBox ("text prompt", "title of the pop-up dialog _
box", "default text for the input box")

The last two arguments to the function are optional.

The MsgBox function shows a message and returns a number based on the button the user
presses. For example:

Introduction to Scripting 1-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

MsgBox ("message text")


Recommended VBScript References
Microsoft Corporation. VBScript User’s Guide.
Available http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/htm-
l/vbstutor.asp.
Childs, M., Lomax, P., and Petrusha, R. VBScript in a Nutshell: A Desktop Quick Reference.
May 2002. O’Reilly & Associates. ISBN: 1-56592-720-6.

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.

Introduction to Scripting 1-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

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 Scripting 1-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

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.

Introduction to Scripting 1-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

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

Introduction to Scripting 1-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

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"

Introduction to Scripting 1-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

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

Set dict = CreateObject _ Delimiters are curly braces. Use a colon


between the key and the value. Separate key
("Scripting.Dictionary") value pairs with a comma:
Add items using the object, key, item syntax: myDict = {
dObject.Add key, item "a" : 1,
"b" : "hello there",
"c" : [ 1, 2, "abc"]
}

Boolean Values

VBScript IronPython
Boolean literals are in lower case: The first letter is capitalized:
true True
false False

Converting Numbers to Strings and Vice Versa

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)

Introduction to Scripting 1-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

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

Looping over Lists

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

For Each i in myArray for i in vals:


Print i print i
Next print " -> " process(i)

Looping over a Range

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

Introduction to Scripting 1-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

Related Topics:

Indentation in IronPython

Methods in IronPython

Introduction to IronPython

Translating Script commands from VBScript to IronPython

Scripting Using Iron Python

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:

Python recommends the use of spaces over tabs.

Indenting Functions

Define a function that starts at 0 indentation:


def multInt(a,b):
Every line following def multInt that is expected to be a part of the function, must be indented
to line up with the function.
def multInt(a,b):
return a
Indenting If Conditions

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

Introduction to Scripting 1-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

Methods in IronPython
Finding Methods

To list all methods available in the string module,import the module:


import string
Then get the directory listing:
dir(string)
This returns a list of all the methods available (as well as some __somename__ internal names
that can be ignored).
Help

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, ...)

Introduction to Scripting 1-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

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

Introduction to Scripting 1-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

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.

Introduction to Scripting 1-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

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

Replace each VBScript primitive with an equivalent IronPython primitive.


Boolean values in IronPython have their first letter capitalized (True instead of true and False
instead of false).
For arrays, the recommended approach is to simply replace a VBScript array with a Python
array. The mapping is simple:
l Change Array( to a square bracket [ and close with another square bracket ] instead of
a parenthesis )
l Remove the line continuation underscore symbol: _
l Map Boolean values correctly
Named Array Arguments

Formatting helps readability immensely but is not required.


All that must be done is:
l Add the parentheses, since the VBScript subroutine omits them
l Replace the Array( ) delimiters with [ ]
l Remove the Char(34) function (which introduced a double quote) and replace it with the
escaped double quote literal: \"
l Replace true with True
l Remove the line continuation symbol: _
Named Array Values with All Key Value Pairs

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.

Introduction to Scripting 1-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

Named Arrays with Nested Named Arrays

l Split the NAME:name field into a key value pair


l Translate array key value pair to a dictionary key value pair.
l Create a new key with the name of the nested array and keep the nested array (as an
array or as a dictionary) as its value. If the nested array is being retained as an array, the
NAME:name field should be retained in the array. If the nested array is being converted to
a dictionary, the name is optional: if also retained in the nested array, it must match the
outer key.

[ "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,

Introduction to Scripting 1-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

"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

Introduction to Scripting 1-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

Standalone IronPython and Desktop 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

Introduction to Scripting 1-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

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.

Figure 1: Run Script dialog and script arguments


Any argument specified here is communicated to the script being executed as the predefined
variable ScriptArgument.

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

Introduction to Scripting 1-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

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).

#import the CLR references


import clr

Introduction to Scripting 1-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

clr.AddReference("System.Windows.Forms")

from System.Windows.Forms import Application, Form, Label, Button,


DockStyle

# the GUI form to show some text


# the class below derives from From (System.Windows.Forms.Form)
# imported above from the .NET assembly.
class ShowPropertiesForm(Form):
def __init__(self, name, text):
self.Name = name
self._label = Label()
self._label.Text = text
self._label.Dock = DockStyle.Fill

_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

Introduction to Scripting 1-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

# in the form.
gui = ShowPropertiesForm("Sample Form", ScriptArgument)

# This makes it a modal dialog.


gui.ShowDialog()

# the following will make it a non-modal dialog


#Application.Run(gui)
Sample Script 12: Demonstrates the use of a .NET form from IronPython
While creating cross platform user interfaces from scripts is one of the main motivations driving
the adoption of IronPython, any .NET assembly can be used with the caveat that Linux use
requires Mono compatibility of any used assemblies.
While this hybrid approach is useful when you have existing VBScript commands that you want
to reuse or when you want to quickly parameterize a recorded sample, the one significant lim-
itation of this approach is the inability to capture return values from VBScript or JavaScript calls
that do return something. Full two way communication with the product requires the use of pure
IronPython to directly invoke the script objects as described below.

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.

Introduction to Scripting 1-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

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"

Introduction to Scripting 1-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

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

# Imports the sys module containing system-specific functions native to IronPython.

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")

# Adds the PythonFiles/DesktopPlugin subfolder to the list of directories Python searches


for modules and files.

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.

You must end the script with:

Introduction to Scripting 1-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

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",

Introduction to Scripting 1-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

"Flags:= ", "",


"Color:= ", "(132 132 193)",
"Transparency:= ", 0,
"PartCoordinateSystem:=", "Global",
"UDMId:= ", "",
"MaterialValue:= ", "\"vacuum\"",
"SolveInside:= ", True
])
oDesign.SetDesignSettings(['NAME:Design Settings Data', 'Allow Mater-
ial Override:=', True, 'Calculate Lossy Dielectrics:=', True])
oEditor.SetModelUnits(['NAME:Units Parameter', 'Units:=', 'mil', 'Res-
cale:=' , False ])
ScriptEnv.Shutdown()
IronPython Samples

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]
]
]

Introduction to Scripting 1-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

])
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

Create a Cone using IronPython

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",

Introduction to Scripting 1-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

"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")

# create the first cone


AddInfoMessage("Creating first cone")
firstConeName = "firstCone"

Introduction to Scripting 1-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

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
}
)

# Now replicate this a few times and create an array out of it


AddInfoMessage("Replicating it 24 times")
for x in range(5):
for y in range(5):
# leave the first one alone in it's created

Introduction to Scripting 1-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

# position
if x == 0 and y == 0:
continue

# all other grid positions, replicate from the


# first one

# copy first
oEditor.Copy(
{
"NAME" : "Selections",
"Selections" : firstConeName
}
)

# paste it and capture the pasted name


# the pasted names come in an array as we could
# be pasting a selection cmposed of multiple objects
pasteName = oEditor.Paste()[0]

# now move the pasted item to it's final position


oEditor.Move(
{
"NAME" : "Selections",
"Selections" : pasteName
},
{
"NAME" : "TransalateParameters",
"CoordinateSystemID" : -1,
"TranslateVectorX" : "%d * 3 * %s" % (x, coneBotRad),

Introduction to Scripting 1-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

"TranslateVectorY" : "%d * 3 * %s" % (y, coneBotRad),


"TranslateVectorZ" : "0mm"
}
)

# Now fit the display to the created grid


oEditor.FitAll()
Sample Script 17: Sample script to create a cone and then use copy/paste/move to rep-
licate it.

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 Structures have the same names as in C implementation.


l Structures fields names are capitalized.
l Arrays in structures become lists in Python (Technically a.NET IList container)

Introduction to Scripting 1-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

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

Methods are described in IUDPExtension methods, IUDMExtension methods, and UDMFunc-


tionLibrary listed further in this document. A separate chapter includes a UDP IronPython
example of fillet and chamfer.
The main differences in functions parameters (from C implementation):
l functions names in UDPFunctionLibrary and UDMFunctionLibrary are capitalized
l arrays become a python list of objects
l void * callback parameter is dropped from the parameter list
l output parameters (pointer types that are filled during the function call) usually become
return values
l 'list size' parameter usually will be omitted as redundant
Output Parameters

The rule for the output parameters is as follows:


l If the function has one output parameter variable and no return value, the variable will
become function's return value.The same will happen if the return value is a 'suc-
cess/failure' boolean ('None' will be returned on failure and parameter variable - on suc-
cess).
l If the function has one output parameter and a return value, the function will return a
Python tuple where function return value will be the first one in the tuple.

Introduction to Scripting 1-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

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()

# one output parameter; return value must be preserved. return


# and output values are packed into the return tupe, in order
(lRet, partIdsList) = udpFunctionLibrary.DetachFaces(nPartIds, faceId-
sList)
# Two output parameter; return value must be preserved
# the return tuple is (returnVal, output1, output2)
(bRet, udpPositionLow, udpPositionHigh) = udmFunc-
tionLibrary.GetBoundingBox(partId,exact);
Comparison with C function:

C Python
bool getDefinition(UDMDefinition* udmDefinition = udmFunctionLibrary.GetDefinition()
udmDefinition,
void* callbackData );
(Note: callbackData is omitted in py interface)

where udmDefinition is an output


parameter

long detachlFaces( int (bRet, partIds) = udmFunctionLibrary.DetachlFaces


nFacesAndPartIds, (nFacesAndPartIds, faceIds)
long* faceIds,
long* partIds, (Note: callbackData is omitted in py interface)
void* callbackData);

where partIds is an output para-


meter

'List Size' Parameters

The rule for the 'list size' is as follows:

Introduction to Scripting 1-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

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)

# output list, output list size


faceIdList = udmFunctionLibrary.GetAllFaces(PartId)

# output list, input list size


(lret, partIdList) = udpFunctionLibrary.DetachFaces(listSize,
faceIdList)
Comparison with C function:

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);

(ignore numObjects as redundant: fol-


where numObjects and objectIds are input parameters ded into objectIds

Introduction to Scripting 1-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

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);

(nSize is not ignored,


where partIds is and output list and nSize is an input callbackData is omitted)
parameters and nSize is the size of partIds.

Added Parameters

There is a special case in UDPFunctionLibrary: two functions - DuplicateAlongLine and Duplic-


ateAroundAxis - have new integer listSize parameter added to their signatures.
This parameter defines the size of the output List. This is done for compliance with C++ geo-
metry library as the size of the List must be predefined and this size is different from the existing
parameter’s values.
Example:
(ret, cloneIDs) = funcLib.DuplicateAlongLine(partID, transVec,
numCubes, cloneIdsSize)
(ret, cloneIDs) = funcLib.DuplicateAroundAxis(partID, axis, angle,
nClones, cloneIdsSize)
Here cloneIdsSize is a new integer parameter.
Comparison with C function:

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,

Introduction to Scripting 1-43


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

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 *

Introduction to Scripting 1-44


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

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 *

Main class: UDPExtension

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()

l returns a list of UDPPrimitiveParameterDefinition2 or None on failure

Introduction to Scripting 1-45


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

AreParameterValuesValid2(errorMsg, udpParams)

l errorMsg is a c# list of strings


l udpParams is a c# list of UDPParam
l returns True if udpParams are valid, False otherwise.

CreatePrimitive2(funcLib, udpParams)

l funcLib is UDMFunction library


l udpParams is a c# list of UDPParam
l returns True on success, False on failure.

Optional methods

These methods, which have default implementations, can be implemented as methods of


UDPExtension class as needed. Default methods will return NULL or FALSE depending on the
return type.

GetPrimitiveParameters()

l returns Python list of strings or NULL

GetRegisteredFaceNames()

l returns Python list of strings or NULL

GetRegisteredEdgeNames()

l returns Python list of strings or NULL

GetRegisteredVertexNames()

l returns Python list of strings or NULL

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.

Introduction to Scripting 1-46


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

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.

Introduction to Scripting 1-47


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

from UDM import *


Main class: UDMExtension

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()

l returns UDMInfo object populated with appropriate UDM information.

IsAttachedToExternalEditor()

l returns True if UDM dll is attached to external editor.


l In case of python UDMs, this should typically return False

CreateInstance(funcLib)

l funcLib is UDMFunctionLibrary
l returns UDMParameters.

GetUnits(instanceId)

l instanceId is a long
l returns string containing units for the instance.

Refresh(funcLib, udmInParams, updatedParams, refreshModifiedPartsOnly,


nonEditedPartRefIds )
This Method is called every time a UDM is refreshed. Geometry creation/refresh should happen
in this method.
l funcLib is UDMFunctionLibrary
l udmInParams is a list of UDMParameters that comes from desktop

Introduction to Scripting 1-48


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

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.

returns True on success, False on failure.

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):

Introduction to Scripting 1-49


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

Replaces the old UDMDialogForDefinitionAndOptions method, which is still supported, but


users are urged to use UDMDialogForDefinitionOptionsAndParams. If both methods are
present, application will use UDMDialogForDefinitionOptionsAndParams.
l UDM can pop up dialog for UDM definition, options, parameters in this method. Definition,
options, and parameters are set/modified by user and returned to application. Dll can also
just give default definition, options and parameters.
l Returns two booleans and a string
l First boolean returns whether the method was successful or not.
l Second boolean returns whether the application should popup a dialog box. If it is True,
application will populate a dialog with definition, options, parameters that are returned.
l String returned contains length units for parameters.
DialogForDefinitionAndOptions(self, defData, optData) [Deprecated]
UDM can pop up dialog for UDM definition and options in this method. Definition, and options
are set/modified by user and returned to application. Dll can also just give default definition and
options.
l Returns two booleans.
l First boolean provides whether the call to this method was successful or not.
l Second boolean determines whether the application should pop up a dialog box. If this is
true, application will populate the dialog with the definitions and options that are returned.
As no parameters are returned, no parameters are shown in this dialog.
GetInstanceSourceInfo(instanceId)

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()

l returns true if any of definition files needs to be attached to project


l returns python list of string containing definition names of files or NULL
Example UDM

class UDMExtension(IUDMExtension):

def IsAttachedToExternalEditor(self):
return False

Introduction to Scripting 1-50


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

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)

(bret, udpPositionLow, udpPositionHigh) = udmFunc-


tionLibrary.GetBoundingBox(partId, exact);

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.

Introduction to Scripting 1-51


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

Functions list:

1. List_of_UDMDefinition: udmDefinitionList = GetDefinition()


2. List_of_UDMOption: udmOptionList = GetOptions()
3. bool: bret = SetMaterialName(string: matName, int: partId)
4. bool: bret = SetMaterialName2(string: matName, string: partName)
5. bool: bret = SetPartName(string: partName, int: partId)
6. int: iret = GetInstanceId()
7. string: str = GetPartRefId(int: partId)
8. bool: bret = SetPartRefId(int: partId, string: refId)
9. List_of_int: faceIds = GetAllFaces(int: partId)
10. List_of_int: edgeIds = GetAllEdges(int: partId)
11. List_of_int: vertexIds = GetAllVertices(int: partId)
12. bool: bret = SetFaceAttribs(List_of_int: faceIds, List_of_string: attribs)
13. bool: bret = SetEdgeAttribs(List_of_int: edgeIds, List_of_string: attribs)
14. bool: bret = SetVertexAttribs(List_of_int: vertexIds, List_of_string: attribs)
15. string: str = GetModelerUnit()
16. string: str = GetCacheFileForUDMResume()
17. bool: bret = SetPartColor(int: partId, int: nColor)
18. bool: bret = SetPartFlags(int: partId, int: nFlags)
19. (bool: bret, UDPPosition: low, UDPPosition: high) = GetBoundingBox(int: partId,
bool: exact)
20. bool: bret = IsParametricUpdate()
21. bool: bret = SetMaterialNameByRefId(string: partRefID, string: matName)
22. bool: bret = SetPartNameByRefId(string: partRefId, string: partName)
23. bool: bret = SetPartColorByRefId(string: partRefId, int: nColor)
24. bool: bret = SetPartFlagsByRefId(string: partRefId, int: nFlags)

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)

Introduction to Scripting 1-52


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

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:

1. bool: SI = AddMessage(MessageSeverity: messageSeverity, string: message)


2. bool: SI = NameAFace(UDPPosition: pointOnFace, string: faceName)
3. bool: SI = NameAEdge(UDPPosition: pointOnEdge, string: edgeName)
4. bool: SI = NameAVertex(UDPPosition: pointOnVertex, string: vertexName)
5. int: ID = GetFaceIDFromPosition(UDPPosition: pointOnFace)
6. int: ID = GetEdgeIDFromPosition(UDPPosition: pointOnEdge)
7. int: ID = CreatePolyline(UDPPolylineDefinition: polylineDefinition)
8. int: ID = CreateRectangle(CoordinateSystemPlane: whichPlane, UDPPosition: center-
Point, List_of_double: widthAndHeight, int: isCovered)
9. int: ID = CreateArc(CoordinateSystemPlane: whichPlane, UDPPosition: centerPoint,
UDPPosition: startPoint, double: fAngle)
10. int: ID = CreateCircle(CoordinateSystemPlane: whichPlane, UDPPosition: center-
Point, double: fRadius, int: isCovered)
11. int: ID = CreateEllipse(CoordinateSystemPlane: whichPlane, UDPPosition: center-
Point, double: fMajorRadius, double: fRadiusRatio, int: isCovered)
12. int: ID = CreateRegularPolygon(CoordinateSystemPlane: whichPlane, UDPPosition:
centerPoint, UDPPosition: startPoint, int: numOfSides, int: isCovered)
13. int: ID = CreateEquationBasedCurve(UDPEquationBasedCurveDefinition:
curveDefinition)
14. int: ID = CreateEquationBasedSurface(UDPEquationBasedSurfaceDefinition: sur-
faceDefinition)
15. int: ID = CreateSpiral(UDPSpiralDefinition: spiralDefinition)
16. int: ID = CreateBox(UDPPosition: startPoint, List_of_double: boxXYZsize)
17. int: ID = CreateSphere(UDPPosition: centerPoint, double: fRadius)
18. int: ID = CreateCylinder(CoordinateSystemAxis: whichAxis, UDPPosition: center-
Point, double: fRadius, double: fHeight)
19. int: ID = CreateCone(CoordinateSystemAxis: whichAxis, UDPPosition: centerPoint,
double: fBottomRadius, double: fTopRadius, double: fHeight)

Introduction to Scripting 1-53


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

20. int: ID = CreateTorus(CoordinateSystemAxis: whichAxis, UDPPosition: centerPoint,


double: fMajorRadius, double: fMinorRadius)
21. int: ID = CreatePolyhedron(CoordinateSystemAxis: whichAxis, UDPPosition: center-
Point, UDPPosition: startPosition, int: numOfSides, double: fHeight)
22. int: ID = CreateHelix(UDPHelixDefinition: helixDefinition)
23. bool: SI = Unite(List_of_int: pObjectIDArray)
24. bool: SI = Subtract(List_of_int: pBlankObjectIDArray, List_of_int: pToolObjectIDArray)
25. bool: SI = Intersect(List_of_int: pObjectIDArray)
26. bool: SI = Imprint(List_of_int: pBlankObjectIDArray, List_of_int: pToolObjectIDArray)
27. bool: SI = SweepAlongVector(int: profileID, UDPVector: sweepVector, UDPSweep-
Options: sweepOptions)
28. bool: SI = SweepAroundAxis(int: profileID, CoordinateSystemAxis: whichAxis,
double: sweepAngle, UDPSweepOptions: sweepOptions)
29. bool: SI = SweepAlongPath(int: profileID, int: pathID, UDPSweepOptions: sweep-
Options)
30. bool: SI = Translate(int: partID, UDPVector: translateVector)
31. bool: SI = Rotate(int: partID, CoordinateSystemAxis: whichAxis, double: rotateAngle)
32. bool: SI = Mirror(int: partID, UDPPosition: mirrorPlaneBasePosition, UDPVector: mir-
rorPlaneNormalVector)
33. bool: SI = Transform(int: partID, List_of_double: rotationMatrix, UDPVector: trans-
lateVector)
34. bool: SI = Scale(int: partID, double: xScale, doublev: yScale, double: zScale)
35. (bool: SI, List_of_int: cloneIDs) = DuplicateAlongLine(int: partID, UDPVector: trans-
lateVector, int: numTotalObjs, int: cloneIDsListSize)
36. (bool: SI, List_of_int: cloneIDs) = DuplicateAroundAxis(int: partID, Coordin-
ateSystemAxis: whichAxis, double: rotateAngle, int: numTotalObjs, int: cloneIDsListS-
ize)
37. int: ID = DuplicateAndMirror(int: partID, UDPPosition: mirrorPlaneBasePosition,
UDPVector: mirrorPlaneNormalVector)
38. bool: SI = Connect(List_of_int: objectIDArray)
39. bool: SI = Offset(int: partID, double: offsetDistance)
40. int: ID? = Section(int: partID, CoordinateSystemPlane: sectionPlane)
41. (bool: SI , int: ID) = Split(int: partID, CoordinateSystemPlane: splitPlane,
SplitWhichSideToKeep: whichSideToKeep, bool: bSplitCrossingObjectsOnly)

Introduction to Scripting 1-54


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

42. (bool: SI , List_of_int: importedObjectIDs) = ImportNativeBody2(string:


fileNameWithFullPath)
43. (bool: SI, List_of_int: importedObjectIDs) = ImportAnsoftGeometry(string:
fileNameWithFullPath, List_of_string: overridingParamsNameArray, List_of_
UDPParam: overridingParamsArray)
44. int:ID = Clone(int: partID)
45. bool: SI = DeletePart(int: partID)
46. int: ID = CreateObjectFromFace(int: faceID)
47. bool: SI = Fillet(UDPBLNDElements: entitiesToFillet, UDPBLNDFilletOptions: fil-
letOptions)
48. bool: SI = Chamfer(UDPBLNDElements: entitiesToChamfer, UDPBLNDCham-
ferOptions: chamferOptions)
49. (bool: SI, List_of_int: newPartIDs) = DetachFaces(int: newPartIDArraySize, List_of_
int: faceIDs)
50. (bool: SI, List_of_int: newPartIDs) = DetachEdges(int: newPartIDArraySize, List_of_
int: edgeIDs)
51. int: ID = CreateObjectFromEdge(int: edgeID)
52. bool: SI = SheetThicken(int: partID, double: fThickness, bool: bThickenBothSides)
53. (bool: SI , List_of_int: newPartIDArray) = SweepFaceAlongNormal(int: newPartIDAr-
raySize, List_of_int: faceIDArray, double: sweepLength)
54. bool: SI = CoverLine(int: partID)
55. bool: SI = CoverSurface(int: partID)
56. bool:SI= UncoverFaces(List_of_int: faceIDArray)
57. (bool: SI , int: numPartsCreated, List_of_int: faceIDArray) = SeparateBodies(int:
partID, int: numPartsCreated)
58. bool: SI = MoveFaces(List_of_int: faceIDArray, bool: bMoveAlongNormal, double: fOff-
setDistance, UDPVector: moveVector)
59. bool: SI = WrapSheet(int: sheetBodyID, int: targetBodyID)
60. bool: SI = ImprintProjection(int: blankBodyID, List_of_int: toolBodyIDArray, bool:
bNormalProjection, UDPVector: projectDirection, double: projectDistance)
61. string: path = GetTempDirPath()
62. string: path = GetSysLibDirPath()
63. string: path = GetUserLibDirPath()
64. string: path = GetPersonalLibDirPath()

Introduction to Scripting 1-55


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

65. string: path = GetInstallDirPath()


66. string: path = GetProjectPath()
67. (bool: SI, bool: abort) = SetProgress(UDPProgress: progress)

UDP/UDM Structures and Constants


The following sections describe:
l UDP/UDM Structures
l UDP/UDM Constants

UDP/UDM Structures

Differences compared to C API


l UDMDefinition
l UDMOptions
l UDMParameters

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.

Example (creating UDMParameter list):

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),

Introduction to Scripting 1-56


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

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:

nCubesParam = UDPParam(ParamDataType.Int, numCubes)

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:

rotationMatrix =[0,0,1, 1,0,0, 0,0,1]

udpFunctionLib.Transform(partId, rotationMatrix, trans-


lationVector)

List of structures

You can use constructors to create a structure. You can also modify fields - directly or by
provided methods.
Example:

Introduction to Scripting 1-57


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

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

Structure Construction Members


UDPPrimitiveTypeInfo UDPPrimitiveTypeInfo( string Name
string name, string Purpose
string purpose, string Company
string company, string Date
string date, string Version
string version)
UDPPrim- UDPPrim- string Name
itiveParameterDefinition itiveParameterDefinition(
string Description
string name,
UnitType UnitType
string description,
double DefaultValue
UnitType unitType,
double defaultValue)
UDPParam UDPParam() ParamDataType DataType
object Data
UDPParam( object can be int, double , string,
bool or UDPPosition
ParamDataType dataType,
object data)
object can be int, double,
string, bool or UDPPosition

methods:
setInt(int val)
setBool(bool val)
setString(string val)
setDouble(double val)

Introduction to Scripting 1-58


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

Structure Construction Members


setPosition(UDPPosition
val)

UDPPrim- UDPPrim- string Name


itiveParameterDefinition2 itiveParameterDefinition2(
string Description
string name,
UnitType UnitType
string description,
ParamPropType PropType
UnitType unitType,
ParamPropFlag PropFlag
ParamPropType propType,
UDPParam DefaultValue
ParamPropFlag propFlag,
UDPParam defaultValue)
UDPPosition UDPPosition( double X
double x, double Y
double y, double Z
double z)
UDPVector UDPVector( double X
double x, double Y
double y, double Z
double z)
UDPSweepOptions UDPSweepOptions( SweepDraftType DraftType
SweepDraftType draftType, double DraftAngle
double draftAngle, double TwistAngle
double twistAngle)
UDPPolylineSeg- UDPPolylineSeg- PolylineSegmentType Seg-
mentDefinition mentDefinition( mentType
PolylineSegmentType seg- int segmentStartIndex,
mentType,
int numberOfPoints,
int segmentStartIndex,
double angle,
int numberOfPoints,
UDPPosition centerPoint,
double angle,
CoordinateSystemPlane
UDPPosition centerPoint, arcPlane)

Introduction to Scripting 1-59


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

Structure Construction Members


CoordinateSystemPlane
arcPlane)
UDPPolylineDefinition UDPPolylineDefinition() int IsClosed
UDPPolylineDefinition( int IsCovered
List_of_UDPPosition pos- List_of_UDPPosition ArrayOfPos-
itions, ition
List_of_UDPPolylineSeg- List_of_UDPPolylineSeg-
mentDefinition segDefs, mentDefinition ArrayOfSeg-
mentDefinition
int closed,
int covered)
UDPEqua- UDPEqua- string FunctionXt
tionBasedCurveDefinition tionBasedCurveDefinition(
string FunctionYt
string functionXt,
string FunctionZt
string functionYt,
double TStart
string functionZt,
double TEnd
double tStart,
int NumOfPointsOnCurve
double tEnd,
int numOfPointsOnCurve)
UDPEqua- UDPEqua- string FunctionXuv
tionBasedSurfaceDefinition tionBasedSurfaceDefinition(
string FunctionYuv
string functionXuv,
string FunctionZuv
string functionYuv,
double UStart
string functionZuv,
double UEnd
double uStart,
double VStart
double uEnd,
double VEnd
double vStart,
two integer arguments that are
double vEnd reserved for future use. They need
to be provided, for example as 0.
int reserved1 For example:
int reserved2) theSurfaceDefinition =
UDPEqua-
tionBasedSur-
faceDefinition
("u","v","1",0,1,0,1,0,0)

Introduction to Scripting 1-60


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

Structure Construction Members


UDPHelixDefinition UDPHelixDefinition( int ProfileID
int profileID, UDPPosition PtOnAxis
UDPPosition ptOnAxis, UDPPosition AxisDir
UDPPosition axisDir, double NoOfTurns
double noOfTurns, bool IsRightHanded
bool isRightHanded, double RadiusChangePerTurn
double radi- double Pitch
usChangePerTurn,
double pitch)
UDPSpiralDefinition UDPSpiralDefinition( int ProfileID
int profileID, UDPPosition PtOnAxis
UDPPosition ptOnAxis, UDPPosition AxisDir
UDPPosition axisDir, double NoOfTurns
double noOfTurns, bool IsRightHanded
bool isRightHanded, double RadiusChangePerTurn
double radi-
usChangePerTurn)
UDPBLNDElements UDPBLNDElements( UDPBLNDElements can hold
either edges or vertices, but not
int partID, both at the same time. Edges
int noOfEdges; should be applied to solids, and
vertices should be applied to
int* listOfEdges; ) sheets.
int PartID /* part to be blended i.e.
filleted/chamfered */
UDPBLNDElements(
int noOfEdges;
int partID,
int* listOfEdges; /* edges to be
int noOfVertices; blended */
int* listOfVertices; int noOfVertices;
) int* listOfVertices; /* vertices to be
blended */

UDPBLNDFilletOptions UDPBLNDFilletOptions( bool SupressFillet /* Reserved for


future */

Introduction to Scripting 1-61


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

Structure Construction Members


bool supressFillet, BLNDFilletRadiusLaw Fil-
letRadiusLaw
BLNDFilletRadiusLaw fil-
letRadiusLaw, double FilletStartRadius
double filletStartRadius, double FilletEndRadius
double filletEndRadius, bool Fol-
lowSmoothEdgeSequence /*
bool fol- Reserved for future */
lowSmoothEdgeSequence,
BLNDFilletType FilletType
BLNDFilletType filletType,
double SetbackDistance
double setbackDistance,
double BulgeFactor /* Reserved
double bulgeFactor) for future */
UDPBLNDChamferOptions UDPBLNDChamferOptions( bool SupressChamfer
bool supressChamfer, BLNDChamferRangeLaw Cham-
ferRangeLaw
BLNDChamferRangeLaw
chamferRangeLaw, double ChamferLeftRange
double chamferLeftRange, double ChamferRightRange
double chamferRightRange)
UDPProgress UDPProgress( int Prog
int prog, int SubProg
int subProg, string Mesg
string mesg, string SubMesg
string subMesg)
UDMInfo UDMInfo( string Name
string name, string Purpose
string purpose, string Company
string company, string Date
string date, string Version
string version)
UDMDefinition UDMDefinition() string DefName
UDPParam DefValue
UDMDefinition( ParamPropType PropType
string name, ParamPropFlag PropFlag

Introduction to Scripting 1-62


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

Structure Construction Members


UDParam value,
ParamPropType propType,
ParamPropFlag propFlag)
UDMOption UDMOption() string OptName
UDPParam OptValue
UDMOption( ParamPropType PropType
string name, ParamPropFlag PropFlag
UDParam value,
ParamPropType propType,
ParamPropFlag propFlag)
UDMParameter UDMParameter() string ParamName
UDPParam ParamValue
UDMParameter( UnitType UnitType
string name, ParamPropType PropType
UDParam value, ParamPropFlag PropFlag
UnitType unitType,
ParamPropType propType,
ParamPropFlag propFlag)

UDP/UDM Constants

Full names of enum constants must be used in scripts.


Example:
unitType = UnitType.LengthUnit
dataType = ParamDataType.Int
Enum constants:

enum Constant Parameters


UnitType NoUnit
LengthUnit
AngleUnit
ParamDataType Int

Introduction to Scripting 1-63


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

enum Constant Parameters


Double
String
Bool
Position
Unknown
ParamPropType Text
Menu
Number
Value
FileName
Checkbox
Position
Unknown
ParamPropFlag NoFlag
ReadOnly
MustBeInt
MustBeReal
Hidden
Unknown
CoordinateSystemAxis XAxis
YAxis
ZAxis
CoordinateSystemPlane XYPlane
YZPlane
ZXPlane
SweepDraftType ExtendedDraft
RoundDraft
NaturalDraft
MixedDraft
SplitWhichSideToKeep SplitKeepBoth

Introduction to Scripting 1-64


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

enum Constant Parameters


SplitKeepPositiveOnly
SplitKeepNegativeOnly
PolylineSegmentType LineSegment
ArcSegment
SplineSegment
AngularArcSegment
MessageSeverity WarningMessage
ErrorMessage
InfoMessage
IncompleteMessage
FatalMessage
BLNDFilletRadiusLaw BLNDConstantRadius
BLNDVariableRadius
BLNDFilletType BLNDRound /* The outward surface of the fillet is curved.*/
BLNDMitered /* The outward surface of the fillet is flat and cut at an
angle.*/
BLNDChamferRangeLaw BLNDConstantRange
BLNDVariableRange
PartPropertyFlags PropNonModel
PropDisplayWireFrame
PropReadOnly
PostprocessingGeometry
PropInvisible
PropShowDirection
PropDummy

UDP Python Example


This Python script example demonstrates how to use the UDPBLNDElements structure and the
UDP chamfer and fillet functions.
import sys
primitive_info = UDPPrimitiveTypeInfo(
name="Fillet_Chamfer",

Introduction to Scripting 1-65


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

purpose="Fillet Chamfer Example",


company="Ansys",
date="09/11/2020",
version="1.0")
primitive_param_definitions = [
UDPPrimitiveParameterDefinition2(
"x_size",
"",
UnitType.LengthUnit,
ParamPropType.Value,
ParamPropFlag.MustBeReal,
UDPParam(ParamDataType.Double, 10)),
UDPPrimitiveParameterDefinition2(
"y_size",
"",
UnitType.LengthUnit,
ParamPropType.Value,
ParamPropFlag.MustBeReal,
UDPParam(ParamDataType.Double, 5)),
UDPPrimitiveParameterDefinition2(
"z_size",
"",
UnitType.LengthUnit,
ParamPropType.Value,
ParamPropFlag.MustBeReal,
UDPParam(ParamDataType.Double, 2))
]
length_units = "mm"

##############################################################

Introduction to Scripting 1-66


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

# 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"]
])

# points on the middle of 4 vertical edges


points = [
[0, 0, param_dict["z_size"]/2],
[param_dict["x_size"], 0, param_dict["z_size"]/2],
[param_dict["x_size"], param_dict["y_size"], param_dict
["z_size"]/2],s
[0, param_dict["y_size"], param_dict["z_size"]/2]
]

Introduction to Scripting 1-67


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

edges = [func_lib.GetEdgeIDFromPosition(UDPPosition(point
[0], point[1], point[2])) for point in points]

fillet_rad = 0.1 * param_dict["x_size"] # 10% of X size


fillet_opt = UDPBLNDFilletOptions(True, BLNDFil-
letRadiusLaw.BLNDConstantRadius, fillet_rad, 0.0, True, BLNDFil-
letType.BLNDRound, 0.0, 0.0)

chamfer_length = 0.1 * param_dict["x_size"] # 10% of X size


chamfer_opt = UDPBLNDChamferOptions(False, BLNDCham-
ferRangeLaw.BLNDConstantRange, chamfer_length, 0.0)

# select your geometry to which to apply operations


blend_element = UDPBLNDElements(box)

# specify attribute ListOfEdges to which edges to apply fil-


let operation
blend_element.ListOfEdges = edges[0:2]
func_lib.Fillet(blend_element, fillet_opt)

# redeclare attribute ListOfEdges to which edges to apply


chamfer operation
blend_element = UDPBLNDElements(box)
blend_element.ListOfEdges = edges[2:4]
func_lib.Chamfer(blend_element, chamfer_opt)

# Provide to the user Info message indicating success


func_lib.AddMessage(MessageSeverity.InfoMessage, "Com-
pleted!")

def GetPrimitiveTypeInfo(self):
return primitive_info

Introduction to Scripting 1-68


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

def GetLengthParameterUnits(self):
return length_units

def GetPrimitiveParametersDefinition2(self):
return primitive_param_definitions

def AreParameterValuesValid2(self, error, udp_params):


return True

# 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

def get_param_dict(self, param_values):


"""
Function to return a dictionary of UDP parameter name and
value (key: value) pairs
:param param_values: list of udp parameter values (user
input) generated by UDP Core
:return: dict of parameter name and values

Introduction to Scripting 1-69


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

"""
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:

(Supported on both Windows and Linux in 24R1)

Launching Ansys Electronics Desktop on a remote machine is not supported in this


release. Initialize() will connect to a remote instance that is already running on the
remote machine, but cannot launch a new instance on the remote machine.

Connect() to an opened project in remote machine needs to use a share network path.

Creating an External Script


While the same as IronPython when run externally, a CPython recorded script must be modified
by adding the following lines to the beginning of your script before import ScriptEnv
import sys

Introduction to Scripting 1-70


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

# Imports the sys module containing system-specific func-


tions native to Python.
sys.path.append(r"<InstallationPath>/PythonFiles/DesktopPlugin")
# Adds the PythonFiles/DesktopPlugin subfolder to the list
of directories Python searches for modules and files.
Those lines are followed by:
import ScriptEnv
# This imports ScriptEnv.py from the installation path spe-
cified above.
Follow that with:
l Either InitializeNew() or Initialize(), as described below.
l Any desired Electronics Desktop scripting commands.
l Closing command, as described below.

Start ansysedt as GRPC server


But default ansysedt process will be started as GRPC server. When there is no argument
provided ansysedt.exe it start listening on the first available port from 50051.
-grpcsrv Flag
ansysedt -grpcsrv <optional port number or port range>.
ansysedt –grpcsrv
If no Port Number specified, same as the default like no grpcsrv flag
ansysedt –grpcsrv portNumber
ansysedt process will be listening on the port number, but report error as the port is used
by other application.
ansysedt –grpcsrv FirstPortNumber:LastPortNumber
ansysedt process will be listening on the first available port within the port range, but
report error if all ports in the range used.
ansysedt –grpcsrv FirstPortNumber:NumberOfPorts
ansysedt process will be listening on the first available port within the port range, but
report error if all ports in the range used.
Note: If the last number if smaller than the first number the last number will be treated as the
number of ports. (50051: 50250 has the same range as 50051:200)

Introduction to Scripting 1-71


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

Connect Functions:
1. Connect(projectPath)

a. Connect to the opened project.


b. Launch ansysedt.exe, open the project, then connect to it.
c. Error if the project does not exist.
2. Connect(portNumber) Connect to running ansysedt process in the local machine. Error if
no ansysedt process listening on this port.
3. Connect(machine, projectPath) connect to an open project in remote Machine. pro-
jectPath must be a network path. Error if no ansysedt process opened the project.
4. Connect(machine, portNumber) connect to a running ansysedt process on the remote
machine. Error if no ansysedt process listening on this port.

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())

Launching Electronics Desktop


To launch a new instance of Electronics Desktop and connect oApplication and oDesktop to it:
InitializeNew(NonGraphical = <True|False>, Module = None, Machine
= "", Port = <Port#>)
Where:
l NonGraphical – Specifies whether to launch Electronics Desktop in non-graphical mode.
l Module – Behavior remains unchanged from Iron Python and should be left defaulted to
"None." See the code in ScriptEnv.py for more details.
l Machine – Currently an empty string, as InitializeNew() will only launch Electronics
Desktop on the current machine.
l Port – Electronics Desktop will launch using the first unused port it finds starting at
<Port#>. If Port = 0, the starting port will be 50051.

Introduction to Scripting 1-72


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

Note:

InitializeNew() will always launch a new instance of Electronics Desktop. Please use Ini-
tialize() to connect to an existing instance. See below.

Connecting with a Running Instance of Electronics Desktop


To connect oApplication and oDesktop to an existing Electronics Desktop instance, or launch a
new instance and connect to it if necessary:
Initialize(name, NG = <True|False>, machine = "", port = <Port#>)
Where:
l Name – Ignored.
l NG – If launch is necessary, specifies whether to launch Electronics Desktop in non-graph-
ical mode.
l Machine – The machine on which to launch/connect. For current machine, pass empty
string or use localhost.
l Port – If port is nonzero, the script tries to connect to an existing instance on <port#> run-
ning on <machine>. If there is no instance running on that <port>, a new instance of Elec-
tronics Desktop launches on that port and then connects to it. If port = 0, the new instance
is launched on the first free port, starting at 50051.

Closing Electronics Desktop/Ending the Script


To close Electronics Desktop, add the following line to the end of the script:
ScriptEnv.Shutdown()
# This stops ScriptEnv.py. If you are running multiple
scripts, include this only at the end of the last script.

-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.

Introduction to Scripting 1-73


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

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:

Standalone Scripting in Iron Python

Ansys Electronics Desktop Scripting


This chapter provides an overview of scripting in Ansys Electronics Desktop.
Overview of Ansys Electronics Desktop Scripting Objects
Running a Script
Recording a Script
Working with Project Scripts
Executing a Script from Within a Script
Ansys Electronics Desktop Scripting Conventions
Overview of Electronics Desktop Scripting Objects
When you record a script using Ansys Electronics Desktop, the beginning of the script must con-
tain some standard commands, as illustrated in the following chart. The commands in the chart
define the objects used by Electronics Desktop in the script and assign values to these objects.
The objects are used in the hierarchical order shown.

Introduction to Scripting 1-74


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

The commands are described below, followed by examples.


oAnsoftApp
The oAnsoftApp object provides a handle for Iron Python or VBscript to access the
Ansoft.ElectronicsDesktop product.
In Iron Python, for example:
oAnsoftApp = CreateObject('Ansoft.ElectronicsDesktop')
In VBscript, for example:
Set oAnsoftApp = CreateObject("Ansoft.ElectronicsDesktop")
oDesktop
The oDesktop object is used to perform desktop-level operations, including project man-
agement.
In Iron Python, for example:
oDesktop = oAnsoftApp.GetAppDesktop()
In VBscript, for example:
Set oDesktop = oAnsoftApp.GetAppDesktop()

Introduction to Scripting 1-75


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

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:

Introduction to Scripting 1-76


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

l 3D Modeler Editor Script Commands


l Schematic Editor Script Commands

Important:

There is no Reporter Editor object for oEditor. Reporter Editor commands are
executed by oDesign.

See: Reporter Editor Script Commands.

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

Example Script Opening


Combining the above objects, a script in Iron Python could begin like the following:
oAnsoftApp = CreateObject("Ansoft.ElectronicsDesktop")
oDesktop = oAnsoftApp.GetAppDesktop()
oProject = oDesktop.SetActiveProject("Project1")
oDesign = oProject.SetActiveDesign("Design1")
oEditor = oDesign.SetActiveEditor("3D Modeler")
oModule = oDesign.GetModule("BoundarySetup")

Introduction to Scripting 1-77


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

In VBscript, this would be:


Dim oAnsoftApp
Dim oDesktop
Dim oProject
Dim oDesign
Dim oEditor
Dim oModule
Set oAnsoftApp = CreateObject("Ansoft.ElectronicsDesktop")
Set oDesktop = oAnsoftApp.GetAppDesktop()
Set oProject = oDesktop.SetActiveProject("Project1")
Set oDesign = oProject.SetActiveDesign("Design1")
Set oEditor = oDesign.SetActiveEditor("3D Modeler")
Set oModule = oDesign.GetModule("BoundarySetup")
GetActiveProject and GetActiveDesign for Wider Use
The sample script above only works for "Design1" within "Project1". To create a script that is
usable for any open project, you can use one or both of GetActiveProject and GetAct-
iveDesign.
In IronPython:
oProject = oDesktop.GetActiveProject()
oDesign = oProject.GetActiveDesign()
In VBscript:
Set oProject = oDesktop.GetActiveProject()
Set oDesign = oProject.GetActiveDesign()
Running a Script
Electronics Desktop scripts can be run from within the software or from the command line.
Within Electronics Desktop
To run scripts in Electronics Desktop:

Introduction to Scripting 1-78


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. Click Tools > Run Script, or select the Automation tab and click the Run Script icon:

The Run Script file browser appears.

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.

Electronics Desktop executes the script.

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.

From the Command Line


To run a script from a command line, add the -runscriptandexit or -runscript argument
to the Electronics Desktop command line syntax.
To use script arguments, add the -scriptargs parameter and specify the arguments. For
example:
ansysedt.exe -scriptargs "hello there"

Introduction to Scripting 1-79


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

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.

Introduction to Scripting 1-80


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

Important:

When you record a script, every subsequent action you take is recorded. You must
manually stop recording.

Recording a Script to File


To record a script to file:

1. Click Tools > Record Script to File, or select the Automation tab and click the Record
Script icon:

A Save As file browser appears.

2. Navigate to the location where you want to save the script.


3. In the File Name field, type a name for the script file.
4. Use the Save as Type drop-down menu to select either IronPython or VBscript.
5. Click Save.

The Record Script button transforms into a Stop Recording button, and Electronics
Desktop begins recording your actions.

6. Perform the steps you want to record.


7. When you have finished recording the script, click Stop Recording, or select Tools >
Stop Script Recording.

The recorded script is saved to the folder you specified.

Recording a Script to a Project

Introduction to Scripting 1-81


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

To record a script to a project:

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.

The Save Script to Project dialog box appears:

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.

Working with Project Scripts


Scripts can be recorded to a project.
Once a script has been recorded to the project, you can manage it in the Project Manager from
the Definitions folder:

Introduction to Scripting 1-82


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

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.

Executing a Script from Within a Script


Electronics Desktop provides a script command that enables you to launch another script from
within the script that is being executed.
In IronPython:
oDesktop.RunScript(<ScriptName>)
In VBscript:
oDesktop.RunScript <ScriptName>

Introduction to Scripting 1-83


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

If the full path to the script is not specified, Electronics Desktop searches for the specified script
in the following locations, in order:

1. Personal Library Directory (PersonalLib)


2. User Library Directory (UserLib)
3. System Library Directory (SysLib)
4. Installation Directory

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:

1. Named data, where name precedes data.

For example:

..., "SolveInside:=", true, ...

2. Named Array, where name precedes array.

For example:

..., "Attributes:=", Array(...),...

3. Named Array, where name is inside an array.

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.

Introduction to Scripting 1-84


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

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"

Introduction to Scripting 1-85


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

],
"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:

oModule.EditVoltage "Voltage1", Array("NAME:Voltage1",


"Voltage:=", 3.5)

l Pass in a string containing the number with units.

In IronPython:

oModule.EditVoltage('Voltage1', ['NAME:Voltage1',
'Voltage:=', '3.5V'])

Introduction to Scripting 1-86


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

In VBscript:

oModule.EditVoltage "Voltage1", Array("NAME:Voltage1",


"Voltage:=", "3.5V" )

l Pass in a variable name.

In IronPython:

var = 3.5

oModule.EditVoltage('Voltage1', ['NAME:Voltage1',
'Voltage:=', var]

In VBscript:

dim var

var = "3.5V"

oModule.EditVoltage "Voltage1", Array("NAME:Voltage1",


"Voltage:=", var)

Event Callback Scripting


Event Callback scripting allows you to define custom JavaScript and VBScript routines that will
run automatically after detecting a triggering event, such as placing a component or running a
simulation. When defining an Event Callback script, specify one or more scripts that will be run
after a particular event is detected.
A callback script can only access functions and other scripts defined by its callback definition.
For example, a Simplorer callback script can call PropHost.GetValue — and all other PropHost
functions — but only from scripts defined in the Property Dialog callback. As a result, "PropHost"
is a Simplorer script item that is only visible in "Property" callback scripts. For more information,
see Callback Scripting Using PropHost Object and Callback Scripting Using CompInstance
Object.
The following table lists allowable callback events, items that are visible from the associated call-
back script, and the set of accessible functions that can be called.

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.

CompInstance.GetPropserverName() – Returns a Com-

Introduction to Scripting 1-87


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

pInstance identification name that can be used in oEditor prop-


erty-method scripts, such as GetPropertyValue(), SetProp-
ertyValue(), etc.

CompInstance.GetComponentName() — Returns the com-


ponent name, e.g. "MS_TRL".
Simulate CompInstance CompInstance.GetDesign() — Returns the interface to the spe-
Component cified design simulation.

CompInstance.GetProgress() – Returns the completion per-


centage (from 0 to 100) of the specified design simulation.

CompInstance.GetRunStatus() — Returns the status number


of the specified design simulation.

CompInstance.Abort() — Aborts the specified design sim-


ulation.

The function, ExecuteAnsoftScript(<ScriptName>), searches the configured Ansys Elec-


tronics Desktop script libraries by name for the script passed to it, and invokes the found
ScriptName. The invoked script will run with the same set of visible script items as the originally
called script. That is, CompInstance is visible from the invoked sub-script, ScriptName, and
CompInstance’s functions can be called from ScriptName.

Introduction to Scripting 1-88


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

2 - Object-Oriented Property Scripting


Object-oriented scripting enhances scripting in AEDT by allowing object-oriented access to retrieve or modify object properties. The
primary gain is the ease with which properties of various existing objects in an AEDT project or design can be read, modified, and set.
This feature also allows for much less code to be written to access object properties and enables much more readable code for users,
avoiding complex array input.
This topic covers the following:
l Logic/syntax
l Basic attributes of project and design properties
l Example Scripts

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.

Object Oriented Property Scripting 2-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

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:

Object Oriented Property Scripting 2-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

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:

Object Oriented Property Scripting 2-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

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:

Object Oriented Property Scripting 2-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

Object Oriented Property Scripting 2-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

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:

Object Oriented Property Scripting 2-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

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:

Object Oriented Property Scripting 2-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

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:

Object Oriented Property Scripting 2-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

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.

Material Properties and Examples


This section discusses the material properties and how to access and modify them. Because materials are globally defined, the
objects are children of the Project, oProject, as shown below:

Object Oriented Property Scripting 2-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

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:

Object Oriented Property Scripting 2-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

To change the conductivity, use the SetPropValue() function as shown below:

Body Properties and Modification


The following example shows how to retrieve the properties of a Body in the model, in this case a Region object. Once you identity the
desired property, you can modify it as needed.

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.:

Object Oriented Property Scripting 2-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

Retrieve Datasets and Values


The GetChildObject, GetChildTypes and GetChildNames functions operate on the oDesktop objects. This allows you to retrieve and
view datasets and values. The dataset script wrapper store all values internally in SI units, and converts them back to user-supplied
units when you request non-SI property values.For example, if you assigned a dataset to the example OptimTee project in HFSS, you
could use these functions in the command window:
>>>oDesktop.GetChildTypes()
['Projects']
>>>oDesktop.GetChildNames()
['OptimTee']
>>>arrProjectNames = oDesktop.GetChildNames()
>>>tp = oDesktop.GetChildObject('OptimTee')
>>>tp.GetChildTypes()

Object Oriented Property Scripting 2-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

['Design', 'Project Data']


>>>tp.GetChildNames('Project Data')
['Variables', 'Materials', 'Surface Materials', 'Datasets']
>>>ds = tp.GetChildObject('datasets')
>>>ds.GetChildNames()
['$ds1']
>>>ds1=ds.GetChildObject('$ds1')
>>>ds1.GetPropValue('[:,:]')
[[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]
>>>ds1.GetPropSIValue()
[[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]
>>>ds1.DimUnits
>>>ds1.DimUnits = ['mm','mm']
>>>ds1.DimUnits
['mm', 'mm']
>>>ds1.GetPropSIValue()
[[0.001, 0.0040000000000000001], [0.002, 0.0050000000000000001], [0.0030000000000000001,
0.0060000000000000001]]
>>>ds1.GetPropValue('[:,:]')
[[1.0, 4.0], [2.0, 5.0], [3.0, 6.0]]

Object Oriented Property Scripting 2-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

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

Object Oriented Property Scripting 2-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

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

For example, a Mechanical design object has these children.


>>> design.GetChildNames()
['Boundaries', 'Excitations', 'Optimetrics', 'Results', '3D Modeler']
Four of the children are of “Module” type

Object Oriented Property Scripting 2-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

>>> 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']

Object Oriented Property Scripting 2-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

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()

Object Oriented Property Scripting 2-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

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

Additional Details Specific to AEDT Solvers


“3D Modeler” of 3D products and “Machine” of RMxprt are exposed as “Editor” type children of a design script object.
“Variables” and “Design Settings” are exposed as “Design Data” type children of a design script object.
The following “Module” types are exposed as “Module” type children of a design script object.
HFSS
l Boundaries, Excitations, Circuit Elements, Hybrid Regions, Analysis, Radiation, Field Overlays, Optimetrics, Results

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

Object Oriented Property Scripting 2-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

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

Object Oriented Property Scripting 2-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

Additional details on Boundaries/Excitations


Each design type presents its boundaries/excitations data in the project tree as different groups. For example, an HFSS design has
Boundaries, Excitations, Circuit Elements and Hybrid Regions while a Icepak design has just a “Thermal” project tree folder.
These module script objects do not have properties
>>> project.GetChildObject("icepak/thermal").GetPropNames()
[]
GetChildTypes of these module script objects returns the types of its immediate children
>>> d = p.GetChildObject("q2d")
>>> d.GetChildObject("conductors").GetChildTypes()
['NonIdealGround', 'SignalLine']
GetChildNames of these module object returns its immediate children
>>> p.GetChildObject("icepak/thermal").GetChildNames()
['Source1', 'Resistance1', 'ConductingPlate1', 'Source2', 'Resistance2', 'ConductingPlate2',
'Source3', 'Resistance3', 'ConductingPlate3']
GetChildNames can be invoked with a “type” and the returns will be filtered by that given type.
>>> p.GetChildObject("icepak/thermal").GetChildNames("resistance")
['Resistance1', 'Resistance2', 'Resistance3']
Children of a module object are scriptable objects and have properties.
>>> port = p.GetChildObject("hfss/excitations/1")
>>> port.GetPropNames(False)
['Name', 'Deembed', 'Deembed Dist', 'Renorm All Terminals']

Object Oriented Property Scripting 2-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

You can query/edit these properties


>>> port.GetPropValue("deembed")
False
>>> port.SetPropValue("deembed", True)
True
>>> port.GetPropValue("deembed")
True
A boundary/excitation script object can also have children. For example, HFSS terminal is a child of its port. Q3D source/sink can be
children of a net.
>>> port.GetChildNames()
['Box1_T1']
>>> port.GetChildTypes()
['Terminal']
>>> p.GetChildObject("q3d/nets/s2").GetChildNames()
['Source2', 'Sink2']
>>> p.GetChildObject("q3d/nets/s2").GetChildTypes()
['Sink', 'Source']

3D component encapsulation
These script interfaces are compliant with encapsulation. For example,

Object Oriented Property Scripting 2-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

l Design.GetChildObject(“boundaries”).GetChildNames() will not return component boundaries


l SetPropValues of component excitations can only be used to edit post processing settings such as 'Deembed', 'Deembed Dist'
of a HFSS port.

Additional details on Solve setup


All solve setups are children of the “Analysis” script object. This parent script object is also of the type “Module”.
>>> d = oDesktop.GetActiveProject().GetChildObject("hfss")
>>> d.GetChildNames()
['Boundaries', 'Excitations', 'Hybrid Regions', 'Circuit Elements', 'Analysis', 'Opti-
metrics', 'RadField', 'Results', '3D Modeler']
>>> setups = d.GetChildObject("analysis")
This module script object has no property
>>> setups.GetPropNames()
[]
The children of this module script object in a 3D design is not categorized into different types because the solve setup type is one-to-
one to the solution type of a 3D design.
>>> setups.GetChildTypes()
[]
The children of this module script object in a 3DLayout and Simplorer/TwinBuilder design is categorized into different solve setup
types, such as “Transient”, “AC” and “DC” in a Simplorer/TwinBuilder design and “HFSS”, “PlanarEM”, “SIwave” in a 3D layout design.
A solve setup script object can also have children. Children are typically frequency sweeps.
>>> setup.GetChildNames()

Object Oriented Property Scripting 2-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

['Sweep', 'Sweep1', 'Sweep2']


>>> setup.GetChildTypes()
['Discrete', 'Interpolating']
>>> sweep1 = setup.GetChildObject("sweep")

Related Topics
Example: GetPropNames and GetPropValues for Layered Impedance Boundary Script

Materials Scripting Support


Supported material properties are shown in a Property window for the material item.

Object Oriented Property Scripting 2-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

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.

Object Oriented Property Scripting 2-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

Object Oriented Property Scripting 2-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

With this feature enabled you can then:


l Get/Set Simple material property
l Get/Set Anisotropic material property
l Get/Set Nonlinear material property
l Get/Set Vector material property
l Components hide/shown as needed
l Get/Set Tensor material property
l Get/Set Choice material property
l AddDefinitionFromBlock
l AddDefiniitonFromLibFile
l GetExtendedDefinitionObect

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.

Object Oriented Property Scripting 2-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

What is not supported:


l Change of property type
l Custom material property, due to its complexity

Object Oriented Scripting for Materials


Materials are Child objects of the Active Project. In the IronPython command window, you can execute GetPropNames() for a spe-
cified material as follows:
>>> omats = oDesktop.GetActiveProject().GetChildObject("Materials")
>>> omat = omats.GetChildObject("vacuum")
>>> omat.GetPropNames()
['Coordinate System Type', 'Coordinate System Type/Choices', 'Relative Permeability Type',
'Relative Permeability Type/Choices', 'Relative Permeability', 'Relative Permeability/SIValue',

Object Oriented Property Scripting 2-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

'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', 'Magnetic
Coercivity Magnitude/SIValue', 'Magnetic Coercivity Magnitude/EvaluatedValue', 'Composition',
'Composition/Choices', "Young's Modulus Type", "Young's Modulus Type/Choices", "Young's Modulus",
"Young's Modulus/SIValue", "Young's Modulus/EvaluatedValue", "Poisson's Ratio Type", "Poisson's
Ratio Type/Choices", "Poisson's Ratio", "Poisson's Ratio/SIValue", "Poisson's Ratio/E-
valuatedValue"]

Examples showing change to material property type:


>>> omat.GetPropValue("Relative Permeability Type/Choices")
['Simple', 'Anisotropic', 'Tensor', 'Nonlinear']
>>> omat.GetPropValue("Relative Permeability Type")
'Nonlinear'
>>> omat.SetPropValue("Relative Permeability Type", "Simple")
True
>>> omat.GetPropValue("Relative Permeability Type")
'Simple'
>>> omat.SetPropValue("Relative Permeability", 10)
True

Examples showing change to a vector component value


>>> omat.GetPropValue("Magnetic Coercivity Magnitude")
'0A_per_meter'
>>> omat.SetPropValue("Magnetic Coercivity Magnitude", "-1A_per_meter")

Object Oriented Property Scripting 2-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

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']

Change choice property value


>>> omat.GetPropValue("Composition/Choices")
['Solid', 'Lamination', 'Litz Wire']
>>> omat.SetPropValue("Composition", "Lamination")
True
>>> omat.GetPropNames()

Object Oriented Property Scripting 2-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

['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', 'Magnetic
Coercivity Magnitude/SIValue', 'Magnetic Coercivity Magnitude/EvaluatedValue', 'Magnetic Coer-
civity Components', 'Magnetic Coercivity Components/Component1', 'Magnetic Coercivity Com-
ponents/Component2', 'Magnetic Coercivity Components/Component3', 'Composition',
'Composition/Choices', '- Stacking Factor Type', '- Stacking Factor', '- Stacking Fact-
or/SIValue', '- Stacking Factor/EvaluatedValue', '- Stacking Direction', '- Stacking Dir-
ection/Choices', "Young's Modulus Type", "Young's Modulus Type/Choices", "Young's Modulus",
"Young's Modulus/SIValue", "Young's Modulus/EvaluatedValue", "Poisson's Ratio Type", "Poisson's
Ratio Type/Choices", "Poisson's Ratio", "Poisson's Ratio/SIValue", "Poisson's Ratio/E-
valuatedValue"]
>>> omat.SetPropValue("Magnetic Coercivity Components/Component2", 2)
True
>>> omat.GetPropValue("Magnetic Coercivity Components")
['Component1:=', '2', 'Component2:=', '2', 'Component3:=', '0']

Change choice property value


>>> omat.GetPropValue("Composition/Choices")
['Solid', 'Lamination', 'Litz Wire']
>>> omat.SetPropValue("Composition", "Lamination")
True
>>> omat.GetPropNames()

Object Oriented Property Scripting 2-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

['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"]
>>>

Project Object Script Commands


Project commands should be executed by the oProject object.
One example of accessing this object is:
Set oProject = oDesktop.GetActiveProject()
Dataset Script Commands:
AddDataset
DeleteDataset
EditDataset
ExportDataset
HasDataset
ImportDataset
Other Project Object Script Commands:

Object Oriented Property Scripting 2-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

AddMaterial
AnalyzeAll
ChangeProperty
ClearMessages
CloneMaterial
Close
CopyDesign
CutDesign
DeleteDesign
DeleteToolObject
EditMaterial
ExportMaterial
GetActiveDesign
GetArrayVariables
GetChildNames [Project]
GetChildObject [Project]
GetChildTypes [Project]
GetConfigurableData
GetDefinitionManager
GetDependentFiles

Object Oriented Property Scripting 2-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

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

Object Oriented Property Scripting 2-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

Paste [Project Object]


Redo [Project Level]
RemoveAllUnusedDefinitions
RemoveMaterial
RemoveUnusedDefinitions
Rename
RunToolkit
Save
SaveAs
SaveAsStandAloneProject
SaveProjectArchive
SetActiveDefinitionEditor
SetActiveDesign
SetPropValue [Project]
SetPropertyValue
SetVariableValue
SimulateAll
Undo [Project]
UpdateDefinitions

AnalyzeAll [project]

Object Oriented Property Scripting 2-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

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.

UI Access Project > Analyze All.


Parameters None.
Return Value None.

Python Syntax AnalyzeAll()


oProject.AnalyzeAll()
Python Example

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.

Object Oriented Property Scripting 2-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

Return Value None.

Python Syntax ClearMessages()


Python Example oProject.ClearMessages()

VB Syntax ClearMessages
VB Example oProject.ClearMessages

Close
Closes the active project.

Warning:

Unsaved changes will be lost.

UI Access N/A
Parameters None.
Return Value None.

Python Syntax Close()

Object Oriented Property Scripting 2-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

Python Example oProject.Close()

VB Syntax Close
VB Example oProject.Close

CopyDesign
Copies a specified design.

UI Access Edit > Copy.

Name Type Description


Parameters
<DesignName> String Name of the design to copy from.

Return Value None.

Python Syntax CopyDesign (<DesignName>)


oProject.CopyDesign ("HFSSDesign1")
Python Example

VB Syntax CopyDesign <DesignName>


VB Example oProject.CopyDesign "HFSSDesign1"

CutDesign
Cuts a design from the active project. The design is stored in memory and can be pasted.

Object Oriented Property Scripting 2-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

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.

UI Access Edit > Cut.

Name Type Description


Parameters
<DesignName> String Name of the design.

Return Value None.

Python Syntax CutDesign (<DesignName>)


oProject.CutDesign("SimplorerDesign1")
Python Example

VB Syntax CutDesign <DesignName>


VB Example oProject.CutDesign "SimplorerDesign1"

DeleteDesign
Deletes a specified design in the project.

UI Access Edit > Delete, or Delete in the ribbon.

Object Oriented Property Scripting 2-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

Name Type Description


Parameters
<DesignName> String Name of the design.

Return Value None.

Python Syntax DeleteDesign (<DesignName>)


oProject.DeleteDesign("MaxwellDesign2")
Python Example

VB Syntax DeleteDesign <DesignName>


VB Example oProject.DeleteDesign "MaxwellDesign2"

DeleteToolObject

Note:
This command is for internal Ansys use only.

UI Access N/A

Name Type Description


Parameters
<ObjectName> String Name of the tool object.

Return Value None.

Object Oriented Property Scripting 2-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

Python Syntax DeleteToolObject(<ObjectName>)


Python Example oProject.DeleteToolObject("object1")

VB Syntax DeleteToolObject <ObjectName>


VB Example oProject.DeleteToolObject "object1"

GetActiveDesign
Returns the design in the active project

Note: GetActiveDesign will return normally if there are no active objects.

UI Access N/A
Parameters None.
Return Value Object of the active design.

Python Syntax GetActiveDesign()


oDesign = oProject.GetActiveDesign()
Python Example

VB Syntax GetActiveDesign
VB Example Set oDesign = oProject.GetActiveDesign

Object Oriented Property Scripting 2-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

GetConfigurableData (Project)

Note:
This command is for internal Ansys use only.

Python Syntax GetConfigurableData()


Python Example oProject.GetConfigurableData()

GetDefinitionManager
Gets the DefinitionManager object.

UI Access N/A
Parameters None.
Return Value DefinitionManager object.

Python Syntax GetDefinitionManager()


Python Example oDefinitionManager = oProject.GetDefinitionManager()

VB Syntax GetDefinitionManager
VB Example Set oDefinitionManager = oProject.GetDefinitionManager

Object Oriented Property Scripting 2-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

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.

Python Syntax GetDependentFiles()


files = oProject.GetDependentFiles()
Python Example

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>

Object Oriented Property Scripting 2-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

Type: <string>
Name of the design to return.
VB Example: Set oDesign = oProject.GetDesign ("Maxwell3DDesign1")
GetEDBHandle
Returns the EDB handle for the project.

Important:

This script is for internal Ansys use only.

UI Access N/A
Parameters None.
Return Value String indicating the EDB handle for the project.

Python Syntax GetEDBHandle()


Python Example oProject.GetEDBHandle()

VB Syntax GetEDBHandle
VB Example oProject.GetEDBHandle

GetLegacyName
Obtains the legacy name of a project.

Object Oriented Property Scripting 2-43


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

Note:
This command is for internal Ansys use only.

UI Access N/A
Parameters None.
Return Value String containing the legacy project name.

Python Syntax GetLegacyName()


Python Example oProject.GetLegacyName()

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.

Object Oriented Property Scripting 2-44


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

Python Syntax GetName()


oProject.GetName()
Python Example

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.

Python Syntax GetPath()


oProject.GetPath()
Python Example

VB Syntax GetPath
VB Example oProject.GetPath

Object Oriented Property Scripting 2-45


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

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.

Python Syntax GetTopDesignList()


oProject.GetTopDesignList()
Python Example

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].

Name Type Description


<DesignType> String Design type."Maxwell 2D", "Maxwell 3D", or "RMxprt".
Parameters
<DesignName> String Design name.
<SolutionType> String Dependent on design type.

Object Oriented Property Scripting 2-46


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

For Maxwell 3D, can be: "Magnetostatic", "EddyCurrent", "Transient", "Elec-


trostatic", "DCConduction", "ElectroDCConduction", or "ElectricTransient".
For Maxwell 2D, can be: "Magnetostatic", "EddyCurrent", "Transient", "Elec-
trostatic", "ACConduction", or "DCConduction".
For RMxprt, can be: "Three-Phase Induction Motor", "Single-Phase Induction
Motor", "Three-Phase Synchronous Machine", "Brushless Permanent-Magnet
DC Motor", "Adjust-Speed Synchronous Machine", "Permanent-Magnet DC
Motor", "Switched Reluctance Motor", "Line-Start Permanent-Magnet Syn-
chronous Motor", "Universal Motor", "DC Machine", "Claw-Pole Alternator",
"Three-Phase Non-Salient Synchronous Machine", or "Generic Rotating
Machine".
"" None Empty argument.

Return Value None.

Python Syntax InsertDesign (<DesignType>, <DesignName>, <SolutionType>,'')


oProject.InsertDesign('Maxwell 3D','MyDesign',
Python Example
'ElectricTransient', '')

VB Syntax InsertDesign <DesignType>, <DesignName>, <SolutionType>,""


oProject.InsertDesign "Maxwell 3D","MyDesign",
VB Example
"ElectricTransient", ""

InsertDesignWithWorkflow
Inserts a design with a named workflow and returns an IDispatch string.

Object Oriented Property Scripting 2-47


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

UI Access N/A

Name Type Description


<type> String Type of design.
<workflowName> String Name of the workflow.
Parameters <specName> String Name of the spec.
<fileName> String Name of the file.
<libLoc> String Type of library, such as SysLib.
<stationaryPath> String Path.

Return Value IDispatch string, such as 'IDispatch(IAltraSimScript)'

Python Syntax InsertDesignWithWorkflow(<type>, <workflowName>, <specName>, <fileName>, <libLoc>, <stationaryPath>)


oProject.InsertDesignWithWorkflow ("Circuit Design", "Serial Design",

Python "PCIe3 Stressed", "LongChannel", "SysLib",


Example "C:\\Program Files\\AnsysEM\\v241\\Win64\\syslib\\MS - RT_duroid 6010 (Er=10.2)
0.010 inch, 0.5 oz copper.asty")

VB Syntax InsertDesignWithWorkflow <type>, <workflowName>, <specName>, <fileName>, <libLoc>, <stationaryPath>


oProject.InsertDesignWithWorkflow "Circuit Design", "Serial Design", _
VB Example "PCIe3 Stressed", "LongChannel", "SysLib", _
"C:\Program Files\AnsysEM\v241\Win64\syslib\MS - RT_duroid 6010" & _

Object Oriented Property Scripting 2-48


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

" (Er=10.2) 0.010 inch, 0.5 oz copper.asty"

InsertToolObject

Note:
This command is for internal Ansys use only.

Python Syntax InsertToolObject()


Python Example oProject.InsertToolObject()

Paste (Project Object)


Pastes a design in the active project.

UI Access Edit > Paste.


Parameters None.
Return Value None

Python Syntax Paste()


Python Example oProject.Paste()

VB Syntax Paste
VB Example oProject.Paste

Object Oriented Property Scripting 2-49


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

Redo [Project Level]


Reapplies the last project-level command.

UI Access Edit > Redo.


Parameters None.
Return Value None.

Python Syntax Redo()


Python Example oProject.Redo()

VB Syntax Redo
VB Example oProject.Redo

Rename
Renames the project and saves it. Similar to SaveAs().

UI Access Edit > Rename.

Name Type Description


<NewName> String Desired name of the project. The path is optional.
Parameters <OverWriteOk> Boolean l True - overwrite the file on disk if it exists.

l False - prevent overwrite.

Object Oriented Property Scripting 2-50


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

Return Value None.

Python Syntax Rename(<NewName>,<OverWriteOK>)


oProject.Rename("c:\projects\MyProject.aedt", True)
Python Example

VB Syntax Rename <NewName>,<OverWriteOK>


VB Example oProject.Rename "c:\projects\MyProject.aedt", true

RestoreProjectArchive
Restores a previously archived project to a specified path.

UI Access File > Restore Archive.

Name Type Description


<ArchiveFilePath> String Path to archived file
Parameters
<ProjectFilePath> String Path to restore location
<OverwriteExistingFiles> Boolean True to overwrite an existing file of the same name; else False.
<OpenPro- Boolean True to open the project after it is restored; else False.
jectAfterRestore>

Return Value None.

Python RestoreProjectArchive (<Archivefilepath>, <ProjectFilePath>, <OverwriteExistingFiles>, <OpenProjectAfterRestore>)


Syntax

Object Oriented Property Scripting 2-51


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

Python oDesktop.RestoreProjectArchive("C:\Users\jdoe\Documents\OptimTee.aedtz", "C:\Docu-


Examp- ments\OptimTee.aedt", False, True)
le

RestoreProjectArchive <Archivefilepath>, <ProjectFilePath>, <OverwriteExistingFiles>, <OpenPro-


VB Syntax
jectAfterRestore>
oDesktop.RestoreProjectArchive "C:\Users\jdoe\Documents\OptimTee.aedtz", _
VB Example
"C:\Documents\OptimTee.aedt", false, true

Save
Saves the active project.

UI Access File > Save.


Parameters None.
Return Value None.

Python Syntax Save()


oProject.Save()
Python Example

VB Syntax Save

Object Oriented Property Scripting 2-52


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

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.

UI Access File > Save As.

Name Type Description


<NewName> String The desired name of the project, with directory and extension.
<OverWriteOK> Boolean True to overwrite the file of the same name, if it exists. False to prevent over-
write.
<DefaultAction> String For Schematic/Layout projects only. Otherwise omit. See note below.

Parameters Valid actions: ef_overwrite , ef_copy_no_overwrite, ef_make_path_abso-


lute, or empty string.
<OverwriteActions> Array For Schematic/Layout projects only. Otherwise omit. See note below.
Structured array: Array("Name: <Action>", <FileName>, <FileName>, ...)
Valid actions: ef_overwrite , ef_copy_no_overwrite, ef_make_path_abso-
lute, or empty string.

Return Value None.

Pytho- For non-Schematic/Layout project: SaveAs ( <NewName> <OverWriteOK>)


n Syn-
tax For Schematic/Layout project: SaveAs (<NewName> <OverWriteOK> <DefaultAction> <OverrideActions>)

Object Oriented Property Scripting 2-53


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

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']]])

VB Syn- For non-Schematic/Layout project: SaveAs <NewName> <OverWriteOK>


tax For Schematic/Layout project: SaveAs <NewName> <OverWriteOK> <DefaultAction> <OverrideActions>
oProject.SaveAs "D:/projects/project1.aedt", true
----
oProject.SaveAs
VB
Exampl- "F:\Designer Projects\TA33097\HighSpeedChannel.aedt", true, "ef_overwrite", Array
es ("NAME:OverrideActions",
Array("NAME:ef_copy_no_overwrite", Array("NAME:Files","$PROJECTDIR/circuit_mod-
els.inc")),
Array("NAME:ef_make_path_absolute", Array("NAME:Files","$PROJECTDIR\SL_6s.sp")))

Object Oriented Property Scripting 2-54


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

Important:

The DefaultAction and OverrideActions strings correspond to the following actions:

l ef_overwrite – Copy file to new project directory and overwrite.


l ef_copy_no_overwrite – Copy file to new project directory and don't overwrite.
l ef_make_path_absolute – Change reference to point to file in old project directory.
l Empty String – Do nothing.

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

Name Type Description


Parameters
<projectName> String The desired name of the project, with directory and extension.

Return Value None.

Object Oriented Property Scripting 2-55


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

Python Syntax SaveAsStandAloneProject( <projectName>)


Python Example oProject.SaveAsStandAloneProject('D:/projects/project1.aedt')

VB Syntax SaveAsStandAloneProject <projectName>

VB Examples oProject.SaveAsStandAloneProject "D:/projects/project1.aedt"

SaveProjectArchive
Saves the active project as an archive to the specified file path.

UI Access File > Archive.

Name Type Description


<archiveFilePath> String Path to archived file.
<IncludeExternalFiles> Boolean True to include external files; False to exclude.
Parameters <IncludeResultsFiles> Boolean True to include simulation files associated with the project; False to
exclude.
<AdditionalFiles> Array Additional specified files to include.
<ArchiveNotes> String String describe the archive.

Return Value None.

Python SaveProjectArchive(<archivefilepath>, <IncludeExternalFiles>, <IncludeResultsFiles>, <AdditionalFiles>,


Syntax <ArchiveNotes>)

Python oProject.SaveProjectArchive("C:\\Users\\Documents\\Ansoft\\Project27.aedtz", True,


Example False, [], "")

Object Oriented Property Scripting 2-56


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

VB Syn- SaveProjectArchive <archivefilepath>, <IncludeExternalFiles>, <IncludeResultsFiles>, <AdditionalFiles>,


tax <ArchiveNotes>

VB oProject.SaveProjectArchive "C:\Documents\OptimTee.aedtz", true, false, Array(), "My


Example notes"

SetActiveDefinitionEditor
Obtains a specified definition editor.

UI Access N/A

Name Type Description


<EditorName> String Name of the definition editor to set active, one of "SymbolEditor",
Parameters "FootprintEditor".
<DefinitionName> String The combination name for the symbol or footprint, <libname>:<def-
name>

Return Value Object for the definition to be edited.

Python Syntax SetActiveDefinitionEditor(<EditorName>, <DefinitionName>)


oProject.SetActiveDefinitionEditor("SymbolEditor",
Python Example "Simplorer Elements\Basic Elements\Circuit\Passive Elements:R")

VB Syntax SetActiveDefinitionEditor <EditorName>, <DefinitionName>

Object Oriented Property Scripting 2-57


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

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

Name Type Description


Parameters
<DesignName> String Name of the design to set as the active design.

Return Value None.

Python Syntax SetActiveDesign (<DesignName>)


Python Example oDesign = oProject.SetActiveDesign("SimplorerDesign2")

VB Syntax SetActiveDesign <DesignName>


VB Example Set oDesign = oProject.SetActiveDesign "SimplorerDesign2"

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

Object Oriented Property Scripting 2-58


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

Parameters None.
Return Value None.

Python Syntax SimulateAll()


oProject.SimulateAll()
Python Example

VB Syntax SimulateAll
VB Example oProject.SimulateAll

Undo [Project]
Cancels the last project-level command.

UI Access Edit > Undo.


Parameters None.
Return Value None.

Python Syntax Undo()


oProject.Undo()
Python Example

Object Oriented Property Scripting 2-59


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

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.

Python Syntax UpdateDefinitions()


oProject.UpdateDefinitions()
Python Example

VB Syntax UpdateDefinitions
VB Example oProject.UpdateDefinitions

Object Oriented Property Scripting 2-60


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

3 - Application Object Script Commands


The Application object commands permit you to get the AppDesktop. Application object commands should be executed by the oAn-
softApp object.
oAnsoftApp.<CommandName> <args>
General Application Script Commands
The following are general script commands recognized by the oAnsoftApp object:
l GetAppDesktop

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)

Application Object Script Commands 3-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

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

Name Type Description


Parameters
None

Return Value Object

Python Syntax GetAppDesktop()


Python Example oDesktop = oAnsoftApp.GetAppDesktop()

VB Syntax GetAppDesktop()
VB Example Set oDesktop = oAnsoftApp.GetAppDesktop()

GetApp
Obtains the product application object.

Application Object Script Commands 3-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

UI Access NA

Name Type Description


Parameters <productname> String One of "Twin Builder", "HFSS", "Maxwell", "Q3D Extractor". "Maxwell Circuit
Editor", "Designer"

Return Value Object

Python Syntax GetApp(<productname>)


Python Example oHFSSApp = oAnsoftApp.GetApp("HFSS")

VB Syntax GetApp(<productname>)
Dim oHFSSApp
VB Example
oHFSSApp = oAnsoftApp.GetApp("HFSS")

Application Object Script Commands 3-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

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

4 - Desktop Object Script Commands


Desktop commands should be executed by the oDesktop object. Some new commands permit you to query objects when you do not
know the names. See: Object Oriented Property Scripting.
Set oDesktop =
CreateObject("Ansoft.ElectronicsDesktop")
oDesktop.CommandName <args>
AddMessage
AreThereSimulationsRunning
ClearMessages
CloseAllWindows
CloseProject
CloseProjectNoForce
Count
DeleteProject
DeleteRegistryEntry
DoesRegistryValueExist
DownloadJobResults
EnableAutoSave
ExportOptionsFiles
GenerateMetadata
GetActiveProject

Desktop Object Script Commands 4-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

GetActiveScheduler
GetActiveSchedulerInfo
GetAutoSaveEnabled
GetBuildDateTimeString
GetCustomMenuSet
GetDefaultUnit
GetDesktopConfiguration
GetDistributedAnalysisMachines
GetDistributedAnalysisMachinesForDesignType
GetExeDir
GetFullGeometry
GetGDIObjectCount
GetGrpcServerPort
GetHashcode
GetIsGrpcServer
GetIsNongraphical
GetLibraryDirectory
GetLocalizationHelper
GetMessages
GetMonitorData

Desktop Object Script Commands 4-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

GetPersonalLibDirectory
GetProcessID
GetProjectDirectory
GetProjectList
GetProjects
GetRegistryInt
GetRegistryString
GetRunningInstancesMgr
GetSchematicEnvironment
GetScriptingToolsHelper
GetSysLibDirectory
GetTempDirectory
GetTool
GetUserLibDirectory
GetVersion
IsFeatureEnabled
KeepDesktopResponsive
LaunchJobMonitor
NewProject
OpenAndConvertProject
OpenMultipleProjects

Desktop Object Script Commands 4-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

OpenProject
OpenProjectWithConversion
PageSetup
PauseRecording
PauseScript
Print
QuitApplication
RefreshJobMonitor
RefreshToolkitUI
ResetLogging
RestoreProjectArchive
RestoreWindow
ResumeRecording
RunACTWizardScript
RunProgram
RunScript
RunScriptWithArguments
SelectScheduler
SetActiveProject
SetActiveProjectByPath

Desktop Object Script Commands 4-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

SetCustomMenuSet
SetDesktopConfiguration
SetLibraryDirectory
SetProjectDirectory
SetRegistryFromFile
SetRegistryInt
SetRegistryString
SetSchematicEnvironment
SetTempDirectory
ShowDockingWindow
Sleep
StopSimulations
SubmitJob
TileWindows
WaitForSimulationsToBeDone

Related Topics:

Desktop Commands For Registry Values

ImportExport Tool Commands

AddMessage
Add a message with severity and context to message window.

Desktop Object Script Commands 4-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

UI Access N/A

Name Type Description


<projectName> String Project name. Passing an empty string adds the message as the desktop
global message.
<designName> String Design name. Ignored if project name is empty. Passing an empty string adds
the message to project node in the message tree.
<severity> Integer One of "Error", "Warning" or "Info". Anything other than the first two is treated
as "Info"
Parameters
0 = Informational, 1 = Warning, 2 = Error, 3 = Fatal
<msg> String The message for the message window.
<category> String Optional. The category is created with the message under the design tree node
if the category does not exist. If the category already exists, the new message
is added to the end of the existing category. It is ignored if the project or design
is empty. If missing or empty, the message is added to the Design node in the
message tree.

Return Value None.

Python Syntax AddMessage( <projectName>, <designName>, <severity>, <msg>, <category>)


Python Example oDesktop.AddMessage("Project1", "Maxwell", 0, "This is a test message", "")

VB Syntax AddMessage <projectName>, <designName>, <severity>, <msg>, <category>


VB Example oDesktop.AddMessage "Project1", "Maxwell1", 0, "This is a test message", ""

Desktop Object Script Commands 4-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

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]...

Name Type Description


<projectName> String Name of the project from which to clear messages.
<designName> String Name of the design under the <projectName> from which to clear messages.
<startSeverity> Integer User-specified severity level at which messages start getting cleared:
l 0 = informational
l 1 = warning
l 2 = error
Parameters
3 = fatal error
l

<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

Desktop Object Script Commands 4-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

If not specified, <stopSeverity> has a default value of 0.

Return Value None.

Python Syntax ClearMessages(<projectName>, <designName>, <startSeverity>, <stopSeverity>)

Preserve Current Functionality; stopSeverity = 0 (DEFAULT VALUE)


# startSeverity = 0; clears just the Info messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor", "Maxwell3DDesign1", 0)
# startSeverity = 1; clears all the Info and Warning messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor", "Maxwell3DDesign1", 1)
# startSeverity = 2; clears all the Info, Warning, Error
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor", "Maxwell3DDesign1", 2)
# startSeverity = 3; clears all messages, i.e., Info, Warning, Error, Fatal
Python Example
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor", "Maxwell3DDesign1", 3)
Extend the current functionality by enabling range-based deletion
# startSeverity = 0; clears the Info messages;
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor", "Maxwell3DDesign1", 0)
# startSeverity = 0 and stopSeverity = 0; clears all the Info messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor", "Maxwell3DDesign1", 0,
0)
# startSeverity = 0 and stopSeverity = 1; clears all the Info and Warning mes-

Desktop Object Script Commands 4-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

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)

# startSeverity = 1; clears all the Info and Warning messages;


oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",1)
# startSeverity = 1 and stopSeverity = 1; clears all the Warning messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",1, 1)
# startSeverity = 1 and stopSeverity = 2; clears all the Warning and Error mes-
sages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",1, 2)
# startSeverity = 1 and stopSeverity = 3; clears all the Warning, Error, and
Fatal messages
oDesktop.ClearMessages("Ex_EC_1_Asymmetrical_Conductor","Maxwell3DDesign1",1, 3)

# startSeverity = 2; clears all the Info, Warning, and Error messages;

Desktop Object Script Commands 4-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

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)

VB Syntax ClearMessages <projectName>, <designName>, <startSeverity>, <stopSeverity>


Set oAnsoftApp = CreateObject("Ansoft.ElectronicsDesktop")
VB Example
Set oDesktop = oAnsoftApp.GetAppDesktop()

Desktop Object Script Commands 4-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

oDesktop.ClearMessages "MyProject", "MyDesign", 0, 3

CloseAllWindows
Closes all MDI child windows on the desktop.

UI Access From main menu, Window > CloseAll.


Parameters None.
Return Value None.

Python Syntax CloseAllWindows()


Python Example oDesktop.CloseAllWindows()

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.

UI Access File > Close

Name Type Description


Parameters <ProjectName> String The name of the project already in the Desktop that is to be closed, without
path or extension

Desktop Object Script Commands 4-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

Return Value None

Python Syntax CloseProject (<ProjectName>)


oDesktop.CloseProject("MyProject")
Python Example

VB Syntax CloseProject <ProjectName>


VB Example oDesktop.CloseProject "MyProject"

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.

UI Access File > Close

Name Type Description


Parameters <ProjectName> String The name of the project already on the Desktop that is to be closed, without
path or extension

Return Value None

Python Syntax CloseProjectNoForce (<ProjectName>)

Desktop Object Script Commands 4-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

oDesktop.CloseProjectNoForce("MyProject")
Python Example

VB Syntax CloseProjectNoForce <ProjectName>


VB Example oDesktop.CloseProjectNoForce "MyProject"

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

Python Syntax Count


projects = oDesktop.GetProjects()
Python Example
numprojects = projects.Count

VB Syntax Count
Dim oAnsoftApp
Dim oDesktop
VB Example Dim oProject
Dim oDesign
Dim oEditor

Desktop Object Script Commands 4-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

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.

UI Access Edit > Delete

Parameters Name Type Description

Desktop Object Script Commands 4-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

<ProjectName> String Name of the project

Return Value None

Python Syntax DeleteProject (<ProjectName>)


oDesktop.DeleteProject("MyProject")
Python Example

VB Syntax DeleteProject <ProjectName>


VB Example oDesktop.DeleteProject "MyProject"

EnableAutoSave
Enable or disable autosave feature.

UI Access N/A

Name Type Description


Parameters
<enable> Boolean True to enable autosave; False disables it.

Return Value None.

Python Syntax EnableAutoSave(<enable>)


oDesktop.EnableAutoSave(True)
Python Example

Desktop Object Script Commands 4-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

VB Syntax EnableAutoSave <enable>


VB Example oDesktop.EnableAutoSave True

ExportOptionsFiles
Copies the options config files to the DestinationDirectory.

UI Access Tools > Options > Export Options Files ...

Name Type Description


Parameters
<DestinationDirectory> String The path to the destination directory.

Return Value None

Python Syntax ExportOptionsFiles( <DestinationDirectory>)


Python Example oDesktop.ExportOptionsFiles("D:/test/export/")

VB Syntax ExportOptionsFiles <DestinationDirectory>


VB Example oDesktop.ExportOptionsFiles"D:/test/export/"

GetActiveProject
Obtains the project currently active in the Desktop, as an object.

Desktop Object Script Commands 4-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

Note:

GetActiveProject returns normally if there are no active objects.

UI Access N/A
Parameters None.
Return Value Object: the project that is currently active in the desktop.

Python Syntax GetActiveProject()


oProject = oDesktop.GetActiveProject()
Python Example

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.

Desktop Object Script Commands 4-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

l 0 – Autosave is not enabled.

Python Syntax GetAutoSaveEnabled()


Enabled = oDesktop.GetAutoSaveEnabled()
Python Example

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

Python Syntax GetBuildDateTimeString()


oDesktop.GetBuildDateTimeString()
Python Example

Desktop Object Script Commands 4-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

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’.

Python Syntax GetCustomMenuSet ()


oDesktop.GetCustomMenuSet()
Python Example

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

Desktop Object Script Commands 4-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

changed, while the script can be used to view additional default units.

Name Type Description


<type> String String containing a type of measurement.
Valid strings are (case insensitive):
l "Acceleration"
l "Angle"
l "AngularAcceleration"
l "AngularDamping"
l "AngularSpeed"
l "Capacitance"
l "Conductance"
Parameters
l "Current"
l "CurrentChangeRate"
l "DataRate"
l "DeltaH" (Magnetic Field Strength)
l "Density"
l "Flux"
l "Force"
l "Frequency"
l "Inductance"
l "Length"

Desktop Object Script Commands 4-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

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").

Python Syntax GetDefaultUnit(<type>)


Python Example oDesktop.GetDefaultUnit("Length")

Desktop Object Script Commands 4-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

VB Syntax GetDefaultUnit <type>


VB Example oDesktop.GetDefaultUnit("Length")

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.

Python Syntax GetDesigns()


oProject.GetDesigns()
Python Example

VB Syntax GetDesigns
VB Example oProject.GetDesigns

Desktop Object Script Commands 4-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

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’.

Python Syntax GetDesktopConfiguration()


oDesktop.GetDesktopConfiguration()
Python Example

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.

Desktop Object Script Commands 4-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

Python Syntax GetDistributedAnalysisMachines()


oDesktop.GetDistributedAnalysisMachines()
Python Example

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

Name Type Description


Parameters <designTypeName> String The name of the type of design, such as "Twin Builder", "HFSS", HFSS-IE",
"Maxwell 3D" , "Maxwell 2D", "RMxprt", "EM Design", "Circuit", "System",
"Q3D Extractor", "2D Extractor"

Return Value Object; returns a collection of machine names.

Python Syntax GetDistributedAnalysisMachinesForDesignType (<designTypeName>)


machineNames =oDesktop.
Python Example GetDistributedAnalysisMachinesForDesignType
("Maxwell")

Desktop Object Script Commands 4-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

VB Syntax GetDistributedAnalysisMachinesForDesignType <designTypeName>


Set machineNames =oDesktop.
VB Example GetDistributedAnalysisMachinesForDesignType
("Maxwell")

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/'

Python Syntax GetExeDir()


Python Example oDesktop.GetExeDir()

VB Syntax GetExeDir
VB Example oDesktop.GetExeDir

Desktop Object Script Commands 4-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

GetGDIObjectCount

Note:
This command is for internal Ansys use only.

Python Syntax GetGDIObjectCount()


Python Example oDesktop.GetGDIObjectCount()

VB Syntax GetGDIObjectCount()
VB Example oDesktop.GetGDIObjectCount()

GetLibraryDirectory
Get the path to the SysLib directory.

UI Access NA

Name Type Description


Parameters
None

String
Return Value
The path to the SysLib directory.

Desktop Object Script Commands 4-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

Python Syntax GetLibraryDirectory()


AddInfoMessage(str(oDesktop.GetLibraryDirectory()))
Python Example

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())

Desktop Object Script Commands 4-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

GetLocalizationHelper

Note:
This command is for internal Ansys use only.

Returns the object for the localization helper.

UI Access NA

Name Type Description


Parameters
None

Object
Return Value
Localization helper object, such as "IDispatch(ILocalizationHelper)"

Python Syntax GetLocalizationHelper()


Python Example oDesktop.GetLocalizationHelper()

VB Syntax GetLocalizationHelper
VB Example oDesktop.GetLocalizationHelper()

GetMessages
Get the messages from a specified project and design.

Desktop Object Script Commands 4-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

UI Access NA

Name Type Description


<ProjectName> String Name of the project for which to collect messages. An incorrect project
name results in no messages (design is ignored). An empty project name
results in all messages (design is ignored)
<DesignName> String Name of the design in the named project for which to collect messages. An
incorrect design name results in no messages for the named project. An
empty design name results in all messages for the named project
Parameters
<Severity> Integer Severity is 0-3, and is tied in to info/warning/error/fatal types as follows:
l 0 – info and above
l 1 – warning and above
l 2 – error and fatal
l 3 – fatal only (rarely used)

Return Value Array of string messages.

Python Syntax GetMessages (<ProjectName>, <DesignName>, <Severity>)


Messages = oDesktop.GetMessages("MyProject", "Maxwell1", 1)
Python Example

VB Syntax GetMessages <ProjectName>, <DesignName>, <Severity>


Messages = oDesktop.GetMessages "MyProject", "Maxwell1", 1
VB Examples

Desktop Object Script Commands 4-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

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-
.

Python Syntax GetName()


set projects = oDesktop.GetProjects()
Python Example
project_name = projects(0).GetName()

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

Desktop Object Script Commands 4-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

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.

Python Syntax GetPersonalLibDirectory()


oDesktop.GetPersonalLibDirectory()
Python Example

Desktop Object Script Commands 4-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

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.

Python Syntax GetProcessID ()


Python Example oDesktop.GetProcessID()

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.

Desktop Object Script Commands 4-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

UI Access N/A
Parameters None.
Return Value Returns a collection containing objects for all open projects in Electronics Desktop.

Python Syntax GetProjects()


oDesktop.GetProjects()
Python Example

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.

Python Syntax GetProjectDirectory()


oDesktop.GetProjectDirectory()
Python Example

Desktop Object Script Commands 4-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

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.

Python Syntax GetProjectList()


list_of_projects = oDesktop.GetProjectList()
Python Example

VB Syntax GetProjectList
VB Example list_of_projects = oDesktop.GetProjectList

Desktop Object Script Commands 4-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

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

Python Syntax GetSchematicEnvironment()


oDesktop.GetSchematicEnvironment()
Python Example

VB Syntax GetSchematicEnvironment
VB Example Set oProject = oDesktop.GetSchematicEnvironment

GetScriptingToolsHelper

Note:
This command is for internal Ansys use only.

Desktop Object Script Commands 4-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

Returns the object for the scripting tools helper.

UI Access NA

Name Type Description


Parameters
None

Object
Return Value
ScriptingTools helper object

Python Syntax GetScriptingToolsHelper()


Python Example oDesktop.GetScriptingToolsHelper()

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.

Desktop Object Script Commands 4-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

Python Syntax GetSysLibDirectory()


oDesktop.GetSysLibDirectory()
Python Example

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.

Python Syntax GetTempDirectory()


oDesktop.GetTempDirectory()
Python Example

VB Syntax GetTempDirectory
VB Example oDesktop.GetTempDirectory

Desktop Object Script Commands 4-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

GetUserLibDirectory
Gets the path to the UserLib directory.

UI Access N/A
Parameters None.
Return Value Stringpath to the UserLib directory.

Python Syntax GetUserLibDirectory()


oDesktop.GetUserLibDirectory()
Python Example

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.

Desktop Object Script Commands 4-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

Python Syntax GetVersion()


oDesktop.GetVersion()
Python Example

VB Syntax GetVersion()
VB Example oDesktop.GetVersion

ImportANF
Imports an ANF file into a new project. For older ANFv2 files, use ImportANFv2.

UI Access File > Import > ANF.

Name Type Description


Parameters
<ANFfilename> String Full path of ANF file.

Return Value None.

Python Syntax ImportANF(<ANFfilename>)


oDesktop.RestoreWindow()
Python Example Set oTool = oDesktop.GetTool('ImportExport')
oTool.ImportANF('C:\\AnsTranslator\\results\\package4.anf')

Desktop Object Script Commands 4-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

VB Syntax ImportANF <ANFfilename>


Dim oAnsoftApp
Dim oDesktop
Dim oProject
Dim oDesign
Dim oEditor
Dim oModule
Dim oProjects
VB Example
Dim omachine
Dim oTool
Set oAnsoftApp = CreateObject("Ansoft.ElectronicsDesktop")
Set oDesktop = oAnsoftApp.GetAppDesktop()
oDesktop.RestoreWindow
Set oTool = oDesktop.GetTool("ImportExport")
oTool.ImportANF("%UserProfile%\Documents\HFSS Examples\package.anf")

ImportAutoCAD
Imports an AutoCAD file into a new project.

UI Access File > Import > AutoCAD.

Parameters Name Type Description

Desktop Object Script Commands 4-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

<dxfFileName> String Full path of DXF file.


<outputPathFileName> String Full path of EDB file to create during import.
<controlFileName> String Full path of XML control file. Pass empty string if none.

Return Value None.

Python Syntax ImportAutoCAD (<dxfFileName>, <outputPathFileName>, <controlFileName>)


Set oTool = oDesktop.GetTool('ImportExport')
Python Example oTool.ImportAutoCAD('C:/MyPath/a4lines.dxf', 'C:/MyPath/a4lines.aedb.edb',
'C:/MyPath/a4lines.xml')

VB Syntax ImportAutoCAD <dxfFileName>, <outputPathFileName>, <controlFileName>


Set oTool = oDesktop.GetTool("ImportExport")
VB Example oTool.ImportAutoCAD "C:/MyPath/a4lines.dxf", "C:/MyPath/a4lines.aedb.edb",
"C:/MyPath/a4lines.xml"

ImportGDSII
Imports a GDSII file into a new project.

UI Access File > Import > GDSII.

Name Type Description


<gdsiiFileName> String Full path of GDSII file.
Parameters
<outputPathName> String Full path of EDB file to create during import.
<controlFileName> String Optional. Full path of XML control file. Pass empty string if none.

Desktop Object Script Commands 4-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

<propertyFileName> String Optional. Full path to property mapping file. Pass empty string if none.

Return Value None.

Python Syntax ImportGDSII(<gdsiiFileName>, <outputPathName>, <controlFileName>, <propertyFileName>)


oDesktop.RestoreWindow()
Set oTool = oDesktop.GetTool('ImportExport')
Python Example
oTool.ImportGDSII('C:/Files/test.gds', 'C:/Files/test.aedb.edb',
'C:/Files/test.xml', 'C:/Files/test.txt')

VB Syntax ImportGDSII <gdsiiFileName>, <outputPathName>, <controlFileName>, <propertyFileName>


Set oTool = oDesktop.GetTool("ImportExport")
VB Example oTool.ImportGDSII "C:/Files/test.gds", "C:/Files/test.aedb.edb", _
"C:/Files/test.xml", "C:/Files/test.txt"

ImportODB
Imports an ODB++ file into a new project.

UI Access File > Import > ODB++.

Parameters Name Type Description

Desktop Object Script Commands 4-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

<odbFileName> String Full path of ODB++ file.


<outputPathName> String Full path of EDB file to create during import.
<controlFileName> String Optional. Full path of XML control file. Pass empty string if none.

Return Value None.

Python Syntax ImportODB(<odbFileName>, <outputPathName>, <controlFileName>)


oDesktop.RestoreWindow()
Set oTool = oDesktop.GetTool('ImportExport')
Python Example
oTool.ImportODB('C:/Files/test.odb', 'C:/Files/test.aedb',
'C:/Files/test.xml')

VB Syntax ImportODB <odbFileName>, <outputPathName>, <controlFileName>


Set oTool = oDesktop.GetTool("ImportExport")
VB Example oTool.ImportODB "C:/Files/test.odb", "C:/Files/test.aedb", _
"C:/Files/test.xml

LaunchJobMonitor
Use: For use in starting job monitoring. This brings up the Monitor Job dialog box.

UI Access Launch Job Monitor

Name Type Description


Parameters
<projectPath> String Path to the project file to be monitored

Desktop Object Script Commands 4-43


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

Return Value None

Python Syntax LaunchJobMonitor()


Python Example oDesktop.LaunchJobMonitor("C:\\projects\\basic.aedt")

VB Syntax LaunchJobMonitor()
VB Example oDesktop.LaunchJobMonitor("C:\\projects\\basic.aedt")

NewProject
Creates a new project. The new project becomes the active project.

UI Access File > New.


Parameters None.
Return Value Object, the project that is added.

Python Syntax NewProject()


oProject = oDesktop.NewProject()
Python Example

Desktop Object Script Commands 4-44


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

VB Syntax NewProject
VB Example Set oProject = oDesktop.NewProject

OpenAndConvertProject
Opens a legacy project and converts or copies it to .aedt format.

UI Access Click File > Open, and choose a legacy project

Name Type Description


<itemPath> String full project path of the legacy project
<legacyChoice> Integer 0: show conversion dialog box, (same as File > Open of a legacy file)
Parameters 1: rename (changes extension to .aedt, the original file and results are
renamed)
2: copy (creates new file with .aedt extension, and the original file and results
remain available)

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.

Python Syntax OpenAndConvertProject(filePath, legacyChoice)


oProject = oDesktop.OpenAndConvertProject("c:\files\optimtee.hfss", 1)
Note: optimtee.hfss is gone after this code executes
Python Example
oProject = oDesktop.OpenAndConvertProject("c:\files\optimtee.hfss", 2)
Note: optimtee.hfss remains after this code executes

Desktop Object Script Commands 4-45


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

VB Syntax OpenAndConvertProject(filePath, legacyChoice)


Set oProject = oDesktop.OpenAndConvertProject("c:\files\optimtee.hfss", 1)
VB Example
Note: optimtee.hfss is gone after this code executes

OpenMultipleProjects
Opens all files of a specified type in a specified directory.

UI Access N/A

Name Type Description


Parameters <directory> String Path to the projects.
<fileType> String Type of projects to open.

Return Value None.

Python Syntax OpenAndConvertProject(<filePath>, <legacyChoice>)


Python Example oProject = oDesktop.OpenAndConvertProject("c:\files\optimtee.", "*.aedt")

VB Syntax OpenAndConvertProject <filePath>, < legacyChoice>


VB Example Set oProject = oDesktop.OpenAndConvertProject "c:\files\optimtee.", "*.aedt"

Desktop Object Script Commands 4-46


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

OpenProject
Opens a specified project.

UI Access Click File > Open.

Name Type Description


Parameters
<FileName> String Full path of the project to open.

Return Value An object reference to the newly opened project.

Python Syntax OpenProject(<FileName>)


Python Example oDesktop.OpenProject("D:/Projects/Project1.aedt")

VB Syntax OpenProject <FileName>


VB Example oDesktop.OpenProject "D:/Projects/Project1.aedt"

OpenProjectWithConversion

Note:
This command is for internal Ansys use only.

Python Syntax OpenProjectWithConversion()


Python Example oDesktop.OpenProjectWithConversion()

Desktop Object Script Commands 4-47


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

Paste (Project Object)


Pastes a design in the active project.

UI Access Edit > Paste


Parameters None
Return Value None

Python Syntax Paste()


oProject.Paste()
Python Example

VB Syntax Paste
VB Example oProject.Paste

Paste (Project Object)


Pastes a design in the active project.

UI Access Edit > Paste.


Parameters None.

Desktop Object Script Commands 4-48


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

Return Value None

Python Syntax Paste()


Python Example oProject.Paste()

VB Syntax Paste
VB Example oProject.Paste

PauseRecording
Temporarily stop script recording.

UI Access NA

Name Type Description


Parameters
None

Return Value None

Python Syntax PauseRecording()


oDesktop.PauseRecording()
Python Example

Desktop Object Script Commands 4-49


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

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.

UI Access Tools > Pause Script

Name Type Description


Parameters
<Message> String Any Text.

Return Value None

Python Syntax PauseScript (<Message>)


oDesktop.PauseScript("Text to display in pop-up dialog box.")
Python Example

VB Syntax PauseScript <Message>


VB Example oDesktop.PauseScript "Text to display in pop-up dialog box."

Print
Prints the contents of the active view window.

Desktop Object Script Commands 4-50


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

UI Access File > Print.


Parameters None.
Return Value None.

Python Syntax Print()


oDesktop.Print()
Python Example

VB Syntax Print
VB Example oDesktop.Print

QuitApplication
Exits the desktop.

UI Access File > Exit.


Parameters None.
Return Value None.

Python Syntax QuitApplication()


oDesktop.QuitApplication()
Python Example

Desktop Object Script Commands 4-51


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

VB Syntax QuitApplication
VB Example oDesktop.QuitApplication

RefreshJobMonitor
For use in monitoring a job.

UI Access Tools > Job Management > Monitor Jobs.


Parameters None.
A string specifing the job state.
The result can be any of the following strings:
l "Monitor Not Visible"
l "Queued"
l "Running"
Return Value
l "Shutting Down"
l "Unknown"
l "Completed"
l "Not Monitoring"
l "Starting Monitoring"

Desktop Object Script Commands 4-52


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

Python Syntax RefreshJobMonitor()


Python Example oDesktop.RefreshJobMonitor()

VB Syntax RefreshJobMonitor
VB Example oDesktop.RefreshJobMonitor

ResetLogging
Redirects simulation log file to a specified directory and log level.

UI Access N/A

Name Type Description


Parameters <logFile> String Path to log file.
<logLevel> Integer Specified log level.

Return Value None.

Python Syntax ResetLogging(<logFile>, <logLevel>)


Python Example oDesktop.ResetLogging("C:/Project1.aedtresults/", 1)

VB Syntax ResetLogging <logFile>, <logLevel>

VB Examples oDesktop.ResetLogging "C:/Project1.aedtresults/", 1

Desktop Object Script Commands 4-53


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

RestoreProjectArchive
Restores a previously archived project to a specified path.

UI Access File > Restore Archive.

Name Type Description


<ArchiveFilePath> String Path to archived file
Parameters
<ProjectFilePath> String Path to restore location
<OverwriteExistingFiles> Boolean True to overwrite an existing file of the same name; else False.
<OpenPro- Boolean True to open the project after it is restored; else False.
jectAfterRestore>

Return Value None.

Python RestoreProjectArchive (<Archivefilepath>, <ProjectFilePath>, <OverwriteExistingFiles>, <OpenProjectAfterRestore>)


Syntax

Python oDesktop.RestoreProjectArchive("C:\Users\jdoe\Documents\OptimTee.aedtz", "C:\Docu-


Examp- ments\OptimTee.aedt", False, True)
le

RestoreProjectArchive <Archivefilepath>, <ProjectFilePath>, <OverwriteExistingFiles>, <OpenPro-


VB Syntax
jectAfterRestore>
oDesktop.RestoreProjectArchive "C:\Users\jdoe\Documents\OptimTee.aedtz", _
VB Example
"C:\Documents\OptimTee.aedt", false, true

Desktop Object Script Commands 4-54


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

RestoreWindow
Restores a minimized Desktop window.

UI Access N/A
Parameters None.
Return Value None.

Python Syntax RestoreWindow()


oDesktop.RestoreWindow()
Python Example

VB Syntax RestoreWindow
VB Example oDesktop.RestoreWindow

ResumeRecording
Resume recording a script.

UI Access N/A
Parameters None.
Return Value None

Desktop Object Script Commands 4-55


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

Python Syntax ResumeRecording()


oDesktop.ResumeRecording()
Python Example

VB Syntax ResumeRecording
VB Example oDesktop.ResumeRecording

RunACTWizardScript

Note:
This command is for internal Ansys use only.

Python Syntax RunACTWizardScript()


Python Example oDesktop.RunACTWizardScript()

RunProgram
Runs an external program.

UI Access NA

Parameters Name Type Description

Desktop Object Script Commands 4-56


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

<ProgName> String Name of the program to run.


<ProgPath> String Location of the program. Pass in an empty string to use the system path.
<WorkPath> String Working directory in which program will start.
<ArgArray> Array of Arguments to pass to the program. If no arguments, pass in None
Strings

Return Value None

Python Syntax RunProgram (<ProgName>, <ProgPath>, <WorkPath>, <ArgArray>)


oDesktop.RunProgram("winword.exe", _
Python Example "C:\Program Files\Microsoft Office\Office10",_
"", None)

VB Syntax RunProgram <ProgName>, <ProgPath>, <WorkPath>, <ArgArray>


oDesktop.RunProgram "winword.exe", _
VB Example "C:\Program Files\Microsoft Office\Office10",_
"", None

RunScript
Launches another script from within the script currently being executed.

UI Access Tools>Run Script

Parameters Name Type Description

Desktop Object Script Commands 4-57


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

<SCriptPath> String Name or full path of the script to execute.


If the full path to the script is not specified, Twin Builder searches for the
specified script in the following locations, in this order:

1. Personal library directory.

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.

2. User library directory.

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.

3. System library directory.

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.

4. HFSS installation directory.

Long
Return Value
the return code for the script method.

Desktop Object Script Commands 4-58


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

Python Syntax RunScript (<ScriptPath>)


oDesktop.RunScript("C:/Project/test1.vbs")
Python Example

VB Syntax RunScript <ScriptPath>


VB Example oDesktop.RunScript ("C:/Project/test1.vbs")

RunScriptWithArguments
Similar to RunScript, launch another script from within the currently executing script, but with arguments.

UI Access NA

Name Type Description


<ScriptPath> String The name or full path of the script to execute. If the full path to the script
is not specified, the software looks for the script in the following loc-
ations:
l Personal library directory: "PersonalLib". The PersonalLib directory can
be specified in Tools>Options>General Options on the 'Project Options'
Parameters tab.
l User library directory: directory "userlib". The UserLib directory can be
specified in Tools>Options>General Options on the 'Project Options'
tab.
l System library directory: directory "syslib". The SysLib directory can be
specified in Tools>Options>General Options on the 'Project Options'
tab.

Desktop Object Script Commands 4-59


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

Software installation directory


l

<Arguments> String The arguments to supply to the specified script.

Long
Return Value
the return code for the script method.

Python Syntax RunScriptWithArguments (<ScriptPath>, <Arguments>)


oDesktop.RunScriptWithArguments
Python Example
("C:/Project/test2.py", "foo")

VB Syntax RunScriptWithArguments <ScriptPath>, <Arguments>


oDesktop.RunScriptWithArguments
VB Example
"C:/Project/test2.vbs", "foo"

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.

UI Access Tools > Job Management > Select Scheduler.

Name Type Description


Parameters
<option> String One of the following options (not case sensitive):

Desktop Object Script Commands 4-60


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

l Empty string for remote RSM service


l "RSM" for local RSM
l "Windows HPC" for Windows HPC
l "LSF" for Load-Sharing Facility