You are on page 1of 100

HyperWorks is a division of Altair altairhyperworks.

com
HyperMesh Customization
Introduction to HyperMesh Customization
Al tair Engineering Support Contact Information
Web site www.altairhyperworks.com

Location Telephone e-mail
Australia 64.9.413.7981 anzsupport@altair.com
Brazil 55.11.3884.0414 br_support@altair.com
Canada 416.447.6463 support@altairengineering.ca
China 86.400.619.6186 support@altair.com.cn
France 33.1.4133.0992 francesupport@altair.com
Germany 49.7031.6208.22 hwsupport@altair.de
India 91.80. 6629.4500
1.800.425.0234 (toll free)
support@india.altair.com
Italy 39.800.905.595 support@altairengineering.it
J apan 81.3.5396.2881 support@altairjp.co.jp
Korea 82.70.4050.9200 support@altair.co.kr
Mexico 55.56.58.68.08 mx-support@altair.com
New Zealand 64.9.413.7981 anzsupport@altair.com
North America 248.614.2425 hwsupport@altair.com
Scandinavia 46.46.460.2828 support@altair.se
United Kingdom 01926.468.600 support@uk.altair.com
In addition, the following countries have resellers for Altair Engineering: Colombia, Czech Republic, Ecuador, Israel, Russia,
Netherlands, Turkey, Poland, Singapore, Vietnam, Indonesia
Official offices with resellers: Canada, China, France, Germany, India, Malaysia, Italy, J apan, Korea, Spain, Taiwan, United
Kingdom, USA

Copyright Altair Engineering Inc. All Rights Reserved for:
HyperMesh1990-2014; HyperCrash2001-2014; OptiStruct1996-2014; RADIOSS1986-2014; HyperView1999-2014;
HyperView Player2001-2014; HyperStudy1999-2014; HyperGraph1995-2014; MotionView1993-2014; MotionSolve2002-
2014; HyperForm1998-2014; HyperXtrude1999-2014; Process Manager 2003-2014; Templex 1990-2014; TextView
1996-2014; MediaView 1999-2014; TableView 2013-2014; BatchMesher 2003-2014; HyperMath2007-2014;
Manufacturing Solutions 2005-2014; HyperWeld2009-2014; HyperMold2009-2014; solidThinking1993-2014; solidThinking
Inspire2009-2014; solidThinking Evolve 1993-2014; Durability Director 2009-2014; Suspension Director 2009-2014;
AcuSolve1997-2014; AcuConsole2006-2014; SimLab2004-2014 and Virtual Wind Tunnel 2012-2014.

In addition to HyperWorkstrademarks 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. Copyright1994-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 inHyperWorksshall not be decompiled, disassembled, or unlocked,
reverse translated, reverse engineered, or publicly displayed or publicly performed in any manner. Usage of the software is only as
explicitly permitted in the end user software license agreement.

Copyright notice does not imply publication



HyperWorks 13.0 Introduction to HM Customization 3
Proprietary Information of Altair Engineering, Inc
Table of Contents
Introduction to HyperMesh
Customization

Chapter 1: Introduction to TCL ......................................................................... 5
About TCL .................................................................................................................................. 5
About Tk ..................................................................................................................................... 6
Basic Tcl Syntax ........................................................................................................................ 6
TCL Command Overview ......................................................................................................... 6
Tk Basic Commands ............................................................................................................... 21
Chapter 2: HyperMesh Process Automation Introduction ........................... 27
What is a HyperMesh Macro ................................................................................................. 27
The HyperMesh Utility Menu ................................................................................................. 28
Practical Exercises .................................................................................................................. 33
Chapter 3: HyperMesh Automation with HyperMesh Macros ....................... 35
HyperMesh Commands ............................................................................................... 35
HyperMesh Macro Structure ........................................................................................ 39
Process to Create HyperMesh Macros ........................................................................ 40

Introduction to HM Customization 4 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc
Modifying Commands to Create Generalized Macros ................................................. 44
Practical Exercises ....................................................................................................... 46
Chapter 4: Using Tcl to Control the HyperMesh Session ............................ 47
HyperMesh Commands vs. Tcl Modify Commands ..................................................... 47
Tcl GUI Commands and Tcl Query Commands .......................................................... 48
Using the Command Window ...................................................................................... 50
Process to Create a Tcl HyperMesh Macro ................................................................. 55
Practical Exercises ....................................................................................................... 60
Chapter 5: Retrieving Data from HyperMesh Entities .................................. 63
HyperMesh Entities and Their Data Names ................................................................. 63
Pointers and Flags ....................................................................................................... 65
Process for Creating a HyperMesh Tcl Script to Retrieve Data
on HyperMesh Entities ...................................................................................... 67
Practical Exercises ....................................................................................................... 71
Chapter 6: Interfacing with HyperMesh Solver Templates .......................... 75
Solver Attributes and Card Images .............................................................................. 76
Querying Solver Attributes ........................................................................................... 77
Assigning Data to Solver Attributes ............................................................................. 81
Creating a Reusable and Modular Procedure .............................................................. 82
Updating Solver Attributes ........................................................................................... 88
Practical Exercises ....................................................................................................... 91
Solutions For Exercises ................................................................................... 93
Chapter 1: Introduction to Tcl/Tk

HyperWorks 13.0 Introduction to HM Customization 5
Proprietary Information of Altair Engineering, Inc
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.

Chapter 1: Introduction to Tcl/Tk


Introduction to HM Customization 6 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
About TK

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

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

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

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

Basic Tcl Syntax

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

TCL Command Overview

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

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

Example 1.1
puts HyperWorks

Output: HyperWorks

Chapter 1: Introduction to Tcl/Tk

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

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

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

As mentioned above, a command in Tcl is terminated with a newline or semicolon. Tcl
comments are designated with a # at the beginning of the line or after a semicolon.

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

Output:
This is line 1
This is line 2

2. Variables and Variable Substitution

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

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

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

Output:
The software we are using is HyperWorks

Chapter 1: Introduction to Tcl/Tk


Introduction to HM Customization 8 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
Example 2.1 illustrates the use of variable substitution. The value "HyperWorks" is
assigned to the variable "software", whose value is then substituted for $software.
Note that variable substitution can occur within a string.

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

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

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

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

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

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

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

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

Example 2.4:
set month 2
set day 3
set year 09
set date "$month:$day:$year"
Chapter 1: Introduction to Tcl/Tk

HyperWorks 13.0 Introduction to HM Customization 9
Proprietary Information of Altair Engineering, Inc
puts $date

Output: 2:3:09

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

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

Output:
hi

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

3. Expressions

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

Operands may be specified in any of the following ways:

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

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


Introduction to HM Customization 10 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
< > <= >= Boolean less, greater, less than or equal, and greater than
or equal.
== != Boolean equal and not equal.
& Bit-wise AND.
^ Bit-wise exclusive OR.
| Bit-wise OR.
&& Logical AND.
|| Logical OR.

Example 3.1:
expr 0 == 1

Output:
0

Example 3.2:
expr 1 == 1

Output:
1

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

Example 3.3:
expr 4 + 5

Output:
9

Example 3.3 shows how to use the expr statement to evaluate an arithmetic
expression. Here the result is simply the sum of 4 and 5.
Tcl supports the following mathematical functions in expressions:
abs cosh log sqrt
acos double log10 srand
asin exp pow tan
atan floor rand tanh
atan2 fmod round wide
ceil hypot sin
cos int sinh

In addition to these predefined functions, applications may define additional functions
using Tcl_CreateMathFunc().

Chapter 1: Introduction to Tcl/Tk

HyperWorks 13.0 Introduction to HM Customization 11
Proprietary Information of Altair Engineering, Inc
Example 3.4:
expr sin(2)

Output:
0.909297

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

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

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

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

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

Example 4.2:
set my_height 6.0

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

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

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

5. Comparisons and Loops

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


Introduction to HM Customization 12 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
well as looping constructs (while, for, and foreach statements), both of which can
alter the flow of execution in response to some condition. The following examples serve
to illustrate these constructs.

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

Output:
Handling is good.

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

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

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

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

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

Output:
It could be a cow.
Chapter 1: Introduction to Tcl/Tk

HyperWorks 13.0 Introduction to HM Customization 13
Proprietary Information of Altair Engineering, Inc

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

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

The string argument is compared to each of the patterns and if a comparison
succeeds, the corresponding body is executed, after which the switch statement
returns. The pattern "default", if present, is always matched, and thus its body always
executed if none of the earlier comparisons succeed.

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

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

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

The general syntax for the for loop is as follows:

for init test reinit body

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

Example 5.4:
set i 0
while {$i < 5} {
puts "In the while loop, and i == $i"
incr i 1
}
Chapter 1: Introduction to Tcl/Tk


Introduction to HM Customization 14 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.

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

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

while test body

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

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

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

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

foreach varName list body

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

HyperWorks 13.0 Introduction to HM Customization 15
Proprietary Information of Altair Engineering, Inc
in the next section), and for each value, the body of the loop is executed, resulting in one
printed statement each time.

6. Lists

Lists in Tcl provide a simple means by which to group collections of items, and deal with
the collection as a single entity. When needed, the single items in the group can be
accessed individually. Lists are represented in Tcl as strings with a specified format. As
such, they can be used in any place where strings are normally allowed. The elements
of a list are also strings, and therefore any form of data that can be represented by a
string can be included in a list (allowing lists to be nested within one another).
Lists can be created in the following ways, in addition to being represented by a string.
by setting a variable to be a list of values
set lst {{item 1} {item 2} {item 3}}
with the split command
set lst [split "item 1.item 2.item 3" "."]
with the list command
set lst [list "item 1" "item 2" "item 3"]
An individual list member can be accessed with the lindex command. The following
examples will illustrate many important list commands:
Example 6.1:
set simple_list John Joe Mary Susan
puts [lindex $simple_list 0]
puts [lindex $simple_list 2]

Output:
John
Mary

Example 6.1 creates a simple list of four elements, each of which consists of one word.
The lindex command is then used to extract two of the elements in the list: the 0
th

element and the 2nd element. Note that list indexing is zero-based. It is also important to
see that the lindex command, along with most other list commands, takes an actual
list as its first argument, not the name of a variable containing a list. Thus the value of
the variable "simple_list" is substitued into the lindex command.

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

foreach varName list body

As mentioned previously, the foreach command will execute the body code one time
for each list item in list. On each pass, varName will contain the value of the next
list item.
Chapter 1: Introduction to Tcl/Tk


Introduction to HM Customization 16 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.

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.

Chapter 1: Introduction to Tcl/Tk

HyperWorks 13.0 Introduction to HM Customization 17
Proprietary Information of Altair Engineering, Inc
Example 7.2
array set fruitColors {tomato red banana yellow}
puts $fruitColors(tomato)

Output:
red

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

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

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

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

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

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

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

Chapter 1: Introduction to Tcl/Tk


Introduction to HM Customization 18 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
The open command is used to open a file. The syntax for this command is:

open filename access

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

Example 9.1
set filename [open temp.txt w]

Output:
file4915610

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

puts ?channelId? string

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

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

Output: file4910020

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

gets channelId

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

Example 9.3
set filname [open "temp.txt" "r"]
set line1 [gets $filename]
set line2 [gets $filename]
close $filename
Chapter 1: Introduction to Tcl/Tk

HyperWorks 13.0 Introduction to HM Customization 19
Proprietary Information of Altair Engineering, Inc
puts "Line 1: $line1"
puts "Line 2: $line2"

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

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

proc name argList body

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

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

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

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

Chapter 1: Introduction to Tcl/Tk


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

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

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

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

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

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

namespace eval Counter {
namespace export bump
variable num 0

proc bump {} {
Chapter 1: Introduction to Tcl/Tk

HyperWorks 13.0 Introduction to HM Customization 21
Proprietary Information of Altair Engineering, Inc
variable num
incr num
}
}

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

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

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

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

Example 1.1
tk_getOpenFile

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

Chapter 1: Introduction to Tcl/Tk


Introduction to HM Customization 22 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.


Figure 1: GUI created from tk_getOpenFile command.


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

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

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

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

tk_getOpenFile ?option value ...?

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

-filetypes filePatternList

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

Examples 1.3
Chapter 1: Introduction to Tcl/Tk

HyperWorks 13.0 Introduction to HM Customization 23
Proprietary Information of Altair Engineering, Inc
set types {
{{Text Files} {.txt} }
{{TCL Scripts} {.tcl} }
{{All Files} * }
}
set filename [tk_getOpenFile -filetypes $types]




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

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

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

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

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

Output:
C:/Documents and Settings/training/My Documents/test.txt
Chapter 1: Introduction to Tcl/Tk


Introduction to HM Customization 24 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.



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


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

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

Example 3.1
set dirname [tk_chooseDirectory]
puts $dirname

Output:
C:/temp

Chapter 1: Introduction to Tcl/Tk

HyperWorks 13.0 Introduction to HM Customization 25
Proprietary Information of Altair Engineering, Inc


Figure 4: GUI from tk_chooseDirectory command.

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

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

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

Output:



Figure 5: GUI from tk_messageBox command.




Chapter 1: Introduction to Tcl/Tk


Introduction to HM Customization 26 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.







Chapter 2: HyperMesh Process Automation Introduction

HyperWorks 13.0 Introduction to HM Customization 27
Proprietary Information of Altair Engineering, Inc
Chapter 2
HyperMesh Process
Automation Introduction

In this chapter we will discuss what HyperMesh automation is and the different
levels of automation available within HyperMesh. We will also examine the
HyperMesh Utility menu, the files that are associated with it, and how to run
macros and scripts from it. Finally an example will be given and after which an
exercise will be done.

What is a HyperMesh Macro

A HyperMesh macro functions like a script or command file and is used to
automate a HyperMesh process or execute a series of steps. The HyperMesh
macro language is an extension of the HyperMesh command layer. The types of
macros you can write vary from basic to advanced. Basic types are simple
macros of HyperMesh commands that run a sequential HyperMesh command
file. More advanced macros involve using the Tcl/Tk scripting language to add
additional logic and user interaction such has entity selection. Even more
advanced automation can be done using the Altair Process Manager. The
Process Manager is a programmable personal workflow manager that guides
users through a standard work process. The Process Manager will be addressed
in a different class. Here the focus will be on creating simple HyperMesh macros
and HyperMesh macros with Tcl/Tk.

The HyperMesh Utility Menu commands provide the means to create an interface
in the form of buttons and button groups. For each you specify the following
characteristics:

The macro page it is displayed on
Its label
Its location and size
Chapter 2: HyperMesh Process Automation Introduction

Introduction to HM Customization 28 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
Its help message
The macro it calls, and any optional arguments

!
The macro command language is an interpreted language. This means each
command executes in the order in which it appears in the macro file.

!
While macros offer a great deal of flexibility, remember once a macro executes, there
is no way to cancel the execution or reject the results. In addition, a macro may not
be recursive (call itself).


The HyperMesh Utility Menu

The Utility menu allows you to customize the standard interface to include
function buttons, radio options, and text that have HyperMesh-supplied and user-
defined macros associated with them. The Utility menu is located on a tab of the
Tab area pane(s), and can be shown or hidden from within the View > Browsers
> HyperMesh pull-down menu.

The Utility menu includes several pages of its own, each dedicated to different
tasks. Thus it presents groups of functionalities accessible from a set of pages
contained by the Utility tab, although only one set of functions is displayed at a
time. Each page is associated with a button at the bottom of the Utility menu;
clicking one of these buttons accesses the page associated with it. A macro file
(hm.mac) controls the display and available operations of the Utility Menu.
Attributes that you can change include:

The Utility menu page on which the operations appear.
Text to be displayed on each control.
Location and size of the menu.
The help string to be displayed in the bubble as the mouse is hovered
over the button.
The macro to call when each control is used.

When HyperMesh starts, it looks for a macro file named hm.mac in the current
directory, HOME directory (UNIX only), or the applications base directory. If it
finds this file, HyperMesh runs it automatically to define the attributes and
contents of the Utility Menu.

The default hm.mac file sources the following additional macro files:

disppage.mac Populates the Display page of the Utility Menu
Chapter 2: HyperMesh Process Automation Introduction

HyperWorks 13.0 Introduction to HM Customization 29
Proprietary Information of Altair Engineering, Inc
geommeshpage.mac Populates the Geom/Mesh page of the Utility
Menu
globalpage.mac Creates the button group that allows you to switch
pages
qamodelpage.mac Populates the QA/Model page of the Utility Menu
userpage.mac Populates the User page of the Utility Menu

A userpage.mac file may exist in the installation directory for HyperMesh or in
the directory from which HyperMesh launches. When HyperMesh starts, it first
looks for the userpage.mac file in the directory from which it launches and then
in the installation directory. UNIX users also have the option of putting the
userpage.mac file in their home directory. This file defines the attributes and
contents of the User page of the Utility menu. By default, the Utility menu
displays when HyperMesh starts, but display of the menu can be turned off by
going to the View > Browsers > HyperMesh pull-down menu.

HyperMesh Utility Menu Commands

HyperMesh macro commands reside in the default hm.mac file. When you open
this file, you will see that it defines the Utility menu contents in order by page. To
change a macro on a given page, find that page in the hm.mac file and the
macro name that you wish to modify.

Attributes you can change on a macro page include:
Buttons to display on that macro page
The location and size of the buttons appearing on a macro page
The label for each button
The help string displayed in the bubble as the mouse is hovered over the
button.
The macro called by each button, with optional arguments to pass

HyperMesh macros consist of valid command file or templex commands, and are
enclosed by the *beginmacro(macroname) and *endmacro() commands.
Macros may accept data passed to them using the arguments $1, $2, etc. Each
argument specifies where the values should be substituted. The *callmacro()
command allows you to call a macro from within another one, which allows you
to create groups of standard reusable macros.

The following skeleton shows the format of a macro:

*beginmacro(macroname)
macro command statements go here
*endmacro()

Chapter 2: HyperMesh Process Automation Introduction

Introduction to HM Customization 30 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
In the next Chapter we will go over HyperMesh macros in more detail. Here we
will focus on how to add a button to the Utility menu.

To activate the macro from HyperMesh, you must create a button on the Utility
menu to invoke the macro. Use the *createbutton() command to define the
button and its characteristics. The syntax for this command is:

*createbutton(page, name, row, column, width, COLOR,
helpString, macroName [ , arg1 ])

Where:

page: Indicates the page number on which the button is to appear (values
1 through n; initially there are 5).
name: The text to display on the button. Enclose the text with quotes ( ).
row: The row in which to place the button (values 1, 1 - n). The number
of rows visible depends upon the graphics resolution setting of your
hardware. A 0 indicates the next available position, and 1
indicates to skip a row.
column: The column where the button starts (values 0 - 10 ).
width: The width of the button ( max 10).
COLOR: The color of the button. The available button colors are: RED,
BLUE, GREEN, CYAN, BUTTON, GREY, YELLOW and
MAGENTA. The color name must appear in capital letters.
helpString: The string to be displayed in the bubble as the mouse is hovered
over the button. Enclose text of string in quotes ( ).
macroName: The name of the macro to call when the button is selected.
Enclose text of string in quotes ( ).
arg1!: A list of one or more optional arguments passed to the macro. You
may have as many arguments as your computers memory will
allow





Figure: Row and Column Designations

Row 1
Column 0
Chapter 2: HyperMesh Process Automation Introduction

HyperWorks 13.0 Introduction to HM Customization 31
Proprietary Information of Altair Engineering, Inc
Below are two examples on how to create a button. The first example illustrates
the button calls needed for a user-created HyperMesh macro:

*createbutton(5, Create force, -1, 0, 10, GREEN, Create
force on selected nodes, createForce_macro)

!
The end of a command is a hard return <cr> (press the ENTER key). In your text
editor, type each command until you get to the end of it, then press ENTER.


The second example shows the button calls for a user created Tcl script using
the EvalTcl command:

*createbutton(5, Create force, -1, 0, 10, GREEN, Create
force on selected nodes, EvalTcl, create_force.tcl)

For each example, 5 refers to the Userpage, Create force is the text on the
button, -1 refers to the row position, 0 is the column number, 10 is the column
width, GREEN is the color of the button, and Create force on selected nodes is
the help string. For the HyperMesh macro example, createForce_macro is
the name of the macro to be evaluated. In the Tcl script example, EvalTcl
needs to be entered before create_force.tcl which is the name of the Tcl
file.

Notice that the full path for create_force.tcl isnt given. A full path can be
specified if the file isnt located in one of the predefined paths that HyperMesh
searches to find scripts. These paths include installation paths as well as the
working directory. Users can add additional search paths using the
TCL_INCLUDE environment variable. Relative paths can also be used from
these search paths.

!
The only commands used in this example are the menu macro commands, which
called an existing tcl procedure. We have yet to use the macro command to create
our own procedures, tasks or actions.


Online Help

The Online Help for HyperMesh can be accessed by either typing h on your
keyboard or by going to Help in the menu bar and selecting HyperWorks
Desktop. Within the HyperWorks 12.0 Welcome Page there is a HyperWorks
Reference Guides Section. Selecting HyperMesh opens the HyperMesh
Reference Guide in a new tab. If you expand HyperMesh Reference Guide in
Chapter 2: HyperMesh Process Automation Introduction

Introduction to HM Customization 32 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
the navigation area you will find another book named Scripts. This contains all
the commands and functions used in HyperMesh.




Figure: Reference Guide in HyperMesh and BatchMesher Online Help
Chapter 2: HyperMesh Process Automation Introduction

HyperWorks 13.0 Introduction to HM Customization 33
Proprietary Information of Altair Engineering, Inc
Practical Exercises
Exercise 2a

Description
Add a button to the User Page on the Utility Menu that executes the macro
modeltour.tcl. This macro is located in the installation under hm\scripts,
so a path is not needed. The name of the button should be Model Tour.
The help string should be Explore HyperMesh Session. The color and
location are up to you.

HyperMesh commands used
*createbutton()

TCL/TK commands used
none

Hints
On Windows, the working directory is located in the My Documents folder.
Create a new text file called userpage.mac in this location and add the
appropriate commands to make the button evaluate the tcl file.

























Chapter 2: HyperMesh Process Automation Introduction

Introduction to HM Customization 34 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.












Chapter 3: HyperMesh Automation with HyperMesh Macros

HyperWorks 13.0 Introduction to HM Customization 35
Proprietary Information of Altair Engineering, Inc
Chapter 3
HyperMesh Automation with
HyperMesh Macros

In this chapter we will go over HyperMesh commands and become familiar with
the general process for creating HyperMesh command macros. These macros
make use of only HyperMesh commands. Such commands are written to the
command.cmf file when an action is performed in HyperMesh.

HyperMesh Commands

As an introduction to HyperMesh commands, an explanation of command files,
entity types, marks, and temporary planes and vectors are described below. In
addition, a list of common command file commands is presented.

Command Files

During each HyperMesh session, HyperMesh generates a command file named
command.cmf. If this file doesn't already exist, then HyperMesh creates it at the
start of a session. If the file does already exist, HyperMesh adds the commands
for the new session to the end of the original file.

HyperMesh command files are standard ASCII files that HyperMesh can read or
write. Command files allow you to program a series of procedures or, in the case
of a power failure or other unexpected system loss, retrieve an earlier work
session. You can use command files in applications that rely on repetitive or
iterative steps, or to create demonstrations.

Command files follow this syntax:
A command begins with an asterisk (*).
A command ends with the left parenthesis.
Chapter 3: HyperMesh Automation with HyperMesh Macros

Introduction to HM Customization 36 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
The parameters for a command are separated by commas, ending with
the right parenthesis.

The following command illustrates the command syntax. The shrink command
is:

*shrink(.2)

The command name that HyperMesh reads is located between the asterisk and
the left parenthesis; in this case, it is the word shrink. The command has one
parameter, .2, which is the factor that HyperMesh shrinks the elements (in this
example, the elements shrink by 20%, leaving open gaps between them).

Commands executed in an active HyperMesh session are not immediately
written to the command files. They are stored in memory and are written to the
command file during idle time (when HyperMesh is not busy performing user
operations).

Entity Types

HyperMesh entities are often used as string parameters in commands that act
directly on entities in some fashion, such as creating filtered sets that contain
only a specific entity type. Examples of entity types are elements, line, groups,
sets, and loads. For a complete listing, please refer to the online help.

Marks

Marks specify groups of entities that are transferred to the command processor.
Marks can be created for most entities, and commands are then issued to
perform operations on the entities on the mark. HyperMesh allows for two
standard marks and a user mark.

Standard marks are referenced by the mark IDs 1 and 2. The following example
demonstrates how to delete elements using standard marks; assume that you
want to delete the elements 50, 51, and 52 from a database. To perform this
operation, you must create a mark with these elements and then instruct
HyperMesh to delete the mark:

*createmark(elements, 1) 50 51 52
*deletemark(elements, 1)

This *createmark command populates mark 1 with elements 50, 51, and 52.
The *deletemark command deletes the elements contained on mark 1.

Chapter 3: HyperMesh Automation with HyperMesh Macros

HyperWorks 13.0 Introduction to HM Customization 37
Proprietary Information of Altair Engineering, Inc
Notice after the *createmark command there are a series of numbers which
correspond to the element ids which were added to the mark. These ids will not
be consistent from model to model. In order to make a macro useful for multiple
models, we can change the selection method.

Several options exist to make the *createmark command general enough to
work with any model. For example, to select all the currently displayed elements
in the model use the command *createmark(elements,1)"by
displayed".

A mark can also be appended using the *appendmark() command. Imagine
from the previous example, we want to delete elements 50, 51, and 52 as well as
all the elements adjacent to those elements. To do this, the commands would be
as follows:

*createmark(elements, 1) 50 51 52
*appendmark(elements, 1) by adjacent
*deletemark(elements, 1)

Another option is to replace the *createmark command with
*createmarkpanel. When executed, this command presents the user with a
selection panel in the entity specified in the command can be selected.

Planes and Vectors

At times, it is necessary to define a vector or plane for a command. HyperMesh
allocates two vectors and two planes with the IDs 1 and 2. The vectors and
planes can be defined at any time during the processing of a command file or Tcl
script.
The following example translates node 10 along the x axis by 5 units:

*createvector(1, 1.0, 0.0, 0.0)
*createmark(nodes, 1) 10
*translatemark(nodes, 1, 1, 5.0)

In this case, vector 1 is loaded with the components (1.0,0.0,0.0) that define the
global x-axis. Node mark 1 is populated with node 10. These are then passed to
the *translatemark command to perform the action.

Additionally, a normal and base point are required to define a plane. The next
example reflects all displayed elements about a plane that has a normal along
the x axis and a base point of (5.0,0.0,0.0):

*createplane(1, 1.0, 0.0, 0.0, 5.0, 0.0, 0.0)
*createmark(elements, 1) displayed
*reflectmark(elements, 1, 1)
Chapter 3: HyperMesh Automation with HyperMesh Macros

Introduction to HM Customization 38 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.

For this example, plane 1 is defined by the normal of (1.0, 0.0, 0.0) and the base
point of (5.0, 0.0, 0.0). The element mark is then populated with all the displayed
elements. These elements and the plane definition are passed to the
*reflectmark() command to perform the reflection.

Common Command File Commands

Below is a table with many common command file commands as well as a
description of the command.

Command Name Description
*appendmark() Add additional entities to a mark
*beginmacro(name) Start the definition of a Utility Menu macro
*callmacro() Call a macro from within another macro
*createbutton()
Add a button to the Utility Menu
*createbuttongroup() Add a button group to the Utility Menu
*createlistpanel() Allow you to interactively select a list of entities
*createmarklast()
Place the entities from the last operation into a
mark
*createmarkpanel() Allow you to interactively select entities
*createtext() Add text to the Utility Menu
*endmacro()
End the definition of a macro started with the
beginmacro command
*enterpanel()
Enter the passed HyperMesh panel
*includemacrofile() Include the contents of the passed macro file
*insertbutton() Insert a button into the Utility Menu
*inserttext() Insert text into the Utility Menu
*setactivegroup() Set the default selection for a button group
*setactivepage()
Set the current displayed Utility Menu page
*setbuttongroupactivecolor()
Set the color for the Utility Menu button groups
current selection indicator

For a complete listing of command file commands, please refer to the online
help. In the Scripts book under the Reference Guide, there is a topic for
Commands and Functions. In this book you will find a complete listing of all the
commands available in HyperMesh.

Chapter 3: HyperMesh Automation with HyperMesh Macros

HyperWorks 13.0 Introduction to HM Customization 39
Proprietary Information of Altair Engineering, Inc






Chapter 3: HyperMesh Automation with HyperMesh Macros

Introduction to HM Customization 40 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
HyperMesh Macro Structure

As mentioned in the previous chapter, the HyperMesh macro consists of valid
command file or templex commands. These commands are enclosed by the
*beginmacro() and *endmacro() commands. The following skeleton shows the
format of a macro.

*beginmacro(macroName)
[commands]
*endmacro()

Macros may accept data passed to them using the arguments $1, $2, etc. Each
argument specifies where the values should be substituted. Below is an example
to turn on/off all geometry.

*beginmacro(ToggleGeom_macro)
*displaycollectorwithfilter(comps,$1,,0,1)
*plot()
*endmacro()

By specifying none for $1 in the *createbutton command, the argument is
passed to the macro so that all geometry is turned off. The *createbutton
command is shown below:

*createbutton(5, Turn off all geometry, -1, 0, 10, GREEN,
Turn off the display of all geometry, ToggleGeom_macro,
none)

Process to Create HyperMesh Macros

The following is a process to assist you in creating HyperMesh macros. While
this procedure does not have to be followed, it is strongly recommended that you
follow this procedure as it has been found to be an effective way to create
HyperMesh macros.

1. Define the task to be automated.
2. Delete the existing command.cmf file. This file is located in either the
start-in directory or the current working directory.
3. Perform the operations in HyperMesh that the script should run.
4. Extract the commands from the command.cmf file.
5. Add the commands to the userpage.mac file.
6. Modify the commands as necessary and add macro wrapper commands
*beginmacro and *endmacro.
7. Add the macro button using the *createbutton command that will call
the new macro defined in Step 6.
Chapter 3: HyperMesh Automation with HyperMesh Macros

HyperWorks 13.0 Introduction to HM Customization 41
Proprietary Information of Altair Engineering, Inc
8. Reload the current .mac file into HyperMesh to load the modified
userpage.mac.
9. Test the macro.



Example 3.1: Automate Creating a Load Collector

The purpose of this example is to become familiar with the general process for
creating a HyperMesh macro. This example will use the process described
above for creating a HyperMesh macro.

Step 1: Define the task to be automated

Create a load collector named forces. A card image does not need to be
specified for the collector.

Step 2: Delete the existing command.cmf file

Every command executed in HyperMesh is recorded in the command.cmf file.
To view only the tasks commands, it is suggested that you delete the
command.cmf file before doing the task. After deleting this file, the file is
automatically recreated when more commands are executed in HyperMesh.

The command.cmf file is located in the My Documents folder on Windows.

Step 3: Do the task in HyperMesh

1. Open HyperMesh.
2. Click the Model tab in the Tab area if the Model Browser is open. Or go
to the menu bar and select View > Browsers > HyperMesh menu and
select Model.
3. Right-click in the white blank area and from the pop-up menu, select
Create > Load Collector.
4. For Name, type forces.
5. Select any color for Color.
6. Verify that there is a check mark next to Close dialog upon creation.
7. Click Create to create the load collector.
8. Keep this HyperMesh session open for steps later in this exercise.

Step 4: Extract commands from the command file and add them
to the userpage.mac file

Chapter 3: HyperMesh Automation with HyperMesh Macros

Introduction to HM Customization 42 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
1. From your HyperMesh working directory, open the command.cmf file.
2. Locate the command *collectorcreateonly() at or near the end of
the file. You should see a line similar to the following:

*collectorcreateonly(loadcols, forces, ,7)

This command creates a load collector named forces and because the
above command as a color id of 7, it has a color of light blue.

3. Copy the *collectorcreateonly() line.
4. From your HyperMesh working directory, open the userpage.mac file. If
this file does not already exist, create an empty text file named
userpage.mac
5. In the userpage.mac file, on the next blank line from the top, paste the
copied line.
6. Save the userpage.mac file.

Step 5: Modify the commands in the userpage.mac file as
necessary

Do not modify the *collectorcreateonly() command as it does not need to
be modified for this example.

Step 6: Add macro wrapper commands

Add the *beginmacro() and *endmacro() commands to create the macro as
shown below:

*beginmacro(macroCreate_LoadCol)
*collectorcreateonly(loadcols, forces, , 7)
*endmacro()

Note: macroCreate_LoadCol is the macros name. It links the macro to its
button, which you will create in the next step, via the macro name field in the
*createbutton() line.

Step 7: Create a button and label for the macro on the Utility
menus User page

Create an activation button in the Utility Menu to execute the macro. Place the
button on page 5 (User) of the Utility Menu as that page is dedicated to user-
defined macros.

Chapter 3: HyperMesh Automation with HyperMesh Macros

HyperWorks 13.0 Introduction to HM Customization 43
Proprietary Information of Altair Engineering, Inc
1. In the userpage.mac file, add the following line at the beginning of the
file to create a green button called Create Load Col. Note that the
*createbutton command should all be on a single line. It is shown on
two lines below simply due to space limitations.

*createbutton(5, Create Load Col, -1, 0, 10, GREEN,
Create a load collector, macroCreate_LoadCol)

2. Create a label for the button using the *createtext() command as
shown below. Add this below the *createbutton command.

*createtext(5, Collectors:, -1, 0)

Step 8: Save the userpage.mac file

The userpage.mac file should look like the following:

*createbutton(5, Create Load Col, -1, 0, 10, GREEN,
Create a load collector, macroCreate_LoadCol)

*createtext(5, Collectors:, -1, 0)

*beginmacro(macroCreate_LoadCol)
*collectorcreateonly(loadcols,"forces","",5)
*endmacro()

Save the userpage.mac file.

Step 9: Load the userpage.mac file into the current HyperMesh
session

The userpage.mac file can be loaded into the current HyperMesh session in a
couple of different ways. By changing the User Profile, the userpage.mac file
gets reloaded. While this method works, if you dont want to change the User
Profile, another method is to either reload the hm.mac file or simply close and
reopen HyperMesh.

1. Close HyperMesh and reopen HyperMesh. OR load a different user
profile.


Step 10: Test the macro

1. Click on the Utility tab in the tab area and select the User page. Notice
the Create Load Col button and the Collectors: label on the User page.
Chapter 3: HyperMesh Automation with HyperMesh Macros

Introduction to HM Customization 44 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
2. Click the Create Load Col button.
3. Notice in the status bar that the message The collector was created
appears.
4. Click on the Model tab to view the Model Browser.
5. Notice how there is now a LoadCollectors folder with a single load
collector called forces inside of it.

Step 11: The exercise is complete. Close the HyperMesh
Session.

Summary

In this example, a macro was created to automate the process of creating a load
collector called forces. First we defined the process and executed it in
HyperMesh. Next we extracted the necessary command from the command.cmf
file. Then in the userpage.mac file we added the necessary command, the
appropriate wrapper commands, and created a button to execute the macro. We
loaded the macro file into HyperMesh and tested it. Creating a macro will not
always be as simple as cutting and pasting commands from the command.cmf
file. Sometimes macros will have to use extended selection options in order to
be general enough to be used on multiple models. Other times the user will need
to interactively select entities as well. The next example will explore these
options.

Modifying Commands to Create Generalized
Macros

As mentioned above, simply copying commands from the command.cmf can
result in macros that are too restrictive. In order to generalize the macros so that
they can be used on multiple models, the *createmark() command will need
to be modified.

Lets examine the *createmark() command. This command places entities on
a mark (which is a storage buffer). For each entity type there are two marks
available, 1 and 2. Once on a mark these entities can be passed to other
commands. When the command using the mark is executed, the changes apply
to all entities in the mark.

When HyperMesh writes the *createmark() command to the command.cmf
file, it operates on entity ids making it very restrictive. Even if a selection method
such as displayed is used, entity ids are listed in the command.cmf file. As a
result, we need to modify the command so that it is less restrictive. We can do
this by either replacing the entity ids with a selection option (such as all,
displayed, on plane, etc) or by replacing the *createmark() command with
Chapter 3: HyperMesh Automation with HyperMesh Macros

HyperWorks 13.0 Introduction to HM Customization 45
Proprietary Information of Altair Engineering, Inc
the *createmarkpanel() command. The *createmarkpanel() command
allows users to interactively select the entities.

First lets look at the first option of modifying the *createmark() command.
The syntax for the *createmark() command is:


*createmark(entity_type, mark_id) ?options? ?list?

entity_type Type of entity to be place on the mark (elements, nodes, etc)
mark_id ID of the mark to be created, 1 or 2
?options? Options used to control how the mark is created. Selection
options such as displayed or by config can be used. If no
option is specified, an attempt is made to find entity by
name first, and if it fails, then by id, etc.
?list? list of IDs, names, or parameters depending on ?options?


Example: To delete the displayed elements:

*createmark(elements, 1) displayed
*deletemark(elements, 1)

The second option is to replace the *createmark() command with the
*createmarkpanel() command which allows the user to interactively select
the entities. The syntax for the *createmarkpanel() command is:

*createmarkpanel(entity_type, mark_id, message)

entity_type Type of entity to be placed on the mark
mark_id ID of the mark to be created, 1 or 2
message Message to display to the user


Example: Allow the user to select the elements and then delete the elements:

*createmarkpanel(elements, 1, Select elements to
delete)
*deletemark(elements, 1)






Chapter 3: HyperMesh Automation with HyperMesh Macros

Introduction to HM Customization 46 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
Practical Exercises
Exercise 3a

Description
Add a button to the Utility Menu that allows elements on the top of the
channel to be translated in the z-direction. Give the users the option of
selecting which elements to translate. You can test the macro using the
file c_channel-tcl_vector.hm.

HyperMesh commands used
*createbutton()
*createmarkpanel()
*translatemark()
*beginmacro()
*endmacro()

TCL/TK commands used
none

Hints
Follow the Process to Create HyperMesh Macros presented in this
Chapter. Do all the steps in HyperMesh and extract the appropriate
commands from the command.cmf file.

















Chapter 4: Using Tcl to Control the HyperMesh Session

HyperWorks 13.0 Introduction to HM Customization 47
Proprietary Information of Altair Engineering, Inc
Chapter 4
Using Tcl to Control the
HyperMesh Session

The macros that have been created thus far are very powerful in their automation
of repetitive tasks. However, there are limitations. For example, in the LoadCol
macro which creates a load collector called forces, the name of the load collector
is hard-coded. If the user wanted to create a load collector with a different name,
it would require editing the name in the userpage.mac file.

The Tcl scripting language can be utilized to provide support for more advanced
tasks. Using the previous example, Tcl could be used to request a name for the
load collector from the user and use that information to tell the HyperMesh
session to create a load collector with the user provided name.

HyperMesh Commands vs. Tcl Modify Commands

The HyperMesh commands that were presented in the previous chapter are also
available through their Tcl Modify commands. For the HyperMesh Tcl Modify
commands, the command syntax has changed and does not contain
parentheses and commas; they have been replaced with a blank space. Also the
wrapper commands *beginmacro() and *endmacro() are not used. For
example, lets compare the following HyperMesh command macro and its Tcl
equivalent.








Chapter 4: Using Tcl to Control the HyperMesh Session

Introduction to HM Customization 48 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
Macro in userpage.mac file Tcl Script
*beginmacro("macroJpeg") Not used in Tcl
*setbackgroundcolor(255,255,255) *setbackgroundcolor 255 255 255
*setmeshlinecolor(6) *setmeshlinecolor 6
*jpegfile() *jpegfile
*setbackgroundcolor(0,0,0) *setbackgroundcolor 0 0 0
*setmeshlinecolor(0) *setmeshlinecolor 0
*endmacro() Not used in Tcl

Notice that while the parentheses and commas have been removed, each of the
commands still begin with an asterisk (*) and that the command name hasnt
changed. In addition to the syntax change, Tcl core commands can also be used
(these are the commands presented in Chapter 1). The addition of the Tcl
commands provides added functionality to the macros.

Tcl GUI Commands and Tcl Query Commands

In addition to the HyperMesh Tcl Modify Commands, there are HyperMesh Tcl
GUI commands and HyperMesh Tcl Query Commands. As their names suggest,
these commands either make changes/updates in the HyperMesh GUI or they
query the HyperMesh database for information. Also, these commands have the
prefix hm_. We will go over a few basic HyperMesh input widgets and a table
of common commands will be presented.

Basic HyperMesh Input Widgets

One of the most basic things that need to be done in a macro is to enter data or
text to be used in the HyperMesh macro. For example, imagine we are creating
a load collector as we did in the previous chapter. In that example, the name of
the load collector was hard-coded into the macro. Using the hm_getstring
command, a string value is returned by providing the user with a HyperMesh
panel. The syntax is:

hm_getstring ?caption? ?message?

where both the caption and message are optional arguments. The caption is
shown in the panel while the message is shown in the message bar. For
example:

hm_getstring Load collector name Enter a name for the
load collector

produces the following panel and message in HyperMesh

Chapter 4: Using Tcl to Control the HyperMesh Session

HyperWorks 13.0 Introduction to HM Customization 49
Proprietary Information of Altair Engineering, Inc


Panel produced by hm_getstring

This command can be used with the set Tcl command to assign the string
entered in the panel to a variable:

set loadname [hm_getstring Load collector name Enter
name for load collector]

In addition to getting a string, the hm_getint and hm_getfloat commands
can be used to get values by posting a panel in the HyperMesh panel area. The
hm_getint command returns a user input integer value while hm_getfloat
returns a user input floating point value. Both these commands have the same
options as the hm_getstring command. As an example, lets assign a floating
point value to a variable called force:

set force [hm_getfloat Force Enter force value]




Panel produced by hm_getfloat

With the addition of the HyperMesh Tcl commands, there are a few commands
which replace the HyperMesh Modify commands. Specifically there are the
hm_createmark and hm_clearmark commands. These commands perform
the same functionality as the *createmark and *clearmark commands, but
they are the HyperMesh Tcl equivalent. The advantage of using these
commands is that it avoids situations where additional Tcl commands need to be
used to evaluate the HyperMesh command. Using hm_createmark and
hm_clearmark when writing Tcl scripts is the more efficient and recommended
method.
Chapter 4: Using Tcl to Control the HyperMesh Session

Introduction to HM Customization 50 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.

The following table contains a list of the commonly used HyperMesh Tcl
commands as well as a short description of that command. For a full explanation
of the commands, please refer to the Reference Guide in the HyperWorks help.

Common HyperMesh Tcl Commands

hm_answernext
Force an answer to the next * command
hm_answernext "yes"
*deletemodel
hm_blockmessages
Inform HyperMesh whether or not messages should
be displayed in header message bar
hm_createmark
Places entities on a mark based on user-supplied
options
hm_elemlist Return list of element ids for passed component id
hm_entityinfo Get information about entities in current model
hm_entitylist
Get list of names or IDs of all entities of the
requested type in current model
hm_entitymaxid Return maximum ID in use for an entity type
hm_errormessage Display error message in header message bar
hm_getclosestnode
Return ID of closest node to point x y z
hm_getentityvalue
Get information for an entity using the HyperMesh
template interface
hm_getfilename Get filename from user using HyperMesh file panel
hm_getfloat
Get floating point value from user using HyperMesh
panel
hm_getint Get integer value from user using HyperMesh panel
hm_getmark Get ids for passed entity type on passed mark mask
hm_getstring Get text string from user using HyperMesh panel
hm_info Get general information about HyperMesh
hm_markclear Clear IDs for entity type from passed mark mask
hm_nodelist Get list of node IDs for passed element
hm_nodevalue Get XYZ values for passed node ID
hm_usermessage
Display message in HyperMesh header message
bar


Using the Command Window

The first step in learning to integrate Tcl scripts into the HyperMesh environment
is to learn how to launch scripts from the HyperMesh interface. An interactive
Command Window is provided and can be access through the View menu. This
Chapter 4: Using Tcl to Control the HyperMesh Session

HyperWorks 13.0 Introduction to HM Customization 51
Proprietary Information of Altair Engineering, Inc
launches the Tk Console (TkCon) which is an interactive console which comes
with Tk.


The Command Window

In the Command Window, users can evaluate any command that can be issued
in Tcl or in HyperMesh through Tcl. Lets examine a few commands. General
Unix command such as ls, pwd, and cd can be used within the Command
Window. The ls command will return the directory contents, the pwd command
will return the current working directory, and the cd command allows users to
change directories.

In addition to general UNIX commands, general and HyperMesh specific Tcl
commands can be entered. For example, lets use the HyperMesh specific Tcl
command hm_info with the following options:

hm_info appinfo SPECIFIEDPATH TEMPLATES_DIR

The above command with the provided options will return the current template
directory. Any command that can be issued in Tcl or in HyperMesh through the
Tcl command layer can be entered at the Command Window prompt and it will
be evaluated. This capability provides the automation tool developer an easy
means of testing a concept before writing the full procedure.

The Command Window also provides the ability to run Tcl scripts by either using
the source command or using the File/Load Menu option. When using the
source command, the complete path and filename needs to be given (unless
the file is located in the directory the user is currently in within the Command
Window).

source C:/temp/my_macro.tcl

The other option is to use the File/Load Menu. This menu is available in the
Command Window by right clicking in the Command Window (shown below).
You can also save the session contents in the Command Window using the
File/Save Menu option.

Chapter 4: Using Tcl to Control the HyperMesh Session

Introduction to HM Customization 52 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.

The Command Window Load Menu

Tcl scripts can also be run in HyperMesh by creating a button on the Utility
menu User page. As was shown in Chapter 2, when creating a button for a Tcl
script, the EvalTcl basic macro will need to be referenced in the
*createbutton() command. In the examples and exercises following, we will
be using this macro to add buttons to the User page for the Tcl scripts that will be
written.

Example 4.1: Using the Command Window

The purpose of this example is to become familiar with using the Command
Window for developing in Tcl. In this example, HyperMesh Tcl and core Tcl
commands, will be used in the Command Window to determine the number of
elements in a component collector for a pre-defined HyperMesh model.

The following commands are used in this exercise:
Modified HyperMesh commands:
*createmark()

HyperMesh Tcl commands
hm_info
hm_getmark

Core Tcl commands
list
llength
set
source


Step 1: Launch the Command Window from HyperMesh

1. Open HyperMesh.
2. Go to the View menu and select Command Window.

Chapter 4: Using Tcl to Control the HyperMesh Session

HyperWorks 13.0 Introduction to HM Customization 53
Proprietary Information of Altair Engineering, Inc
Step 2: Run operating system commands from the Command
Window

Run a couple operating system commands to become familiar with entering
commands and getting the output.
1. Run the command pwd.
The present working directory is returned.
2. Run the command ls
A list of the present working directorys contents is returned.

Step 3: Run HyperMesh Tcl and core Tcl commands from the
Command Window

1. Run the command set a [list 1 2 3 4 5]
A Tcl list variable named a is created and values 1-5 are added to this
list.
2. Run the command set a_length [llength $a]
The length of the list a is set to the variable a_length.

Step 4: Retrieve the HyperMesh file c_channel-tcl_vector.hm

Step 5: Create a buffer (mark) for the elements in the
component upper

Create a mark which contains all the elements in the component upper using
the by comp name option in the *createmark command. In the Command
Window, type the following:

*createmark elems 1 by comp name upper

Step 6: Retrieve the element ids from the mark and store them
in a Tcl list variable.

In order to get the elements ids stored in the mark, the hm_getmark command is
used. This command returns the entity IDs of the passed entity type from the
specified mark In the Command Window, type the following:

set elemIds [hm_getmark elems 1]

Step 7: Count the number of elements in the list and display the
result

Chapter 4: Using Tcl to Control the HyperMesh Session

Introduction to HM Customization 54 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
By using the llength Tcl command, the number of entities in the list elemIds
can be found.

set numElems [llength $elemIds]

In the Command Window the value of 390 is returned, which is the number of
elements in the component collector upper.

Step 8: Display the element count result

Using the puts command, we can print the output of a variable to the Command
Window.

puts $numElems

Again the value returned is 390 which is the number of elements in the
component collector upper.

Step 9: Verify the returned number of elements is the same
number reported in HyperMeshs Count panel.

1. On the Tool page, enter the count panel, FE entities subpanel.
2. Switch the entity selector to comps.
3. Select comps >> upper.
4. Click select to complete the selections.
5. Click selected.
6. Notice in the elems field is the number 390.
7. Click return to exit the count panel.

Step 10: Save the executed commands to a file

1. In the Command Window, right click and select File >> Save >> History.
2. For File name type command_window_ex.tcl.
3. In a text editor, open the file command_window_ex.tcl and verify it
contains all of the commands you typed in the Command Window.

Step 11: Load the command_window_ex.tcl file into the
Command Window.

1. Right click in the Command Window and select File >> Load File.
2. Select the command_window_ex.tcl file.

390 is returned.

Chapter 4: Using Tcl to Control the HyperMesh Session

HyperWorks 13.0 Introduction to HM Customization 55
Proprietary Information of Altair Engineering, Inc
This example is complete. You can close the HyperMesh session.

Process to Create a Tcl HyperMesh Macro

1. Define the task.
2. Delete the existing command.cmf file. This file is located in either the
start-in directory or the current working directory.
3. Perform the operations in HyperMesh that the script should run.
4. Extract the commands from the command.cmf
5. Create a Tcl script by converting the commands to Tcl format and
modifying as necessary (this includes adding additional Tcl commands)
6. Create a new Utility menu macro that runs a Tcl script.
7. Add macro button using *createbutton that calls the macro created in
Step 6 with the appropriate Tcl script filename.
8. Reload the current .mac file into HyperMesh to load the modified
userpage.mac.
9. Test the macro.

This process is nearly identical to developing a HyperMesh Basic macro. The
only differences are that the HyperMesh commands must be converted to Tcl
format and that Tcl core commands are allowed to introduce control logic to the
automation tools.

Example 4.2: Automate Creating Forces with a
User Specified Magnitude

In this example, we will go through the general process for creating HyperMesh
Tcl scripts. The script will automate the creating of forces with a user defined
magnitude.

The following commands are used in this example:

Modified and added HyperMesh commands:
*createmark
*clearmark

HyperMesh Tcl commands:
hm_getfloat

Core Tcl commands:
set

Step 1: Define the task to be automated.

Chapter 4: Using Tcl to Control the HyperMesh Session

Introduction to HM Customization 56 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
1. Create a load collector named forces.
2. Request the user to select the nodes on which to apply a force.
3. Request the user to specify the magnitude of the forces to be created.
4. Create the forces and organize them into the forces collector.

Step 2: Delete the command.cmf file from your working
directory.

Every command executed in HyperMesh is recorded in the command.cmf file.
To view only the tasks commands, it is suggested you delete the command.cmf
file before doing the task. After deleting this file, the file is automatically
recreated when more commands are executed in HyperMesh.

Steps 3-5: Do the task in HyperMesh to capture its commands to
the command.cmf file.

Step 3: Retrieve the file c_channel-tcl_vector.hm

1. Open HyperMesh.
2. From File > Open, select the file c_channel-tcl_vector.hm

Step 4: Create a load collector.

1. Click the Model tab in the tab or go to the menu bar and select View >
Browsers > HyperMesh > Model.
2. Right-click in the white blank area and from the pop-up menu, select
Create > Load Collector..
3. For Name, type forces.
4. Select any color for Color.
5. Verify that there is a check mark next to Close dialog upon creation.
6. Click Create to create the load collector.

Step 5: Create a force on the beam

1. On the Analysis page, enter the Forces panel.
2. With the nodes selector active, select any node.
3. For magnitude =, type 23.
4. For the direction selector, select the z-axis.
5. Toggle from magnitude % = to uniform size =.
6. Create the force.
7. Return to the main menu.
8. Keep this HyperMesh session open for steps later in this example.

Chapter 4: Using Tcl to Control the HyperMesh Session

HyperWorks 13.0 Introduction to HM Customization 57
Proprietary Information of Altair Engineering, Inc
Step 6: Copy the tasks commands in the command.cmf file and
paste them to the create_force.tcl file.

1. Open a text editor and create a new text file named create_force.tcl.
Save the file to your HyperMesh working directory (My Documents on
Windows).
2. From your HyperMesh working directory, open the command.cmf file.
3. Locate the following four commands at or near the end of the file.

*collectorcreateonly(loadcols, forces, , 7)
*loadsize(1,15,0,1)
*createmark(nodes,1) 3237
*loadcreateonentity(nodes,1,1,1,0,0,23,0,0,23,0,0,0,0,0)

4. Copy these commands and add them to the text file create_force.tcl

Steps 7-9 Modify and add to the script commands as necessary.

Step 7: Modify the code so it is in Tcl syntax

To modify the code so that it is in the appropriate Tcl syntax, parentheses and
commas need to be replaced with a blank space. This results in the following
four lines:

*collectorcreate loadcols forces 7
*loadsize 1 15 0 1
*createmark nodes 1 3237
*loadcreateonentity nodes 1 1 1 0 0 23 0 0 23 0 0 0 0 0

Step 8: Allow the user to select nodes on which to apply a force.

Here we are updating the code by adding the *clearmark command and
replacing the *createmark command with *createmarkpanel. The
*clearmark command clears the node ids that are currently in the mark (if any
are currently there). The *createmarkpanel command is used to get user
selected nodes using a HyperMesh panel and store them in the buffer.

1. Before the *createmark command, add the following line which clears
the node ids currently in mark 1.

*clearmark nodes 1

2. Modify the *createmark command to allow users to select the nodes
using a HyperMesh panel and store them in the buffer.

Chapter 4: Using Tcl to Control the HyperMesh Session

Introduction to HM Customization 58 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
*createmarkpanel nodes 1 Select nodes

Step 9: Allow the user to specify a force magnitude.

Using the hm_getfloat command, the user can enter a value for the
magnitude and then using the set command it can be stored as a variable. The
variable can then be substituted for the hard coded force magnitude.

1. Get a force magnitude from the user using a HyperMesh panel and store it
in a variable. Enter the following line after the *createmarkpanel
command.

set mag_val [hm_getfloat Magnitude = Enter the force magnitude]

2. Substitute the hard coded force magnitude with the variable mag_val.

*loadcreateonentity nodes 1 1 1 0 0 $mag_val 0 0 $mag_val 0 0 0 0 0

Step 10: Review the script to see if it looks similar to the
following:

*collectorcreate loadcols forces 7
*loadsize 1 15 0 1
*clearmark nodes 1
*createmarkpanel nodes 1 Select nodes
set mag_val [hm_getfloat Magnitude = Enter the force magnitude]
*loadcreateonentity nodes 1 1 1 0 0 $mag_val 0 0 $mag_val 0 0 0 0 0

Step 11: Test the script by running it from the command window

1. Go to the currently open HyperMesh session.
2. Open the file c_channel-tcl_vector.hm.
This refreshes the HyperMesh database. The load collector and forces
you created earlier no longer exist.
3. Go to the View menu and select Command Window.
4. In the Command Window, type the following and then press Enter:

source create_force.tcl

A HyperMesh panel with a nodes selector appears.
5. Select node(s) in any manner you wish.
6. Click proceed to continue the scripts task.
A HyperMesh panel with an input field for the force magnitude appears.
7. For Magnitude =, type any number.
8. Click proceed to continue the scripts task.
The force(s) are created.
Chapter 4: Using Tcl to Control the HyperMesh Session

HyperWorks 13.0 Introduction to HM Customization 59
Proprietary Information of Altair Engineering, Inc

Steps 12-14 Test the script from a Utility tab button.

Step 12: Create a button on the Utility tabs User page.

1. In your HyperMesh working directory, open the file userpage.mac.
If this file does not already exist, create a text file named userpage.mac.
2. On the next blank line from the top of the file, type the following
*createbutton line:

*createbutton(5, Create Force, -1, 0, 10, YELLOW,
Create a force on selected nodes, EvalTcl,
create_force.tcl)

3. Save the userpage.mac file.

Step 13: Load the userpage.mac file into the current HyperMesh
session.

The userpage.mac file can be loaded into the current HyperMesh session in a
couple of ways. By changing the User Profile the userpage.mac file gets
reloaded. While this method works, if you dont want to change the user profile,
another method is to simply reload the hm.mac file or to simply close and reopen
HyperMesh.

1. Close HyperMesh and then reopen HyperMesh.

Step 14: Test the script from the Utility menus button.

1. Open the file c_channel-tcl_vector.hm.
2. In the Utility tabs User page, click the Create Force button. A
HyperMesh panel with a nodes selector appears.
3. Select node(s) in any manner you wish.
4. Click proceed to continue the scripts task.
A HyperMesh panel with an input field for the force magnitude appears.
5. For Magnitude =, type any number.
6. Click proceed to continue the scripts task.
The force(s) are created.

Step 15: The exercise is complete. Close the HyperMesh
session.



Chapter 4: Using Tcl to Control the HyperMesh Session

Introduction to HM Customization 60 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.

Practical Exercises
Exercise 4a

Description
Using the file c_channel-tcl_vector.hm, create a HyperMesh Tcl script to
automate the following task
1) Create a component collector with a user specified name
2) Select elements and move those elements into the new component
collector.
3) Translate the elements in the new component collector a user
specified distance in the z direction.

Writing this script will make you more familiar with the general process for
creating HyperMesh Tcl scripts.

HyperMesh commands used

hm_getstring *collectorcreateonly
*createmarkpanel *movemark
*clearmark *createvector
hm_getfloat *translatemark

TCL/TK commands used

set

Hints

Be sure to do the steps in HyperMesh and then extract the appropriate
commands from the command.cmf file. Modify the commands as necessary and
be sure to clear the mark when needed.














Chapter 4: Using Tcl to Control the HyperMesh Session

HyperWorks 13.0 Introduction to HM Customization 61
Proprietary Information of Altair Engineering, Inc

Exercise 4b

Description
Using the file c_channel-tcl_vector.hm, for each element in the HyperMesh
model, build a list where the contents of the list are as follows

ELEMID {NODE1 NODE2 !}

These lists should then be included in a list of lists:

{{ELEMID1 {NODE1 NODE2 !} {ELEMID2 {NODE1 NODE2 !} !

Thus generating a record of the element information. No means of reporting this
to the user is necessary for this exercise

HyperMesh commands used

*createmark hm_getmark
hm_nodelist

TCL/TK commands used

for foreach
list lappend
set incr
if elseif
else

Hints
The majority of this assignment will be discovering where to find information
about commands and how to apply the information you find. Be patient and use
the resources available to you, including the HyperWorks online help.













Chapter 4: Using Tcl to Control the HyperMesh Session

Introduction to HM Customization 62 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.








Chapter 5: Retrieving Data from HyperMesh Entities

HyperWorks 13.0 Introduction to HM Customization 63
Proprietary Information of Altair Engineering, Inc
Chapter 5
Retrieving Data from
HyperMesh Entities

In the previous chapters, commands were extracted from the command.cmf file
and then modified as necessary to create scripts to be used in HyperMesh. This
chapter will focus on creating Tcl routines which retrieve data from HyperMesh
entities. These scripts make use of HyperMesh commands, Tcl core scripting
commands, and HyperMesh Tcl commands.

HyperMesh Entities and Their Data Names

Data names are generic references to the information that physically defines an
entity in the HyperMesh environment. An example of this would be the x, y, and z
coordinates that define a nodes location in three-dimensional space. This
information is part of the entitys definition and is consistent for all solvers. It is
possible though that these can change from one HyperMesh version to the next.
For this reason, please refer to the online help. Information on the data names
can be found in the following location:

HyperMesh > Reference Guide > Scripts > Creating Scripts > Tcl > Using
Data Names

Data names are accessed using the hm_getentityvalue command. This
command is one of the most common commands used by a developer in the
HyperMesh environment. It is used to access the data names and template
information associated with an entity. The command will return a value that is
either a string or a numeric value, depending on the flag value and the value
stored in that field or data name. The syntax for this command is:

hm_getentityvalue entity_type name_or_id data_name_string
flag ?search_type?
Chapter 5: Retrieving Data from HyperMesh Entities

Introduction to HM Customization 64 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.

The following is an example using hm_getentityvalue:

set force_x [hm_getentityvalue loads 12 "comp1" 0]

In this example, loads corresponds to the entity_type, 12 is the
name_or_id of the load, comp1 is the data_name_string, and 0 is the
flag. The flag can be set to either 0 (indicating a floating value should be
returned) or to 1 (indicating that a string should be returned. Using these
options, the x component of a force with ID 12 is returned and set to the variable
force_x. The table below shows several of the data names for the force load:


node when a load is applied to a node, this serves as a
pointer to the node
comp1 x component of the vector
comp2 y component of the vector
comp3 z component of the vector
magnitude magnitude of the load vector
collector collector that owns the load (load collector pointer)
Data names for force load

Another example for hm_getentityvalue is shown below. This example is a
Tcl acript which prompts the user to select several nodes and then displays their
x, y, and z coordinates:

hm_markclear nodes 1
*createmarkpanel nodes 1

set nodes [hm_getmark nodes 1]

if { ! [ Null nodes ] } {
foreach node $nodes {
set xVal [hm_getentityvalue nodes $node "x" 0]
set yVal [hm_getentityvalue nodes $node "y" 0]
set zVal [hm_getentityvalue nodes $node "z" 0]
tk_messageBox -message "Node $node = $xVal $yVal $zVal"
}
}

In the example above, nodes corresponds to the entity_type, $nodes is a
variable which passes the node id, x, y, or z is the
data_name_string, and 0 is the flag. Below is a table which shows some of
the data names available for nodes.

Chapter 5: Retrieving Data from HyperMesh Entities

HyperWorks 13.0 Introduction to HM Customization 65
Proprietary Information of Altair Engineering, Inc
id The ID of the node (integer).
inputsystem Pointer to the node input system (pointer).
outputsystem Pointer to the node output system (pointer).
x
The x coordinate of the node in its local system
(real).
y
The y coordinate of the node in its local system
(real).
z
The z coordinate of the node in its local system
(real).
Data names for nodes


!
Note in both scripts that to assign the return value from the command to a variable,
the command is placed within square brackets.


Pointers and Flags

Notice that several of the data names in the two tables above are defined as
pointers. A pointer is used to directly access another data name. For example,
the collector and node data names for force loads are pointers. This means they
point to the data names available for either collectors or nodes. In order to
retrieve any data from a pointer, the data name requested for the particular
pointer must also be supplied. The additional data names are separated by a
period or dot (.).

The following are a few examples on how a pointer is used. To retrieve the node
id that load 12 is applied to the following set of commands is used:

set node_id [hm_getentityvalue loads 12 "node.id" 0]

To retrieve the y coordinate of the node that load 12 is applied to use the
following set of commands:

set node_id [hm_getentityvalue loads 12 "node.y" 0]

To retrieve the load collector name that contains load 12, use the following set of
commands:

set ld_col [hm_getentityvalue loads 12 "collector.name" 1]

All data names for that particular entity are available for reference when using
pointers. For the collector name, notice the flag value is set to 1 as the expected
return value is a string value as opposed to a numeric value. In the node
Chapter 5: Retrieving Data from HyperMesh Entities

Introduction to HM Customization 66 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
examples above, the flag value is set to 0, indicating that a floating point number
is to be returned.

Another example is with component collectors. There is no data name
associated with a component collector to get the material name, only the material
ID. The following set of commands is used to get the material ID:

set matID [hm_getentityvalue comps 12 "materialid" 0]

A second set of commands would then be required to get the name of the
material with that ID:

set matName [hm_getentityvalue mats $matID "name" 1]

Alternatively, the component collector has a material pointer data name. From
this pointer, any valid material data name can be substituted by separating the
pointer and the new data name with a period (.). From the example above the
following line can replace the previous two lines:

set matName [hm_getentityvalue comps 12 "material.name" 1]

Process for Creating a HyperMesh Tcl Script to Retrieve
Data on HyperMesh Entities

1) Define the task to be automated.
2) Write the commands to a user-created *.tcl text file
! Skip doing the task in HyperMesh as there are likely no commands
to capture to the command.cmf file; the task is to retrieve
information, not to perform a HyperMesh action.
! Use HyperMesh Tcl commands to extract data on HyperMesh
entities.
! Use core Tcl commands to retrieve, manipulate, display and store
extracted data in variables.
3) Test the script from the Command Window.
4) Define the Utility menu button for the macro in userpage.mac file.
5) In the current HyperMesh session, reload the hm.mac file (this also
reloads the userpage.mac file).
6) Run the script from the Utility menu.



Chapter 5: Retrieving Data from HyperMesh Entities

HyperWorks 13.0 Introduction to HM Customization 67
Proprietary Information of Altair Engineering, Inc
Example 5.1: Automate Computing the Vector Sum of
Forces

The purpose of this example is to become familiar with creating HyperMesh Tcl
scripts to retrieve data on HyperMesh entities (nodes, elements, loads, etc.).

The following HyperMesh commands are modified in this exercise.
*clearmark()
*createmarkpanel()

The following HyperMesh Tcl commands are used in this exercise.
hm_getentityvalue
hm_getmark
hm_usermessage
hm_errormessage

The following core Tcl commands are used in this exercise.
brackets [ ]
expr
foreach
if
set
return
llength

Step 1: Define the task to be automated.

1. Request the user to select forces.
2. If the user does not select loads, display a message stating this.
3. Retrieve the X, Y, and Z component information from the user-selected forces.
4. Sum the X, Y, and Z components.
5. Display the resulting X, Y, and Z components.

Step 2: Do the task in HyperMesh to capture its commands to
the command.cmf file.

Do nothing for this step because the task is not performed on model entities.
Rather, the task is to retrieve information from model entities. There are no
HyperMesh commands to capture to the command.cmf file for this task.

Step 3: Create a text file named sum_force_comps.tcl for the
script to be created.

Chapter 5: Retrieving Data from HyperMesh Entities

Introduction to HM Customization 68 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
Step 4: Allow the user to select the forces.

1. Create a buffer (mark) to store loads selected in the panel by the user.

*clearmark loads 1
*createmarkpanel loads 1 Select forces for resultant

Notice the HyperMesh entity type for force is loads.

2. Retrieve loads from the buffer (mark) and create a list variable.

set loads_list [hm_getmark loads 1]

Step 5: Before proceeding to calculate the sum, determine
whether or not loads were selected. If none were selected,
display a message stating this.

By checking the length of the variable $loads_list, it can be determined if any
loads have been selected. If the length of the list of loads is equal to 0, this
means that no loads have been selected. By using this check within an if
statement, a message will be displayed only when no loads are selected and the
script will be exited.

if { [llength $loads_list] == 0 } {
hm_errormessage "No loads selected"
return
}

Step 6: Initialize variables that store the X, Y and Z components
of the vector sum of the selected forces.

Initialization is done by setting the variables xsum, ysum, and zsum to 0.

set xsum 0
set ysum 0
set zsum 0

Step 7: Loop through the list of selected loads, retrieve their
component values, and add them to the total for each
component.

By using the foreach statement, each load in the list can be extracted and set
to the variable load_id. Then, the x component can be retrieved and set to the
variable xcomp, the y component can be retrieved and set to the variable ycomp,
Chapter 5: Retrieving Data from HyperMesh Entities

HyperWorks 13.0 Introduction to HM Customization 69
Proprietary Information of Altair Engineering, Inc
and the z component can be retrieved and set to the variable zcomp. Finally
each component is added to the appropriate sum variable using the expr
command.


foreach load_id $loads_list {
set xcomp [hm_getentityvalue LOADS $load_id "comp1" 0]
set ycomp [hm_getentityvalue LOADS $load_id "comp2" 0]
set zcomp [hm_getentityvalue LOADS $load_id "comp3" 0]
set xsum [expr $xsum +$xcomp]
set ysum [expr $ysum +$ycomp]
set zsum [expr $zsum +$zcomp]
}

Step 8: Display the result (components of the resultant).

Using the hm_usermessage command, a message is shown in the message bar
which reports the x, y, and z components of the resultant force.

hm_usermessage Resultant force: $xsum, $ysum, $zsum

Step 9: Review your script to see if it looks similar to the
following.

*clearmark loads 1
*createmarkpanel loads 1 Select forces for resultant

set loads_list [hm_getmark loads 1]

if { [llength $loads_list] == 0 } {
hm_errormessage "No loads selected"
return
}

set xsum 0
set ysum 0
set zsum 0

foreach load_id $loads_list {
set xcomp [hm_getentityvalue LOADS $load_id "comp1" 0]
set ycomp [hm_getentityvalue LOADS $load_id "comp2" 0]
set zcomp [hm_getentityvalue LOADS $load_id "comp3" 0]
set xsum [expr $xsum +$xcomp]
set ysum [expr $ysum +$ycomp]
set zsum [expr $zsum +$zcomp]
}
Chapter 5: Retrieving Data from HyperMesh Entities

Introduction to HM Customization 70 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.

hm_usermessage Resultant force: $xsum, $ysum, $zsum

Step 10: Save the sum_force_comps.tcl file.

Step 11: Test the script by running it from the Command
Window.

1. Open HyperMesh from your HyperMesh working folder.
2. Retrieve the file c_channel-tcl_vector.hm.
3. Go to View >> Command Window to open the Command Window if it
isnt already open.
4. In the Command Window, execute the command
source sum_force_comps.tcl
5. A HyperMesh panel with a loads selector appears.
6. Select the 3 loads in the model and then press proceed to continue with
running the script. (HINT: It may be easiest to select displayed to select
all 3 loads).
7. The force resultant values appear in the message bar.
8. Run the script again, but this time, do not select any loads. The message
No loads selected appears in the message bar.

Step 12: Create a button for the script on the macro menus User
page.

1. In your HyperMesh working folder, open the file userpage.mac. If this
file does not already exist, create a text file named userpage.mac.
2. On the next blank line from the files top, type the following
*createbutton() line:

*createbutton(5,Sum force comps,-1,0,10,GREEN,Sum
comps of forces, EvalTcl, sum_force_comps.tcl)

3. Save the userpage.mac file to your HyperMesh working folder.

Step 13: Test the script by running it from its button on the
macro menu.

Step 14: The exercise is complete. Close the HyperMesh
session.




Chapter 5: Retrieving Data from HyperMesh Entities

HyperWorks 13.0 Introduction to HM Customization 71
Proprietary Information of Altair Engineering, Inc

Practical Exercises
Exercise 5a

Description:
Create a HyperMesh Tcl script to automate the following task:
1) Request the user to select a component to be translated.
2) Request the user to select a HyperMesh defined vector along which
the component is to be translated.
3) Get the Xcomp Ycomp and Zcomp of the selected vector from the
HyperMesh database.
4) Request the user to enter in a translation distance.
5) Use all of the above information to translate the given component.

Test the file using the HyperMesh file c_channel-tcl_vector.hm.

HyperMesh commands used

*createmarkpanel
hm_getfloat
hm_getmark
hm_getentityvalue
*createvector
*translatemark
*clearmark

TCL/TK commands used

set

Hints















Chapter 5: Retrieving Data from HyperMesh Entities

Introduction to HM Customization 72 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
Exercise 5b
Description
Starting with the results of Exercise 4b:
Create a node at the centroid of the element. Translate the node in the positive
direction of the element normal by an amount equal to the shortest diagonal of a
quad element and the shortest side of a tria element. Create either a tetra
element or a pyramid element using the original element node list and the new
node created by the script. Test the file using the HyperMesh file c_channel-
tcl_vector.hm.

HyperMesh commands used

*createmark *createvector
*translatemark *createnode
*createelement *collectorcreate
*currentcollector hm_getmark
hm_nodelist hm_entityinfo
hm_getentityvalue

TCL/TK commands used

for foreach
set if
elseif else

Hints

This assignment will require you to think more, but the process is still the same.
Pay careful attention to vector directions and look closely at the data you have
generated. What are some ways to make this cleaner in the user environment?
What are some problems that you might encounter?















Chapter 5: Retrieving Data from HyperMesh Entities

HyperWorks 13.0 Introduction to HM Customization 73
Proprietary Information of Altair Engineering, Inc
Exercise 5c

Description
Create a HyperMesh Tcl script to automate the following task:
1) Request the user to select elements on which to create system.
2) Calculate the centroidal coordinates of each element.
3) Create a node at each of these centroidal locations.
4) Create systems with these nodes as an orientation node.

Writing this script will make you more familiar with the general process for
creating HyperMesh Tcl scripts. Test the file using the HyperMesh file
c_channel-tcl_vector.hm.

HyperMesh commands used

*createmarkpanel *createnode
*clearmark *hm_nodelist
hm_getmark *systemcreate
hm_entityinfo

TCL/TK commands used

set for
foreach eval
lindex llength

Hints

The majority of this assignment will be discovering where to find information
about commands and how to apply the information you find. Be patient and use
the resources available to you, including the HyperWorks online help.















Chapter 5: Retrieving Data from HyperMesh Entities

Introduction to HM Customization 74 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.













Chapter 6: Interfacing with HyperMesh Solver Templates

HyperWorks 13.0 Introduction to HM Customization 75
Proprietary Information of Altair Engineering, Inc
Chapter 6
Interfacing with HyperMesh
Solver Templates


Solver specific data created within HyperMesh can be defined, reviewed, and
edited in the card images. Card images are an interpretation of the loaded solver
template. Each piece of data that defines a card image has a text string (data
name) and a numeric attribute ID.

An example is the Youngs Modulus for a material. Each solver, and even each
different material type for a particular solver, can have a Youngs Modulus
attribute and a corresponding data name. These data names and attributes are
defined in each solvers feoutput template. They are unique and are not
necessarily consistent between solvers or even between each material within a
solver.

Templates exist for each solver supported by HyperMesh and are located in
subfolders under the <altair_home>/templates/feoutput directory.
These templates define every solver specific attribute including data names,
attribute IDs, card image formats, and the format of the data upon export. The
*defineattribute command is used to define attribute data names and IDs
in a template file.

There are several different types of attributes including array, double, entity,
integer and string. Each of these types is handled in a similar fashion to the
examples below. The difference is that each entity type uses an appropriate
*attributeupdate command based on its type. There are also a number of
hm_attribute commands to query entity attributes.



Chapter 6: Interfacing with HyperMesh Solver Templates

Introduction to HM Customization 76 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
Solver Attributes and Card Images

A sample card image for an OptiStruct MAT1 material collector is shown below:


Figure 6.1: Card image for MAT1 card in OptiStruct.

For each field in the above card image there is, a corresponding attribute and
data name in one the optistruct templates (in
<altair_home>/templates/feoutput/common_nas_os/attribs) . An
excerpt is shown below for several of the card image fields:

*defineattribute(E,1,real,none)
*defineattribute(G,2,real,none)
*defineattribute(Nu,3,real,none)
*defineattribute(Rho,4,real,none)

The first argument in the *defineattribute command is the solver data
name. The second is the attribute ID and the third is the attribute type. There
are 11 different attribute types. Attributes of different types are created and
updated with different commands, but the overall concept is the same.

Each attribute in the template has a definition similar to these. Additionally, there
are card image definitions that define how the card editor is generated inside of
HyperMesh for each attribute. For optistruct, these card images are defined in
<altair_home>/templates/feoutput/optistruct. An excerpt of the
optistruct MAT1 card image is shown below:

*menustring("MAT1 ")
*menufield(ID,integer,id,8)
*menufield(E,real,$E,8)
*menudefaultvalue(" ")
*menuinitialvalue(210000.0)
*menurestrictedvalue(>,0.0)
*menufield(G,real,$G,8)
*menudefaultvalue(" ")
*menuinitialvalue(80769.2)
*menurestrictedvalue(>,0.0)
Chapter 6: Interfacing with HyperMesh Solver Templates

HyperWorks 13.0 Introduction to HM Customization 77
Proprietary Information of Altair Engineering, Inc
*menufield(NU,real,$Nu,8)
*menudefaultvalue(" ")
*menurestrictedvalue(>,-1.0)
*menurestrictedvalue(<,0.5)
*menuinitialvalue(0.3)
*menufield(RHO,real,$Rho,8)
*menudefaultvalue(" ")
*menuinitialvalue(7.85e-09)

Notice that the *menufield command is used above. This command
determines how a field is created in the card editor for a particular attribute. The
first argument is the text string to show above the data field and the third
argument is the particular data name that is associated with that field. For
example, the attribute and card image definitions for the Youngs Modulus for the
MAT1 material are:

*defineattribute(E,1,real,none)
*menufield(E,real,$E,8)

Knowing all of this information allows us to assign, update and query the data.

Querying Solver Attributes

In addition to the standard HyperMesh data names, data names also refer to
solver specific attributes as described above. Solver data names are accessed
similarly to HyperMesh data names, using the hm_getentityvalue,
hm_attributearrayvalue and hm_attributearray2dvalue commands.
These commands use a data_name_string to access a particular piece of
data. As noted above, each attribute has both an ID and a data name. For
example, from the MAT1 material card we have several attributes of interest:

*defineattribute(E,1,real,none)
*defineattribute(G,2,real,none)
*defineattribute(Nu,3,real,none)
*defineattribute(Rho,4,real,none)

Again, the first argument is the solver data name and the second is the attribute
ID. So in order to extract the value of E from a material with ID 11:

hm_getentityvalue mats 11 "\$E" 0

There are two things to notice. The first is that the data name is accessed using
a leading $, which must be explicitly escaped with the forward slash \. If this is
not done, Tcl will attempt to evaluate $E as a variable. The \ indicates that the
Chapter 6: Interfacing with HyperMesh Solver Templates

Introduction to HM Customization 78 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
variable should not be evaluated but instead passed as $E. The second is that
the flag argument is set to 0.
Example 6.1: Automate Extracting Data in a Card Image

The purpose of this exercise is to become familiar with creating HyperMesh Tcl
scripts which automate extracting data in HyperMesh card images.

The following HyperMesh Tcl commands are used in this exercise:
hm_getentityvalue

!The following core Tcl/Tk commands are used in this exercise:
set
return
proc
tk_messageBox

Step 1: Define the task to be automated.

1. An OptiStruct MAT1 material of id 1 exists in the HyperMesh database.
Extract from its card image its values for the parameters Youngs Modulus
(E), Shear Modulus (G), Poissons ratio (Nu), and density (Rho).
2. Display the values for the parameters.

Step 2: In the optistruct template file, identify the attribute
names for the parameters Youngs Modulus, Shear Modulus,
Poisons ratio, and density.

1. In the HyperWorks installation, open the file
<altair_home>\templates\feoutput\optistruct\optistruct.
This file contains the card image definitions for the optistruct template.
2. Notice that on line 22 another template file is included. Open the file
<altair_home>\templates\feoutput\common_nas_os\attribs.
This file contains the *defineattribute commands for the optistruct
template.
3. As shown in the above section on Solver Attributes and Card Images, in
the MAT1 card image, the field names for Youngs Modulus, Shear
Modulus, Poissons ratio, and density are E, G, Nu, and Rho, respectively.
Identify the attribute lines for these field names in the optistruct attribs
file.

*defineattribute(E,1,real,none)
*defineattribute(G,2,real,none)
*defineattribute(Nu,3,real,none)
*defineattribute(Rho,4,real,none)
Chapter 6: Interfacing with HyperMesh Solver Templates

HyperWorks 13.0 Introduction to HM Customization 79
Proprietary Information of Altair Engineering, Inc

Step 3: Create a text file named extract_mat.tcl for the script to
be created.

Step 4: Retrieve the parameter values from the MAT1 card image
and store them in variables.

Now that the *defineattribute lines has been found, the field names for
Youngs Modulus, Shear Modulus, Poissons ratio, and density have been
determined. Now using those field names and the hm_getentityvalue
command, the parameter values can be stored in variables.

set mat_id 1
set mat_E [hm_getentityvalue materials $mat_id \$E 0]
set mat_G [hm_getentityvalue materials $mat_id \$G 0]
set mat_NU [hm_getentityvalue materials $mat_id \$Nu 0]
set mat_RHO [hm_getentityvalue materials $mat_id \$Rho 0]

Again, notice how \ is used to indicate that the variable should not be evaluated
but instead passed as $E. Also notice that the flag argument is set to 0 so that a
floating point value is returned.

Step 5: Return all parameter values as a string.

After the 4 lines created in step 4, add an additional line which prints the
parameter values to the Command Window.

return [ list $mat_E $mat_G $mat_NU $mat_RHO ]

Note: The Tcl return command returns a single value. One way of returning
multiple values is to return a string containing all the values to be returned.
This is done using brackets [].

Step 6: Wrap the code into a Tcl procedure and pass the material
id as an argument to it.

Create a procedure called extract_mat which passes a variable called
mat_id. Place the code written in steps 4 and 5 within the procedure.

proc extract_mat {mat_id} {
[code]
}


Chapter 6: Interfacing with HyperMesh Solver Templates

Introduction to HM Customization 80 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.

Step 7: Evaluate the procedure.

To call the procedure, at the end of the file place the procedure name followed by
the material id to be processed (in this case, the material id to be evaluated is 1).

extract_mat 1

Step 8: Save the extract_mat.tcl file.

Step 9: Test the script by running it from the Command Window.

1. Open HyperMesh from your HyperMesh working folder.
2. Load the OptiStruct User Profile when the User Profile GUI appears.
3. Retrieve the file c_channel-tcl_vector.hm.
4. From the Command Window, run the following command:
source extract_mat.tcl
Values for E, G, NU, and RHO are returned.
5. Verify that the returned values match the values on the MAT1 card image.

Step 10: Create a button on the Utility menus User
page.

1. In your HyperMesh working folder, open the file userpage.mac.
If this file does not already exist, create a text file named userpage.mac.
2. On the next blank line from the top of the file, type the following
*createbutton() line:
*createbutton(5,Extract mat data,-1,0,10,GREEN,
Extract material data,EvalTcl,extract_mat.tcl)
3. Save the userpage.mac file to your HyperMesh working folder.

Step 11: Test the script from its button in the macro menu.

Although the parameter values are returned, you cannot see them. This is
because there is no place (such as the Command Window) to display them.
Modify the script in the next step to rectify this when running the script from the
Utility menu.

Step 12: Display the result of the extract procedure in a
tk_messageBox command.

Change the script line:

extract_mat 1
Chapter 6: Interfacing with HyperMesh Solver Templates

HyperWorks 13.0 Introduction to HM Customization 81
Proprietary Information of Altair Engineering, Inc

to

tk_messageBox -message [ extract_mat 1 ] -title \
Altair HyperMesh, Extract mat data

Using tk_messageBox message command a small GUI will pop up which
returns the parameter values.

Step 13: Test the script again from its button in the Utility menu.

The script should return the values for E, G, NU, and RHO in a pop-up window
titled Altair HyperMesh, Extract mat data.

Step 14: The exercise is complete. Close the HyperMesh
session.

Assigning Data to Solver Attributes

It is easiest to understand how to assign data to solver attributes with a specific
example. When the MAT1 material collector shown above is initially created, the
relevant commands to assign values to its attributes are written to the
command.cmf file. Note that the values below correspond to those shown in
Figure 6.1 above:

*collectorcreate(materials,"steel","",11)
*createmark(materials,2) "steel"
*dictionaryload(materials,2,"C:/Altair/hw10.0/templates/feo
utput/optistruct/optistruct","MAT1")
*attributeupdateint(materials,1,3240,1,2,0,1)
*attributeupdatedouble(materials,1,1,1,1,0,210000)
*attributeupdatedouble(materials,1,2,1,0,0,0)
*attributeupdatedouble(materials,1,3,1,1,0,0.3)
*attributeupdatedouble(materials,1,4,1,1,0,7.85e-009)
*attributeupdatedouble(materials,1,5,1,0,0,0)
*attributeupdatedouble(materials,1,6,1,0,0,0)
*attributeupdatedouble(materials,1,7,1,0,0,0)
*attributeupdatedouble(materials,1,341,1,0,0,0)
*attributeupdatedouble(materials,1,343,1,0,0,0)
*attributeupdatedouble(materials,1,345,1,0,0,0)
*attributeupdateint(materials,1,5237,1,2,0,0)

Each of these commands sets one of the MAT1 attributes either to its default
value or to the user defined value. The third argument in the
Chapter 6: Interfacing with HyperMesh Solver Templates

Introduction to HM Customization 82 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
*attributeupdateint and *attributeupdatedouble commands is the
attribute ID. Looking at one of the commands above we have:

*attributeupdatedouble(materials,1,1,1,1,0,210000)

Where:
materials is the type of entity that owns the attribute
1 is the ID of the entity
1 is the identifier of the attribute
1 is the solver number of the attribute
1 is the status of the attribute
0 is the behavior of the attribute
210000 is the value of the attribute

Looking at the optistruct attribs template, attribute 1 corresponds to the data
name E, or Youngs Modulus.

Once these commands have been generated, they can be used in Tcl by
extracting them from the command.cmf file and updating the syntax by replacing
all () and , with spaces:

*collectorcreate materials "steel" "" 11;
*createmark materials 2 "steel";
*dictionaryload materials 2 \
"C:/Altair/hw10.0/templates/feoutput/optistruct/optistruct" \
"MAT1";
*attributeupdateint materials 1 3240 1 2 0 1;
*attributeupdatedouble materials 1 1 1 1 0 210000;
*attributeupdatedouble materials 1 2 1 0 0 0;
*attributeupdatedouble materials 1 3 1 1 0 0.3;
*attributeupdatedouble materials 1 4 1 1 0 7.85e-009;
*attributeupdatedouble materials 1 5 1 0 0 0;
*attributeupdatedouble materials 1 6 1 0 0 0;
*attributeupdatedouble materials 1 7 1 0 0 0;
*attributeupdatedouble materials 1 341 1 0 0 0;
*attributeupdatedouble materials 1 343 1 0 0 0;
*attributeupdatedouble materials 1 345 1 0 0 0;
*attributeupdateint materials 1 5237 1 2 0 0;

These commands can now be run in Tcl to duplicate the creation of the MAT1
material. However, simply running these commands as they are is not very
flexible. The material ID, name and values are all hard coded. The template file
location in the *dictionaryload command is also hard coded. Also, there are
a lot of extra commands that set attributes that arent necessary. These will all
be updated or removed to make the script more flexible.


Chapter 6: Interfacing with HyperMesh Solver Templates

HyperWorks 13.0 Introduction to HM Customization 83
Proprietary Information of Altair Engineering, Inc

Creating a Reusable and Modular Procedure

In order to make this more flexible, we can create a Tcl procedure that allows us
to substitute variables for the name, color and data values. We can make the
template file path modular across different platforms. Also we can make the
material ID a variable that references the newly created material ID, so that the
*attributeupdatedouble and *attributeupdateint commands work
properly.

proc mat_create { name color E Nu Rho } {
if {[hm_entityinfo exist mats $name -byname] == 1} {
hm_errormessage "Material $name already exists"
return;
} else {
*collectorcreate materials "$name" "" $color;
*createmark materials 2 "$name";
#Retrieve material ID for use below;
set mat_id [hm_getmark mats 2];
*dictionaryload materials 2 "[hm_info exporttemplate]" \
"MAT1";
*attributeupdateint materials $mat_id 3240 1 2 0 1;
*attributeupdatedouble materials $mat_id 1 1 1 0 $E;
*attributeupdatedouble materials $mat_id 3 1 1 0 $Nu;
*attributeupdatedouble materials $mat_id 4 1 1 0 $Rho;
return;
}
}

The advantage of doing this is that mat_create is now modular. Notice the
following:
1. The developer only needs to pass the material name, color and the values
for the material properties and the procedure will create the material
accordingly.
2. The variables are then used in the later commands to pass the
appropriate arguments.
3. This procedure also checks to see if a material with that name already
exists, and if it does, a message is returned in the HyperMesh message
bar.
4. The hm_info command is used to find the appropriate template to load.

Example 6.2: Automate Defining a Card Image
with Data

Chapter 6: Interfacing with HyperMesh Solver Templates

Introduction to HM Customization 84 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
The purpose of this example is to become familiar with creating HyperMesh Tcl
scripts which automate defining solver data in HyperMesh card images. This
example will help you become familiar with defining and calling Tcl procedures.

The following HyperMesh commands are added and modified in this exercise:
*dictionaryload()
*attributeupdateint()
*attributeupdatedouble()

The following HyperMesh Tcl commands are used in this exercise:
hm_mark
hm_info

!The following core Tcl commands are used in this exercise:
set
proc



Step 1: Define the task to be automated.

1. Create an OptiStruct MAT1 material with the following parameter values.
Assume the OptiStruct template is already loaded.
Youngs Modulus (E)
Shear Modulus (G)
Poissons ratio (Nu)
density (Rho)
2. Upon automating the task, wrap the code into a Tcl procedure.

Note: The advantage of creating a procedure is that it is accessible from any part
of the script. The developer only needs to pass the material name and its
parameter values a material will be created with them.

Steps 2-4: Do the task in HyperMesh to capture its commands to
the command.cmf file.

Step 2: Delete the command.cmf file from your HyperMesh
working folder.

Every command executed in HyperMesh is recorded in the command.cmf file.
To view only the tasks commands, it is suggested you delete the command.cmf
file before doing the task. After deleting this file, the file automatically reappears
when more commands are executed in HyperMesh.

Chapter 6: Interfacing with HyperMesh Solver Templates

HyperWorks 13.0 Introduction to HM Customization 85
Proprietary Information of Altair Engineering, Inc
Step 3: Open HyperMesh and load the OptiStruct User Profile.

1. Open HyperMesh from your HyperMesh working folder (the folder from
where HyperMesh is invoked).
2. When HyperMesh is launched it will ask which User Profile to load.
3. Select OptiStruct.
4. Click OK.

Step 4: Create an OptiStruct MAT1 material.

1. From the pull down menus select Materials -> Create.
2. For name =, type steel.
3. For card image =, select MAT1.
4. Create/edit the material. A card image for MAT1 appears.
5. Click [E] and type in its field 123.
6. Click [G] and type in its field 45.
7. Click [NU] and type in its field 0.078.
8. Click [RHO] and type in its field 90.
9. Return to the main menu.
10. Keep this HyperMesh session open for steps later in this exercise.

Step 5: Copy the tasks commands in the command.cmf
file and paste them to the create_mat.tcl file.

1. Open a text editor and create a new text file named create_mat.tcl. Save
the file to your HyperMesh working folder.
2. From your HyperMesh working folder, open the command.cmf file.
3. Locate the command line *collectorcreate() at or near the end of
the file. You should see lines similar to the following.

*collectorcreate(materials,"steel","",11)
*createmark(materials,2) "steel"
*dictionaryload(materials,2,"C:/Altair/hw13.0/templates/feo
utput/optistruct/optistruct","MAT1")
*attributeupdateint(materials,1,3240,1,2,0,1)
*attributeupdatedouble(materials,1,1,1,0,0,210000)
*attributeupdatedouble(materials,1,2,1,0,0,80769.2)
*attributeupdatedouble(materials,1,3,1,0,0,0.3)
*attributeupdatedouble(materials,1,4,1,0,0,7.85e-009)
*attributeupdatedouble(materials,1,5,1,0,0,0)
*attributeupdatedouble(materials,1,6,1,0,0,0)
*attributeupdatedouble(materials,1,7,1,0,0,0)
*attributeupdatedouble(materials,1,341,1,0,0,0)
*attributeupdatedouble(materials,1,343,1,0,0,0)
Chapter 6: Interfacing with HyperMesh Solver Templates

Introduction to HM Customization 86 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
*attributeupdatedouble(materials,1,345,1,0,0,0)
*attributeupdateint(materials,1,5237,1,2,0,0)
*attributeupdateint(materials,1,7142,1,2,0,0)
*attributeupdateint(materials,1,7143,1,2,0,0)
*attributeupdateint(materials,1,7144,1,2,0,0)
*attributeupdatedouble(materials,1,1,1,1,0,123)
*attributeupdatedouble(materials,1,2,1,1,0,45)
*attributeupdatedouble(materials,1,3,1,1,0,0.078)
*attributeupdatedouble(materials,1,4,1,1,0,90)

4. Copy and paste the lines into the create_mat.tcl file. Looking at the
commands above, the first ten *attributeupdatedouble commands
and first four *attributeupdateint commands are setting the default
values for the parameters in HyperMesh. The last four
*attributeupdatedouble commands are setting the values that were
entered in HyperMesh in Step 4.
5. Notice that each *attributeupdatedouble command has an attribute
value. You can match the first four *attributeupdatedouble
commands to the four parameter values you entered in the card image.
6. Since it is desired to create a script that only specifies the values for the
parameters E, G, NU, and RHO, delete all the
*attributeupdatedouble() lines except for the 4 that define these
variables. Also delete the four *attributeupdateint() lines. Your
script should now have eight lines.

Steps 6-12: Modify and add to the commands as necessary.

Step 6: Modify the code so it is in Tcl syntax.

Replace the parentheses and commas with a blank space.

Step 7: Substitute the attribute values with variables E, G, NU,
and RHO.

*attributeupdatedouble materials 1 1 1 1 0 $E
*attributeupdatedouble materials 1 2 1 1 0 $G
*attributeupdatedouble materials 1 3 1 1 0 $NU
*attributeupdatedouble materials 1 4 1 1 0 $RHO

Step 8: Substitute all instances of the hard coded material name
steel with the variable mat_name.

*collectorcreate materials "$mat_name" "" 7
*createmark materials 2 "$mat_name"

Chapter 6: Interfacing with HyperMesh Solver Templates

HyperWorks 13.0 Introduction to HM Customization 87
Proprietary Information of Altair Engineering, Inc
Step 9: Once the material is created, retrieve its id from the mark
and store it in a variable.

Add the following command just below the *createmark line.

set mat_id [hm_getmark materials 2]

Step 10: Substitute all instances of the hard coded material id
with the variable $mat_id.

*attributeupdateint materials $mat_id 3240 1 2 0 1
*attributeupdatedouble materials $mat_id 1 1 1 0 123
*attributeupdatedouble materials $mat_id 2 1 1 0 45
*attributeupdatedouble materials $mat_id 3 1 1 0 0.078
*attributeupdatedouble materials $mat_id 4 1 1 0 90

Step 11: Substitute the hard coded path to the OptiStruct
feoutput template with a request for the global template.

*dictionaryload materials 2 "[hm_info templatefilename]"
"MAT1"

This line now assumes the OptiStruct feoutput template has been loaded prior to
running the script. If it is not loaded, a 0 is returned.

Step 12: Review your script to see if it looks similar to the
following.

*collectorcreate materials "$mat_name" "" 7
*createmark materials 2 "$mat_name"
set mat_id [hm_getmark materials 2]
*dictionaryload materials 2 "[hm_info templatefilename]"
"MAT1"
*attributeupdateint materials $mat_id 3240 1 2 0 1
*attributeupdatedouble materials $mat_id 1 1 1 0 $E
*attributeupdatedouble materials $mat_id 2 1 1 0 $G
*attributeupdatedouble materials $mat_id 3 1 1 0 $NU
*attributeupdatedouble materials $mat_id 4 1 1 0 $RHO

Step 13: Wrap the code into a Tcl procedure and pass the
variables mat_name, E, G, NU and RHO as arguments to it.

proc mat_create {mat_name E G NU RHO} {
[code]
}
Chapter 6: Interfacing with HyperMesh Solver Templates

Introduction to HM Customization 88 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.

Step 14: Evaluate the procedure and save the create_mat.tcl file.

mat_create aluminum 10 20 0.3 40

Step 15: Test the script by running it from the Command
Window.

1. Go to the File menu and select New > Model to clear the current session.
2. In the Command Window, type the following and then press Enter.
source create_mat.tcl
The aluminum material is created.

Step 16: Create a button on the macro menus User page.

1. In your HyperMesh working folder, open the file userpage.mac.
If this file does not already exist, create a text file named userpage.mac.
2. On the next blank line from the top of the file, type the following
*createbutton()line:
3. *createbutton(5,Create OS MAT1,-1,0,10,GREEN,Create
OS MAT1 material,EvalTcl,create_mat.tcl)
4. Save the userpage.mac file to your HyperMesh working folder.

Step 17: Test the script by running it from its button in the Utility
menu.

Step 18: The exercise is complete. Close the HyperMesh
session.

Updating Solver Attributes

In addition to creating a card image from scratch, it is also possible to update an
existing card image. A procedure to do this is almost identical to the procedure
to create a new card image, with the exception that the material is not created
and thus the procedure requires a material ID to be passed instead of a material
name.

proc mat_update { mat_id E Nu Rho } {
if {[hm_entityinfo exist mats $mat_id -byid] == 0} {
hm_errormessage "Material $mat_id does not exist"
return;
} else {
*createmark materials 2 "by id" "$mat_id";
*dictionaryload materials 2 "[hm_info exporttemplate]" \
Chapter 6: Interfacing with HyperMesh Solver Templates

HyperWorks 13.0 Introduction to HM Customization 89
Proprietary Information of Altair Engineering, Inc
"MAT1";
*attributeupdatedouble materials $mat_id 1 1 1 0 $E;
*attributeupdatedouble materials $mat_id 3 1 1 0 $Nu;
*attributeupdatedouble materials $mat_id 4 1 1 0 $Rho;
return;
}
}

Exercise 6.3: Automate Defining/Updating Multiple
Materials

This example will continue to illustrate how to define/update materials.

Step 1: Define the task to be automated.

This task is an extension to example 6.2 of this chapter. Automate defining three
OptiStruct MAT1 materials with values for the parameters Youngs Modulus (E),
Shear Modulus (G), Poissons ratio (Nu), and density (Rho). If the materials exist
in HyperMesh, simply update the values, otherwise create the material before
setting the parameters. The three materials are:

NAME E G NU RHO
aluminum 10 20 0.3 40
altairium 1000 200 0.3 400
steel 2.00E+06 1.00E+06 0.3 7.80E-09

Step 2: Update the script you created in exercise two of this
chapter or update its solution file create_mat_solution.tcl.

1. Break up the create_mat procedure defined in the previous example. Put
the update functions ( *attributeupdate" ) into a proc called
update_mat and leave the creation functions in the proc create_mat. The
create_mat procedure will call the update_mat procedure:

proc update_mat {mat_id E G NU RHO} {
*attributeupdatedouble materials $mat_id 1 1 1 0 $E
*attributeupdatedouble materials $mat_id 2 1 1 0 $G
*attributeupdatedouble materials $mat_id 3 1 1 0 $NU
*attributeupdatedouble materials $mat_id 4 1 1 0 $RHO
}

proc create_mat {mat_name E G NU RHO} {
*collectorcreate materials "$mat_name" "" 7
*createmark materials 2 "$mat_name"
set mat_id [hm_getmark materials 2]
*dictionaryload materials 2 "[hm_info templatefilename]" "MAT1";
Chapter 6: Interfacing with HyperMesh Solver Templates

Introduction to HM Customization 90 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
update_mat $mat_id $E $G $NU $RHO
}

2. Use a foreach loop to loop through the three materials to be created
and set the variables for the material parameters. Then use an if
statement to determine if a material with that name already exists. If so
update the material using the update_mat procedure. If the material does
not exist, create the material. Place these commands in a procedure
called main.

proc main {} {
set materialList [ hm_entitylist materials name ]
foreach {materialName E G N R} \
[list "aluminum" "10" "20" "0.3" "40" \
"altairium" "1000" "200" "0.3" "400" \
"steel" "2.0e6" "1.0e6" "0.3" "7.8e-9"] {
if {[lsearch $materialList $materialName] == -1 } {
create_mat $materialName $E $G $N $R
} else {
set mat_id [ hm_entityinfo id materials $materialName ];
update_mat $mat_id $E $G $N $R
}
}
}

Step 3: Test the script by running it from the Command Window.

Step 4: Test the script by creating a button & running it from its
button in the macro menu.

If necessary, refer to previous exercises on methods to update the
userpage.mac file.

Step 5: The exercise is complete. Close the HyperMesh session.











Chapter 6: Interfacing with HyperMesh Solver Templates

HyperWorks 13.0 Introduction to HM Customization 91
Proprietary Information of Altair Engineering, Inc
Practical Exercises
Exercise 6a

Description:
Generate a procedure to create a property collector with a PSHELL card
image in the OptiStruct template. Ask the user to supply a thickness
value. Try to incorporate checks into the procedure to avoid errors. For
example, if a property with that name already exists, what happens?

HyperMesh commands used
hm_errormessage *createmark
*collectorcreateonly *dictionaryload
*attributeupdatedouble hm_getmark
hm_getfloat

TCL/TK commands used
set
if

Hints
Do the steps in HyperMesh and then extract the commands from the
command.cmf file.
























Chapter 6: Interfacing with HyperMesh Solver Templates

Introduction to HM Customization 92 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc.
Exercise 6b

Description:
Generate a procedure to scale the values of the Youngs Modulus and
density in each of the materials that exist in your model. Scale the
Youngs Modulus by a factor of 100 and the density by a factor of 10. Do
not scale the value of Poissons ratio.

HyperMesh commands used
*createmark *attributeupdateint
*dictionaryload *attributeupdatedouble
*hm_allentitiesinfo *hm_getentityvalue

TCL/TK commands used
proc lindex
set expr
foreach

Hints
Remember to user a \ before referencing $E, etc in the
hm_getentityvalue command.










Solutions for Exercises

HyperWorks 13.0 Introduction to HM Customization 93
Proprietary Information of Altair Engineering, Inc
SOLUTIONS FOR EXERCISES

CHAPTER 2

Exercise 2a

*createbutton(5, "Model Tour", -1, 0, 10, YELLOW, "Explore HyperMesh
Session", "EvalTcl", "modeltour.tcl")


CHAPTER 3

Exercise 3a

*createbutton(5,"Translate Elements",-1,0,10,YELLOW,"Translate
elements","macroTranslate_elem")

*beginmacro(macroTranslate_elem)
*createmarkpanel(elements,1,"Select Elements")
*createvector(1,0.0000,0.0000,1.0000)
*translatemark(elements,1,1,10)
*endmacro()




CHAPTER 4

Exercise 4a


In userpage.mac file:

*createbutton(5,"Move and Translate Elements",-1,0,10,BLUE,"Move elems
to new comp and translate in z dir","EvalTcl","translate_elem.tcl")

In TCL File:

set user_comp [hm_getstring "Component Name" "Enter a Component
Collector Name"]
*collectorcreateonly components $user_comp "" 3
*createmarkpanel elements 1 "Elements"
*movemark elements 1 $user_comp
Solutions for Exercises

Introduction to HM Customization 94 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc
*clearmark elements 1
*createmark elements 1 "by collector name" $user_comp
*createvector 1 0.0 0.0 1.0
set user_distance [hm_getfloat "Translate Distance" "Enter the distance
to translate elements in z direction"]
*translatemark elements 1 1 $user_distance
*clearmark elements 1




Exercise 4b


In userpage.mac file:

*createbutton(5,"Create Elem List" -1,0,10,RED,"Create list of elems
and their nodes","EvalTcl","elem_list.tcl"

In TCL File:

hm_markclear elements 1

# Selects all elements and places in the mark
*createmark elems 1 all
set elemList [ hm_getmark elements 1 ]

set i 1

# for every element, find the nodes and centroid coordinates
foreach eList $elemList {
set nodeIDs [hm_nodelist $eList]
set ShortList [list $eList $nodeIDs]

# prints every list
puts $ShortList

# appends a list with all the elements information
lappend LongList $ShortList


# creates a list with a name SList_1, SList_2, etc for each
# element with their nodes and centroid coord

set SList_$i $ShortList
incr i 1
}

# prints the complete list of all the elements information
puts $LongList



Solutions for Exercises

HyperWorks 13.0 Introduction to HM Customization 95
Proprietary Information of Altair Engineering, Inc
CHAPTER 5

Exercise 5a

proc translatecomps { } {

*createmarkpanel components 1 "Select components to be
translated"
*createmarkpanel vectors 1 "Select translational vector"

set dist [hm_getfloat "Translation distance =" "Enter
translational distance"]

set vect [hm_getmark vectors 1]

set xcomp [hm_getentityvalue vectors $vect "xcomp" 0]
set ycomp [hm_getentityvalue vectors $vect "ycomp" 0]
set zcomp [hm_getentityvalue vectors $vect "zcomp" 0]

*createvector 1 $xcomp $ycomp $zcomp

*translatemark components 1 1 $dist
*clearmark comps 1
*clearmark vectors 1
}

translatecomps


Exercise 5b


hm_markclear all 1

# Selects all elements and places in the mark

*createmark elems 1 all
set elemList [ hm_getmark elements 1 ]

set i 1

# for every element, find the nodes and centroid coordinates


foreach eList $elemList {

set nodeIDs [hm_nodelist $eList]
set Centroid [hm_entityinfo centroid elements $eList]
set ShortList [list $eList $nodeIDs $Centroid]

# set each component of the centroid to a variable
Solutions for Exercises

Introduction to HM Customization 96 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc
set j 1
foreach cent $Centroid {
set x_$j $cent
incr j 1
}

# Create a node at the centroid x y z location
#set topnode [*createnode $x_1 $x_2 $x_3 0 0 0]
*createnode $x_1 $x_2 $x_3 0 0 0
*createmark node 1 -1

#put the element in the mark
*createmark elems 1 $eList

# get the x y and z values of the normal of the elements and then
# create a vector
set xComp [ hm_getentityvalue elems $eList "normalx" 0 ]
set yComp [ hm_getentityvalue elems $eList "normaly" 0 ]
set zComp [ hm_getentityvalue elems $eList "normalz" 0 ]
*createvector 1 $xComp $yComp $zComp

# get the # of nodes in the element and then based on the # nodes,
# create the 3D element
set no_nodes [llength $nodeIDs ]
if { $no_nodes == 4} {
set height [hm_getentityvalue elems $eList "shortestdiagonal" 0 ]
*translatemark node 1 1 $height
set top_id [ hm_getmark nodes 1 ]
eval *createlist nodes 1 "$top_id $nodeIDs"
*createelement 205 205 1 1
} elseif {$no_nodes == 3 } {
set height [hm_getentityvalue elems $eList "shortestside" 0 ]
*translatemark node 1 1 $height
set top_id [ hm_getmark nodes 1 ]
eval *createlist nodes 1 "$top_id $nodeIDs"
*createelement 204 204 1 1
} else {
puts "element not quad or tria"
}



# appends a list with all the elements information

lappend LongList $SList


# creates a list with a name SList_1, SList_2, etc for each element
# with their nodes and centroid coord

set SList_$i $ShortList
incr i 1
# mask nodes
*nodecleartempmark
Solutions for Exercises

HyperWorks 13.0 Introduction to HM Customization 97
Proprietary Information of Altair Engineering, Inc

hm_markclear elements 1
# hm_markclear nodes 1
# hm_markclear vector 1
}

# prints the complete list of all the elements information

# puts $LongList



Exercise 5c

#######################################################################
##############################
##### Solution to Practical Exercise 5c
#####
#######################################################################
##############################

### Use the *createmarkpanel to allow users to select the elements
### Then create a list of the selected element ids
### Finally clear the existing mark (no longer needed as ids have been
assigned to a list

*createmarkpanel elems 1 "Select Elements to create nodes at the
centroid"
set elemlist [hm_getmark elems 1]
*clearmark elems 1

### use the llength command to determine the number of element id in
the list

set ellistlength [llength $elemlist]

### Loop through each element in the list

for {set i 0} {$i < $ellistlength} {incr i} {

###assign the current element id to a variable

set elemid [lindex $elemlist $i]

### use the foreach command to get the x y z coordinates of the
centroid

foreach {x y z} [hm_entityinfo centroid elems $elemid] {break};

### Create a node at the x y z location of the centroid, add it
to mark 1, assign the id to a variable and clear the mark

eval *createnode $x $y $z 0 0 0
Solutions for Exercises

Introduction to HM Customization 98 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc
*createmark nodes 1 -1
set newnode [hm_getmark nodes 1]
*clearmark nodes 1

##$ Get the node ids that define the current element - they will
be used to orient the systems

set N1 [lindex [ hm_nodelist $elemid ] 0]
set N2 [lindex [ hm_nodelist $elemid ] 1]
set N3 [lindex [ hm_nodelist $elemid ] 2]
set N4 [lindex [ hm_nodelist $elemid ] 3]

### Create a new system with the origin at the node at the
element centroid, and oriented by the x axis and
### xy plane

*systemcreate 1 0 $newnode "x" $N2 "xy" $N3
}



CHAPTER 6

Exercise 6a

set prop_name [hm_getstring "Name="]
if {$prop_name == ""} {
hm_errormessage "No name specified"
return;
} elseif {[hm_entityinfo exist properties $prop_name -byname] == 1} {
hm_errormessage "Preoperty already exists"
return;
}

set prop_thick [hm_getfloat "Thickness="]
if {$prop_thick == "" || $prop_thick <= 0.0} {
hm_errormessage "Invalid thickness value specified"
return;
}
*collectorcreateonly properties "$prop_name" "" 11
*createmark properties 2 "$prop_name"
set prop_id [hm_getmark props 2]
*dictionaryload properties 2 "[hm_info -appinfo SPECIFIEDPATH
TEMPLATES_DIR]/feoutput/optistruct/optistruct" "PSHELL"
*attributeupdatedouble properties $prop_id 95 1 1 0 $prop_thick






Solutions for Exercises

HyperWorks 13.0 Introduction to HM Customization 99
Proprietary Information of Altair Engineering, Inc
Exercise 6b

# Update the E, NU, and RHO on the MAT1 card
proc update_mat1 {matid E NU RHO} {
*createmark materials 2 $matid
*dictionaryload materials 2 "[hm_info exporttemplate]" "MAT1"
*attributeupdateint materials $matid 3240 1 2 0 1
*attributeupdatedouble materials $matid 1 1 1 0 $E
*attributeupdatedouble materials $matid 3 1 1 0 $NU
*attributeupdatedouble materials $matid 4 1 0 0 $RHO
}

set dnst_scale_fac "10.0"
set ymd_scale_fac "100.0"

# Material Update for ALL materials
set materials_list [hm_allentitiesinfo materials]
foreach mat_info $materials_list {
set mat_id [lindex $mat_info 1]
# Extract the E, NU, and RHO values from the existing cards
# NOTE: For more complex models, there is a need to wrap
# hm_getentityvalue with a catch in case it throws an
error
set mat_E_orig [hm_getentityvalue MATS $mat_id "\$E" 0]
set mat_NU_orig [hm_getentityvalue MATS $mat_id "\$Nu" 0]
set mat_RHO_orig [hm_getentityvalue MATS $mat_id "\$Rho" 0]
# Convert the units on the E, NU, and RHO values
set mat_E [expr $mat_E_orig * $ymd_scale_fac]
set mat_NU $mat_NU_orig
set mat_RHO [expr $mat_RHO_orig * $dnst_scale_fac]
# Update the MAT1 card
update_mat1 $mat_id $mat_E $mat_NU $mat_RHO
}

















Solutions for Exercises

Introduction to HM Customization 100 HyperWorks 13.0
Proprietary Information of Altair Engineering, Inc