Sunteți pe pagina 1din 68

HyperMesh Customization

Introduction to HyperMesh Customization

HyperWorks is a division of Altair altairhyperworks.com


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

Location Telephone e-mail

Australia 64.9.413.7981 anzsupport@altair.com

Brazil 55.11.3884.0414 br_support@altair.com

Canada 416.447.6463 support@altairengineering.ca

China 86.400.619.6186 support@altair.com.cn

France 33.1.4133.0992 francesupport@altair.com

Germany 49.7031.6208.22 hwsupport@altair.de

India 91.80. 6629.4500 support@india.altair.com


1.800.425.0234 (toll free)

Italy 39.800.905.595 support@altairengineering.it

Japan 81.3.5396.2881 support@altairjp.co.jp

Korea 82.70.4050.9200 support@altair.co.kr

Mexico 55.56.58.68.08 mx-support@altair.com

New Zealand 64.9.413.7981 anzsupport@altair.com

North America 248.614.2425 hwsupport@altair.com

Scandinavia 46.46.460.2828 support@altair.se

South Africa 27 21 8311500 support@altair.co.za

United Kingdom 01926.468.600 support@uk.altair.com

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

Practical Exercises .................................................................................................................. 27

Chapter 3: HyperMesh Automation with HyperMesh Commands ................ 29

Exercise 3.1 Automate Creating a Load Collector ....................................................... 29

Practical Exercises ....................................................................................................... 32

Chapter 4: Using Tcl to Control the HyperMesh Session ............................ 33

Exercise 4.1 Using the Command Window .................................................................. 33

Exercise 4.2 Automate Creating Forces with a User Specified Magnitude .................. 36

HyperWorks 14.0 Introduction to HM Customization 3

Proprietary Information of Altair Engineering, Inc


Practical Exercises .......................................................................................................... 40

Chapter 5: Retrieving Data from HyperMesh Entities ................................... 43

Exercise 5.1 Automate Computing the Vector Sum of Forces ..................................... 43

Practical Exercises ....................................................................................................... 48

Chapter 6: Interfacing with HyperMesh Solver Templates ........................... 51

Exerise 6.1 Automate Extracting Data in a Card Image .............................................. 51

Exercise 6.2 Automate Defining a Card Image with Data ............................................ 55

Exercise 6.3 Automate Defining/Updating Multiple Materials ...................................... 59

Practical Exercises ....................................................................................................... 61

Solutions For Exercises ................................................................................... 63

Introduction to HM Customization 4 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

Chapter 1

Introduction to TCL/Tk

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

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

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

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

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

HyperWorks 14.0 Introduction to HM Customization 5

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

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

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

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

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

Basic Tcl Syntax


• First 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

Introduction to HM Customization 6 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

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

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

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

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


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

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

Output:
This is line 1
This is line 2

2. Variables and Variable Substitution


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

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

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

Output:
The software we are using is HyperWorks

HyperWorks 14.0 Introduction to HM Customization 7

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

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

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

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

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


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

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

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

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

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

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

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

Introduction to HM Customization 8 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

puts $date

Output: 2:3:09

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

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

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

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

Operands may be specified in any of the following ways:

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


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

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

HyperWorks 14.0 Introduction to HM Customization 9

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

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

Example 3.1:
expr 0 == 1

Output:
0

Example 3.2:
expr 1 == 1

Output:
1

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

Example 3.3:
expr 4 + 5

Output:
9

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

Tcl supports the following mathematical functions in expressions:

abs cosh log sqrt


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

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


using Tcl_CreateMathFunc().

Introduction to HM Customization 10 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

Example 3.4:
expr sin(2)

Output:
0.909297

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

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

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

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

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

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

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

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

5. Comparisons and Loops


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

HyperWorks 14.0 Introduction to HM Customization 11

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

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

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

Output:
Handling is good.

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

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

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

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


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

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

Output:
It could be a cow.

Introduction to HM Customization 12 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

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

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

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


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

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

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

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

The general syntax for the for loop is as follows:

for init test reinit body

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

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

HyperWorks 14.0 Introduction to HM Customization 13

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

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

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

while test body

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

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

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

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

foreach varName list body

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

Introduction to HM Customization 14 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

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

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

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

by setting a variable to be a list of values


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

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

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

Output:
John
Mary

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

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

foreach varName list body

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

HyperWorks 14.0 Introduction to HM Customization 15

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

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

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

Output:
List length is: 4

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

Output:
New list is: Canada India China USA UK

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

Output:
New list is: Canada India USA UK China

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

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

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

Output:
bar

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

Introduction to HM Customization 16 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

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

Output:
red

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

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

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

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

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

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

9. Writing and Reading Files


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

HyperWorks 14.0 Introduction to HM Customization 17

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

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

open filename access

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

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

Output:
file4915610

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

puts ?channelId? string

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

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

Output: file4910020

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

gets channelId

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

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

Introduction to HM Customization 18 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

puts "Line 1: $line1"


puts "Line 2: $line2"

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

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

proc name argList body

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

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

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

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

HyperWorks 14.0 Introduction to HM Customization 19

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

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

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

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


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

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

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

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

namespace eval Counter {


namespace export bump
variable num 0

proc bump {} {

Introduction to HM Customization 20 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

variable num
incr num
}
}

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

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

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

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

Example 1.1
tk_getOpenFile

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

HyperWorks 14.0 Introduction to HM Customization 21

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

Figure 1: GUI created from tk_getOpenFile command.

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

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

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

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

tk_getOpenFile ?option value ...?

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

-filetypes filePatternList

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

Examples 1.3

Introduction to HM Customization 22 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

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

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

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

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

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

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

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

HyperWorks 14.0 Introduction to HM Customization 23

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

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

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

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

Example 3.1
set dirname [tk_chooseDirectory]
puts $dirname

Output:
C:/temp

Introduction to HM Customization 24 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 1: Introduction to Tcl/Tk

Figure 4: GUI from tk_chooseDirectory command.

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

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

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

Output:

Figure 5: GUI from tk_messageBox command.

HyperWorks 14.0 Introduction to HM Customization 25

Proprietary Information of Altair Engineering, Inc


Chapter 1: Introduction to Tcl/Tk

Introduction to HM Customization 26 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 2: HyperMesh Process Automation Introduction

Chapter 2

HyperMesh Process
Automation Introduction

Practical Exercises
Exercise 2a

Description
Add the following pull down menus:

HyperMesh commands used


none

TCL/TK commands used


none

Hints
On Windows, the working directory is located in the My Documents
folder. Copy Exercise_Stat.tcl in the Chapter 2 folder and save it
there. Rename it to hmcustom.tcl and edit the file to add the
commands to make the pull down menus. The menu will not launch any
scripts, we are just focused on the format needed to create the menu
structure.

HyperWorks 14.0 Introduction to HM Customization 27

Proprietary Information of Altair Engineering, Inc


Chapter 2: HyperMesh Process Automation Introduction

Introduction to HM Customization 28 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 3: HyperMesh Automation with HyperMesh Macros

Chapter 3

HyperMesh Automation with


HyperMesh Macros
Exercise 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.tcl file

Every command executed in HyperMesh is recorded in the command.tcl file.


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

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

OR

You can reset the command.tcl within HyperMesh by following these steps:

1. Open HyperMesh.
2. Open the Scripting toolbar by selecting View > Toolbars > HyperWorks
> Scripting.

HyperWorks 14.0 Introduction to HM Customization 29

Proprietary Information of Altair Engineering, Inc


Chapter 3: HyperMesh Automation with HyperMesh Macros

3. Select Open Command File, .


4. Select File > New to clear the command.tcl file.
5. Select File > Save and save the file as command.tcl in the current
directory.
6. Select Yes to overwrite the current file.
7. Close the Edit Command File window.

Step 3: Do the task in HyperMesh


1. 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.
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.
7. Keep this HyperMesh session open for steps later in this exercise.

Step 4: Extract commands from the command file and add them
to your TCL file

1. From the Scripting toolbar select Open Command 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 has a color id of 7, it has a color of light blue.

3. Copy the *collectorcreateonly line.


4. From your HyperMesh working directory, open a new text file and save it
as Ex3_1.tcl.
5. In the file paste the copied line.
6. Save the Ex3_1.tcl file.

Step 5: Add the Script to a User Pull Down Menu

Using the provided hmcustom.tcl we will add the Ex3_1.tcl script.


Introduction to HM Customization 30 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 3: HyperMesh Automation with HyperMesh Macros

1. Open the hmcustom.tcl file in the Ch 3 folder provided.


2. Find the following line in the file:
$class.sub1 add command -label "Ch3_1 Exercise" -
command "source {UPDATE.tcl}" -underline 0

3. Edit the UPDATE.tcl field to point to the location of the Ex3_1.tcl file
(make sure you use / in the path name).
4. Save the hmcustom.tcl file in your working directory (generally the My
Documents folder).
5. Either reopen HyperMesh or change the User Profile to refresh the
session.

Step 6: Test the macro


1. Select File > New > Session to create a new session.
2. From the pull down menu, select Class Scripts > Ch3 > Ch3_1 Exercise.
3. A load collector is added with the name and color given in step 4.

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

HyperWorks 14.0 Introduction to HM Customization 31

Proprietary Information of Altair Engineering, Inc


Chapter 3: HyperMesh Automation with HyperMesh Macros

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


*createmarkpanel
*translatemark

TCL/TK commands used


none

Hints
Do all the steps in HyperMesh and extract the appropriate commands
from the command.tcl file.

Introduction to HM Customization 32 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 4: Using Tcl to Control the HyperMesh Session

Chapter 4

Using Tcl to Control the


HyperMesh Session
Exercise 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:


HyperMesh commands:
*createmark
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.

Step 2: Run operating system commands from the Command


Window

HyperWorks 14.0 Introduction to HM Customization 33

Proprietary Information of Altair Engineering, Inc


Chapter 4: Using Tcl to Control the HyperMesh Session

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 directory’s 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
By using the llength Tcl command, the number of entities in the list elemIds
can be found.

set numElems [llength $elemIds]

Introduction to HM Customization 34 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 4: Using Tcl to Control the HyperMesh Session

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

This example is complete. You can close the HyperMesh session.

HyperWorks 14.0 Introduction to HM Customization 35

Proprietary Information of Altair Engineering, Inc


Chapter 4: Using Tcl to Control the HyperMesh Session

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

HyperMesh commands:
*createmark
*clearmark
hm_getfloat

Core Tcl commands:


set

Step 1: Define the task to be automated.


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.tcl file from your working


directory.
Every command executed in HyperMesh is recorded in the command.tcl file.
To view only the task’s commands, it is suggested you delete the command.tcl
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 > Model, select the file c_channel-tcl_vector.hm

Step 4: Create a load collector.

Introduction to HM Customization 36 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 4: Using Tcl to Control the HyperMesh Session

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.

Step 6: Copy the task’s commands in the command.tcl 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.tcl file.
3. Locate the following four commands at or near the end of the file.

*collectorcreateonly loadcols “forces” “” 7


*loadsize 1 10 0 1
*createmark nodes 1 3237
*loadcreateonentity_curves 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 Add to the script commands as necessary.

Step 7: Modify and 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
HyperWorks 14.0 Introduction to HM Customization 37

Proprietary Information of Altair Engineering, Inc


Chapter 4: Using Tcl to Control the HyperMesh Session

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

*createmarkpanel nodes 1 “Select nodes”

Step 8: 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_curv e nodes 1 1 1 0 0 $mag_val 0 0 $mag_val 0 0


0 0 0

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


following:
*collectorcreate loadcols “forces” “” 7
*loadsize 1 10 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 10: 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.

Introduction to HM Customization 38 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 4: Using Tcl to Control the HyperMesh Session

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 script’s 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 script’s task.
The force(s) are created.

Steps 11-12 Test the script from Pull Down Menu.

Step 11: Add the Script to a User Pull Down Menu

Using the provided hmcustom.tcl we will add the create_force.tcl script.

1. Open the hmcustom.tcl file in the Ch 4 folder provided (or work with the
hmcustom.tcl file you edited in Chapter 3).
2. Find the following line in the file:
$class.sub2 add command -label "Ch4_2 Exercise" -
command "source {UPDATE.tcl}" -underline 0

3. Edit the UPDATE.tcl field to point to the location of the


create_force.tcl file (make sure you use / in the path name).
4. Save the hmcustom.tcl file in your working directory (generally the My
Documents folder).
5. Either reopen HyperMesh or change the User Profile to refresh the
session.

Step 12: Test the macro


1. From the pull down menu, select Class Scripts > Ch4 > Ch4_2 Exercise.
2. Follow the instructions to create the force(s) on the selected node(s).

Step 13: The exercise is complete. Close the HyperMesh


session.

HyperWorks 14.0 Introduction to HM Customization 39

Proprietary Information of Altair Engineering, Inc


Chapter 4: Using Tcl to Control the HyperMesh Session

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.

Introduction to HM Customization 40 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 4: Using Tcl to Control the HyperMesh Session

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.

HyperWorks 14.0 Introduction to HM Customization 41

Proprietary Information of Altair Engineering, Inc


Chapter 4: Using Tcl to Control the HyperMesh Session

Introduction to HM Customization 42 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 5: Retrieving Data from HyperMesh Entities

Chapter 5

Retrieving Data from


HyperMesh Entities
Exercise 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.

The following HyperMesh commands are used in this exercise.


*clearmark
*createmarkpanel
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

HyperWorks 14.0 Introduction to HM Customization 43

Proprietary Information of Altair Engineering, Inc


Chapter 5: Retrieving Data from HyperMesh Entities

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.tcl 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.tcl file for this task.

Step 3: Create a text file named sum_force_comps.tcl for the


script to be created.

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

Introduction to HM Customization 44 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 5: Retrieving Data from HyperMesh Entities

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

HyperWorks 14.0 Introduction to HM Customization 45

Proprietary Information of Altair Engineering, Inc


Chapter 5: Retrieving Data from HyperMesh Entities

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


Using the tk_messageBox command, a window which reports the x, y, and z
components of the resultant force is shown.

tk_messageBox –message “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]
}

tk_messageBox –message “Resultant force: $xsum, $ysum,


$zsum”

Step 10: Save the sum_force_comps.tcl file.

Introduction to HM Customization 46 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 5: Retrieving Data from HyperMesh Entities

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 isn’t
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 window.
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: Add the Script to a User Pull Down Menu

Using the provided hmcustom.tcl we will add the sum_forces_comps.tcl


script.

1. Open the hmcustom.tcl file in the Ch 5 folder provided (or work with the
hmcustom.tcl file you edited in Chapter 3).
2. Find the following line in the file:
$class.sub3 add command -label "Ch5_1 Exercise" -
command "source {UPDATE.tcl}" -underline 0

3. Edit the UPDATE.tcl field to point to the location of the


sum_forces_comps.tcl file (make sure you use / in the path name).
4. Save the hmcustom.tcl file in your working directory (generally the My
Documents folder).
5. Either reopen HyperMesh or change the User Profile to refresh the
session.

Step 13: Test the macro


1. Reopen the c_channel-tcl_vector.hm file.
2. Create a few loads.
3. From the pull down menu, select Class Scripts > Ch5 > Ch5_1 Exercise.
4. Follow the instructions to run the script.

Step 14: The exercise is complete. Close the HyperMesh


session.
HyperWorks 14.0 Introduction to HM Customization 47

Proprietary Information of Altair Engineering, Inc


Chapter 5: Retrieving Data from HyperMesh Entities

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

Introduction to HM Customization 48 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 5: Retrieving Data from HyperMesh Entities

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?

HyperWorks 14.0 Introduction to HM Customization 49

Proprietary Information of Altair Engineering, Inc


Chapter 5: Retrieving Data from HyperMesh Entities

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.

Introduction to HM Customization 50 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 6: Interfacing with HyperMesh Solver Templates

Chapter 6

Interfacing with HyperMesh


Solver Templates
Exercise 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_getvalue

·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 Young’s Modulus
(E), Shear Modulus (G), Poisson’s 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 Young’s Modulus, Shear Modulus,
Poison’s 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.
HyperWorks 14.0 Introduction to HM Customization 51

Proprietary Information of Altair Engineering, Inc


Chapter 6: Interfacing with HyperMesh Solver Templates

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. In the MAT1 card image, the field names for Young’s Modulus, Shear
Modulus, Poisson’s 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)

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
Young’s Modulus, Shear Modulus, Poisson’s ratio, and density have been
determined. Now using those field names and the hm_getvalue command, the
parameter values can be stored in variables.

set mat_id 1
set mat_E [hm_getvalue mats id=1 dataname=E]
set mat_G [hm_getvalue mats id=1 dataname=G]
set mat_NU [hm_getvalue mats id=1 dataname=Nu]
set mat_RHO [hm_getvalue mats id=1 dataname=Rho]

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.
Introduction to HM Customization 52 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 6: Interfacing with HyperMesh Solver Templates

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

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: Display the result of the extract procedure in a


tk_messageBox command.
Change the script line:

extract_mat 1

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.

HyperWorks 14.0 Introduction to HM Customization 53

Proprietary Information of Altair Engineering, Inc


Chapter 6: Interfacing with HyperMesh Solver Templates

Step 11: Add the Script to a User Pull Down Menu


Using the provided hmcustom.tcl we will add the extract_mat.tcl script.

1. Open the hmcustom.tcl file in the Ch 6 folder provided (or work with the
hmcustom.tcl file you edited in Chapter 3).
2. Find the following line in the file:
$class.sub4 add command -label "Ch6_1 Exercise" -
command "source {UPDATE.tcl}" -underline 0

3. Edit the UPDATE.tcl field to point to the location of the


extract_mat.tcl file (make sure you use / in the path name).
4. Save the hmcustom.tcl file in your working directory (generally the My
Documents folder).
5. Either reopen HyperMesh or change the User Profile to refresh the
session.

Step 12: Test the macro


1. From the pull down menu, select Class Scripts > Ch6 > Ch6_1 Exercise.
2. Follow the instructions to execute the script.

Step 13: The exercise is complete. Close the HyperMesh


session.

Introduction to HM Customization 54 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 6: Interfacing with HyperMesh Solver Templates

Exercise 6.2: Automate Defining a Card Image


with Data
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:
*createentity
*setvalue
*createmark
hm_getmark

·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.
• Young’s Modulus (E)
• Shear Modulus (G)
• Poisson’s 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.tcl file.

Step 2: Delete the command.tcl file from your HyperMesh


working folder.

Every command executed in HyperMesh is recorded in the command.tcl file.


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

HyperWorks 14.0 Introduction to HM Customization 55

Proprietary Information of Altair Engineering, Inc


Chapter 6: Interfacing with HyperMesh Solver Templates

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 task’s commands in the command.tcl 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.tcl file.
3. Locate the command line *createentity at or near the end of the file.
You should see lines similar to the following.

*createentity mats cardimage=MAT1 name=material1


*setvalue mats id=1 name=steel
*setvalue mats id=1 cardimage="MAT1"
*setvalue mats id=1 STATUS=1 1=123
*setvalue mats id=1 STATUS=1 2=45
*setvalue mats id=1 STATUS=1 3=0.078
*setvalue mats id=1 STATUS=1 4=90

4. Copy and paste the lines into the create_mat.tcl file.

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

Introduction to HM Customization 56 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 6: Interfacing with HyperMesh Solver Templates

Step 6: Substitute the attribute values with variables E, G, NU,


and RHO.
*setvalue mats id=1 STATUS=1 1=$E
*setvalue mats id=1 STATUS=1 2=$G
*setvalue mats id=1 STATUS=1 3=$NU
*setvalue mats id=1 STATUS=1 4=$RHO

Step 7: Substitute all instances of the hard coded material name


steel with the variable mat_name.

*setvalue mats id=$mat_id name=$mat_name

Step 8: Once the material is created, retrieve its id from the mark
and store it in a variable.
Add the following command just below the *createentity line.

*createmark materials 1 -1
set mat_id [hm_getmark materials 1]

Step 9: Substitute all instances of the hard coded material id


with the variable $mat_id.
*setvalue mats id=$mat_id name=$mat_name
*setvalue mats id=$mat_id cardimage="MAT1"
*setvalue mats id=$mat_id STATUS=1 1=$E
*setvalue mats id=$mat_id STATUS=1 2=$G
*setvalue mats id=$mat_id STATUS=1 3=$NU
*setvalue mats id=$mat_id STATUS=1 4=$RHO

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


following.
*createentity mats cardimage=MAT1 name=material1
*createmark materials 1 -1
set mat_id [hm_getmark materials 1]
*setvalue mats id=$mat_id name=$mat_name
*setvalue mats id=$mat_id cardimage="MAT1"
*setvalue mats id=$mat_id STATUS=1 1=$E
*setvalue mats id=$mat_id STATUS=1 2=$G
*setvalue mats id=$mat_id STATUS=1 3=$NU
*setvalue mats id=$mat_id STATUS=1 4=$RHO

HyperWorks 14.0 Introduction to HM Customization 57

Proprietary Information of Altair Engineering, Inc


Chapter 6: Interfacing with HyperMesh Solver Templates

Step 11: 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]
}

Step 12: Evaluate the procedure and save the create_mat.tcl file.
mat_create “aluminum” “10” “20” “0.3” “40”

Step 13: 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 14: Add the Script to a User Pull Down Menu


Using the provided hmcustom.tcl we will add the create_mat.tcl script.

1. Open the hmcustom.tcl file in the Ch 6 folder provided (or work with the
hmcustom.tcl file you edited in Chapter 3).
2. Find the following line in the file:
$class.sub4 add command -label "Ch6_2 Exercise" -
command "source {UPDATE.tcl}" -underline 0

3. Edit the UPDATE.tcl field to point to the location of the


create_mat.tcl file (make sure you use / in the path name).
4. Save the hmcustom.tcl file in your working directory (generally the My
Documents folder).
5. Either reopen HyperMesh or change the User Profile to refresh the
session.

Step 15: Test the macro


1. Create a new session by selecting File > New > Session.
2. From the pull down menu, select Class Scripts > Ch6 > Ch6_2 Exercise.
3. Follow the instructions to execute the script.

Step 16: The exercise is complete. Close the HyperMesh


session.
Introduction to HM Customization 58 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 6: Interfacing with HyperMesh Solver Templates

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 Young’s Modulus (E),
Shear Modulus (G), Poisson’s 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 ( *setvalue… ) 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} {


*setvalue mats id=$mat_id cardimage="MAT1"
*setvalue mats id=$mat_id STATUS=1 1=$E
*setvalue mats id=$mat_id STATUS=1 2=$G
*setvalue mats id=$mat_id STATUS=1 3=$NU
*setvalue mats id=$mat_id STATUS=1 4=$RHO
}

proc create_mat {mat_name E G NU RHO} {


*createentity mats cardimage=MAT1 name=material1
*createmark materials 1 -1
set mat_id [hm_getmark materials 1]
*setvalue mats id=$mat_id name=$mat_name
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
HyperWorks 14.0 Introduction to HM Customization 59

Proprietary Information of Altair Engineering, Inc


Chapter 6: Interfacing with HyperMesh Solver Templates

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 and then call the procedure 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
}
}
}
main

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

Step 4: Add the Script to a User Pull Down Menu


Using the provided hmcustom.tcl we will add the create_mat.tcl script.

1. Open the hmcustom.tcl file in the Ch 6 folder provided (or work with the
hmcustom.tcl file you edited in Chapter 3).
2. Find the following line in the file:
$class.sub4 add command -label "Ch6_3 Exercise" -
command "source {UPDATE.tcl}" -underline 0

3. Edit the UPDATE.tcl field to point to the location of the


create_mat.tcl file (make sure you use / in the path name).
4. Save the hmcustom.tcl file in your working directory (generally the My
Documents folder).
5. Either reopen HyperMesh or change the User Profile to refresh the
session.

Step 5: Test the macro


1. From the pull down menu, select Class Scripts > Ch6 > Ch6_3 Exercise.
2. Follow the instructions to execute the script.

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


Introduction to HM Customization 60 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Chapter 6: Interfacing with HyperMesh Solver Templates

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
*setvalue hm_getmark
hm_getfloat *createntity

TCL/TK commands used


set
if

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

HyperWorks 14.0 Introduction to HM Customization 61

Proprietary Information of Altair Engineering, Inc


Chapter 6: Interfacing with HyperMesh Solver Templates

Exercise 6b

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

HyperMesh commands used


*createmark *setvalue
*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.

Introduction to HM Customization 62 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc.


Solutions for Exercises

SOLUTIONS FOR EXERCISES

CHAPTER 3
Exercise 3a
*createmarkpanel elements 1 "Select Elements"
*createvector 1 0.0000 0.0000 1.0000
*translatemark elements 1 1 10

CHAPTER 4
Exercise 4a
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
*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
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]

HyperWorks 14.0 Introduction to HM Customization 63

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

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

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

Introduction to HM Customization 64 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

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


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

HyperWorks 14.0 Introduction to HM Customization 65

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

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 $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
# mask nodes
*nodecleartempmark

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

Introduction to HM Customization 66 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

### 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
*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;

HyperWorks 14.0 Introduction to HM Customization 67

Proprietary Information of Altair Engineering, Inc


Solutions for Exercises

} 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;
}
*createentity props cardimage=PSHELL name=$prop_name
*createmark properties 2 "$prop_name"
set prop_id [hm_getmark props 2]
*setvalue props id=$prop_id STATUS=1 thickness=$prop_thick

Exercise 6b

# Update the E, NU, and RHO on the MAT1 card


proc update_mat1 {matid E NU RHO} {
*createmark materials 2 $matid
*setvalue mats id=$matid cardimage=MAT1
*setvalue mats id=$matid STATUS=1 1=$E
*setvalue mats id=$matid STATUS=1 3=$NU
*setvalue mats id=$matid STATUS=1 4=$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
}

Introduction to HM Customization 68 HyperWorks 14.0

Proprietary Information of Altair Engineering, Inc

S-ar putea să vă placă și