You are on page 1of 122

HWD Customization

Introduction to HyperView & HyperGraph


Customization

HyperWorks is a division of Altair altairhyperworks.com


Altair Engineering Support Contact Information
Web site www.altairhyperworks.com

Location Telephone e-mail

Australia 64.9.413.7981 anzsupport@altair.com

Brazil 55.11.3884.0414 br_support@altair.com

Canada 416.447.6463 support@altairengineering.ca

China 86.400.619.6186 support@altair.com.cn

France 33.1.4133.0992 francesupport@altair.com

Germany 49.7031.6208.22 hwsupport@altair.de

India 91.80. 6629.4500 support@india.altair.com


1.800.425.0234 (toll free)

Italy 39.800.905.595 support@altairengineering.it

Japan 81.3.5396.2881 support@altairjp.co.jp

Korea 82.70.4050.9200 support@altair.co.kr

Mexico 55.56.58.68.08 mx-support@altair.com

New Zealand 64.9.413.7981 anzsupport@altair.com

North America 248.614.2425 hwsupport@altair.com

Scandinavia 46.46.460.2828 support@altair.se

United Kingdom 01926.468.600 support@uk.altair.com

In addition, the following countries have resellers for Altair Engineering: Colombia, Czech Republic, Ecuador, Israel, Russia,
Netherlands, Turkey, Poland, Singapore, Vietnam, Indonesia
Official offices with resellers: Canada, China, France, Germany, India, Malaysia, Italy, Japan, Korea, Spain, Taiwan, United
Kingdom, USA

Copyright© Altair Engineering Inc. All Rights Reserved for:


HyperMesh® 1990-2014; HyperCrash® 2001-2014; OptiStruct® 1996-2014; RADIOSS®1986-2014; HyperView®1999-2014;
HyperView Player® 2001-2014; HyperStudy® 1999-2014; HyperGraph®1995-2014; MotionView® 1993-2014; MotionSolve® 2002-
2014; HyperForm® 1998-2014; HyperXtrude® 1999-2014; Process Manager™ 2003-2014; Templex™ 1990-2014; TextView™
1996-2014; MediaView™ 1999-2014; TableView™ 2013-2014; BatchMesher™ 2003-2014; HyperMath® 2007-2014;
Manufacturing Solutions™ 2005-2014; HyperWeld® 2009-2014; HyperMold® 2009-2014; solidThinking® 1993-2014; solidThinking
Inspire® 2009-2014; solidThinking Evolve®™ 1993-2014; Durability Director™ 2009-2014; Suspension Director™ 2009-2014;
AcuSolve® 1997-2014; AcuConsole® 2006-2014; SimLab®™2004-2014 and Virtual Wind Tunnel™ 2012-2014.

In addition to HyperWorks® trademarks noted above, Display Manager™, Simulation Manager™, Compute Manager™, PBS™,
PBSWorks™, PBS GridWorks®, PBS Professional®, PBS Analytics™, PBS Desktop™, PBS Portal™, PBS Application Services™,
e-BioChem™, e-Compute™ and e-Render™ are trademarks of ALTAIR ENGINEERING INC.

Altair trademarks are protected under U.S. and international laws and treaties. Copyright© 1994-2014. Additionally, Altair software
is protected under patent #6,859,792 and other patents pending. All other marks are the property of their respective owners.

ALTAIR ENGINEERING INC. Proprietary and Confidential. Contains Trade Secret Information. Not for use or disclosure outside of
ALTAIR and its licensed clients. Information contained inHyperWorks® shall not be decompiled, disassembled, or “unlocked”,
reverse translated, reverse engineered, or publicly displayed or publicly performed in any manner. Usage of the software is only as
explicitly permitted in the end user software license agreement.

Copyright notice does not imply publication


Table of Contents

Table of Contents

Introduction to HyperWorks
Desktop Customization

Chapter 1: Introduction to TCL ......................................................................... 7

About TCL .................................................................................................................................. 7

About Tk ..................................................................................................................................... 8

Basic Tcl Syntax ........................................................................................................................ 8

TCL Command Overview ......................................................................................................... 8

Tk Basic Commands ............................................................................................................... 23

Chapter 2: HyperWorks Desktop Environment ............................................. 29

The HyperWorks Desktop ..................................................................................................... 29

The Command Layer ..................................................................................................... 31

Exercise 2.1 Changing the Client Type using the Command Window ............................ 39

Practical Exercises .................................................................................................................. 42

Chapter 3: The Command Layer Explored ..................................................... 43

Command Categories .................................................................................................. 43

Basic Commands ......................................................................................................... 44

HyperWorks 13.0 Introduction to HWD Customization 3

Proprietary Information of Altair Engineering, Inc


Table of Contents

Working With Handles ................................................................................................. 46

Exercise 3.1 Basic Commands and Working with Handles ......................................... 49

Practical Exercises ..............................................................................................................................54

Chapter 4: The Animation Client .................................................................... 55

Animation Window ....................................................................................................... 55

Exercise 4.1 Loading a Model and Results File ........................................................... 59

Model Object ................................................................................................................ 61

Exercise 4.2 Working with the Model Object ............................................................... 67

Practical Exercises ....................................................................................................... 71

Chapter 5: Results and Query ......................................................................... 73

Applying Results .......................................................................................................... 73

Exercise 5.1:Contouring Results and Contouring by Selection .................................. 77

Querying Results ......................................................................................................... 81

Exercise 5.2 Querying Contoured Results and Creating a List of Results ................... 84

Practical Exercises ....................................................................................................... 88

Chapter 6: The Plotting Client ......................................................................... 91

The Plotting Window .................................................................................................... 91

Defining Curves from Data Files .................................................................................. 92

Defining Curves from Math Expressions ...................................................................... 94

Adding Notes to a Plot ................................................................................................. 95

Introduction to Templex Statements ............................................................................ 97

Exercise 6.1 Creating Plots and Notes with Templex inside the Notes ....................... 98

Practical Exercises ..................................................................................................... 106

Introduction to HWD Customization 4 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Table of Contents

Chapter 7: The MotionView Model Client ..................................................... 109

Model Window ........................................................................................................... 109

Solutions For Exercises ................................................................................. 113

HyperWorks 13.0 Introduction to HWD Customization 5

Proprietary Information of Altair Engineering, Inc


Table of Contents

Introduction to HWD Customization 6 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

Chapter 1

Introduction to Tcl/Tk

About TCL
Tcl (Tool Command Language) is used by developers worldwide and has become a
critical component in thousands of corporations. It has a simple and programmable
syntax and can be either used as a standalone application or embedded in application
programs. Best of all, Tcl is open source so it's completely free.

The main difference between Tcl and languages such as C is that Tcl is an interpreted
rather than a compiled language. Tcl programs are simply scripts consisting of Tcl
commands that are processed by a Tcl interpreter at run time. One advantage that this
offers is that Tcl programs can themselves generate Tcl scripts that can be evaluated at
a later time. This can be useful, for example, when creating a graphical user interface
with a command button that needs to perform different actions at different times.

One of Tcl's most useful features is its extensibility. If an application requires some
functionality not offered by standard Tcl, new Tcl commands can be implemented using
the C language, and integrated fairly easily. Since Tcl is so easy to extend, many people
have written extension packages for some common tasks, and made these freely
available on the Internet.

Businesses and engineering teams today are often faced with the problem of making
diverse collections of resources work together. We call these programming tasks
integration applications. For enterprises, the integration platform is becoming as
strategically important as the operating system and database platforms.

Tcl is the integration platform of choice because of its speed of use, breadth of
functionality, and enterprise-ready features such as thread-safety, internationalization
and cross platform deployment. The latest version of Tcl provides all the features an
enterprise needs for all integration and scripting needs.

HyperWorks 13.0 Introduction to HWD Customization 7

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

About TK
Tk is a graphical user interface toolkit that makes it possible to create powerful GUIs
quickly. It proved so popular that it now ships with all distributions of Tcl. Tk shares
many concepts with other windowing toolkits, but you do not need to know much about
graphical user interfaces to get started with Tk.

Tk adds about 35 Tcl commands that let you create and manipulate widgets in a
graphical user interface. A widget is a window in a graphical user interface that has a
particular appearance and behavior. The terms widget and window are often used
interchangeably. Widget types include buttons, scrollbars, menus, and text windows. Tk
also has a general-purpose drawing widget called a canvas that lets you create lighter-
weight items such as lines, boxes, and bitmaps.

Tcl and Tk are highly portable, running on essentially all flavors of Unix (Linux, Solaris,
IRIX, AIX, *BSD*, the list goes on and on), Windows, Macintosh, and more.

Some basic Tk commands will be discussed later. For additional information, please
refer to the manual.

Basic Tcl Syntax


• First item of a command line is a command name.
• The words in the command line are separated by one or more spaces.
• Words can be grouped with double quotes or curly braces.
• Commands are terminated with new line or semi-colon.
• A word starting with a dollar sign ($) must be a variable name. The string will be
replaced by the value of the variable.
• Words enclosed within square brackets must be a legal Tcl command. The
strings would be replaced by the results of evaluating the command.

TCL Command Overview


In the following command overview it is recommend that the students try the examples
themselves.

1. Text Output
Printing out a string using Tcl is done using the puts command. A single unit of text
after the puts command will be output.

Example 1.1
puts HyperWorks

Output: HyperWorks

Introduction to HWD Customization 8 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

If the string is more than one word, the string must be enclosed in either double quotes
(“ “) or braces ({ }). Many commands, including the puts command, accept multiple
arguments. If the string is not enclosed in quotes or braces, the individual words are
considered arguments. A set of words enclosed in quotes or braces will treated as a
single unit. The two options of quotes or braces behave differently and the differences
will be discussed in the next section.

Example 1.2
puts “This is an example with quotes”
puts {This is an example with braces}

Output:
This is an example with quotes
This is an example with braces

As mentioned above, a command in Tcl is terminated with a newline or semicolon. Tcl


comments are designated with a # at the beginning of the line or after a semicolon.

Example 1.3
# An example using a semicolon
puts “This is line 1”; puts {This is line 2};#Note after the ;

Output:
This is line 1
This is line 2

2. Variables and Variable Substitution


Unlike C, Tcl does not require that variables be declared before they are used. Tcl
variables are simply created when they are first assigned values. Values are assigned
using the set command. Although they do not have to be deleted, Tcl variables can be
deleted using the unset command.

The value stored in a variable can be accessed by prefacing the name of the variable
with a dollar sign ("$"). This is known as variable substitution, and is illustrated in the
examples below. A variable can be used to store a number, a date, a string, or even
another Tcl script.

Example 2.1:
set software "HyperWorks"
puts "The software we are using is $software"

Output:
The software we are using is HyperWorks

HyperWorks 13.0 Introduction to HWD Customization 9

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

Example 2.1 illustrates the use of variable substitution. The value "HyperWorks" is
assigned to the variable "software", whose value is then substituted for $software.
Note that variable substitution can occur within a string.

As Example 2.2 (below) shows, the backslash (\) disables substitution for the single
character following the backslash. Any character following the backslash will stand
without substitution. This is also true when the backslash precedes a quote, brace, or
bracket.

Example 2.2
set Z Albany
set Z_LABEL “This Capitol of New York is: “

puts “$Z_LABEL $Z” ; # Prints the value of Z


puts “$Z_LABEL \$Z”; #Prints a literal $Z instead of the value of
Z

Output
Albany
The Capitol of New York is:
The Capitol of New York is: Albany
The Capitol of New York is: $Z

When defining a string, if there are multiple words in the string we have learned that we
can either use double quotes or braces. The difference between these two options is
how they treat variables that are in their strings.

Example 2.3
puts "$Z_LABEL $Z"
puts {$Z_LABEL $Z}

Output
The Capitol of New York is: Albany
$Z_LABEL $Z

Example 2.3 shows how using the double brace actually disables the substitution of
variables within the braces. Note that braces have this effect only when they are used
for grouping (i.e. at the beginning and end of a sequence of words). If a string is already
grouped, either with quotes or braces, and braces occur in the middle of the grouped
string (i.e. "foo{bar"), then the braces are treated as regular characters with no special
meaning. If the string is grouped with quotes, substitutions will occur within the quoted
string, even between the braces.

Example 2.4:
set month 2
set day 3
set year 09
set date "$month:$day:$year"

Introduction to HWD Customization 10 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

puts $date

Output: 2:3:09

Here variable substitution is used in several places: The values of the variables "month",
"day", and "year" are substituted in the set command that assigns the value of the
"date" variable, and the value of the "date" variable is then substituted in the line that
displays the output.

Example 2.5:
set foo "puts hi"
eval $foo
Output:
hi

In this example, the variable "foo" holds another (small) Tcl script that simply prints the
word "hi". The value of the variable "foo" is substituted into an eval command. The
eval command takes one or more arguments which together comprise a Tcl script and
passes it to the Tcl interpreter.

3. Expressions
Tcl allows several types of expressions, including mathematical expressions and
relational expressions. Tcl expressions are usually evaluated using the expr command.
A Tcl expression consists of a combination of operands, operators, and parentheses.
White space may be used between the operands and operators and parentheses; it is
ignored by the expression's processor.

Operands may be specified in any of the following ways:

• As a numeric value, either integer or floating-point.


• As a Tcl variable, using standard $ notation. The variable's value will be used as
the operand.
• As a string enclosed in double-quotes. The expression parser will perform
backslash, variable, and command substitutions on the information between the
quotes, and use the resulting value as the operand
• As a string enclosed in braces. The characters between the open brace and
matching close brace will be used as the operand without any substitutions.
• As a Tcl command enclosed in brackets. The command will be executed and its
result will be used as the operand.

The valid operators are listed below, grouped in decreasing order of precedence. For a
detailed listing of what these operators please view the Tcl manual.
• - + ~ ! Unary minus, unary plus, bit-wise NOT, logical NOT.
• * / % Multiply, divide, remainder.
• + - Add and subtract.
• << >> Left and right shift.

HyperWorks 13.0 Introduction to HWD Customization 11

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

• < > <= >= Boolean less, greater, less than or equal, and greater than
or equal.
• == != Boolean equal and not equal.
• & Bit-wise AND.
• ^ Bit-wise exclusive OR.
• | Bit-wise OR.
• && Logical AND.
• || Logical OR.

Example 3.1:
expr 0 == 1

Output:
0

Example 3.2:
expr 1 == 1

Output:
1

Examples 3.1 and 3.2 illustrate the use of relational expressions with the expr
command. The first expression evaluates to 0 (false) since 0 does not equal 1, whereas
the second expression evaluates to 1 (true), since, obviously, 1 does equal 1. The
relational operator "==" is used to do the comparison.

Example 3.3:
expr 4 + 5

Output:
9

Example 3.3 shows how to use the expr statement to evaluate an arithmetic
expression. Here the result is simply the sum of 4 and 5.

Tcl supports the following mathematical functions in expressions:

abs cosh log sqrt


acos double log10 srand
asin exp pow tan
atan floor rand tanh
atan2 fmod round wide
ceil hypot sin
cos int sinh

In addition to these predefined functions, applications may define additional functions


using Tcl_CreateMathFunc().

Introduction to HWD Customization 12 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

Example 3.4:
expr sin(2)

Output:
0.909297

This example shows that the expr statement can be used to evaluate the result of a
mathematical function, in this case, the sine of an angle.

4. Command Substitution
Just as variable substitution is used to substitute the value of a variable into a Tcl script,
command substitution can be used to replace a Tcl command with the result that it
returns. Consider the following example:

Example 4.1:
puts "I am [expr 10*2] years old, and my I.Q. is [expr 100 - 25]"

Output:
I am 20 years old, and my I.Q. is 75

As this example shows, square brackets are used to achieve command substitution. The
text between the square brackets is evaluated as a Tcl script, and its result is then
substituted in its place. In this case, command substitution is used to place the results of
two mathematical expressions into a string. Command substitution is often used in
conjunction with variable substitution, as shown in Example 4.2:

Example 4.2:
set my_height 6.0
puts "If I was 2 inches taller, I would be [expr $my_height +
(2.0 / 12.0)] feet tall"

Output:
If I was 2 inches taller, I would be 6.16667 feet tall

In this example, the value of the variable "my_height" is substituted inside the square
brackets before the command is evaluated. This is a good illustration of Tcl's one-pass
recursive parsing mechanism. When evaluating a statement, the Tcl interpreter, makes
one pass over it, and in doing so makes all the necessary substitutions. Once this is
done, the interpreter then evaluates the resulting expression. If, during its pass over the
expression, the interpreter encounters square brackets (indicating that command
substitution is to be performed), it recursively parses the script inside the square
brackets in the same manner.

5. Comparisons and Loops


In all but the simplest scripts, some mechanism is needed to control the flow of
execution. Tcl offers decision-making constructs (if-else and switch statements) as

HyperWorks 13.0 Introduction to HWD Customization 13

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

well as looping constructs (while, for, and foreach statements), both of which can
alter the flow of execution in response to some condition. The following examples serve
to illustrate these constructs.

Example 5.1:
set k 35
if {$k == 35} {
puts "Handling is good."
} elseif {$k == 20} {
puts "Ride is good."
} else {
puts "I am not sure of the quality of ride or handling."
}

Output:
Handling is good.

Example 5.1 uses the if statement. It sets the value of the variable "k" to 35, and then
uses an if statement to choose which statement to print. The general syntax of the if
statement is as follows:

if test1 body1 ?elseif test2 body2 elseif ...? ?else bodyn?

If the test1 expression evaluates to a true value, then body1 is executed. If not, then if
there are any elseif clauses present, their test expressions are evalutated and, if true,
their bodies are executed. If any one of the tests is made successfully, after its
corresponding body is executed, the if statement terminates, and does not make any
further comparisons. If there is an else clause present, its body is executed if no other
test succeeds.

Another decision making construct is the switch statement. It is a simplification of the


if statement that is useful when one needs to take one of several actions depending on
the value of a variable whose possible values are known. This is illustrated in Example
5.2, which uses a switch statement to print a sentence, depending on the value of the
variable "num_legs".

Example 4.2:
set num_legs 4
switch $num_legs {
2 {puts "It could be a human."}
4 {puts "It could be a cow."}
6 {puts "It could be an ant."}
8 {puts "It could be a spider."}
default {puts "It could be anything."}
}

Output:
It could be a cow.

Introduction to HWD Customization 14 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

The switch statement has two general forms (both of which are described in detail in
the manual page), but the form used here is as follows:

switch ?options? string {pattern body ?pattern body ...?}

The string argument is compared to each of the patterns and if a comparison


succeeds, the corresponding body is executed, after which the switch statement
returns. The pattern "default", if present, is always matched, and thus its body always
executed if none of the earlier comparisons succeed.

It is often useful to execute parts of a program repeatedly, until some condition is met. In
order to facilitate this, Tcl offers three looping constructs: the while, for, and foreach
statements, each of which is shown in the examples below.

Example 5.3:
for {set i 0} {$i < 5} {incr i 1} {
puts "In the for loop, and i == $i"
}

Output:
In the for loop, and i == 0
In the for loop, and i == 1
In the for loop, and i == 2
In the for loop, and i == 3
In the for loop, and i == 4

The general syntax for the for loop is as follows:

for init test reinit body

The init argument is a Tcl script that initializes a looping variable. In the for loop used
in Example 5.3, the looping variable was called "i", and the init argument simply set it
to 0. The test argument is a Tcl script which will be evaluated to decide whether or not
to enter the body of the for loop. Each time this script evaluates to a true value, the
body of the loop is executed. The first time this script evaluates to false, the loop
terminates. The reinit argument specifies a script that will be called after each time
the body is executed. In Example 5.3, the reinit script increments the value of the
looping variable, "i" using the incr command. Thus, the for loop in this example
executes its body 5 times, before its test script evaluates to false, causing the loop to
terminate.

Example 5.4:
set i 0
while {$i < 5} {
puts "In the while loop, and i == $i"
incr i 1
}

HyperWorks 13.0 Introduction to HWD Customization 15

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

Output:
In the while loop, and i == 0
In the while loop, and i == 1
In the while loop, and i == 2
In the while loop, and i == 3
In the while loop, and i == 4

Example 5.4 illustrates the use of a while loop, the general syntax of which follows the
form:

while test body

The basic concept behind the while loop is that while the script specified by the test
argument evaluates to a true value, the script specified by the body argument is
executed. The while loop in Example 5.4 accomplishes the same effect as the for
loop in Example 5.3. A looping variable, "i", is again initialized to 0 and incremented
each time the loop is executed. The loop terminates when the value of "i" reaches 5.
Note, that in the case of the while loop, the initialization and re-initialization of the
looping variable are not part of the while statement itself. Therefore, the initialization of
the variable is done before the while loop, and the reinitialization is incorporated into its
body. If these statements were left out, the code would probably still run, but with
unexpected results.

Example 5.5:
foreach vowel {a e i o u} {
puts "$vowel is a vowel"
}

Output:
a is a vowel
e is a vowel
i is a vowel
o is a vowel
u is a vowel

The foreach loop, illustrated in Example 5.5, operates in a slightly different manner to
the other types of Tcl loops described in this section. Whereas for loops and while
loops execute while a particular condition is true, the foreach loop executes once for
each element of a fixed list. The general syntax for the foreach loop is:

foreach varName list body

The variable specified by varName takes on each of the values in the list in turn, and
the body script is executed each time. In Example 5.5, the variable "vowel" takes on
each of the values in the list "{a e i o u}" (Tcl list structure will be discussed in more detail

Introduction to HWD Customization 16 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

in the next section), and for each value, the body of the loop is executed, resulting in one
printed statement each time.

6. Lists
Lists in Tcl provide a simple means by which to group collections of items, and deal with
the collection as a single entity. When needed, the single items in the group can be
accessed individually. Lists are represented in Tcl as strings with a specified format. As
such, they can be used in any place where strings are normally allowed. The elements
of a list are also strings, and therefore any form of data that can be represented by a
string can be included in a list (allowing lists to be nested within one another).

Lists can be created in the following ways, in addition to being represented by a string.

by setting a variable to be a list of values


set lst {{item 1} {item 2} {item 3}}
with the split command
set lst [split "item 1.item 2.item 3" "."]
with the list command
set lst [list "item 1" "item 2" "item 3"]

An individual list member can be accessed with the lindex command. The following
examples will illustrate many important list commands:

Example 6.1:
set simple_list “John Joe Mary Susan”
puts [lindex $simple_list 0]
puts [lindex $simple_list 2]

Output:
John
Mary

Example 6.1 creates a simple list of four elements, each of which consists of one word.
The lindex command is then used to extract two of the elements in the list: the 0th
element and the 2nd element. Note that list indexing is zero-based. It is also important to
see that the lindex command, along with most other list commands, takes an actual
list as its first argument, not the name of a variable containing a list. Thus the value of
the variable "simple_list" is substitued into the lindex command.

The items in a list can be iterated through using the foreach command:

foreach varName list body

As mentioned previously, the foreach command will execute the body code one time
for each list item in list. On each pass, varName will contain the value of the next
list item.

HyperWorks 13.0 Introduction to HWD Customization 17

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

The length of a list can be determined using the llength command. Also, a value can
be inserted into a list using the linsert command. Another option is the lappend
command which appends values to a list. Examples 6.2, 6.3, and 6.4 show how these
commands can be used.

Example 6.2:
set names {Canada India USA UK}
puts “List length is: [llength $names]”

Output:
List length is: 4

Example 6.3
set names {Canada India USA UK}
set newnames [linsert $names 2 China]
puts “New list is: $newnames”

Output:
New list is: Canada India China USA UK

Example 6.4
set names {Canada India USA UK}
set newnames [lappend names China]
puts “New list is: $newnames”

Output:
New list is: Canada India USA UK China

Notice how with lappend the name of a variable containing the list (names) is used
rather than the list itself ($names).

7. Arrays
Unlike arrays in many other languages, Tcl arrays are indexed by keywords. The
keywords can be easy to remember strings or integers. The values of the array elements
can also be strings or numbers. A Tcl array is created when you assign the first array
element:

Example 7.1
set myArray(foo) "bar"
puts $myArray(foo)

Output:
bar

The array command is used in Tcl to manipulate array data. In Example 7.2 we use the
array command to create an array from a so-called option-value list.

Introduction to HWD Customization 18 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

Example 7.2
array set fruitColors {tomato red banana yellow}
puts $fruitColors(tomato)

Output:
red

For more information on arrays, please refer to your Tcl manual.

8. Strings
Most often, the task of extracting and manipulating information via a scripting language
is described using the term “string manipulation”. Strings are a set of alphanumeric
characters stored and manipulated together. These sets are concatenated, truncated, or
partitioned by the script with a specific end in mind.

All data items in Tcl, including numeric values, are treated as strings. They are treated
as other data types only as needed. This makes string manipulation and the associated
commands very important and frequently utilized.

There are a large number of string manipulation commands, as well as pattern and
regular expression matching. Example 8.1 contains some commonly used string
manipulation commands. For more in-depth explanations and a complete listing, please
refer to the Tcl manual.

Example 8.1
set str "This is Canada"
puts "The string is: $str"
puts "The length of the string is: [string length $str]"
puts "The character at index 3 is: [string index $str 3]"
puts "The characters from index 3 through end are: [string range
$str 3 end]"
puts "The index of the first occurrence of letter \"i\" is:
[string first i $str]“

Output:
This is Canada
The string is: This is Canada
The length of the string is: 14
The character at index 3 is: s
The characters from index 3 through end are: s is Canada
The index of the first occurrence of letter “I” is 2.

9. Writing and Reading Files


Since Tcl/Tk scripts run on a variety of platforms, and there are so many use cases for
accessing files, Tcl provides many commands for file manipulation. In this section we
will focus on how to open a file and then read and write data from that file. For more in-
depth explanations and a complete listing, please refer to the Tcl manual.

HyperWorks 13.0 Introduction to HWD Customization 19

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

The open command is used to open a file. The syntax for this command is:

open filename access

The access argument is used to indicate whether the file is read only (r), write only (w),
or read/write (w+), as well as other options. Example 9.1 illustrates how to open a write
only file and assign it to a variable. The open command returns a channel identifier
which is used by Tcl in the commands we will discuss later.

Example 9.1
set filename [open temp.txt “w”]

Output:
file4915610

In order to write data to the open file, the puts command is used. The syntax for the
puts command is

puts ?channelId? string

This command writes the characters given by string to the channel given by
channelId. ChannelId must be a channel identifier such as returned from the open
command. Also, the channel must have been opened for output (or writing). The puts
command also normally outputs a newline character after the string. Example 9.2 shows
how to open a write only file, add data to it, and then close the file.

Example 9.2
set filename [open "temp.txt" "w"]
puts $filename "We live in Canada."
puts $filename "Just Testing"
close $filename

Output: file4910020

The last option we will go over is how to read data from a file and assign it to variables.
This is done with the gets command. The syntax is

gets channelId

This command reads the next line from channelId and returns everything in the line up
to (but not including) the end-of-line character(s). Example 9.3 takes the file we wrote in
Example 9.2 and assigns each line to a variable.

Example 9.3
set filname [open "temp.txt" "r"]
set line1 [gets $filename]
set line2 [gets $filename]
close $filename

Introduction to HWD Customization 20 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

puts "Line 1: $line1"


puts "Line 2: $line2"

Output:
Line 1: We live in Canada.
Line 2: Just Testing

10. Procedures
Procedures in Tcl serve a similar purpose to functions in C. They can take arguments,
and can return values. The basic syntax for defining a procedure is:

proc name argList body

Once a procedure is created, it is considered to be a command, just like any other built-
in Tcl command. As such, it may be called using its name, followed by a value for each
of its arguments. The return value from a procedure is equivalent to the result of a built-
in Tcl command. Thus, command substitution can be used to substitute the return value
of a procedure into another expression.

By default, the return value from a procedure is the result of the last command in its
body. However, to return another value, the return command may be used. If an
argument is given to the return command, then the value of this argument becomes
the result of the procedure. The return command may be used anywhere in the body
of the procedure, causing the procedure to exit immediately.

Example 10.1:
proc sum_proc {a b} {
return [expr $a + $b]
}
proc magnitude {num} {
if {$num > 0} {
return $num
}
set num [expr $num * (-1)]
return $num
}
set num1 12
set num2 14
set sum [sum_proc $num1 $num2]
puts "The sum is $sum"
puts "The magnitude of 3 is [magnitude 3]"
puts "The magnitude of -2 is [magnitude -2]"

Output:
The sum is 26
The magnitude of 3 is 3
The magnitude of -2 is 2

HyperWorks 13.0 Introduction to HWD Customization 21

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

This example first creates two procedures, "sum_proc" and "magnitude". "sum_proc"
takes two arguments, and simply returns the value of their sum. "magnitude" returns
the absolute value of a number. After the procedure definitions, three global variables
are created. The last of these, "sum" is assigned the return value of the procedure
"sum_proc", called with the values of the variables "num1" and "num2" as arguments.
The "magnitude" procedure is then called twice, first with "3" as an argument, then with
"-2".

The "sum_proc" procedure uses the expr command to calculate the sum of its
arguments. The result of the expr command is substituted into the return statement,
making it the return value for the procedure.

The "magnitude" procedure makes use of an if statement to take different actions,


depending on the sign of its argument. If the number is postive, its value is returned, and
the procedure exits immediately, skipping all the rest of its code. Otherwise, the number
is multiplied by -1 to obtain its magnitude, and this value is returned. The same effect
could be achieved by moving the statement that multiplies the value by -1 into an else
clause, but the purpose of this example was to illustrate the use of the return
statement at several locations within a procedure.

11. Namespaces
Namespaces provide a means of organizing procedures and variables in Tcl. A
namespace basically creates a unique local scope. Within each unique scope, variables
and procedures created in that scope are isolated from both the global scope and from
other scopes. This allows the developer a means to segregate procedures and
variables in an organized manner. Namespaces can be nested, and procedures and
variables can be imported to, exported from, and referenced in other namespaces or the
global scope.

A global procedure acts just like any function within Tcl. A global procedure can be
called from a namespace without any need to import or otherwise localize the procedure.
A procedure within a namespace is local to the namespace unless it is explicitly called or
the procedure is exported from the namespace. The global scope is also designed such
that any variables defined outside of a procedure or a namespace are automatically in
the global scope. To access a global variable in a local scope, such as a procedure or
namespace, you will need to use the global command. As a script grows and as the
number of scripts running simultaneously increases, the ability of the developer to avoid
conflict between the names of procedures and variables defined in the global scope
decreases.

The namespace eval command lets you create new namespaces. For example,

namespace eval Counter {


namespace export bump
variable num 0

proc bump {} {

Introduction to HWD Customization 22 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

variable num
incr num
}
}

creates a new namespace containing the variable num and the procedure bump. The
commands and variables in this namespace are separate from other commands and
variables in the same program. If there is a command named bump in the global
namespace, for example, it will be different from the command bump in the Counter
namespace.

For more information on namespaces, please refer to your Tcl manual.

Tk Basic Commands
In this section we will go over 4 basic Tk widgets that are used with Tcl. These are the
tk_getOpenFile, tk_getSaveFile, tk_chooseDirectory, and
tk_messageBox procedures. These procedures allow you to set the full file name and
directory paths to be used in your Tcl scripts.

1. tk_getOpenFile
The tk_getOpenFile pops up a dialog box for the user to select a file to open. The
tk_getOpenFile command is usually associated with the Open command in the File
menu. Its purpose is for the user to select an existing file only. If the user enters a non-
existent file, the dialog box gives the user an error prompt and requires the user to give
an alternative selection. This dialog box does not open a file, it simply returns the
filename so that it can be used in your script.

Example 1.1
tk_getOpenFile

This command creates the GUI in Figure 1 where you can select an existing file from a
dialog box:

HyperWorks 13.0 Introduction to HWD Customization 23

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

Figure 1: GUI created from tk_getOpenFile command.

Example 1..2
set filename [tk_getOpenFile]
puts $filename

Output:
C:/Documents and Settings/training/My Documents/autosave.mvw

This sets the value of the variable filename to be the full file name of the file selected in
the dialog box (as shown in the output above).

There are additional options that can be used with tk_getOpenFile. The format for
the tk_getOpenFile with options is:

tk_getOpenFile ?option value ...?

The option presented below is the -filetypes option. There are additional options
available, please refer to the manual for these other options.

-filetypes filePatternList

If a filetypes listbox exists in the file dialog on the particular platform, this option gives the
filetypes in this listbox. When the user chooses a file type in the listbox, only the files of
that type are listed. If this option is unspecified, or if it is set to the empty list, or if the
filetypes listbox is not supported by the particular platform, then all files are listed
regardless of their types. Example 1.3 below shows how to set the filetypes list and use
it with the –filetypes option.

Examples 1.3

Introduction to HWD Customization 24 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

set types {
{{Text Files} {.txt} }
{{TCL Scripts} {.tcl} }
{{All Files} * }
}
set filename [tk_getOpenFile -filetypes $types]

Figure 2: GUI from tk_getOpenFile command with -filetypes option.

In Figure 2 above, the available file types are set to Text Files, TCL Scripts, and All
Files. As a result of using the –filetypes option, only these file types are listed.

2. tk_getSaveFile
The procedure tk_getSaveFile pops up a dialog box for the user to select a file to
save. This command is usually associated with the Saveas command in the File menu.
If the user enters a file that already exists, the dialog box prompts the user for
confirmation whether the existing file should be overwritten or not. The dialog itself does
not write out the file; it only returns the file name for your script to use.

This procedure behaves the same way as the tk_getOpenFile procedure does. It
even has the same options available. Below the –title option is shown.

Exercise 2.1
set filename [tk_getSaveFile –title “Select a File”]
puts $filename

Output:
C:/Documents and Settings/training/My Documents/test.txt

HyperWorks 13.0 Introduction to HWD Customization 25

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

Figure 3: GUI from tk_getSavwFile command with -title option.

Notice that the title of the dialog box in Figure 3 is “Select a File”.

3. tk_chooseDirectory
The procedure tk_chooseDirectory pops up a dialog box for the user to select a
directory. Example 3.1 shows how to set a directory name to a variable.

Example 3.1
set dirname [tk_chooseDirectory]
puts $dirname

Output:
C:/temp

Introduction to HWD Customization 26 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

Figure 4: GUI from tk_chooseDirectory command.

4. tk_messageBox
The procedure tk_messageBox procedure creates and displays a message window
with an application-specified message, an icon, and a set of buttons. The buttons, icon,
and message are specified with the various options that are available. Please refer to
your manual for a complete listing of these options.

Example 3.1 illustrates the tk_messageBox command with the message option. This
option allows you to specify the message to be displayed in the message box.

Example 4.1
tk_messageBox -message "This is the message to be displayed"

Output:

Figure 5: GUI from tk_messageBox command.

HyperWorks 13.0 Introduction to HWD Customization 27

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

Introduction to HWD Customization 28 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

Chapter 2
HyperWorks Desktop
Introduction

HyperWorks Desktop
In this chapter we will take a look at the HyperWorks Desktop Environment and
introduce the scripting language that is used to customize the product.
Customization is possible using the embedded scripting language of Tcl/Tk.
HyperWorks Desktop also offers a set of TCL commands that form the
Command Layer.

The HyperWorks Desktop is the framework that contains the applications


HyperView, MotionView, HyperGraph, HyperGraph 3D, TextView, MediaView,
and FE Model. Through this framework, other HyperWorks applications, such as
HyperMesh, Manufacturing Solutions, Data Manager, Process Manager,
HyperStudy, OptiStruct, as well as third party solvers, can be accessed.

Framework Overview
When the HyperWorks Desktop application is launched, a new session is
created. This session contains a project (only one project can be created), which
contains a page. The main display area of the Graphical User Interface (GUI) is
the page. Each page can contain from 1 to 16 windows. Any window on a page
can display an MBD model (MotionView), animation (HyperView), 2-D plot
(HyperGraph), 3-D plot (HyperGraph 3D), text (TextView), media file

HyperWorks 13.0 Introduction to HWD Customization 29

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

(MediaView), or HyperMesh file (FE Model). You can create any number of
pages in a session. However, only one page is displayed at a time and this page
is always referred to as the active page; the same applies for windows inside the
active page where only one window is considered active at any given time.
The GUI can be divided into six main areas (see figure 1). These areas are:

§ Menu Bar
§ Browser
§ Page
§ Window
§ Tool Bar
§ Panel

As an example, the figure below shows a session containing one page (page 1 of
1). The page consists of 3 windows each showing a different client. Window 1
showing an animation model (animation client), Window 2 is showing curves
(HyperGraph 2d client), and Window 3 is showing a test video (Video client).

HyperWorks Desktop Framework

Introduction to HWD Customization 30 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

Scripting Language
The HyperWorks Desktop framework is an open architecture systems where it
can be extended and customized using the scripting language Tcl/Tk. Using this
built-in scripting language, users can create utilities, macros, custom pop up
menus, context sensitive menus, dialogs, browser tabs, custom panels and other
widgets. These topics will be discussed in more details in subsequent sections.

When the application is launched, the Tcl/Tk interpreter is automatically initialized


and a set of commands are created to form the command layer inside the
framework. Every client in the HyperWorks Desktop framework has a command
associated with it. Each of these commands is created when the respective
client is loaded. These commands are:

§ “post” à Animation client


§ “hwplot” à HyperGraph 2D client
§ “plot3d” à HyperGraph 3D client
§ “texteditor”à TextView client
§ “video” à MediaView client
§ “model” à MotionView client

These commands are global and are used for creating the GUI components such
as panels, browser tabs, toolbar icons, etc… For example, if you need to add a
panel in the animation client you need to use “post panel add …”

Macros
A Macro can be defined as a tool, utility, or a set of functions that perform a
particular action – or a set of actions. Macros are simply Tcl scripts that are
created using Tcl; these scripts must have a names with “.tcl” extension. To
activate a particular Macro, the user must use the source command. For
example, if I have a Macro named my_macro.tcl, I have to use the following
command:

source my_maro.tcl

The Command Layer


As mentioned earlier, the scripting interface that’s available inside HyperWorks
Desktop is Tcl/Tk. Aside from the set of native commands provided by Tcl/Tk, a
set of HyperWorks Desktop specific commands are created to form the
Command Layer. This command layer is accessible and available to all clients
available inside the HyperWorks Desktop framework.

HyperWorks 13.0 Introduction to HWD Customization 31

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

The command layer was created based on the way the HyperWorks Desktop
framework is structured. The command layer can basically be broken into two
main levels, 1) common level, and 2) client specific level. In other words, the
same commands are used to get to the client level and after that, a separate set
commands exist for each client. This will be explained in more details in later
sections.

Command Types
The command layer is a set of TCL commands that follow a simple and
consistent syntax. All commands are object-centric, which means that you must
have an object to which a command can be applied. The basic command syntax
is:

{object_name} {command} {command parameter(s)}

These commands fall into four categories that manipulate the HyperWorks
database:
§ Handle Commands
§ Operation Commands
§ Property Commands
§ List Commands
These types will be explained in more details in Chapter 2.

Getting Started
The HyperWorks database consists of a hierarchy of objects, the root of which is
the hwi (HyperWorks Interface) object, which is automatically created. The hwi
command provides access to the hwISession object and a few high level utilities.
Currently, HyperWorks supports only one session per run and one project per
session. The session object can be retrieved by using the following command:

hwi GetSessionHandle session1

F
The last argument in the above command is a handle name. Remember that
“session1” is a arbitrary name chosen by the user. One could choose to name it
“session1” while another could choose to name it “my_session” or anything else.

Once the session handle is retrieved, it can be used to access all objects in the
HyperWorks database. The figure below shows an example of a typical session.

Introduction to HWD Customization 32 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

Session Example

For example, in order to get to “Page 2” and set its title to “My page”, you will
need to type the following commands:

session1 GetProjectHandle project1


project1 GetPageHandle page2 2
page2 SetTitle “My page”

Windows are assigned a client type, which can be modified. A window's client
type cannot be changed after the client handle has been retrieved. The client
handle must be released and retrieved again if the window's client type is
changed. For Example, in order to get to window 1 in page 1 and set the client
type to animation, you will need to type the following commands:

project1 GetPageHandle page1 1


page1 GetWindowHandle win1 1
win1 SetClientType "Animation"

Object Hierarchy
As mentioned earlier, the command layer has two levels. The first level is
common to all clients and applies at the framework level. This level starts at the
session object/command and down to the window. The figure below illustrates
the class hierarchy for the HyperWorks Desktop, MotionView, MediaView, and
TextView.

HyperWorks 13.0 Introduction to HWD Customization 33

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

Object Hierarchy for HyperWorks Desktop, MotionView, MediaView, and TextView

F The darker shade boxes in the diagrams above represent the common object
hierarchy.

The second level is unique to each client inside HyperWorks Desktop. Although
you might encounter commands that have the same syntax, it doesn’t mean that
they are common to other clients. Efforts have been made to keep consistency
for similar commands just to keep things simple and easier to learn. A good
example would be SetColor or SetLabel command where you will find them
available in more than one object and in different clients. The figures below show
the object hierarchy for the Animation client and Plot 2D clients respectively.

Introduction to HWD Customization 34 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

Object Hierarchy for Animation client

HyperWorks 13.0 Introduction to HWD Customization 35

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

Object Hierarchy for Plot 2D client

F
Remember that “hwi” command is available as soon as you launch the application
and it is the entry point to the command layer and provides access to all available
commands for all clients.

In this chapter, we have discussed very briefly some of the key components of
the command layer. This topic will be covered in greater detail in Chapter 3.

Introduction to HWD Customization 36 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

Documentation and Online Help


Documentation and Online Help is available for users and accessible by clicking
on the Help menu item and selecting HyperWorks Desktop or HyperWorks Help
Home.

Help Menu

The online help also contains extensive information on the programming


interface along with examples. This information is provided when selecting
HyperWorks Help Home from the main menu and then under Reference Guides
selecing HyperWorks Desktop. In the side browser you can find Programming
with Tcl/Tk Commands found under the HyperWorks Desktop Reference Guide.

Online Help

HyperWorks 13.0 Introduction to HWD Customization 37

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

Command Window
To access Tcl/Tk and the command layer inside HyperWorks Desktop, you need
to launch the Command Window. You can start the Command Window by
selecting View > Command Windiow. This places the Command Window at the
bottom of the HyperWorks Desktop GUI.

Command Window

The Command Window provides the user with an interactive environment. It also
allows users to load and save file TCL files, also known and scripts, as well as
saving a history of recent commands or scripts.

Working with Command Window


When working with the Command Window, here’s what you need to know and
remember:

§ To load a script (TCL file), use Fileà Load File menu item, or you can
simply type “source filename.tcl” in the console.
§ When typing a handle, you can use the tab key for auto-complete
feature (this only works for handles you have created, not for
commands).
§ Text highlighting is supported. All global commands are highlighted in
green and error code is highlighted in red.
§ You can click on an error (red text) to launch a new window displaying
the stack trace; this is very useful feature for debugging purposes.
§ Use the Up/Down arrow keys to go through commands in the history
§ All menu items are accessible via pop up menu using the right mouse
button
§ Copy and paste is supported via menu items, but also available by
highlighting any text and then using the middle mouse button to paste
(similar to UNIX functionality)
§ Use clear command to clear all text form the console

Introduction to HWD Customization 38 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

Exercise 2.1: Changing the Client Type using the Command


Window
In this exercise, the appropriate handles will be gotten so that the client type can be
changed to the plotting client.

Step 1: Launch HyperView and open the Command Window


1. From the Start Menu, select All Programs > Altair HyperWorks 12.0 >
HyperView.
This launches HyperWorks Desktop with the Animation client loaded.

2. Click on the View pulldown menu and select Command Window.


This launches the Command Window where Tcl commands can be entered.

Step 2: Enter the appropriate commands to get the session and project
handles.
1. In the first line of the Command Window, enter the following line and then press
Enter:

HyperWorks 13.0 Introduction to HWD Customization 39

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

hwi GetSessionHandle sess


This gets the session handle sess. Remember, the name of the handle can be any
name you want, it just can’t already exist. The output from the GetSessionHandle
command is either an error or if it is successful it is the handle name.
Also, notice how the commands are case sensitive.
2. Next, using the session handle sess, we can get the project handle by entering the
following line:
sess GetProjectHandle proj
This gets the project handle and it is named proj. For all the Get Handle
commands, just like the GetSessionHandle, the output is either an error or the
handle name.

Step 3: Enter the appropriate commands to get the page handle for page 1
and the window handle for window 1.
1. For the next line, enter the following:
proj GetPageHandle pg1 1
Notice that the GetPageHandle command requires the name of the handle as well
as the number of the page you wish to get the handle for.
2. Next, using the page handle pg1, we can get the window handle for window 1:
pg1 GetWindowHandle win1 1
The GetWindowHandle command also needs the window number which should be
gotten.

Step 4: Change the Client Type from Animation to Plot.


1. Now that we have the window handle, the SetClientType command can be used
to change the client from the Animation client to the Plotting client. Enter the
following in the Command Window:
win1 SetClientType plot
Notice that after you hit Enter that the HyperWorks Desktop changes and loads the
Plotting Client.

After entering all the commands, the Command Window should look like the
following:

Introduction to HWD Customization 40 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

HyperWorks 13.0 Introduction to HWD Customization 41

Proprietary Information of Altair Engineering, Inc.


Chapter 2 HyperWorks Desktop Introduction

Practical Exercises
Exercise 2a

Description
Start HyperWorks Desktop and launch the command window. By typing
commands inside the console, set the page title to “my first page”. To
view the page title in the Graphics area, you must first turn on the display
of the page title. Also, change the client type to Plot 2D.

Handles used
session, project, page, window

TCL/TK commands used


set, SetClientType, SetTitleDisplayed

Hints
If you make a make a mistake and need to release a handle, use the
ReleaseHandle command on the handle you would like to clear. For
example, if you need to release the project handle named proj, simply use
the following command:
proj ReleaseHandle

Introduction to HWD Customization 42 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

Chapter 3

The Command Layer Explored

In Chapter 2, we discussed how the TCL Command Layer was designed to


reflect the architecture of the HyperWorks Desktop environment. In this Chapter,
we will take a closer look at the Command Layer and explain how to work with
some of the key commands.

Command Categories
The TCL commands that are available in the Command Layer follow a simple
and consistent syntax. All commands are object-centric, which means that you
must have an object to which a command can be applied. The basic command
syntax is:

{object_name} {command} {command parameter(s)}

These commands fall into four categories that manipulate the HyperWorks
database:

1. Handle Commands: obtain access to other objects. Handle commands


have a "Get" prefix and a "Handle" suffix. Example:
session1 GetProjectHandle project1

2. Operation Commands: perform an operation or task. Example:


sess1 CaptureScreen "jpeg" "myimage.jpg"

HyperWorks 13.0 Introduction to HWD Customization 43

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

3. Property Commands: query operations prefixed by "Get" return the


internal state of an object. Mutate operations prefixed by "Set" modify the
internal state of an object. Examples:
page1 GetTitle
page1 SetTitle "My Page"

4. List Commands: return a list of values. List commands have a "Get"


prefix and a "List" suffix. Example:
anim GetModelList

F
Just like any generic TCL command, all HyperWorks Desktops’ commands are case
sensitive. Also, remember that every part of a command name starts with a Capital
letter (i.e. GetTitle, SetColor, GetSessionHandle,etc…)

Basic Commands
There are some basic commands that are necessary to know which allow users
to get started with using the command layer. These commands are available for
all clients inside the HyperWorks Desktop.

hwi Command
As mentioned earlier, the top level hwi command is created as soon as you
launch the application. It is a global command and is considered the entry point
to the Command Layer. When you launch the HyperWorks Desktop, you can
start the TkCon and then immediately type in the following command:

hwi GetSessionHandle session1

Using the session handle, you can get to any other object in the command layer.
Aside from the GetSessionHandle command, hwi command also supports the
following utility commands:

§ ListAllHandles
§ OpenStack
§ CloseStack

NOTE: these commands are covered in more details in “Working with Handles”
section.

Introduction to HWD Customization 44 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

ListMethods Command
Every command object supports the ListMethods commands. This command
does exactly what it says “it lists the methods available for a given object”.
Essentially, by remembering the hwi command and the ListMethods commands,
you can start exploring the command layer immediately.

Start the TkCon window, and type the following:

hwi ListMethods

This command will return the following:


Methods for hwi:
GetSessionHandle handle_name
ListAllHandles
OpenStack
CloseStack

The returned list of commands means that there are ONLY these four commands
available to use with the session object.

One way to learn the command layer is to use the ListMethods more often. It
provides a a quick way to figure out what commands are available for you to use
with a certain handle/command.

GetHandle Command
So far we know that command objects within the command layer can be
accessed using a special GetHandle command. Although this special command
varies from one abject to another, the idea is still the same where the command
follows these rules:

§ Starts with “Get”


§ Followed by “ObjectName”
§ Ends with “Handle”

For example: GetSessionHandle, GetPageHandle, and GetWindowHandle.

Every GetHandle command requires a handle name as an argument. This


command name is assigned by the user. For example, when getting a session
handle, you can choose the name to be my_session, session1, or any other
name. You will also notice that some GetHandle commands require one

HyperWorks 13.0 Introduction to HWD Customization 45

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

argument, a handle name, while other GetHandle commands require two


arguments, a handle name and an ID. Here’s what you need to remember:
§ Certain command object can have only one instance within any given
session, in this case you need only one argument
o Example: hwi GetSessionHandle my_session
§ Other command object can have multiple instances within any given
session, in this case you need two arguments
o Example: hwi GetPageHandle my_page 1

F
Remember that what we refer to as a “command object” is any object that can be
accessed using a “GetObjectNameHandle” command. For example,
GetSessionHandle, GetPageHandle.

Working with Handles


So far, the term handle has been used in many examples. In case this concept
is not clear enough, a handle:

§ Is a TCL command that gets created on demand using a GetHandle


command
§ Allows access to various command objects within the HyperWorks
Desktop
§ Allows users to get information and/or set attributes for certain command
objects
§ Is a TCL command that is global within a given session

This concept is essential to comprehend in order to understand and learn how to


work with the command layer.

Every HyperWorks’ command object supports the following utility commands:

§ ListHandles Lists the names of all command objects of the same type
§ ReleaseHandle Releases the command object

The top level hwi command object supports the following utility commands:

§ ListAllHandles: Displays all command objects currently in use within the


session
§ OpenStack: Begins automatic handle tracking
§ CloseStack: Ends automatic handle tracking and releases any handles
acquired during handle tracking

Introduction to HWD Customization 46 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

Handle Names
A handle name must be unique within a given session. If you try to violate this
rule, an error will occur. For example, if you type the following commands in
command window, you will get the appropriate error message:

hwi GetSessionHandle my_session


my_session
hwi GetSessionHandle my_session
my_session: object with this name already exists.

Because handle names must be unique, sometimes it can be challenging to


ensure that a handle name is unique within a session, especially when dealing
with large customization projects or when dealing with multiple scripts or macros.
It is recommended that you assign some “not-so-generic” names such as
session1, or page1. However, there is a way of coming up with unique names
that will be discussed in more advanced topics.

F
It is possible to get more than one handle to the same object. For example, I can get
two page handles at the same time and name them page1 and page_one. Although
this is allowed, it is not recommended as it adds confusion.

Getting and Releasing Handles


The rule of thumb to remember when working with handles is “Get the handle,
work with it and immediately release it”. Getting a handle is done by using the
appropriate GetHandle command (discussed earlier). Releasing a handle is
done by using the ReleaseHandle command, which means giving up access to
that command object; you can easily re-get access to the same object by using
the appropriate GetHandle command.

Releasing a handle is also necessary for the efficiency and performance of the
script. Here’s an example:

hwi GetSessionHandle session1


session1 GetProjectHandle project1
project1 GetPageHandle page1 1
page1 SetTitle “My page”
session1 ReleaseHandle
project1 ReleaseHandle
page1 ReleaseHandle

HyperWorks 13.0 Introduction to HWD Customization 47

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

In the example above, we did apply the rule of thumb, we got the handles, we
used them, and then we released them immediately.

Sometimes, it is hard to keep track of all handles that you are working with;
especially for more complicated procedures of macros. To make things easier,
the command layer offers two very important and useful commands, 1) hwi
OpenStack and 2) hwi CloseStack. These two commands will keep track of all
handles that were obtained within a scope and will automatically delete those
handles. Using the same example, we can show how to use these commands:

hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
project1 GetPageHandle page1 1
page1 SetTitle “My page”
hwi CloseStack

You can also use these commands by defining multiple scopes or even nested
scopes. To define a scope within a scope, you need to repeat the two
commands. Here’s an example:

hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
hwi OpenStack
project1 GetPageHandle page1 1
page1 GetWindowHandle win1 1
win1 SetClientType animation
hwi CloseStack
hwi CloseStack

The first CloseStack statement will release the handles that were obtained after
the second OpenStack statement (page1 and win1) and the second CloseStack
statement will release the remaining handles (session1 and project1).

Introduction to HWD Customization 48 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

Exercise 3.1: Basic Commands and Working with Handles


In this exercise, we will get the appropriate handles to set the page title for page 1. In
addition, the strength of the OpenStack and CloseStack commands as well as the
ListMethods command will be shown.

Step 1: Launch HyperView and open the Command Window


1. From the Start Menu, select All Programs > Altair HyperWorks 12.0 >
HyperView.
This launches HyperWorks Desktop with the Animation client loaded.

2. Click on the View pulldown menu and select Command Window.


This launches the Command Window where Tcl commands can be entered.

Step 2: Enter the appropriate command to get the session handle.


1. In the first line of the Command Window, enter the following line and then press
Enter:
hwi GetSessionHandle my_session

HyperWorks 13.0 Introduction to HWD Customization 49

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

This gets the session handle my_session. my_session is also returned as the
output of the GetSessionHandle command as this command was successful.
2. Remember that handle names are unique within a given session. Enter the following
line again into the command window to view the error message which occurs
hwi GetSessionHandle my_session

Step 3: Enter the appropriate commands to get the project and page handle
for page 1.
1. For the next line, enter the following:
my_session GetProjectHandle proj_1
2. Next, using the proj handle proj_1, we can get the page handle for page 1:
proj_1 GetPageHandle page1 1
Notice how the GetPageHandle command needs the page number in addition to
the handle name.

Step 4: Set the page title using the SetTitle command on the page handle.
1. Now that we have the page handle, the SetTitle command can be used to set the
page title for page 1. Enter the following in the Command Window:
page1 SetTitle Pg1_Animation
2. After hitting Enter, go into the Session Browser, you will see that the page title has
been updated to Pg1_Animation:

Introduction to HWD Customization 50 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

Step 5: Release each of the handles as they are no longer needed


1. To release the page handle, use the ReleaseHandle command. Type the
following into the Command Window:
page1 ReleaseHandle
2. The same process is done to release the project handle and the session handle.
Type the following two lines into the Command Window to release these handles:
proj_1 ReleaseHandle
my_session ReleaseHandle

Notice how for each of the handles, the ReleaseHandle command needs to be
used. While this isn’t too cumbersome when there are only three handles, when
there are more handles, this very cumbersome. In Step 6 the OpenStack and
CloseStack commands are used to eliminate the need to release the handles
individually.

HyperWorks 13.0 Introduction to HWD Customization 51

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

Step 6: Set the page title for page 1 using the OpenStack and CloseStack
commands.
1. Before getting any handles, use the OpenStack command to keep track of the
handles. Enter the following command into the Command Window:
hwi OpenStack
2. The same process is used to get the appropriate handles and set the page title.
Enter the following commands in to the Command Window:
hwi GetSessionHandle my_session
my_session GetProjectHandle proj_1
proj_1 GetPageHandle page1 1
page1 SetTitle Pg1_Animation_updated
3. Next, let’s use the ListMethods command on the page handle to see what other
commands are available:
page1 ListMethods
This returns the following list of commands as well as the necessary input for each
command:

Introduction to HWD Customization 52 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

4. Notice that there is a GetTitle command. This command will return the page title
for the given page handle:
page1 GetTitle

5. Finally, use the CloseStack command to release all the handles which exist
between the OpenStack command and this point.
hwi CloseStack
Using the OpenStack and CloseStack commands is a much more efficient way to
manage handles.

HyperWorks 13.0 Introduction to HWD Customization 53

Proprietary Information of Altair Engineering, Inc.


Chapter 3 The Command Layer Explored

Practical Exercises
Exercise 3a

Description
Create a HW session with 3 pages. The first page has one window, the
second page two windows, and the third page 3 windows. On the third
page, set window 1 to animation, window 2 to plot, and window 3 to the
text editor. Make 3rd page active. And finally, make use that no handles
exist after you execute the script. Save a history file and then load the
history file to re-run the same commands.

Handles used
session, project, page, window
TCL/TK commands used
SetClientType, AddPage, SetActivePage
Hints
You need to find out the proper command to set the right layout. Look in
the online help.

Introduction to HWD Customization 54 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc.


Chapter 4 The Animation Client

Chapter 4

The Animation Client

In this Chapter, we will start working with the animation client. We will take a
detailed look at two Command Objects in particular; the Post and the Model
objects. We will also cover some of the most frequently used functionality, such
as loading a model and attaching results. As you start writing macros for the
animation client, you will notice that the objects that you will use the most are the
Post and the Model objects.

Animation Window
For any given window within a session, you can set the client type to Animation.
By doing so, you are essentially loading the animation client into that window,
which in turn creates the post object. Sometimes both terms, post and
animation, are used interchangeably; however, it is important to understand that
Animation is just a client type while post is an actual TCL command created
inside the animation client.

Assuming we have a session with one page and one window, here’s how you
can set the client type to animation.

hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
project1 GetPageHandle page1 1
page1 GetWindowHandle win1 1
win1 SetClientType Animation
hwi CloseStack

HyperWorks 13.0 Introduction to HWD Customization 55

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

Remember that you don’t always have to set the client type to animation. When you

F launch HyperView, the client is animation by default. Using the window handle, you
can also get the client type using GetClientType command.

Animation Client Handle


After setting the client type, you can access the animation client and get full
access to its functionality. To access the animation client, you need to use the
GetClientHandle command off the window.

page1 GetWindowHandle win1 1


win1 GetClientHandle anim

The figure below shows a portion of the object hierarchy; you can clearly see that
the poIPost, which is equivalent to the animation client, gives you access to
major functionalities such as measures, notes, section cuts, and the model.

Post Object

F The prefix “poI” is used internally for naming the classes within the animation client.
It stands for “post Interface”.

When working with the client handle, one thing to remember is that you always
have to add an object first using the appropriate Add command (i.e. AddModel,
AddMeasure, AddNote and AddSectionCut). The Add command returns an ID
that you should use to get the proper handle.

Loading a Model
One of the basic functionalities provided by the animation client handle is the
ability to load a model. This is done using the AddModel command. Continuing

Introduction to HWD Customization 56 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

with the previous example and assuming that we have a H3D model named
bumper.h3d; we can load the model using the following statement:

page1 GetWindowHandle win1 1


win1 GetClientHandle anim
anim AddModel bumper.h3d

If you look at the documentation provided for the AddModel command, you will
see that it requires two arguments, 1) the file name and 2) an optional reader
name; you don’t have to worry about the second argument as HyperView will
recognize the model automatically and assign the proper reader.

HyperView allows you to overlay multiple models in the same window. This is
the default behavior for the AddModel command. Therefore, to overlay two
models (bumper.h3d and bumper_foam.h3d) in the same window, you need the
following statements:

anim AddModel bumper.h3d


anim AddModel bumper_foam.h3d
anim Draw

Furthermore, if you have a model loaded in the window and you need to load a
new model (not overlay), then you can use the Clear command.

anim Clear
anim AddModel bumper_foam.h3d
anim Draw

F
The statement “anim Draw” is needed to update the graphics. Without it, you won’t
be able to see that the model was loaded unless you force a draw by resizing the
Application or moving the TkCon window around.

Attaching Results
So far, we were able to load a model in the animation window. However, we
don’t have any results loaded or attached to the model, which means we can’t
animate or created a contour plot. Just like in the File Load panel in HyperView,
we need to specify a model file name as well as a results file name.

HyperWorks 13.0 Introduction to HWD Customization 57

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

To attach results to the loaded model, we need to use the model object by
getting a model handle. We can do this by using the GetModelHandle command
available in the post object. The GetModelHandle requires two arguments, 1)
handle name and 2) model id. We can choose any name for the fist argument;
however, we need a valid id for the second argument. We can get a valid id from
the AddModel command, which returns a model id. Here’s an example:

set id [anim AddModel bumper.h3d]


anim GetModelHandle my_model $id

Now that we have a valid model handle (my_model), we can attach results using
the SetResult command.

my_model SetResult bumper.h3d

At this point, we have a model and its results loaded. We can animate and/or
view results such as contour, tensor, and vector plots.

Therefore, to load a model and attach results, here is a full set of commands that
are needed:

hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
project1 GetPageHandle page1 1
page1 GetWindowHandle win1 1
win1 GetClientHandle anim
anim Clear
set id [anim AddModel bumper.h3d]
anim GetModelHandle my_model $id
my_model SetResult bumper.h3d
anim Draw
hwi CloseStack

F
When getting a model handle, try to avoid assuming that the id is going to be 1 (for
example: anim GetModleHandle my_model 1). Instead, use a valid id that you can
get using proper commands such AddModel or GetActiveModel.

Introduction to HWD Customization 58 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

Exercise 4.1: Loading a Model and Results File


In this exercise, we will load a model and results file into the session using the command
layer. First we will set the client type to animation and get the client handle. Next we will
add a model file and then the results file

Step 1: Launch HyperView and open the Command Window


1. From the Start Menu, select All Programs > Altair HyperWorks 12.0 >
HyperView.
This launches HyperWorks Desktop with the Animation client loaded.
2. Click on the View pulldown menu and select Command Window.
This launches the Command Window where Tcl commands can be entered.

Step 2: Enter the appropriate command to get the session handle, project
handle, page handle and window handle.
1. First, use the OpenStack command to keep track of all the handles we are going to
get in this exercise:
hwi OpenStack
2. In the Command Window, enter the following lines to get the session handle and
the project handle:
hwi GetSessionHandle sess
sess GetProjectHandle proj
3. Next get the page handle for page 1 and the window handle for window 1:
proj GetPageHandle pg1 1
pg1 GetWindowHandle win1 1

Step 3: Set the client type to animation and then get the client handle:
1. When HyperView is launched, by default the animation client is loaded. If the
animation client is not loaded, you can set this by using the SetClientType
command on the window handle. Enter the following line in the Command Window:
win1 SetClientType Animation
2. Now that the client type has been set, you can access the animation client and get
full access to its functionality using the GetClientHandle command. Enter the
following line into the Command Window:
win1 GetClientHandle anim
Now that we have the client handle (which is the post object), we now have access
to major functionalities such as measures, notes, section cuts, and the model object.

HyperWorks 13.0 Introduction to HWD Customization 59

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

Step 4: Load a model file and a results file into the animation client.
1. Now that we have the client handle, a model file and results file can be loaded into
the session. First, let’s load the model file into the session. Cd to folder where the
file bezel.h3d is located. Enter the following in the Command Window:
cd “C:/Program Files/Altair/13.0/tutorials/mv_hv_hg/animation”
If HyperWorks is installed in a different location, you will have to update the path
above to point to the appropriate folder.
2. Next, let’s load the file bezel.h3d into the session as the model file.
set id [anim AddModel bezel.h3d]
The complete path to the file bezel.h3d could also have been used in the
AddModel command, but because we moved to the correct directory, we can simply
use the filename.
Also, notice how the result of the AddModel command is assigned to the variable id.
This is because the result of the AddModel command is the model id.
3. Notice that while we loaded the file into the session, the graphics area still remains
blank. This is because we need to update the graphics using the Draw command:
anim Draw
4. Next, we need to get the model handle so that the result file can be loaded into the
session:
anim GetModelHandle my_mod $id
Notice how the GetModelHandle command needs a model id passed to it in
additionl a model handle. This is why the result of the AddModel command was
assigned to the id variable.
5. In order to load the results into the session, the SetResult command is used on
the model handle:
my_mod SetResult bezel.h3d
6. Finally, the last step needed is to draw the graphics again and to close the stack to
release the handles:
anim Draw
hwi CloseStack

Introduction to HWD Customization 60 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

Model Object
So far, we loaded a model and attached results to it in an animation window.
Once a model is loaded, we can get a model handle and start exploring what
else we can do. In fact, if you list all methods available in the model handle, you
will get a list of about 100 methods. This of course means that there is so much
you can do using the model object. The figure below shows a part of the object
hierarchy, which shows all objects that the model object has access to.

Notice that this is for poIModel which is the HyperView or animation model
object. There is also a mdlIModel which is the MotionView model object.

Model Object

These objects include the Result Control, Query Control, Selection Sets and
many other objects. Also, the Result Control provides access to Contour,
Tensor, and Vector controls along with other result type information and features.

Working with the Model Handle


When working with HyperView, there is only one active model within a session at
any given time. However, when working with the command layer, you can work
with any model that’s loaded in the session; you are not restricted to the active
model only, as long as you get the proper model handle.

Consider the following scenario, we have one page with two windows; window 1
has bumper.h3d loaded and window 2 has bumper_foam.h3d loaded. Now, let’s
get some information about the model, such as label and file name.

HyperWorks 13.0 Introduction to HWD Customization 61

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
project1 GetPageHandle page1 1

#get information from first model


page1 GetWindowHandle wn1 1
wn1 GetClientHandle anim1
anim1 GetModelHandle model1 [anim1 GetActiveModel]
set label1 [model1 GetLabel]
set name1 [model1 GetFileName]
# print info
puts "Model 1 info:\n Label: $label1\n Name:$name1"

#get information from second model


page1 GetWindowHandle wn2 2
wn2 GetClientHandle anim2
anim2 GetModelHandle model2 [anim2 GetActiveModel]
set label2 [model2 GetLabel]
set name2 [model2 GetFileName]
# print info
puts "Model 2 info:\n Label: $label2\n Name:$name2"

hwi CloseStack

F
If you have a model handle and the model gets deleted, then the handle is not valid
anymore, although it still exists. The same applies to any other handle like a window
or a page etc…

Result Control
The result control is commonly used in macros or any customization projects.
Just like any other control or object, you need to get result handle to gain access
to the loaded results. The result control handle allows you to query information
such as load cases, simulation steps and data types. It also allows you to apply
results such as contour, tensor and vector plots and other features.

In the following example we are going to get a list of data types for the current
load case (also referred to as subcase).

Introduction to HWD Customization 62 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
project1 GetPageHandle page1 1
page1 GetWindowHandle wn1 1
wn1 GetClientHandle anim
anim GetModelHandle my_model [anim GetActiveModel]
my_model GetResultCtrlHandle my_result
set current [my_result GetCurrentSubcase]
set data_types [my_result GetDataTypeList $current]
hwi CloseStack

If you look at the documentation for GetDataTypeList command, you will notice
that it accepts an additional optional argument “context”. This argument is
helpful to get a subset of data types (scalar, tensor or vector) instead the whole
list. For example, if you are only interested with the tensor data types, then you
can specify the optional arguments. Going back to the above example, the
statement would be:

set data_types [my_result GetDataTypeList $current tensor]

This will return a list of tensor data types only, which is the same list available in
the tensor panel inside HyperView.

F
You should never assume that loadcase IDs start at 1. It is possible to have one
load case and its ID is not 1, or multiple load cases with arbitrary IDs like 14, 22, 200
etc…

Query Control
The query control allows you to query or get information for all entity types in the
model. The information is the same that’s available in the query panel. Aside
form basic information you can also query results, such as stress values,
displacements, etc…

To start working with the query control, you need to get a handle and then
perform the desired query. When working with the query control you have to
remember the following:

§ Choose the entity type (i.e. node, element, component or system)


§ Specify the request (i.e. “node.id”, “contour.value” etc…)

HyperWorks 13.0 Introduction to HWD Customization 63

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

§ Specify a set of entities that you need information for (i.e. all nodes, or IDs
100-200, or all entities above/below a certain contour value, etc…)
§ Output the data to a file or any other channel

In the following example, we are going to assume that we have bumper.h3d


loaded and we have a model handle named my_model. We will get the
coordinates for a set of nodes ranging from 1 to 100; we will output the data to a
file named “out.txt”.

my_model GetQueryCtrlHandle my_query


# create a node set and add ids 1-100
set set_id [my_model AddSelectionSet node]
my_model GetSelectionSetHandle node_set $set_id
node_set Add "id <= 100"
my_query SetSelectionSet $set_id
# ask for ids and coordinates
my_query SetQuery "node.id node.coords"
my_query WriteData out.txt
# clean up
my_model RemoveSelectionSet $set_id

This example gives a general overview of the query control. In the next chapter,
we will provide more detailed examples. Also, this example uses the “selection
set” object, which will be covered in the next section.

Selection Sets
A Selection Set can be defined as a place-holder for entities that are supported
inside HyperView; these entities are nodes, elements, parts/components and
systems. Selection sets are used extensively and are needed by many
objects/commands in the command layer. Almost all result related objects
(contour, tensor, vector, fld, etc…) as well as other controls, such as the
exploded view and query, require a selection set.

Because selection sets are used quite often, it is very important to learn how to
use them efficiently in a macro or any script. There are a few basic rules to
remember:

1. Create the needed set of the right type


2. Add/Remove entities and use it based on your needs
3. Remove it when it is not needed

Introduction to HWD Customization 64 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

It is very important to remove the selection set after it is not needed. Having
many selection sets (especially if they are populated with IDs) will affect the
overall macro performance and memory usage.

Creation of a selection set is done via the AddSelectionSet command. This


command requires a valid entity type (node, element, part/component,
assemblies, and system) and it returns a set ID. This ID should be used to get a
selection set handle. In the following examples, we are going to assume that we
have a valid model handle named my_model.

# create an element set


set set_id [my_model AddSelectionSet element]
my_model GetSelectionSetHandle elem_set $set_id

Now let’s add some element ID {10 20 30 40 50 60 70 80 90 100}

set id_list { 10 20 30 40 50 60 70 80 90 100}


foreach id $id_list {
elem_set Add "id $id"
}

Now let’s subtract all IDs below 50

elem_set Subtract "id < 50"

So now we are left with a selection set that has the following IDs: 50 60 70 80 90
and 100. Furthermore, let’s add all elements that are adjacent to the elements in
the set.

elem_set Add adjacent

And finally, let’s subtract any TRIAS that are selected.

elem_set Subtract "config 103"

As you can see in this example, the selection set offers a lot of methods to help
you build the needed set of entities to work with. In addition, you can reverse the
selection and even add by contour value for example. The online help offers a
comprehensive example showing all available methods.

HyperWorks 13.0 Introduction to HWD Customization 65

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

Groups and Sets


Aside from the basic operations, selection sets can also be used to create groups
inside HyperView. Just like in the Groups Panel, you can see the selected
entities highlighted on the screen with their respective IDs. All you need to
create a group is to add a selection set and set its label. For example, let’s
create a group of all elements that have a contour value above 1200 (assuming
we have bumper.h3d loaded and a contour plot of Stress).

set set_id [my_model AddSelectionSet element]


my_model GetSelectionSetHandle elem_set $set_id
elem_set Add "contour > 1200"
elem_set SetLabel "Stress > 1200"
elem_set SetIDVisibility true
elem_set SetVisibility true
elem_set SetColor yellow

After creating this group, you should be able to go to the Groups Panel and turn
the display on/off or change other options.

Introduction to HWD Customization 66 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

Exercise 4.2: Working with the Model Object


In this exercise, we will load a model and results file into the session. Using the model
handle the mesh mode will be determined and then updated to show meshlines. Also
get a list of the subcase ids. Finally, create a selection set of elements with an id of
greater than 500. Print the size of the selection set and the type of entity in the selection
set.

Step 1: Launch HyperView and open the Command Window


1. From the Start Menu, select All Programs > Altair HyperWorks 12.0 > HyperView.
This launches HyperWorks Desktop with the Animation client loaded.
2. Click on the View pulldown menu and select Command Window.
This launches the Command Window where Tcl commands can be entered.

Step 2: Enter the appropriate command to get the session handle, project
handle, page handle and window handle.
1. First, use the OpenStack command to keep track of all the handles we are going to
get in this exercise:
hwi OpenStack
2. In the Command Window, enter the following lines to get the session handle and
the project handle:
hwi GetSessionHandle sess
sess GetProjectHandle proj
3. Next get the page handle for page 1 and the window handle for window 1, then get
the client handle:
proj GetPageHandle pg1 1
pg1 GetWindowHandle win1 1
win1 SetClientType Animation
win1 GetClientHandle anim

Step 3: Load a model file and a results file into the animation client.
1. Now that we have the client handle, a model file and results file can be loaded into
the session. First, let’s load the model file into the session. Cd to folder where the
file bezel.h3d is located. Enter the following in the Command Window:
cd “C:/Program Files/Altair/13.0/tutorials/mv_hv_hg/animation”
2. Next, let’s load the file bezel.h3d into the session as the model and result file.

HyperWorks 13.0 Introduction to HWD Customization 67

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

set id [anim AddModel bezel.h3d]


anim GetModelHandle my_mod $id
my_mod SetResult bezel.h3d
3. Refresh the graphics area using the Draw command:
anim Draw
Step 4: Using the model handle, determine what the current mesh mode is
and then update the mesh mode to meshlines
1. Using the GetMeshMode command on the model handle, the current mesh mod can
be determined:
my_mod GetMeshMode

This returns the value of none. The other options available are edges, features, or
meshlines.
2. In the Command Window, use the SetMeshMode command with the model handle:
my_mod SetMeshMode meshlines
Notice that the graphics doesn’t update and draw the meshlines. This is because the
Draw command is needed again.
3. Refresh the graphics area using the Draw command:
anim Draw
Step 5: Using the result control handle, get the subcase list and then get
the subcase type for the first subcase.
1. To get the list of subcases, we first have to get the ResultCtrl handle. Use the
following line to do this:
my_mod GetResultCtrlHandle my_res
Using the model handle, my_mod, we were able to get the ResultCtrl handle,
my_res.
2. Now that we have the ResultCtrl handle, we can generate a list of subcases. This is
done using the GetSubcaseList command on the ResultCtrl handle. We can
assign the output from this command to a variable using the following statement:
set subcase_list [my_res GetSubcaseList base]
Notice that the output of this command is the following list:

Introduction to HWD Customization 68 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

1 2 3 4
These are the subcases in the model. In the next step we will use the variable
subcase_list and determine the type of subcase that subcase 1 is.
3. Use the GetSubcaseType command to determine the type of subcase that subcase
1 is:
my_res GetSubcaseType [lindex $subcase_list 0]
The output from this command is linear, which is the type of subcase that subcase
1 is.

Step 6: Create a selection set of elements which contains all elements with
an id greater than 200. Then print the size of the selection set and the type
of entities in the selection set.
1. Using the model handle, we can use the AddSelectionSet command to create a
new selection set containing elements. The output of this command is an id for the
selection set. We will assign the output to a variable so that this id can be used later.
Enter the following into the Command Window:
set set_id [my_mod AddSelectionSet element]
2. The next step is to get the selection set handle from the model handle. In this
command, the selection set id is needed. Enter the following into the Command
Window:
my_mod GetSelectionSetHandle elem_list $set_id
There is a method for getting the selection set handle and adding a new selection set
in a single step. This would be done in the following manner (do not enter this in the
Command Window, this is simply to illustrate another method of doing the same
thing:
my_mod GetSelectionSetHandle elem_list [my_mod AddSelectionSet element]
3. Now that we have the selection set handle, we can add elements to this selection set
using the Add command on the selection set handle. To add elements with the id
greater than 200, the expression “id > 200” is used. Enter the following into the
Command Window:
elem_list Add “id > 200”
4. Finally use the following line to print the size of the selection set and the type of
entities in the selection set:
puts “Selection Set [elem_list GetSize] [elem_list GetType]”
Notice how the selection set handle elem_list is used with the GetSize command (to
get the number of entities in the selection set) and the GetType command (to get the
type of entities in the selection set). The output from this line is the following:
Selection Set 36 element

HyperWorks 13.0 Introduction to HWD Customization 69

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

5. The last step is to close the stack to delete the handles created during this exercise:
hwi CloseStack

Introduction to HWD Customization 70 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

Practical Exercises

Exercise 4a

Description
Load two models (bezel.h3d and bezel_iter2.h3d) in two separate
windows. Both of these files are located in C:/Program
Files/Altair/13.0/tutorials/mv_hv_hg/animation. First, capture the screen to
a file name screen.jpg and then capture each window separately to two
separate files, window1.jpg and window2.jpg

Handles used
session, project, page, window, client

TCL/TK commands used


AddModel, CaptureScreen, SetActiveWindow, CaptureActiveWindow

Hints
Use the session to capture screen and then set the active window to
capture the individual windows.

Exercise 4b

Description
Load bezel.h3d. Get the following information: number of nodes,
elements and parts. Create a note displaying the information you have
acquired.

Handles used
session, project, page, window, client, model, selection set, note

TCL/TK commands used


GetSize, AddNote, SetText

Hints
Use the GetSize command on the selection set handle to get the number
of elements in the selection set.

HyperWorks 13.0 Introduction to HWD Customization 71

Proprietary Information of Altair Engineering, Inc


Chapter 4 The Animation Client

Introduction to HWD Customization 72 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Chapter 5

Results and Query

So far, we have learned how to load a model, attach results and perform some
basic queries. In this chapter, we will take a closer look at applying results (i.e.
contour, vector, tensor, etc), and querying these results and other important
information.

Applying Results
Looking at the figure below, we can see that from the result control object you
can access all other result-related objects including contour, iso value, tensor,
vector, etc. To apply any type of results, you have to make sure that you have
attached a results file to the model that’s loaded in the animation client.

Result Control

Once you have a result control handle, you can get a handle to the desired
control using GetNameCtrlHandle (i.e. GetContourCtrlHandle, Get

HyperWorks 13.0 Introduction to HWD Customization 73

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

TensorCtrlHandle, etc). The methods provided by the various control are almost
identical (i.e. SetDataType, SetDataComponent, etc). Once you get familiar with
one control, then it is easy to work with the rest. For the purpose of this training
material, we will cover the contour control in the next section.

Contour Plot
The first thing to remember when working with the contour control is that you get
the contour control handle and work with it without having a contour plot
displayed. From the result control, use GetContourCtrlHandle to get the contour
control. After that, you can set up the request as needed (i.e. data type, data
component, data layer etc...).

So let’s start with a simple example that shows how to apply a contour plot
(assuming we have bumper.h3d model and results loaded in the animation
window). In this example, we will create a contour plot showing Stress à
vonMises à Max.

hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
project1 GetPageHandle page1 1
page1 GetWindowHandle win1 1
win1 GetClientHandle anim
anim GetModelHandle my_model [anim GetActiveModel]
my_model GetResultCtrlHandle my_result
my_result GetContourCtrlHandle my_contour
#set up request
my_contour SetDataType Stress
my_contour SetDataComponent vonMises
my_contour SetLayer Max
#update graphics
anim Draw
hwi CloseStack

If you type the code above in the Command Window, you would expect to see a
contour plot; however, no changes appear on the screen. The reason is you
have yet to enable drawing of the contour plot. To enable drawing of the contour
plot, you need two commands before the “anim Draw” statement:

#enable drawing of contour plot


my_contour SetEnableState true

Introduction to HWD Customization 74 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

anim SetDisplayOptions contour true


#update graphics
anim Draw

After adding these statements, you will actually see a contour plot, but it is all
“grey” color; this is because we are still at the model step (you can animate the
results by pressing on the traffic light to see the contour plot). To do this
programmatically by setting the current simulation using the result control.

#go to first simulation


my_result SetCurrentSimulation 0
#update graphics
anim Draw

After forcing the animation off the model step, you should be able to see some
colors. Depending on the use case, you can go to last step, for example, by
using the GetNumberOfSimualations command.

Contour by Selection
So far, we have applied a contour to all parts in the model, which is the default
behavior. However, it is possible to apply a contour to a set of elements or parts.
This can be done using the SetSelectionSet command available in the contour
control. The procedure is to create a selection set, add particular IDs to it, and
then set it as the selection set to by used by contour control. For example, let’s
now apply contour to one part only (part ID 2):

#add part set


set set_id [my_model AddSelectionSet part]
my_model GetSelectionSetHandle my_set $set_id
my_set Add "id 2"
#enable set inside contour control
my_contour SetSelectionSet $set_id
# clean up (set not needed anymore)
my_model RemoveSelectionSet $set_id
#update graphics
anim Draw

Using this method, you can now selectively apply a contour to a specified set of
entities.

HyperWorks 13.0 Introduction to HWD Customization 75

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Rules to Remember
When working with the contour control, or any other result-related control, it is
very important to remember and follow these rules:

§ Data types names, data component names, or any other part of the
request must exist in the list of results.
- You can get the list from the result control and check if it exists
§ You can selectively apply results using selection sets
§ You must enable drawing using two settings:
- Set enable state in the control (use SetEnableState command)
- Set display option in the animation client (use SetDisplayOptions
command)
§ Make sure you enable drawing last (after setting up the request)
§ If results don’t show up, make sure you’re not at the model step

Introduction to HWD Customization 76 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Exercise 5.1: Contouring Results and Contouring by Selection


In this exercise, we will load a model and results file into HyperView, and then contour
the entire model with stress. Then, a selection set will be created so that only part of the
model is contoured.

Step 1: Launch HyperView and open the Command Window


1. From the Start Menu, select All Programs > Altair HyperWorks 12.0 >
HyperView.
This launches HyperWorks Desktop with the Animation client loaded.
2. Click on the View pulldown menu and select Command Window.
This launches the Command Window where Tcl commands can be entered.

Step 2: Enter the appropriate command to get the session handle, project
handle, page handle and window handle.
1. First, use the OpenStack command to keep track of all the handles we are going to
get in this exercise:
hwi OpenStack
2. Next, enter the following lines to get the session handle and the project handle:
hwi GetSessionHandle sess
sess GetProjectHandle proj
3. Next get the page handle for page 1 and the window handle for window 1:
proj GetPageHandle pg1 1
pg1 GetWindowHandle win1 1

Step 3: Get the client handle and then use the appropriate commands to
load a model and results file:
1. Use the following two commands to set the client type to animation and then get the
client handle:
win1 SetClientType Animation
win1 GetClientHandle anim
2. Next, change directories (cd) to the location where the files are located and then
load in the file
cd “C:/Program Files/Altair/13.0/tutorials/mv_hv_hg/animation/bumper”

HyperWorks 13.0 Introduction to HWD Customization 77

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

3. Next lets load in the model file (bumper_deck.key), get the model handle, and then
load the results file (d3plot). Also use the Draw command to view the model in the
graphics area:
set id [anim AddModel bumper_deck.key]
anim GetModelHandle my_mod $id
my_mod SetResult d3plot
anim Draw

Step 4: Get the result control handle and then get the contour handle. Set
the contour data type, component, and layer.
1. Use the following two commands to get the result control handle and then get the
contour handle:
my_mod GetResultCtrlHandle my_result
my_result GetContourCtrlHandle my_contour
2. Next, using the contour control handle, set the data type to Stress
my_contour SetDataType Stress
3. After setting the data type, we need to set the component of stress to contour. For
this example set vonMises:
my_contour SetDataComponent vonMises
4. Next we need to select the layer to contour. Set the layer to Max:
my_contour SetLayer Max
5. In the Command Window, enter the following command to refresh the graphics area:
anim Draw
Notice how model has not changed (no contour has been applied). This is because
the appropriate display settings have not been set yet.

Step 5: Set the appropriate display settings to view the contour in the
graphics area:
1. The first display setting we need to set allows the drawing of the contour plot. This is
done with the SetEnableState command on the contour control handle and the
SetDisplayOptions command on the client handle:
my_contour SetEnableState true
anim SetDisplayOptions contour true
2. Use the Draw command to update the graphics area:
anim Draw

Introduction to HWD Customization 78 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Notice how the model is now grey. This is because we are still in the model step.
We have to update the simulation step to view the contour.
3. To set the simulation to the first step and update the graphics, enter the following two
lines:
my_result SetCurrentSimulation 0
anim Draw
4. To set the simulation to the fifth step and update the graphics, enter the following two
lines:
my_result SetCurrentSimulation 4
anim Draw

Step 6: Contour a single component of the bumper model.


1. There is also the option of contouring only a portion of the model by creating a
selection set and only contouring that set. First, enter the following three commands
to create the selection set and then add the component with the id of 6.
set set_id [my_mod AddSelectionSet part]
my_mod GetSelectionSetHandle my_set $set_id
my_set Add “id 6”
2. Using the contour control handle, update the contour selection set to the one we just
created with the my_set handle.
my_contour SetSelectionSet $set_id
3. Now that we are finished with the selection set, we should remove it from the session
using the RemoveSelectionSet command.
my_mod RemoveSelectionSet $set_id
4. Finally use the Draw command to update the graphics area and only contour the part
with id 6. After the Draw command, close the stack to delete the handles created for
this exercise.

HyperWorks 13.0 Introduction to HWD Customization 79

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

anim Draw
hwi CloseStack

Introduction to HWD Customization 80 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Querying Results
We have already looked at the query control in the previous chapter. In this
section, we will look at querying results in particular. Querying results is a
common function that’s required in a lot of macros. That’s why it is essential to
get familiar with this functionality and develop some good understanding on how
to query results.

The example we are going to start with is to extract results for a set of elements.
We are going to assume that we have a contour plot of Stress à vonMises à
Max, and we need to get the stress values for element IDs ranging from 100 to
110.

hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
project1 GetPageHandle page1 1
page1 GetWindowHandle win1 1
win1 GetClientHandle anim
anim GetModelHandle my_model [anim GetActiveModel]
my_model GetQueryCtrlHandle my_query
# create an element set and add ids 100-110
set set_id [my_model AddSelectionSet element]
my_model GetSelectionSetHandle elem_set $set_id
elem_set Add "id 100-110"
my_query SetSelectionSet $set_id
# ask for ids and stress value
my_query SetQuery "element.id contour.value"
# clean up
my_model RemoveSelectionSet $set_id
hwi CloseStack

Query Output
As mentioned earlier, we can write the data to a file using the WriteData
command. For example, let’s write this to C:/Temp/out.txt.

my_query WriteData C:/Temp/out.txt


hwi CloseStack

HyperWorks 13.0 Introduction to HWD Customization 81

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

By default, the output file is comma separated; for this case, if you open the
output file, you will see that the data looks like this:

id,value
109,7.525E+02
107,7.620E+02
100,7.200E+02
103,7.534E+02
104,7.478E+02
105,5.956E+02
106,5.302E+02
108,6.860E+02
110,7.287E+02
101,9.593E+02
102,9.842E+02

Query Iterator
There is another option to get the data from the query. The option is provided via
the iterator class using the GetIteratorHandle command. The iterator allows you
to go over the data one record at a time. To do so, you must use the GetDataList
command. Also, you must use First, Valid, and Next commands in conjunction.
It is recommended to use these commands in the following loop control
(assuming we have a handle called my_iter).

for {my_iter First} {[my_iter Valid]} {my_iter Next} {


my_iter GetDataList
}

Using the previous example, let’s assume that we need to store the data in a list
for later usage. Here’s a possible solution:

my_query GetIteratorHandle my_iter


set data_list ""
for {my_iter First} {[my_iter Valid]} {my_iter Next} {
lappend data_list [my_iter GetDataList]
}

Now the variable named “data_list” is a list of lists containing the following data:

{109 7.525E+02} {107 7.620E+02} {100 7.200E+02} {103 7.534E+02}


{104 7.478E+02} {105 5.956E+02} {106 5.302E+02} {108 6.860E+02}
{110 7.287E+02} {101 9.593E+02} {102 9.842E+02}

Introduction to HWD Customization 82 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Furthermore, it is very important to remember that the iterator handle you have is
valid only for the current step. This means that the data you get is for the current
step only. To get data for different time steps, you need to get and then release
the iterator handle as you set the current step. Here’s an example to clarify the
idea.

set subcase [my_result GetCurrentSubcase]


set sims [my_result GetNumberOfSimulations $subcase]
for {set step 0} {$step < $sims} {incr step} {
my_result SetCurrentSimulation $step
my_query GetIteratorHandle my_iter
for {my_iter First}{[my_iter Valid]}{my_iter Next} {
my_iter GetDataList
}
my_iter ReleaseHandle
}

F In the case of dealing with multiple time steps, It is very important to


remember that the iterator handle is valid only for the current step.

Output Binding
When dealing with results, values can be reported on elements or nodes. All that
depends on the source of data and what was requested. If we apply a contour
plot of stress, the values are reported on the element; however, if we enable
averaging, the values will be reported on the node. So whenever we query
results, we have to have the proper selection set type. For example, we have to
have element set for elemental results, and node set for nodal results.

When writing a macro, if you are not sure whether to use a node set or an
element set, you should use the GetBinding command. This command is
available for contour, tensor, and vector controls. Here’s an example:

my_model GetResultCtrlHandle my_result


my_result GetContourCtrlHandle my_contour
set entity_type [my_contour GetBinding]
set set_id [my_model AddSelectionSet $entity_type]

F The GetBinding command also returns “node_on_element”. In this


case, the selection set type should be “element”.

HyperWorks 13.0 Introduction to HWD Customization 83

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Exercise 5.2: Query contoured results and create a list of results


for node ids less than 100.
In this exercise, we will create a Tcl file which loads a model and results file, contours
the model with displacement. We will create a selection set with node ids less than 100
and then query those results. We will then create a list from the queried results.

Step 1: Launch HyperView and open the Command Window


1. From the Start Menu, select All Programs > Altair HyperWorks 12.0 >
HyperView.
This launches HyperWorks Desktop with the Animation client loaded.
2. Open a text editor to create a Tcl file. Once all the commands are written to the Tcl
file we will source the file to run the macro.

Step 2: Enter the appropriate command to get the session handle, project
handle, page handle and window handle.
1. First, use the OpenStack command to keep track of all the handles we are going to
get in this exercise:
hwi OpenStack
2. Next, enter the following lines to get the session handle and the project handle:
hwi GetSessionHandle sess
sess GetProjectHandle proj
3. Next get the page handle for page 1 and the window handle for window 1:
proj GetPageHandle pg1 1
pg1 GetWindowHandle win1 1

Step 3: Get the client handle and then use the appropriate commands to
load a model and results file:
1. Use the following two commands to set the client type to animation and then get the
client handle:
win1 SetClientType Animation
win1 GetClientHandle anim
2. Next, change directories (cd) to the location where the files are located and then
load in the file
cd “C:/Program Files/Altair/13.0/tutorials/mv_hv_hg/animation/bumper”

Introduction to HWD Customization 84 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

3. Next lets load in the model file (bumper_deck.key), get the model handle, and then
load the results file (d3plot). Also use the Draw command to view the model in the
graphics area:
set id [anim AddModel bumper_deck.key]
anim GetModelHandle my_mod $id
my_mod SetResult d3plot

Step 4: Get the result control handle and then get the contour handle. Set
the contour data type, and component.
1. Use the following two commands to get the result control handle and then get the
contour handle:
my_mod GetResultCtrlHandle my_result
my_result GetContourCtrlHandle my_contour
2. Next, using the contour control handle, set the data type to Displacement
my_contour SetDataType Displacement
3. After setting the data type, we need to set the component of stress to contour. For
this example set vonMises:
my_contour SetDataComponent Mag
4. Set the current simulation step to the 5th time step:
my_result SetCurrentSimulation 4

Step 5: Set the appropriate display settings to view the contour in the
graphics area:
1. The first display setting we need to set allows the drawing of the contour plot. This is
done with the SetEnableState command on the contour control handle and the
SetDisplayOptions command on the client handle:
my_contour SetEnableState true
anim SetDisplayOptions contour true
2. Use the Draw command to update the graphics area:
anim Draw

HyperWorks 13.0 Introduction to HWD Customization 85

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Step 6: Create a selection set which contains the nodes with ids less than
100. Then create a query handle and add the selection set to the query to
query for node ids and contour values.
1. First, create a selection set which contains only nodes with the ids between 1 and
100 by using the following 3 commands:
set set_id [my_mod AddSelectionSet node]
my_mod GetSelectionSetHandle node_set $set_id
node_set Add “id < 100”
Notice the spaces between id and < and then between < and 100. These spaces
are needed to add the nodes correctly.
2. Using the model handle we can use the GetQueryCtrlHandle to create a query
handle:
my_mod GetQueryCtrlHandle my_query
3. Add the selection set to the query by using the SetSelectionSet command on the
query control handle:
my_query SetSelectionSet $set_id
4. Next query the selection set to get the node id and the contour value. This is done
by using the SetQuery command on the query control handle.
my_query SetQuery “node.id contour.value”
Step 7: Get the query iterator handle and create a list of the query results
1. Using the query handle, get the query iterator handle so that results from the query
can be stored in a list:
my_query GetIteratorHandle my_iter
2. Next, create an empty list to store the values from the query in:
set query_list “”
3. Using a for loop and the appropriate values for the iterator handle (First, Valid,
and Next), loop through each of the items in the query and append them to the list
query_list:
for {my_iter First} {[my_iter Valid]} {my_iter Next} {
lappend query_list [my_iter GetDataList]
}
4. Finally print the list contained in the variable query_list to the Command Window:
puts $query_list

Introduction to HWD Customization 86 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Step 8: Cleanup the session and then source the file in the Command
Window
1. Remove the selection set from the session using the following command
my_mod RemoveSelectionSet $set_id
2. Delete the handles created in the session by using the CloseStack command:
hwi CloseStack
3. Save the file as Ex_5.2.tcl. Save the file in your My Documents folder.
4. Finally, run the macro by using the source command in the Command Window.
Open the Command Window and cd to you My Documents directory. Then type
the following:
source Ex5_2.tcl
Notice that the model is loaded into the session and that the output is printed into the
Command Window.

HyperWorks 13.0 Introduction to HWD Customization 87

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Practical Exercises
Exercise 5a
Description
Assuming you have loaded bumper_deck_key and d3plot (located in C:/Program
Files/Altair/13.0/tutorials/mv_hv_hg/animation/bumper), applied a contour plot
Stress à vonMises à Max and you are at the last time step. Get all elements
that have a stress value above 1200. Create a group labeled “stress value >
1200” and make it visible.

Handles used
session, project, page, window, client, model, selection set

TCL/TK commands used


set, expr, GetNumberOfSimulations, SetCurrentSimulation

Hints
Find out what rules you can use to add entities to a selection set

Exercise 5b
Description
Assuming you have loaded bumper_deck_key and d3plot (located in C:/Program
Files/Altair/13.0/tutorials/mv_hv_hg/animation/bumper), applied a contour plot
Stress à vonMises à Max à Simple averaging and you are at the last time
step. Using the query control, get the top 100 entities with highest values and
extract the min, max and average. Output the results (min, max, and average) to
the Command Window.

Handles used
session, project, page, window, client, model, selection set, query, iterator

TCL/TK commands used


set, foreach, expr, SetAverageMode, SetQuery, lsort, lindex,

Hints
Find out what rules you can use to add entities to a selection set

Introduction to HWD Customization 88 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Exercise 5c (optional)
Description
Assuming you have loaded bumper_deck_key and d3plot (located in C:/Program
Files/Altair/13.0/tutorials/mv_hv_hg/animation/bumper) and applied any contour
plot (elemental of nodal). Create a namespace named myspace. Using the
query control, get the maximum contour value for every time step in every
loadcase and then the overall maximum value for the loadcase. Output the
following to the console for every time step:
- Time step label
- Max value
- Entity ID
- Part ID
And at the end:
- loadcase label
- Max value
- Entity ID
- Part ID
- Time step label

Handles used
session, project, page, window, client, model, query, iterator
TCL/TK commands used
set, foreach, expr
Hints
Make sure you use the iterator handle properly

HyperWorks 13.0 Introduction to HWD Customization 89

Proprietary Information of Altair Engineering, Inc


Chapter 5 Results and Query

Introduction to HWD Customization 90 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

Chapter 6

The Plotting Client

In this chapter we will explore the plotting client and the various Command
Objects under the “plot” object. In particular we will cover loading in a data file,
plotting curves, and how to do math on curves. In addition, we will take a look at
how to create notes and cover a brief introduction to Templex.

Plotting Window
Similar to how any given window in a session can be an animation window, you
can also set the client type to Plot. This loads the plotting client into the given
window, which in turn creates the plot object.

Assuming we have a one page, one window session, you can set the client type
to plot by the following.

hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
project1 GetPageHandle page1 1
page1 GetWindowHandle win1 1
win1 SetClientType plot
hwi CloseStack

F
Remember that you don’t always have to set the client type to plot. When you
launch HyperGraph, the client is plot by default. Using the window handle, you can
also get the client type using GetClientType command.

HyperWorks 13.0 Introduction to HWD Customization 91

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

Plot Client Handle

Once the client type is set, you can access the plotting client and gain full access
to its functionality. To access the plotting client, you need to use the
GetClientHandle command.

page1 GetWindowHandle win1 1


win1 GetClientHandle plot1

The figure below illustrates the object hierarchy of the plot client. From the
pltPlot object, you have access to all functionalitiels in the plotting client such as
curves, legends, datum lines, and notes.

The Plot Object

F The prefix “pltI” is used internally for naming the classes within the plotting client. It
stands for “plot Interface”.

Defining Curves from Data Files


So far we have simply set the client type to the plotting window. The next step is
to bring some data into the session. To do this, we will define a curve from a
data file. In order to do this, we need to add a curve within the current plot and
we also need to define the data file.

Introduction to HWD Customization 92 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

First, let’s add a curve. We can do this by using the AddCurve command
available in the plot object. The AddCurve command adds an empty curve to
the plot and it returns the curve index. For this example, because no other curve
is defined, an index of 1 is returned. If the AddCurve command is used again, an
index of 2 will be returned, and so on.

We also need to get the curve handle, using the GetCurveHandle command.
The GetCurveHandle command requires two arguments, 1) the handle name and
2) the curve index. We can choose any name for the first argument; however,
we need a valid curve index for the second argument. We can use the AddCurve
command to get a valid curve index. Here is an example:

set curve_index [plot1 AddCurve]


plot1 GetCurveHandle curve1 $curve_index

Up to this point we have added an empty curve to the plot. The next step to
defining a curve is to specify the vector handle. This is done with the
GetVectorHandle command. This command also has two arguments, 1) the
handle name and 2) a string indicating which vector to get. The options for the
second argument in the xy plotting client are x, y, or time. Below is an example
for getting the x and y vector handle.

curve1 GetVectorHandle xvector1 x


curve1 GetVectorHandle yvector1 y

Now that we have the vector handles, we need to set the type of vectors to file
using the SetType command on the vector handle. Also, we need to reference
the file. We will do this by setting a variable which points to the file and then use
this variable in the SetFilename command.

xvector1 SetType file


yvector1 SetType file

set filename nodout

xvector1 SetFilename $filename


yvector1 SetFilename $filename

The last step we need to create the curve is to define the data type, request, and
component, just like we do in the Build Plots panel within HyperGraph. This is
done by using the SetDataType, SetRequest, and SetComponent commands on
the vector handle. In this example, the x vector is also the time vector, so for
each of the data type, request, and component, we set them to Time as shown
below.

HyperWorks 13.0 Introduction to HWD Customization 93

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

xvector1 SetDataType "Time"


xvector1 SetRequest "Time"
xvector1 SetComponent "Time"

In the nodout file, there are many more options for data type, request, and
component. In this example, we want the data type to be “Node Data”, the
request to be “Nodal Point 26742”, and the component to be “X Displacement”.
We do this using the same commands we used above, except we do so on the y
vector handle as shown below.

yvector1 SetDataType "Node Data"


yvector1 SetRequest "Nodal Point 26742"
yvector1 SetComponent "X Displacement"

The final step in creating a curve on a plot window is to tell the window to
calculate the curve and draw it. We do this with the Recalculate, Autoscale, and
Draw commands on the plot handle. The Recalculate command forces the plot
to regenerate all calculated data and reread all file data. Only curve data that
has been modified since the last call to Recalculate is recomputed. The
Autoscale command forces the plot to recompute the minimum and maximum
values for its axes. This method uses the current curve data to determine the
minimum and maximum values. It may be necessary to call Recalculate first for
recent data changes to be considered. Finally, the Draw command actually
draws the plot with the curves on the window. Changes made by other methods
may not be displayed properly until Draw is called. A common practice is to
make multiple changes and then call Draw only once, limiting the number of
redraws. Below illustrates an example of the three commands.

plot1 Recalculate
plot1 Autoscale
plot1 Draw

Defining Curves from Math Expressions


So far we have learned how to define curves from a data file, but we can also
define curves using math operations. For an example, we are going to add two
curves together; imagine that both curves are on page 1, window 1, and their
curve ids are 1 and 2.

The first thing we need to understand is how curves are referenced in


HyperGraph. HyperGraph uses x and y vector expressions to reference any

Introduction to HWD Customization 94 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

curve vector in a session. A curve vector reference defines the x or y vector by


page, window, and curve number. An example of a curve vector reference is
p2w3c4.x, where:

p2 is page 2
w3 is window 3
c4 is curve 4
x is the vector

Similarly you can have p2w3c4.y to reference the y vector. So in our scenario,
we will be adding p1w1c1 and p1w1c2.

Just as we had to define the type using SetType when we defined the curves
based on a data file, we also need to set this on the vector handles when we are
defining a curve by math. In the situation when you are defining a curve by a
math expression, the SetType needs to be set to math.

xvector1 SetType math


yvector1 SetType math

Next we need to set the expressions to be used on both the x and y vectors.
This is done using the SetExpression command on the vector handles. The
SetExpression command requires a single additional input and that is the vector
expression to be used. In our example, the x vector is simply defined as one of
the x vectors from the two curves being added. The y vector is the summation of
the two vectors as shown below.

xvector1 SetExpression p1w1c1.x


yvector1 SetExpression p1w1c1.y+p1w1c2.y

Just as with the previous example, we need to use the Recalculate, Autoscale,
and Draw commands to calculate the curves and draw the plot.

Adding Notes to a Plot


Adding a note to a plot is just one example of the many different things you can
do in the plotting client. As you look at the Object Hierarchy for the plotting client,
some additional objects are title, axis, datum, and legend. Here we will focus on
how to add a note, set the title and text of the note, and how to attach it to a
curve.

The first step in creating a note is to add a note to the plotting client. This is done
with the AddNote command on the plotting client handle. The AddNote

HyperWorks 13.0 Introduction to HWD Customization 95

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

command will return the index of the note and add an empty note to the plotting
client. You also need to use the GetNoteHandle command on the plotting client
handle to make any changes to the note. The GetNoteHandle command
requires the handle name for the note as well as the note id. Similarly to adding
a curve, we can use both of these commands together as shown below:

win1 GetClientHandle plot1


plot1 GetNoteHandle note1 [plot1 AddNote]

Once we have the note handle, we can now add a title to the note and well as
text. This is done with the SetName and the SetText commands on the note
handle.

note1 SetName “My Note”


note1 SetText “This is my note”

Now that a name and title have been added to the note, you can also use the
GetName and GetText commands on the note handle. The GetName command
will return the title of the note referenced by the note handle and the GetText
command will return the text of the note referenced by the note handle.

note1 GetName
returns: My Note
note1 GetText
returns: This is my note

Another option available with a note is the attachment method. A note can be
attached to a window, view, curve or point. To set this attachment method, the
SetAttachment command on the note handle is used. The SetAttachment
command requires that the attachment method be supplied as either “window”,
“view”, “curve”, or “point”. For this example we are attaching the note to a curve.
Once the attachment method is set to curve, we also have to set which curve the
note is attached to. To do this the SetAttachToCurveIndex command on the note
handle is used. This command requires that the curve id is supplied. Once the
curve id is determined, we need to supply the index point that the note is
attached to. This is done with the SetAttachToPointIndex. Below is an example
where we are attaching the note to a curve with an id of 2 and the point index is 0
for the initial point of the curve.

note1 SetAttachment curve


note1 SetAttachToCurveIndex 2
note1 SetAttachToPointIndex 0

Introduction to HWD Customization 96 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

Introduction to Templex Statements


Let’s image that instead of attaching the note to the first point of the curve, we
want to attach it to the last point of the curve. In order to do this, you need to
know how many points are in the curve. If you don’t know how many points there
are, you can still do this using a Templex statement. Templex is a general
purpose text and numeric processor. It is used within HyperGraph to create fully
annotated notes and labels capable of performing data analysis and curve
statistics within a plot window.

In our example above, the Templex statement we need to use is the numpts
statement. The numpts statement returns the number of elements in an
expression and the result is always a scalar. So, in order to find the number of
points in the y vector for a curve on page 1 and window 1, the command is as
follows

numpts(p1w1c2.y)

The SetAttachToPointIndex command requires that the index be supplied, which


is different than the number of points. Since the indexing starts with a value of 0
instead of 1, we simply need to subtract 1 from the expression above. This will
result in the following being set for the attachment point:

note1 SetAttachment curve


note1 SetAttachToCurveIndex 2
note1 SetAttachToPointIndex “numpts(p1w1c2.y)-1”

In addition to using Templex functions to define the attachment point, we can


also use Templex in the note text to report various values. Let’s image we want
the note to report the maximum value of a curve. We can do this with the max
statement as shown below.

Note1 SetText "maximum value is {max(p1w1c2.y)}"

Note that the Templex statement max(p1w1c2.y) is in { }. The { } indicates that


this is a Templex statement that needs to be evaluated in a text field. When you
actually run the commands, the Templex that is in the { } is automatically
evaluated so that in the note you see the numerical value.

HyperWorks 13.0 Introduction to HWD Customization 97

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

Exercise 6.1: Creating Plots and Notes with Templex inside the
Notes.
In this exercise, we will create two curves in the first window which come from a data file.
We will then create a note which reports the maximum value of each of those curves
using Templex. Next, we will use math to create a new curve in the second window
which is the average of the two curves in the first window. We will again use Templex to
report the maximum value of the averaged curve in a note in window 2.

Step 1: Launch HyperView and open the Command Window


1. From the Start Menu, select All Programs > Altair HyperWorks 13.0 >
HyperView.
This launches HyperWorks Desktop with the Animation client loaded.
2. Open a text editor to create a Tcl file. Once all the commands are written to the Tcl
file we will source the file to run the macro.

Step 2: Enter the appropriate command to get the session handle, project
handle, page handle and window handle. Also, set the page layout to have
2 vertical windows.
1. First, use the OpenStack command to keep track of all the handles we are going to
get in this exercise:
hwi OpenStack
2. Next, enter the following lines to get the session handle and the project handle:
hwi GetSessionHandle sess
sess GetProjectHandle proj
3. Next get the page handle for page 1 and the window handle for window 1:
proj GetPageHandle pg1 1
pg1 GetWindowHandle win1 1
4. Using the page handle, using the SetLayout command and set it to 1. This is a
vertical 2 window layout.
pg1 SetLayout 1

Step 3: Set the client type to plot and then get the client handle.
1. Use the following commands to set the client type to Plot
win1 SetClientType Plot

Introduction to HWD Customization 98 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

2. Once the client type has been set to the plotting client, get the client handle for
window 1:
win1 GetClientHandle plot1

Step 4: Add a new curve to the plotting client in window 1. The get the
curve and vector handles and set the curve type to file.
1. Using the client handle, add a new curve to window 1. The result of the AddCurve
command is the curve index, so set the result of this command to a variable to store
the index:
set curve_1 [plot1 AddCurve]
2. Next, using the client handle, get the curve handle for the first curve:
plot1 GetCurveHandle curve1 $curve_1
Notice that the GetCurveHandle requires the curve index, which is why we
assigned the result of the AddCurve command to the variable curve_1.
3. Now that we have the curve handle, we can get the vector handles for x and y for
curve 1:
curve1 GetVectorHandle xvector1 x
curve1 GetVectorHandle yvector1 y
4. Next, set the type of curve using the SetType command on the vector handle. The
options for this command are File, Math, or Values:
xvector1 SetType File
yvector1 SetType File

Step 5: Set a variable to the file nodout and then assign the filename to the
vector.
1. Set a variable which points to the nodout file which is the data file we are creating
our plots from:
set filename “C:/Program Files/Altair/13.0/demos/mv_hv_hg/plotting/dyna/nodout”
2. Using the SetFilename command on the vector handles, assign the filename to the
vector:
xvector1 SetFilename $filename
yvector1 SetFilename $filename

HyperWorks 13.0 Introduction to HWD Customization 99

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

Step 6: Set the data type, request, and component for both the x and y
vector:
1. First, let’s set the data type for the x vector. Because we are setting this vector to
Time, we only need to set the data type:
xvector1 SetDataType “Time”
2. Next, set the data type for the y vector to “Node Data”:
yvector1 SetDataType “Node Data”
3. Now we can set the request to “Nodal Point 26742”:
yvector1 SetRequest “Nodal Point 26742”
4. Finally set the component to “X Displacement”:
yvector1 SetComponent “X Displacement”

Step 7: Repeat Steps 4-6 to add a second curve to the window.


1. Repeat Steps 4-6 to add a second curve to the window. This curve should have the
same x and y vector types except the y Request should be “Nodal Point 26758”.
Add the following lines to your file:
set curve_2 [plot1 AddCurve]
plot1 GetCurveHandle curve2 $curve_2
curve2 GetVectorHandle xvector2 x
curve2 GetVectorHandle yvector2 y
xvector2 SetType File
yvector2 SetType File
xvector2 SetFilename $filename
yvector2 SetFilename $filename
xvector2 SetDataType "Time"
yvector2 SetDataType "Node Data"
yvector2 SetRequest "Nodal Point 26758"
yvector2 SetComponent “X Displacement”

Introduction to HWD Customization 100 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

Step 8: Use the appropriate commands to calculate the curves and draw
them. Then test the macro in the Command Window:
1. Next add the appropriate commands to calculate the curves and draw them. This is
done with the following three commands:
plot1 Recalculate
plot1 Autoscale
plot1 Draw
2. Now, let’s test the macro up until this point. Save the file as Ex_6_1.tcl in your My
Documents folder.
3. Open the Command Window and type the following:
source Ex_6_1.tcl
This results in a 2 window layout where the 2 curves are plotted into the first window:

Step 9: Next, find the number of curves in the window and then create a
note for each curve which reports the maximum value of the curve.
1. Using the client handle, we can get the number of curves in the plot and assign the
result to a variable. Add the following line to your tcl file:

HyperWorks 13.0 Introduction to HWD Customization 101

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

set num_curves [plot1 GetNumberOfCurves]


2. Next, let’s create a loop which goes through each curve in the client and creates a
note. To begin the loop, the for command is used. We are starting our loop at 1
and increasing by 1 until the value in num_curves is reached. In this case, we
know that only 2 curves exist, but we are using the result of the
GetNumberOfCurves command for educational purposes.
for {set i 1} {$i<=$num_curves} {incr i} {
3. Using the client handle, we can get the note handle. Notice how the note handle is
defined with the $i. This is so that there is a unique value for each note handle.
Also notice that for the note index the AddNote command on the client handle is
used:
plot1 GetNoteHandle note_$i [plot1 AddNote]
4. Next the name of the note is set using the SetName command and the text to be
displayed is set using the SetText command. Notice that both strings for the
SetName and SetText commands are in quotes. Also notice how for the SetText
command part of the string is enclosed in curly braces {}. This is because inside the
curly braces there is a Templex command which needs to be evaluated. In this
case, we are finding the maximum value of curve:
note_$i SetName "Max curve $i"
note_$i SetText "Max curve $i = {max(p1w1c$i.y)}"
5. Finally we an assign the attachment point of the note. Using the command
SetAttachment we can attach the note to a curve and using
SetAttachToCurveIndex we can assign which curve the note should be attached
to:
note_$i SetAttachment curve
note_$i SetAttachToCurveIndex $i
6. The last part of the loop we have to define is the ending brace to the for statement:
}
The entire loop should look like the following:
set num_curves [plot1 GetNumberOfCurves]
for {set i 1} {$i<=$num_curves} {incr i} {
plot1 GetNoteHandle note_$i [plot1 AddNote]
note_$i SetName "Max curve $i"
note_$i SetText "Max curve $i = {max(p1w1c$i.y)}"
note_$i SetAttachment curve
note_$i SetAttachToCurveIndex $i
}

Introduction to HWD Customization 102 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

7. Use the Draw command on the client handle to refresh the graphics area and view
the note which was created:
plot1 Draw
Step 10: Next we will get the window handle for the second window. Set
the client to the plotting client and add a new curve. Set the curve type to
be Math.
1. Using the page handle we got earlier, get the window handle for the second window,
set the client type to plot, and get the client handle:
pg1 GetWindowHandle win2 2
win2 SetClientType plot
win2 GetClientHandle plot2
2. Next, add a curve to the second window and get the curve and vector handles:
set curve_3 [plot2 AddCurve]
plot2 GetCurveHandle curve3 $curve_3
curve3 GetVectorHandle xvector3 x
curve3 GetVectorHandle yvector3 y
3. Using the vector handles, set the curve type to math:
xvector3 SetType Math
yvector3 SetType Math

Step 11: Define the expression to be used on the vector handles.


1. Now that we have the vector handles, we can define the math expressions for the x
and y vectors. First, for the x vector, set this vector to be the same as the x vector
for curve 1 on window 1:
xvector3 SetExpression p1w1c1.x
2. Next, set the expression for the y vector. This expression is the sum of curve 1 and
curve 2 on window 1 divided by 2 (we are finding the average of those two curves):
yvector3 SetExpression (p1w1c1.y+p1w1c2.y)/2
NOTE : You could also define the math expressions using a command which would get
the appropriate math reference based on a vector handle. For example, xvector3 could
be defined with the following line:
xvector3 SetExpression [xvector1 GetMathReference]
The math reference for the vector defined by the vector handle, xvector1, is determined
using the GetMathReference command. The same could be used to define yvector3:
yvector3 SetExpression [yvector1 GetMathReference]+[yvector2 GetMathReference]/2

HyperWorks 13.0 Introduction to HWD Customization 103

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

Step 12: Add a note to window 2 which reports the maximum value of the
curve in window 2.
1. This is similar to the steps we followed in Step 9, except we won’t be using a loop in
this example. First, add a note and get the note handle:
plot2 GetNoteHandle note_3 [plot2 AddNote]
2. Next set the note name and text and then assign the attachment point:
note_3 SetName "Max curve ave"
note_3 SetText "Max curve ave = {max(p1w2c1.y)}"
note_3 SetAttachment curve
note_3 SetAttachToCurveIndex 1
Step 13: Add the appropriate draw commands to calculate and draw the
plot on the second window. Close the stack to delete the handles created
and test the file.
1. Next add the appropriate commands to calculate the curves and draw them. This is
done with the following three commands:
plot2 Recalculate
plot2 Autoscale
plot2 Draw
2. Close the stack to delete the handles created during this exercise:
hwi CloseStack
3. Save the file and test the macro by sourcing the file in the Command Window:
source Ex_6_1.tcl

Introduction to HWD Customization 104 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

HyperWorks 13.0 Introduction to HWD Customization 105

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

Practical Exercises
Exercise 6a
Description
Load in the data file demo.dat and create a curve using the following Y
Type, Y Request, and Y Component vs Time:
Y Type:Force
Y Request: REQ/13 Curve 13
Y Component: Z
Then in the same window, create a second curve using the following vs.
Time:
Y Type:Force
Y Request: REQ/18 Curve 18
Y Component: Z
Update the X axis so that the label is “Time (seconds)” and the Y axis
label is “Force (Newtons)”.

Handles used
session, project, page, window, client, curve, vector

TCL/TK commands used


AddCurve, SetFilename, SetType, SetDataType, SetRequest,
SetComponent

Hints
Try loading the demo.dat file into HyperGraph to see how the Y Type, Y
Request, or Y Component are defined.

Introduction to HWD Customization 106 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

Exercise 6b
Description
Using the 2 curves created in Exercise 6a, add those two curves together.
Update the title of the curve to be “Sum Fz Request 13 and 18”. Add a note
which reports the minimum of the new curve. Attach the note to the minimum as
well.

Handles used
session, project, page, window, client, curve, vector, note

TCL/TK commands used


SetType, SetExpression, AddNote, SetAttachment

Hints
To attach a note to the curve at the same point as the minimum, try using
the Templex command indexofmin.

HyperWorks 13.0 Introduction to HWD Customization 107

Proprietary Information of Altair Engineering, Inc


Chapter 6 The Plotting Client

Introduction to HWD Customization 108 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 7 The MotionView Model Client

Chapter 7

The MotionView Model Client


In this Chapter, we will start working with the MotionView model client. We will
take a detailed look at the MotionView model Command Object. We will also
cover some of the most frequently used functionality, such as loading a model,
exporting an xml, adding an entity and grabbing the properties of an entity.

Model Window
For any given window within a session, you can set the client type to Model. By
doing so, you are essentially loading the MotionView client into that window,
which in turn creates the model object.

Assuming we have a session with one page and one window, here’s how you
can set the client type to Model.

hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
project1 GetPageHandle page1 1
page1 GetWindowHandle win1 1
win1 SetClientType Model
hwi CloseStack

F
Remember that you don’t always have to set the client type to model. When you
launch MotionView, the client is Model by default. Using the window handle, you can
also get the client type using GetClientType command.

HyperWorks 13.0 Introduction to HWD Customization 109

Proprietary Information of Altair Engineering, Inc


Chapter 7 The MotionView Model Client

Model Client Handle


After setting the client type, you can access the model client and get full access
to its functionality. To access the model client, you need to use the
GetClientHandle command off the window.

page1 GetWindowHandle win1 1


win1 GetClientHandle client

The figure below shows a portion of the object hierarchy; this shows that the
mdlIModelClient and mdlIModel, which are equivalent to the MotionView client,
gives you access to its major functionalities.

Model Object

F The prefix “mdlI” is used internally for naming the classes within the model client. It
stands for “mdl Interface”.

Loading a Model
One of the basic functionalities provided by the model client handle is the ability
to load an existing model (mdl file). This is done using the CreateModel
command. Continuing with the previous example and assuming that we have an
mdl model named full_car.mdl; we can load the model using the following
statement:

page1 GetWindowHandle win1 1


win1 GetClientHandle client
client CreateModel full_car.mdl mdl

If you look at the documentation provided for the CreateModel command, you will
see that it requires two arguments, 1) the file name and 2) type. For mdl files,
use “mdl” as the type when using CreateModel command.

Introduction to HWD Customization 110 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Chapter 7 The MotionView Model Client

Create a Blank Model


If you wish to create a blank model, use the CreateBlankModel command from
the ClientHandle.

page1 GetWindowHandle win1 1


win1 GetClientHandle client
client CreateBlankModel

Export a model
To be able to export an existing model in MotionView to MotionSolve, use the
ExportModel command.

page1 GetWindowHandle win1 1


win1 GetClientHandle client
client ExportModel “full_car.xml”

Notice that ExportModel requires a filename to be specified to which you want to


export the model.

Run MotionSolve

Using the RunSolverScript command, we can submit a job to MotionSolve. This


command requires us to specify the filename as an input argument to which the
results from the script are to be written out.

page1 GetWindowHandle win1 1


win1 GetClientHandle client
client RunSolverScript “full_car.xml”

For more information about Customizing MotionView, please refer to the


MotionView class material.

HyperWorks 13.0 Introduction to HWD Customization 111

Proprietary Information of Altair Engineering, Inc


Chapter 7 The MotionView Model Client

Introduction to HWD Customization 112 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

SOLUTIONS FOR EXERCISES


CHAPTER 2

Exercise 2a

### Practical Exercise 2a ###

### Get Appropriate Handles to get to page 1, window 1 ###


hwi GetSessionHandle sess
sess GetProjectHandle proj
proj GetPageHandle pg 1
pg GetWindowHandle win 1
win SetClientType plot

### Set a Variable to be used as the page title ###


set title "my first page"

### Set the TitleDisplayed to true so that the page title can be viewed ###
pg SetTitleDisplayed true

### Use the variable set previously to set the page title
pg SetTitle $title

CHAPTER 3
Exercise 3a

### Practical Exercise 2a ###

### Open the stack to keep track of the handles ###


hwi OpenStack

### Get Appropriate Handles to get to page 1###


hwi GetSessionHandle sess
sess GetProjectHandle proj
proj GetPageHandle pg1 1

### Add a second page and set the layout to 2 windows ###
proj GetPageHandle pg2 [proj AddPage]
pg2 SetLayout 1

### Add a third page and set the layout to 3 windows ###
proj GetPageHandle pg3 [proj AddPage]
pg3 SetLayout 3

HyperWorks 13.0 Introduction to HWD Customization 113

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

### Set the active page to window 3 ###


proj SetActivePage 3

### Set window 1 to animation, window 2 to plot, and window 3 to the text
editor ###
pg3 GetWindowHandle win1 1
win1 SetClientType animation
pg3 GetWindowHandle win2 2
win2 SetClientType plot
pg3 GetWindowHandle win3 3
win3 SetClientType TextEditor

### Close the stack to remove all handles created ###


hwi CloseStack

CHAPTER 4
Exercise 4a
### Practical Exercise 4a ###

### Open stack to organize handles ##


hwi OpenStack

### Get the appropriate handles to set a 2 window layout and set both windows
to animation##
hwi GetSessionHandle sess
sess GetProjectHandle proj
proj GetPageHandle pg 1
pg SetLayout 1
pg GetWindowHandle win1 1
pg GetWindowHandle win2 2
win1 GetClientHandle anim1
win2 GetClientHandle anim2

### Create variables which point to the files, then add the model and result
file to each window. ###
set filename1 "C:/Program
Files/Altair/12.0/tutorials/mv_hv_hg/animation/bezel.h3d"
set filename2 "C:/Program
Files/Altair/12.0/tutorials/mv_hv_hg/animation/bezel_iter2.h3d"
set id1 [anim1 AddModel $filename1]
anim1 GetModelHandle my_mod1 $id1
my_mod1 SetResult $filename1
set id2 [anim2 AddModel $filename2]
anim2 GetModelHandle my_mod2 $id2
my_mod2 SetResult $filename2

### Use the Draw command to refresh the graphics


pg Draw

### Capture the entire page to a file ###


sess CaptureScreen jpeg screen.jpeg 100

### Set the active window and then capture the active window to a file ###
pg SetActiveWindow 1

Introduction to HWD Customization 114 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

sess CaptureActiveWindow jpeg window1.jpeg percent 100 100


pg SetActiveWindow 2
sess CaptureActiveWindow jpeg window2.jpeg percent 100 100

### close the stack to delete the handles gotten during the script ###
hwi CloseStack

Exercise 4b
### Practical Exercise 4b ###

### Open stack to organize handles ##


hwi OpenStack

### Get Appropriate handles to load a model and results ###


hwi GetSessionHandle sess
sess GetProjectHandle proj
proj GetPageHandle pg 1
pg GetWindowHandle win1 1
win1 GetClientHandle anim1
set filename1 "C:/Program
Files/Altair/12.0/tutorials/mv_hv_hg/animation/bezel.h3d"
set id1 [anim1 AddModel $filename1]
anim1 GetModelHandle my_mod1 $id1
my_mod1 SetResult $filename1

### Create selection set of all nodes in the model and use GetSize command to
get number of nodes ###
set set_id1 [my_mod1 AddSelectionSet node]
my_mod1 GetSelectionSetHandle node_list $set_id1
node_list Add all
set num_nodes [node_list GetSize]

### Create selection set of all elements in the model and use GetSize command
to get number of elements ###
set set_id2 [my_mod1 AddSelectionSet element]
my_mod1 GetSelectionSetHandle elem_list $set_id2
elem_list Add all
set num_elems [elem_list GetSize]

### Create selection set of all parts in the model and use GetSize command to
get number of parts ###
set set_id3 [my_mod1 AddSelectionSet part]
my_mod1 GetSelectionSetHandle part_list $set_id3
part_list Add all
set num_parts [part_list GetSize]

### Add a note and get the note handle, also set the text for the note ###
anim1 GetNoteHandle note1 [anim1 AddNote]
note1 SetText "Number of Nodes = $num_nodes Number of Elements = $num_elems
Number of Parts = $num_parts"

### Use the draw command to refresh the graphics and then close the stack to
delete the handles which were gotten in the script ###
anim1 Draw
hwi CloseStack

HyperWorks 13.0 Introduction to HWD Customization 115

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

CHAPTER 5
Exercise 5a
### Practical Exercise 5a ###

### Open stack to organize handles ##


hwi OpenStack

### Get Appropriate handles to load a model and results ###


hwi GetSessionHandle sess
sess GetProjectHandle proj
proj GetPageHandle pg 1
pg GetWindowHandle win1 1
win1 GetClientHandle anim1
set mod_name "C:/Program
Files/Altair/12.0/tutorials/mv_hv_hg/animation/bumper/bumper_deck.key"
set res_name "C:/Program
Files/Altair/12.0/tutorials/mv_hv_hg/animation/bumper/d3plot"
set id1 [anim1 AddModel $mod_name]
anim1 GetModelHandle my_mod1 $id1
my_mod1 SetResult $res_name

### Contour the model with stress ###


my_mod1 GetResultCtrlHandle my_res
my_res GetContourCtrlHandle my_cont
my_cont SetDataType Stress
my_cont SetDataComponent vonMises
my_cont SetLayer Max

### Get the number the number of simulations in step one and set the current
simulation to the last simulation of the step ###
set num_sims [my_res GetNumberOfSimulations 1]
set num_ind [expr $num_sims-1]
my_res SetCurrentSimulation $num_ind

### Enable display of the contour


my_cont SetEnableState true
anim1 SetDisplayOptions contour true
anim1 Draw

### Create a set of elements whose stress is greater than 1200. Turn on the
display of the set and element ids ###
set set_id [my_mod1 AddSelectionSet elements]
my_mod1 GetSelectionSetHandle elem_list $set_id
elem_list Add "contour > 1200"
elem_list SetLabel "Stress > 1200"
elem_list SetIDVisibility true
elem_list SetVisibility true
elem_list SetColor yellow

### refresh the graphics to view the sets and then close the stack to remove
the handles. ###
anim1 Draw
hwi CloseStack

Introduction to HWD Customization 116 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

Exercise 5b
### Practical Exercise 5b ###

### Open stack to organize handles ##


hwi OpenStack

### Get Appropriate handles to load a model and results ###


hwi GetSessionHandle sess
sess GetProjectHandle proj
proj GetPageHandle pg 1
pg GetWindowHandle win1 1
win1 GetClientHandle anim1
set mod_name "C:/Program
Files/Altair/12.0/tutorials/mv_hv_hg/animation/bumper/bumper_deck.key"
set res_name "C:/Program
Files/Altair/12.0/tutorials/mv_hv_hg/animation/bumper/d3plot"
set id1 [anim1 AddModel $mod_name]
anim1 GetModelHandle my_mod1 $id1
my_mod1 SetResult $res_name

### Contour the model with stress ###


my_mod1 GetResultCtrlHandle my_res
my_res GetContourCtrlHandle my_cont
my_cont SetDataType Stress
my_cont SetDataComponent vonMises
my_cont SetLayer Max

### Use the SetAverageMode command to apply a simple average ###


my_cont SetAverageMode simple

### Get the number the number of simulations in step one and set the current
simulation to the last simulation of the step ###
set num_sims [my_res GetNumberOfSimulations 1]
set num_ind [expr $num_sims-1]
my_res SetCurrentSimulation $num_ind

### Enable display of the contour


my_cont SetEnableState true
anim1 SetDisplayOptions contour true
anim1 Draw

### Determine if the contour is based on elements or nodes ###


set entity_type [my_cont GetBinding]

### Create a set of elements whose stress is greater than 1200. Turn on the
display of the set and element ids ###
set set_id [my_mod1 AddSelectionSet $entity_type]
my_mod1 GetSelectionSetHandle entity_list $set_id
entity_list Add "contour top 100"
set id_list [entity_list GetList]

### Get QueryCtrl Handle, add the selection set and then remove the selection
set ###
my_mod GetQueryCtrlHandle my_query
my_query SetSelectionSet $set_id
my_mod RemoveSelectionSet $set_id

### Query for the contoured values ###

HyperWorks 13.0 Introduction to HWD Customization 117

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

my_query SetQuery "contour.value";

### Get iterator and extract data and store in a list ###
my_query GetIteratorHandle my_iter;
for {my_iter First} {[my_iter Valid]} {my_iter Next} {
lappend data_list [my_iter GetDataList];
}

### Sort the data and get min and max ###
set sorted [lsort -real -increasing $data_list];
set min [lindex $sorted 0];
set max [lindex $sorted end];

### Calculate the average of the 100 contour values ###


set sum 0;
set count 0;
foreach item $data_list {
set sum [expr $sum + $item];
incr count;
}
set average [expr $sum/$count];

### Print the minimum, maximum and average values to the Command Window ###
puts "Minimum: \t $min\nMaximum : \t $max\nAverage: \t $average"

### Close the stack to remove the handles. ###


hwi CloseStack

Exercise 5c
#====================================================================
# create a namespace
#====================================================================
namespace eval myspace {

#====================================================================
# gets the maximum contour value for every part for all time steps
# it alss reports the global max for every subcase
#====================================================================
proc ::myspace::GetOverallMax { model_handle } {

hwi OpenStack;

# create a part selection set and add all parts


set set_id [$model_handle AddSelectionSet part];
$model_handle GetSelectionSetHandle my_set $set_id;
my_set Add all;

# set selection set inside the query ctrl


$model_handle GetQueryCtrlHandle my_query
my_query SetSelectionSet [ my_set GetID ];
$model_handle RemoveSelectionSet [my_set GetID];

# create request
my_query SetQuery "component.id contour.maxid contour.max misc.sim";

Introduction to HWD Customization 118 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

$model_handle GetResultCtrlHandle my_result;

foreach subcase_id [my_result GetSubcaseList] {

my_result SetCurrentSubcase $subcase_id;

set num_sims [ my_result GetNumberOfSimulations $subcase_id];

set subcase_max_value 0;
set subcase_max_entid 0;
set subcase_max_partid 0;
set subcase_max_step 0;

for { set step 0 } { $step < $num_sims } { incr step } {

# max value and entity id for this step


set step_max_value 0;
set step_max_entid 0;
set step_max_partid 0;
set step_max_step 0;

# set current simulation


my_result SetCurrentSimulation $step;

# get iterator handle AFTER calling SetCurrentSimulation so that


# the data is retrieved for the proper simulation step.
my_query GetIteratorHandle my_iterator;

for {my_iterator First} { [my_iterator Valid] } { my_iterator


Next } {

set data_list [my_iterator GetDataList];

set comp_id [lindex $data_list 0];


set comp_max_entid [lindex $data_list 1];
set comp_max_value [lindex $data_list 2];
set comp_max_step [lindex $data_list 3];

if { $comp_max_value == "N/A" } { continue }

if {$comp_max_value >= $step_max_value} {


set step_max_value $comp_max_value;
set step_max_entid $comp_max_entid;
set step_max_partid $comp_id;
set step_max_step $comp_max_step;
}
}
my_iterator ReleaseHandle;

puts "[my_result GetSimulationLabel $subcase_id $step]\n\tMax =


$step_max_value\n\tEntity ID = $step_max_entid\n\tPart ID = $step_max_partid";

if { $step_max_value >= $subcase_max_value } {


set subcase_max_value $step_max_value;
set subcase_max_entid $step_max_entid;
set subcase_max_partid $step_max_partid;
set subcase_max_step $step_max_step;
}
}

HyperWorks 13.0 Introduction to HWD Customization 119

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

puts "[my_result GetSubcaseLabel $subcase_id]\n\tMax =


$subcase_max_value\n\tEntity ID = $subcase_max_entid\n\tPart ID =
$subcase_max_partid\n\tStep = $subcase_max_step";
puts "##################################################\n"
}

hwi CloseStack;
}

#====================================================================
# get a handle named "name" to the active model only
#====================================================================
proc ::myspace::GetActiveModelHandle { name } {

hwi GetSessionHandle my_session;


my_session GetProjectHandle my_project;
my_project GetPageHandle my_page [my_project GetActivePage];

my_page GetWindowHandle my_window [my_page GetActiveWindow];


my_window GetClientHandle my_client;
my_client GetModelHandle $name [my_client GetActiveModel];

my_session ReleaseHandle;
my_project ReleaseHandle;
my_page ReleaseHandle;
my_window ReleaseHandle;
my_client ReleaseHandle;
}

#====================================================================
# main procedure
#====================================================================
proc ::myspace::Main {} {

hwi OpenStack;

# get active model handle


GetActiveModelHandle my_model;

# get max value for every part


GetOverallMax my_model;

hwi CloseStack;
}

#====================================================================
# call main procedure
::myspace::Main;

Introduction to HWD Customization 120 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

CHAPTER 6

Exercise 6a:
hwi OpenStack

hwi GetSessionHandle session


session GetProjectHandle project
project GetPageHandle pg [project GetActivePage]
pg GetWindowHandle win [pg GetActiveWindow]

win SetClientType plot


win GetClientHandle plot
set filename "demo.dat"

plot GetCurveHandle cur1 [plot AddCurve]


cur1 GetVectorHandle cur1x x
cur1 GetVectorHandle cur1y y
cur1x SetType file
cur1y SetType file
cur1x SetFilename $filename
cur1y SetFilename $filename

cur1x SetDataType "Time"


cur1x SetRequest "Time"
cur1x SetComponent "Time"

cur1y SetDataType "Force"


cur1y SetRequest "REQ/13 Curve 13"
cur1y SetComponent "Z"

plot GetCurveHandle cur2 [plot AddCurve]


cur2 GetVectorHandle cur2x x
cur2 GetVectorHandle cur2y y
cur2x SetType file
cur2y SetType file
cur2x SetFilename $filename
cur2y SetFilename $filename

cur2x SetDataType "Time"


cur2x SetRequest "Time"
cur2x SetComponent "Time"

cur2y SetDataType "Force"


cur2y SetRequest "REQ/18 Curve 18"
cur2y SetComponent "Z"

plot GetVerticalAxisHandle y_axis [plot GetNumberOfVerticalAxes]


y_axis SetLabel "Force (Newtons)"

plot GetHorizontalAxisHandle x_axis [plot GetNumberOfHorizontalAxes]


x_axis SetLabel "Time (Seconds)"

plot Recalculate
plot Autoscale
plot Draw

hwi CloseStack

HyperWorks 13.0 Introduction to HWD Customization 121

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

Exercise 6b:
hwi OpenStack
hwi GetSessionHandle session
session GetProjectHandle project
project GetPageHandle pg [project GetActivePage]
pg GetWindowHandle win [pg GetActiveWindow]

win SetClientType plot


win GetClientHandle plot
set filename "demo.dat"

set num_curve [plot GetNumberOfCurves]


set y_math_list ""

for {set i 1} {$i <= $num_curve} {incr i} {


plot GetCurveHandle cur_handle_$i $i
cur_handle_$i GetVectorHandle vecy_$i y
cur_handle_$i GetVectorHandle vecx_$i x
append y_math_list "[vecy_$i GetMathReference] + "
}

set x_ref [vecx_1 GetMathReference]


set updated_ref [string trimright $y_math_list "+ "]

plot GetCurveHandle cur_sum [plot AddCurve]


cur_sum GetVectorHandle x_sum x
cur_sum GetVectorHandle y_sum y
x_sum SetType math
x_sum SetExpression $x_ref

y_sum SetType math


y_sum SetExpression $updated_ref

cur_sum SetName "Sum Fz Request 13 and 18"

plot GetNoteHandle min_note [plot AddNote]


set ref_sum_y [y_sum GetMathReference]

min_note SetName min_note


min_note SetText "minimum value is {min($ref_sum_y)}"
min_note SetAttachment Curve
min_note SetAttachToCurveIndex [plot GetNumberOfCurves]
set templex_exp indexofmin($ref_sum_y)
min_note SetAttachToPointIndex $templex_exp

plot Recalculate
plot Autoscale
plot Draw

hwi CloseStack

Introduction to HWD Customization 122 HyperWorks 13.0

Proprietary Information of Altair Engineering, Inc

You might also like