Professional Documents
Culture Documents
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
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.
Table of Contents
Introduction to HyperWorks
Desktop Customization
About Tk ..................................................................................................................................... 8
Exercise 2.1 Changing the Client Type using the Command Window ............................ 39
Exercise 5.2 Querying Contoured Results and Creating a List of Results ................... 84
Exercise 6.1 Creating Plots and Notes with Templex inside the Notes ....................... 98
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.
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.
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
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
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
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
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: “
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"
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.
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.
• < > <= >= 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.
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.
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 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.
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.
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:
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 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
}
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:
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:
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
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.
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:
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.
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.
Example 7.2
array set fruitColors {tomato red banana yellow}
puts $fruitColors(tomato)
Output:
red
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.
The open command is used to open a file. The syntax for this command is:
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
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
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:
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
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.
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,
proc bump {} {
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.
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:
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:
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
set types {
{{Text Files} {.txt} }
{{TCL Scripts} {.tcl} }
{{All Files} * }
}
set filename [tk_getOpenFile -filetypes $types]
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
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
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:
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.
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
(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).
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.
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 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:
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:
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.
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:
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:
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.
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.
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.
Help Menu
Online Help
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.
§ 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
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:
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.
After entering all the commands, the Command Window should look like the
following:
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
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
Chapter 3
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:
These commands fall into four categories that manipulate the HyperWorks
database:
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:
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.
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.
hwi ListMethods
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:
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.
§ 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:
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:
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.
Releasing a handle is also necessary for the efficiency and performance of the
script. Here’s an example:
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).
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:
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.
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:
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.
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.
Chapter 4
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
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.
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
with the previous example and assuming that we have a H3D model named
bumper.h3d; we can load the model using the following statement:
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:
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.
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:
Now that we have a valid model handle (my_model), we can attach results using
the SetResult command.
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.
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.
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
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.
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.
hwi OpenStack
hwi GetSessionHandle session1
session1 GetProjectHandle project1
project1 GetPageHandle page1 1
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).
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:
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:
§ 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
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:
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.
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.
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.
After creating this group, you should be able to go to the Groups Panel and turn
the display on/off or change other options.
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.
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:
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
5. The last step is to close the stack to delete the handles created during this exercise:
hwi CloseStack
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
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
Hints
Use the GetSize command on the selection set handle to get the number
of elements in the selection set.
Chapter 5
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
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:
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.
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):
Using this method, you can now selectively apply a contour to a specified set of
entities.
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
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”
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
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
anim Draw
hwi CloseStack
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.
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).
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:
Now the variable named “data_list” is a list of lists containing the following data:
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.
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:
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”
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
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
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.
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
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
Hints
Find out what rules you can use to add entities to a selection set
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
Chapter 6
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.
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.
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.
F The prefix “pltI” is used internally for naming the classes within the plotting client. It
stands for “plot Interface”.
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:
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.
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.
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.
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.
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
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.
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.
Just as with the previous example, we need to use the Recalculate, Autoscale,
and Draw commands to calculate the curves and draw the plot.
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
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:
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.
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.
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)
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 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
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
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 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:
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 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
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
Hints
Try loading the demo.dat file into HyperGraph to see how the Y Type, Y
Request, or Y Component are defined.
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
Hints
To attach a note to the curve at the same point as the minimum, try using
the Templex command indexofmin.
Chapter 7
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.
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:
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.
Export a model
To be able to export an existing model in MotionView to MotionSolve, use the
ExportModel command.
Run MotionSolve
Exercise 2a
### 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
### 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
### 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
CHAPTER 4
Exercise 4a
### Practical Exercise 4a ###
### 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
### Set the active window and then capture the active window to a file ###
pg SetActiveWindow 1
### close the stack to delete the handles gotten during the script ###
hwi CloseStack
Exercise 4b
### Practical Exercise 4b ###
### 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
CHAPTER 5
Exercise 5a
### Practical Exercise 5a ###
### 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
### 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
Exercise 5b
### Practical Exercise 5b ###
### 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
### 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
### 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];
### Print the minimum, maximum and average values to the Command Window ###
puts "Minimum: \t $min\nMaximum : \t $max\nAverage: \t $average"
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 request
my_query SetQuery "component.id contour.maxid contour.max misc.sim";
set subcase_max_value 0;
set subcase_max_entid 0;
set subcase_max_partid 0;
set subcase_max_step 0;
hwi CloseStack;
}
#====================================================================
# get a handle named "name" to the active model only
#====================================================================
proc ::myspace::GetActiveModelHandle { name } {
my_session ReleaseHandle;
my_project ReleaseHandle;
my_page ReleaseHandle;
my_window ReleaseHandle;
my_client ReleaseHandle;
}
#====================================================================
# main procedure
#====================================================================
proc ::myspace::Main {} {
hwi OpenStack;
hwi CloseStack;
}
#====================================================================
# call main procedure
::myspace::Main;
CHAPTER 6
Exercise 6a:
hwi OpenStack
plot Recalculate
plot Autoscale
plot Draw
hwi CloseStack
Exercise 6b:
hwi OpenStack
hwi GetSessionHandle session
session GetProjectHandle project
project GetPageHandle pg [project GetActivePage]
pg GetWindowHandle win [pg GetActiveWindow]
plot Recalculate
plot Autoscale
plot Draw
hwi CloseStack