Documente Academic
Documente Profesional
Documente Cultură
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
About Tk ..................................................................................................................................... 6
Exercise 4.2 Automate Creating Forces with a User Specified Magnitude .................. 36
Chapter 1
Introduction to TCL/Tk
About TCL
Tcl (Tool Command Language) is used by developers worldwide and has become a
critical component in thousands of corporations. It has a simple and programmable
syntax and can be either used as a standalone application or embedded in application
programs. Best of all, Tcl is open source so it's completely free.
The main difference between Tcl and languages such as C is that Tcl is an interpreted
rather than a compiled language. Tcl programs are simply scripts consisting of Tcl
commands that are processed by a Tcl interpreter at run time. One advantage that this
offers is that Tcl programs can themselves generate Tcl scripts that can be evaluated at
a later time. This can be useful, for example, when creating a graphical user interface
with a command button that needs to perform different actions at different times.
One of Tcl's most useful features is its extensibility. If an application requires some
functionality not offered by standard Tcl, new Tcl commands can be implemented using
the C language, and integrated fairly easily. Since Tcl is so easy to extend, many people
have written extension packages for some common tasks, and made these freely
available on the Internet.
Businesses and engineering teams today are often faced with the problem of making
diverse collections of resources work together. We call these programming tasks
integration applications. For enterprises, the integration platform is becoming as
strategically important as the operating system and database platforms.
Tcl is the integration platform of choice because of its speed of use, breadth of
functionality, and enterprise-ready features such as thread-safety, internationalization
and cross platform deployment. The latest version of Tcl provides all the features an
enterprise needs for all integration and scripting needs.
About TK
Tk is a graphical user interface toolkit that makes it possible to create powerful GUIs
quickly. It proved so popular that it now ships with all distributions of Tcl. Tk shares
many concepts with other windowing toolkits, but you do not need to know much about
graphical user interfaces to get started with Tk.
Tk adds about 35 Tcl commands that let you create and manipulate widgets in a
graphical user interface. A widget is a window in a graphical user interface that has a
particular appearance and behavior. The terms widget and window are often used
interchangeably. Widget types include buttons, scrollbars, menus, and text windows. Tk
also has a general-purpose drawing widget called a canvas that lets you create lighter-
weight items such as lines, boxes, and bitmaps.
Tcl and Tk are highly portable, running on essentially all flavors of Unix (Linux, Solaris,
IRIX, AIX, *BSD*, the list goes on and on), Windows, Macintosh, and more.
Some basic Tk commands will be discussed later. For additional information, please
refer to the manual.
1. Text Output
Printing out a string using Tcl is done using the puts command. A single unit of text
after the puts command will be output.
Example 1.1
puts HyperWorks
Output: HyperWorks
If the string is more than one word, the string must be enclosed in either double quotes
(“ “) or braces ({ }). Many commands, including the puts command, accept multiple
arguments. If the string is not enclosed in quotes or braces, the individual words are
considered arguments. A set of words enclosed in quotes or braces will treated as a
single unit. The two options of quotes or braces behave differently and the differences
will be discussed in the next section.
Example 1.2
puts “This is an example with quotes”
puts {This is an example with braces}
Output:
This is an example with quotes
This is an example with braces
Example 1.3
# An example using a semicolon
puts “This is line 1”; puts {This is line 2};#Note after the ;
Output:
This is line 1
This is line 2
The value stored in a variable can be accessed by prefacing the name of the variable
with a dollar sign ("$"). This is known as variable substitution, and is illustrated in the
examples below. A variable can be used to store a number, a date, a string, or even
another Tcl script.
Example 2.1:
set software "HyperWorks"
puts "The software we are using is $software"
Output:
The software we are using is HyperWorks
Example 2.1 illustrates the use of variable substitution. The value "HyperWorks" is
assigned to the variable "software", whose value is then substituted for $software.
Note that variable substitution can occur within a string.
As Example 2.2 (below) shows, the backslash (\) disables substitution for the single
character following the backslash. Any character following the backslash will stand
without substitution. This is also true when the backslash precedes a quote, brace, or
bracket.
Example 2.2
set Z Albany
set Z_LABEL “This Capitol of New York is: “
Output
Albany
The Capitol of New York is:
The Capitol of New York is: Albany
The Capitol of New York is: $Z
When defining a string, if there are multiple words in the string we have learned that we
can either use double quotes or braces. The difference between these two options is
how they treat variables that are in their strings.
Example 2.3
puts "$Z_LABEL $Z"
puts {$Z_LABEL $Z}
Output
The Capitol of New York is: Albany
$Z_LABEL $Z
Example 2.3 shows how using the double brace actually disables the substitution of
variables within the braces. Note that braces have this effect only when they are used
for grouping (i.e. at the beginning and end of a sequence of words). If a string is already
grouped, either with quotes or braces, and braces occur in the middle of the grouped
string (i.e. "foo{bar"), then the braces are treated as regular characters with no special
meaning. If the string is grouped with quotes, substitutions will occur within the quoted
string, even between the braces.
Example 2.4:
set month 2
set day 3
set year 09
set date "$month:$day:$year"
puts $date
Output: 2:3:09
Here variable substitution is used in several places: The values of the variables "month",
"day", and "year" are substituted in the set command that assigns the value of the
"date" variable, and the value of the "date" variable is then substituted in the line that
displays the output.
Example 2.5:
set foo "puts hi"
eval $foo
Output:
hi
In this example, the variable "foo" holds another (small) Tcl script that simply prints the
word "hi". The value of the variable "foo" is substituted into an eval command. The
eval command takes one or more arguments which together comprise a Tcl script and
passes it to the Tcl interpreter.
3. Expressions
Tcl allows several types of expressions, including mathematical expressions and
relational expressions. Tcl expressions are usually evaluated using the expr command.
A Tcl expression consists of a combination of operands, operators, and parentheses.
White space may be used between the operands and operators and parentheses; it is
ignored by the expression's processor.
The valid operators are listed below, grouped in decreasing order of precedence. For a
detailed listing of what these operators please view the Tcl manual.
• - + ~ ! Unary minus, unary plus, bit-wise NOT, logical NOT.
• * / % Multiply, divide, remainder.
• + - Add and subtract.
• << >> Left and right shift.
• < > <= >= Boolean less, greater, less than or equal, and greater than
or equal.
• == != Boolean equal and not equal.
• & Bit-wise AND.
• ^ Bit-wise exclusive OR.
• | Bit-wise OR.
• && Logical AND.
• || Logical OR.
Example 3.1:
expr 0 == 1
Output:
0
Example 3.2:
expr 1 == 1
Output:
1
Examples 3.1 and 3.2 illustrate the use of relational expressions with the expr
command. The first expression evaluates to 0 (false) since 0 does not equal 1, whereas
the second expression evaluates to 1 (true), since, obviously, 1 does equal 1. The
relational operator "==" is used to do the comparison.
Example 3.3:
expr 4 + 5
Output:
9
Example 3.3 shows how to use the expr statement to evaluate an arithmetic
expression. Here the result is simply the sum of 4 and 5.
Example 3.4:
expr sin(2)
Output:
0.909297
This example shows that the expr statement can be used to evaluate the result of a
mathematical function, in this case, the sine of an angle.
4. Command Substitution
Just as variable substitution is used to substitute the value of a variable into a Tcl script,
command substitution can be used to replace a Tcl command with the result that it
returns. Consider the following example:
Example 4.1:
puts "I am [expr 10*2] years old, and my I.Q. is [expr 100 - 25]"
Output:
I am 20 years old, and my I.Q. is 75
As this example shows, square brackets are used to achieve command substitution. The
text between the square brackets is evaluated as a Tcl script, and its result is then
substituted in its place. In this case, command substitution is used to place the results of
two mathematical expressions into a string. Command substitution is often used in
conjunction with variable substitution, as shown in Example 4.2:
Example 4.2:
set my_height 6.0
puts "If I was 2 inches taller, I would be [expr $my_height +
(2.0 / 12.0)] feet tall"
Output:
If I was 2 inches taller, I would be 6.16667 feet tall
In this example, the value of the variable "my_height" is substituted inside the square
brackets before the command is evaluated. This is a good illustration of Tcl's one-pass
recursive parsing mechanism. When evaluating a statement, the Tcl interpreter, makes
one pass over it, and in doing so makes all the necessary substitutions. Once this is
done, the interpreter then evaluates the resulting expression. If, during its pass over the
expression, the interpreter encounters square brackets (indicating that command
substitution is to be performed), it recursively parses the script inside the square
brackets in the same manner.
well as looping constructs (while, for, and foreach statements), both of which can
alter the flow of execution in response to some condition. The following examples serve
to illustrate these constructs.
Example 5.1:
set k 35
if {$k == 35} {
puts "Handling is good."
} elseif {$k == 20} {
puts "Ride is good."
} else {
puts "I am not sure of the quality of ride or handling."
}
Output:
Handling is good.
Example 5.1 uses the if statement. It sets the value of the variable "k" to 35, and then
uses an if statement to choose which statement to print. The general syntax of the if
statement is as follows:
If the test1 expression evaluates to a true value, then body1 is executed. If not, then if
there are any elseif clauses present, their test expressions are evalutated and, if true,
their bodies are executed. If any one of the tests is made successfully, after its
corresponding body is executed, the if statement terminates, and does not make any
further comparisons. If there is an else clause present, its body is executed if no other
test succeeds.
Example 4.2:
set num_legs 4
switch $num_legs {
2 {puts "It could be a human."}
4 {puts "It could be a cow."}
6 {puts "It could be an ant."}
8 {puts "It could be a spider."}
default {puts "It could be anything."}
}
Output:
It could be a cow.
The switch statement has two general forms (both of which are described in detail in
the manual page), but the form used here is as follows:
It is often useful to execute parts of a program repeatedly, until some condition is met. In
order to facilitate this, Tcl offers three looping constructs: the while, for, and foreach
statements, each of which is shown in the examples below.
Example 5.3:
for {set i 0} {$i < 5} {incr i 1} {
puts "In the for loop, and i == $i"
}
Output:
In the for loop, and i == 0
In the for loop, and i == 1
In the for loop, and i == 2
In the for loop, and i == 3
In the for loop, and i == 4
The init argument is a Tcl script that initializes a looping variable. In the for loop used
in Example 5.3, the looping variable was called "i", and the init argument simply set it
to 0. The test argument is a Tcl script which will be evaluated to decide whether or not
to enter the body of the for loop. Each time this script evaluates to a true value, the
body of the loop is executed. The first time this script evaluates to false, the loop
terminates. The reinit argument specifies a script that will be called after each time
the body is executed. In Example 5.3, the reinit script increments the value of the
looping variable, "i" using the incr command. Thus, the for loop in this example
executes its body 5 times, before its test script evaluates to false, causing the loop to
terminate.
Example 5.4:
set i 0
while {$i < 5} {
puts "In the while loop, and i == $i"
incr i 1
}
Output:
In the while loop, and i == 0
In the while loop, and i == 1
In the while loop, and i == 2
In the while loop, and i == 3
In the while loop, and i == 4
Example 5.4 illustrates the use of a while loop, the general syntax of which follows the
form:
The basic concept behind the while loop is that while the script specified by the test
argument evaluates to a true value, the script specified by the body argument is
executed. The while loop in Example 5.4 accomplishes the same effect as the for
loop in Example 5.3. A looping variable, "i", is again initialized to 0 and incremented
each time the loop is executed. The loop terminates when the value of "i" reaches 5.
Note, that in the case of the while loop, the initialization and re-initialization of the
looping variable are not part of the while statement itself. Therefore, the initialization of
the variable is done before the while loop, and the reinitialization is incorporated into its
body. If these statements were left out, the code would probably still run, but with
unexpected results.
Example 5.5:
foreach vowel {a e i o u} {
puts "$vowel is a vowel"
}
Output:
a is a vowel
e is a vowel
i is a vowel
o is a vowel
u is a vowel
The foreach loop, illustrated in Example 5.5, operates in a slightly different manner to
the other types of Tcl loops described in this section. Whereas for loops and while
loops execute while a particular condition is true, the foreach loop executes once for
each element of a fixed list. The general syntax for the foreach loop is:
The variable specified by varName takes on each of the values in the list in turn, and
the body script is executed each time. In Example 5.5, the variable "vowel" takes on
each of the values in the list "{a e i o u}" (Tcl list structure will be discussed in more detail
in the next section), and for each value, the body of the loop is executed, resulting in one
printed statement each time.
6. Lists
Lists in Tcl provide a simple means by which to group collections of items, and deal with
the collection as a single entity. When needed, the single items in the group can be
accessed individually. Lists are represented in Tcl as strings with a specified format. As
such, they can be used in any place where strings are normally allowed. The elements
of a list are also strings, and therefore any form of data that can be represented by a
string can be included in a list (allowing lists to be nested within one another).
Lists can be created in the following ways, in addition to being represented by a string.
An individual list member can be accessed with the lindex command. The following
examples will illustrate many important list commands:
Example 6.1:
set simple_list “John Joe Mary Susan”
puts [lindex $simple_list 0]
puts [lindex $simple_list 2]
Output:
John
Mary
Example 6.1 creates a simple list of four elements, each of which consists of one word.
The lindex command is then used to extract two of the elements in the list: the 0th
element and the 2nd element. Note that list indexing is zero-based. It is also important to
see that the lindex command, along with most other list commands, takes an actual
list as its first argument, not the name of a variable containing a list. Thus the value of
the variable "simple_list" is substitued into the lindex command.
The items in a list can be iterated through using the foreach command:
As mentioned previously, the foreach command will execute the body code one time
for each list item in list. On each pass, varName will contain the value of the next
list item.
The length of a list can be determined using the llength command. Also, a value can
be inserted into a list using the linsert command. Another option is the lappend
command which appends values to a list. Examples 6.2, 6.3, and 6.4 show how these
commands can be used.
Example 6.2:
set names {Canada India USA UK}
puts “List length is: [llength $names]”
Output:
List length is: 4
Example 6.3
set names {Canada India USA UK}
set newnames [linsert $names 2 China]
puts “New list is: $newnames”
Output:
New list is: Canada India China USA UK
Example 6.4
set names {Canada India USA UK}
set newnames [lappend names China]
puts “New list is: $newnames”
Output:
New list is: Canada India USA UK China
Notice how with lappend the name of a variable containing the list (names) is used
rather than the list itself ($names).
7. Arrays
Unlike arrays in many other languages, Tcl arrays are indexed by keywords. The
keywords can be easy to remember strings or integers. The values of the array elements
can also be strings or numbers. A Tcl array is created when you assign the first array
element:
Example 7.1
set myArray(foo) "bar"
puts $myArray(foo)
Output:
bar
The array command is used in Tcl to manipulate array data. In Example 7.2 we use the
array command to create an array from a so-called option-value list.
Example 7.2
array set fruitColors {tomato red banana yellow}
puts $fruitColors(tomato)
Output:
red
8. Strings
Most often, the task of extracting and manipulating information via a scripting language
is described using the term “string manipulation”. Strings are a set of alphanumeric
characters stored and manipulated together. These sets are concatenated, truncated, or
partitioned by the script with a specific end in mind.
All data items in Tcl, including numeric values, are treated as strings. They are treated
as other data types only as needed. This makes string manipulation and the associated
commands very important and frequently utilized.
There are a large number of string manipulation commands, as well as pattern and
regular expression matching. Example 8.1 contains some commonly used string
manipulation commands. For more in-depth explanations and a complete listing, please
refer to the Tcl manual.
Example 8.1
set str "This is Canada"
puts "The string is: $str"
puts "The length of the string is: [string length $str]"
puts "The character at index 3 is: [string index $str 3]"
puts "The characters from index 3 through end are: [string range
$str 3 end]"
puts "The index of the first occurrence of letter \"i\" is:
[string first i $str]“
Output:
This is Canada
The string is: This is Canada
The length of the string is: 14
The character at index 3 is: s
The characters from index 3 through end are: s is Canada
The index of the first occurrence of letter “I” is 2.
The open command is used to open a file. The syntax for this command is:
The access argument is used to indicate whether the file is read only (r), write only (w),
or read/write (w+), as well as other options. Example 9.1 illustrates how to open a write
only file and assign it to a variable. The open command returns a channel identifier
which is used by Tcl in the commands we will discuss later.
Example 9.1
set filename [open temp.txt “w”]
Output:
file4915610
In order to write data to the open file, the puts command is used. The syntax for the
puts command is
This command writes the characters given by string to the channel given by
channelId. ChannelId must be a channel identifier such as returned from the open
command. Also, the channel must have been opened for output (or writing). The puts
command also normally outputs a newline character after the string. Example 9.2 shows
how to open a write only file, add data to it, and then close the file.
Example 9.2
set filename [open "temp.txt" "w"]
puts $filename "We live in Canada."
puts $filename "Just Testing"
close $filename
Output: file4910020
The last option we will go over is how to read data from a file and assign it to variables.
This is done with the gets command. The syntax is
gets channelId
This command reads the next line from channelId and returns everything in the line up
to (but not including) the end-of-line character(s). Example 9.3 takes the file we wrote in
Example 9.2 and assigns each line to a variable.
Example 9.3
set filname [open "temp.txt" "r"]
set line1 [gets $filename]
set line2 [gets $filename]
close $filename
Output:
Line 1: We live in Canada.
Line 2: Just Testing
10. Procedures
Procedures in Tcl serve a similar purpose to functions in C. They can take arguments,
and can return values. The basic syntax for defining a procedure is:
Once a procedure is created, it is considered to be a command, just like any other built-
in Tcl command. As such, it may be called using its name, followed by a value for each
of its arguments. The return value from a procedure is equivalent to the result of a built-
in Tcl command. Thus, command substitution can be used to substitute the return value
of a procedure into another expression.
By default, the return value from a procedure is the result of the last command in its
body. However, to return another value, the return command may be used. If an
argument is given to the return command, then the value of this argument becomes
the result of the procedure. The return command may be used anywhere in the body
of the procedure, causing the procedure to exit immediately.
Example 10.1:
proc sum_proc {a b} {
return [expr $a + $b]
}
proc magnitude {num} {
if {$num > 0} {
return $num
}
set num [expr $num * (-1)]
return $num
}
set num1 12
set num2 14
set sum [sum_proc $num1 $num2]
puts "The sum is $sum"
puts "The magnitude of 3 is [magnitude 3]"
puts "The magnitude of -2 is [magnitude -2]"
Output:
The sum is 26
The magnitude of 3 is 3
The magnitude of -2 is 2
This example first creates two procedures, "sum_proc" and "magnitude". "sum_proc"
takes two arguments, and simply returns the value of their sum. "magnitude" returns
the absolute value of a number. After the procedure definitions, three global variables
are created. The last of these, "sum" is assigned the return value of the procedure
"sum_proc", called with the values of the variables "num1" and "num2" as arguments.
The "magnitude" procedure is then called twice, first with "3" as an argument, then with
"-2".
The "sum_proc" procedure uses the expr command to calculate the sum of its
arguments. The result of the expr command is substituted into the return statement,
making it the return value for the procedure.
11. Namespaces
Namespaces provide a means of organizing procedures and variables in Tcl. A
namespace basically creates a unique local scope. Within each unique scope, variables
and procedures created in that scope are isolated from both the global scope and from
other scopes. This allows the developer a means to segregate procedures and
variables in an organized manner. Namespaces can be nested, and procedures and
variables can be imported to, exported from, and referenced in other namespaces or the
global scope.
A global procedure acts just like any function within Tcl. A global procedure can be
called from a namespace without any need to import or otherwise localize the procedure.
A procedure within a namespace is local to the namespace unless it is explicitly called or
the procedure is exported from the namespace. The global scope is also designed such
that any variables defined outside of a procedure or a namespace are automatically in
the global scope. To access a global variable in a local scope, such as a procedure or
namespace, you will need to use the global command. As a script grows and as the
number of scripts running simultaneously increases, the ability of the developer to avoid
conflict between the names of procedures and variables defined in the global scope
decreases.
The namespace eval command lets you create new namespaces. For example,
proc bump {} {
variable num
incr num
}
}
creates a new namespace containing the variable num and the procedure bump. The
commands and variables in this namespace are separate from other commands and
variables in the same program. If there is a command named bump in the global
namespace, for example, it will be different from the command bump in the Counter
namespace.
Tk Basic Commands
In this section we will go over 4 basic Tk widgets that are used with Tcl. These are the
tk_getOpenFile, tk_getSaveFile, tk_chooseDirectory, and
tk_messageBox procedures. These procedures allow you to set the full file name and
directory paths to be used in your Tcl scripts.
1. tk_getOpenFile
The tk_getOpenFile pops up a dialog box for the user to select a file to open. The
tk_getOpenFile command is usually associated with the Open command in the File
menu. Its purpose is for the user to select an existing file only. If the user enters a non-
existent file, the dialog box gives the user an error prompt and requires the user to give
an alternative selection. This dialog box does not open a file, it simply returns the
filename so that it can be used in your script.
Example 1.1
tk_getOpenFile
This command creates the GUI in Figure 1 where you can select an existing file from a
dialog box:
Example 1..2
set filename [tk_getOpenFile]
puts $filename
Output:
C:/Documents and Settings/training/My Documents/autosave.mvw
This sets the value of the variable filename to be the full file name of the file selected in
the dialog box (as shown in the output above).
There are additional options that can be used with tk_getOpenFile. The format for
the tk_getOpenFile with options is:
The option presented below is the -filetypes option. There are additional options
available, please refer to the manual for these other options.
-filetypes filePatternList
If a filetypes listbox exists in the file dialog on the particular platform, this option gives the
filetypes in this listbox. When the user chooses a file type in the listbox, only the files of
that type are listed. If this option is unspecified, or if it is set to the empty list, or if the
filetypes listbox is not supported by the particular platform, then all files are listed
regardless of their types. Example 1.3 below shows how to set the filetypes list and use
it with the –filetypes option.
Examples 1.3
set types {
{{Text Files} {.txt} }
{{TCL Scripts} {.tcl} }
{{All Files} * }
}
set filename [tk_getOpenFile -filetypes $types]
In Figure 2 above, the available file types are set to Text Files, TCL Scripts, and All
Files. As a result of using the –filetypes option, only these file types are listed.
2. tk_getSaveFile
The procedure tk_getSaveFile pops up a dialog box for the user to select a file to
save. This command is usually associated with the Saveas command in the File menu.
If the user enters a file that already exists, the dialog box prompts the user for
confirmation whether the existing file should be overwritten or not. The dialog itself does
not write out the file; it only returns the file name for your script to use.
This procedure behaves the same way as the tk_getOpenFile procedure does. It
even has the same options available. Below the –title option is shown.
Exercise 2.1
set filename [tk_getSaveFile –title “Select a File”]
puts $filename
Output:
C:/Documents and Settings/training/My Documents/test.txt
Notice that the title of the dialog box in Figure 3 is “Select a File”.
3. tk_chooseDirectory
The procedure tk_chooseDirectory pops up a dialog box for the user to select a
directory. Example 3.1 shows how to set a directory name to a variable.
Example 3.1
set dirname [tk_chooseDirectory]
puts $dirname
Output:
C:/temp
4. tk_messageBox
The procedure tk_messageBox procedure creates and displays a message window
with an application-specified message, an icon, and a set of buttons. The buttons, icon,
and message are specified with the various options that are available. Please refer to
your manual for a complete listing of these options.
Example 3.1 illustrates the tk_messageBox command with the message option. This
option allows you to specify the message to be displayed in the message box.
Example 4.1
tk_messageBox -message "This is the message to be displayed"
Output:
Chapter 2
HyperMesh Process
Automation Introduction
Practical Exercises
Exercise 2a
Description
Add the following pull down menus:
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.
Chapter 3
Create a load collector named forces. A card image does not need to be
specified for the collector.
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.
Step 4: Extract commands from the command file and add them
to your TCL file
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. 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.
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.
Hints
Do all the steps in HyperMesh and extract the appropriate commands
from the command.tcl file.
Chapter 4
1. Open HyperMesh.
2. Go to the View menu and select Command Window.
Step 3: Run HyperMesh Tcl and core Tcl commands from the
Command Window
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:
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:
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.
In the Command Window the value of 390 is returned, which is the number of
elements in the component collector upper.
puts $numElems
Again the value returned is 390 which is the number of elements in the
component collector upper.
HyperMesh commands:
*createmark
*clearmark
hm_getfloat
1. Open HyperMesh.
2. From File > Open > Model, select the file c_channel-tcl_vector.hm
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.
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.
*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
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.
2. Substitute the hard coded force magnitude with the variable mag_val.
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.
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
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
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.
hm_getstring *collectorcreateonly
*createmarkpanel *movemark
*clearmark *createvector
hm_getfloat *translatemark
set
Hints
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
*createmark hm_getmark
hm_nodelist
for foreach
list lappend
set incr
if elseif
else
Hints
The majority of this assignment will be discovering where to find information
about commands and how to apply the information you find. Be patient and use
the resources available to you, including the HyperWorks online help.
Chapter 5
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.
*clearmark loads 1
*createmarkpanel loads 1 “Select forces for resultant”
2. Retrieve loads from the buffer (mark) and create a list variable.
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
}
set xsum 0
set ysum 0
set zsum 0
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.
if { [llength $loads_list] == 0 } {
hm_errormessage "No loads selected"
return
}
set xsum 0
set ysum 0
set zsum 0
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
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.
*createmarkpanel
hm_getfloat
hm_getmark
hm_getentityvalue
*createvector
*translatemark
*clearmark
set
Hints
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.
*createmark *createvector
*translatemark *createnode
*createelement *collectorcreate
*currentcollector hm_getmark
hm_nodelist hm_entityinfo
hm_getentityvalue
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?
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.
*createmarkpanel *createnode
*clearmark *hm_nodelist
hm_getmark *systemcreate
hm_entityinfo
set for
foreach eval
lindex llength
Hints
Chapter 6
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 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]
After the 4 lines created in step 4, add an additional line which prints the
parameter values to the Command Window.
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
extract_mat 1
extract_mat 1
to
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
The following HyperMesh commands are added and modified in this exercise:
*createentity
*setvalue
*createmark
hm_getmark
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.
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.
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 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”
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
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
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
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
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?
Hints
Do the steps in HyperMesh and then extract the commands from the
command.cmf file.
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.
Hints
Remember to user a \ before referencing $E, etc in the
hm_getentityvalue command.
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
set i 1
CHAPTER 5
Exercise 5a
proc translatecomps { } {
translatecomps
Exercise 5b
hm_markclear all 1
set i 1
# 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 } {
# creates a list with a name SList_1, SList_2, etc for each element
# with their nodes and centroid coord
hm_markclear elements 1
# hm_markclear nodes 1
# hm_markclear vector 1
}
# puts $LongList
Exercise 5c
#######################################################################
##############################
##### Solution to Practical Exercise 5c
#####
#######################################################################
##############################
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
### Create a new system with the origin at the node at the
element centroid, and oriented by the x axis and
### xy plane
CHAPTER 6
Exercise 6a
Exercise 6b