HM_Customization_v13.pdf

Share Embed Donate


Short Description

Download HM_Customization_v13.pdf...

Description

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

[email protected]

Brazil

55.11.3884.0414

[email protected]

Canada

416.447.6463

[email protected]

China

86.400.619.6186

[email protected]

France

33.1.4133.0992

[email protected]

Germany

49.7031.6208.22

[email protected]

India

91.80. 6629.4500 1.800.425.0234 (toll free)

[email protected]

Italy

39.800.905.595

[email protected]

Japan

81.3.5396.2881

[email protected]

Korea

82.70.4050.9200

[email protected]

Mexico

55.56.58.68.08

[email protected]

New Zealand

64.9.413.7981

[email protected]

North America

248.614.2425

[email protected]

Scandinavia

46.46.460.2828

[email protected]

United Kingdom

01926.468.600

[email protected]

In addition, the following countries have resellers for Altair Engineering: Colombia, Czech Republic, Ecuador, Israel, Russia, Netherlands, Turkey, Poland, Singapore, Vietnam, Indonesia Official offices with resellers: Canada, China, France, Germany, India, Malaysia, Italy, Japan, Korea, Spain, Taiwan, United Kingdom, USA Copyright© Altair Engineering Inc. All Rights Reserved for: HyperMesh® 1990-2014; HyperCrash® 2001-2014; OptiStruct® 1996-2014; RADIOSS®1986-2014; HyperView®1999-2014; HyperView Player® 2001-2014; HyperStudy® 1999-2014; HyperGraph®1995-2014; MotionView® 1993-2014; MotionSolve® 20022014; HyperForm® 1998-2014; HyperXtrude® 1999-2014; Process Manager™ 2003-2014; Templex™ 1990-2014; TextView™ 1996-2014; MediaView™ 1999-2014; TableView™ 2013-2014; BatchMesher™ 2003-2014; HyperMath® 2007-2014; Manufacturing Solutions™ 2005-2014; HyperWeld® 2009-2014; HyperMold® 2009-2014; solidThinking® 1993-2014; solidThinking Inspire® 2009-2014; solidThinking Evolve®™ 1993-2014; Durability Director™ 2009-2014; Suspension Director™ 2009-2014; AcuSolve® 1997-2014; AcuConsole® 2006-2014; SimLab®™2004-2014 and Virtual Wind Tunnel™ 2012-2014. In addition to HyperWorks® trademarks noted above, Display Manager™, Simulation Manager™, Compute Manager™, PBS™, PBSWorks™, PBS GridWorks®, PBS Professional®, PBS Analytics™, PBS Desktop™, PBS Portal™, PBS Application Services™, e-BioChem™, e-Compute™ and e-Render™ are trademarks of ALTAIR ENGINEERING INC. Altair trademarks are protected under U.S. and international laws and treaties. Copyright© 1994-2014. Additionally, Altair software is protected under patent #6,859,792 and other patents pending. All other marks are the property of their respective owners. ALTAIR ENGINEERING INC. Proprietary and Confidential. Contains Trade Secret Information. Not for use or disclosure outside of ALTAIR and its licensed clients. Information contained inHyperWorks® shall not be decompiled, disassembled, or “unlocked”, reverse translated, reverse engineered, or publicly displayed or publicly performed in any manner. Usage of the software is only as explicitly permitted in the end user software license agreement. Copyright notice does not imply publication

Table of Contents

Introduction to HyperMesh Customization Chapter 1: Introduction to TCL ......................................................................... 5 About TCL .................................................................................................................................. 5 About Tk ..................................................................................................................................... 6 Basic Tcl Syntax ........................................................................................................................ 6 TCL Command Overview ......................................................................................................... 6 Tk Basic Commands ............................................................................................................... 21

Chapter 2: HyperMesh Process Automation Introduction ........................... 27 What is a HyperMesh Macro ................................................................................................. 27 The HyperMesh Utility Menu ................................................................................................. 28 Practical Exercises .................................................................................................................. 33

Chapter 3: HyperMesh Automation with HyperMesh Macros ....................... 35 HyperMesh Commands ............................................................................................... 35 HyperMesh Macro Structure ........................................................................................ 39 Process to Create HyperMesh Macros ........................................................................ 40

HyperWorks 13.0

Introduction to HM Customization 3 Proprietary Information of Altair Engineering, Inc

Modifying Commands to Create Generalized Macros ................................................. 44 Practical Exercises ....................................................................................................... 46

Chapter 4: Using Tcl to Control the HyperMesh Session ............................ 47 HyperMesh Commands vs. Tcl Modify Commands ..................................................... 47 Tcl GUI Commands and Tcl Query Commands .......................................................... 48 Using the Command Window ...................................................................................... 50 Process to Create a Tcl HyperMesh Macro ................................................................. 55 Practical Exercises ....................................................................................................... 60

Chapter 5: Retrieving Data from HyperMesh Entities .................................. 63 HyperMesh Entities and Their Data Names ................................................................. 63 Pointers and Flags ....................................................................................................... 65 Process for Creating a HyperMesh Tcl Script to Retrieve Data on HyperMesh Entities ...................................................................................... 67 Practical Exercises ....................................................................................................... 71

Chapter 6: Interfacing with HyperMesh Solver Templates .......................... 75 Solver Attributes and Card Images .............................................................................. 76 Querying Solver Attributes ........................................................................................... 77 Assigning Data to Solver Attributes ............................................................................. 81 Creating a Reusable and Modular Procedure .............................................................. 82 Updating Solver Attributes ........................................................................................... 88 Practical Exercises ....................................................................................................... 91

Solutions For Exercises ................................................................................... 93

Introduction to HM Customization 4 Proprietary Information of Altair Engineering, Inc

HyperWorks 13.0

Chapter 1: Introduction to Tcl/Tk

Chapter 1

Introduction to Tcl/Tk About TCL Tcl (Tool Command Language) is used by developers worldwide and has become a critical component in thousands of corporations. It has a simple and programmable syntax and can be either used as a standalone application or embedded in application programs. Best of all, Tcl is open source so it's completely free. The main difference between Tcl and languages such as C is that Tcl is an interpreted rather than a compiled language. Tcl programs are simply scripts consisting of Tcl commands that are processed by a Tcl interpreter at run time. One advantage that this offers is that Tcl programs can themselves generate Tcl scripts that can be evaluated at a later time. This can be useful, for example, when creating a graphical user interface with a command button that needs to perform different actions at different times. One of Tcl's most useful features is its extensibility. If an application requires some functionality not offered by standard Tcl, new Tcl commands can be implemented using the C language, and integrated fairly easily. Since Tcl is so easy to extend, many people have written extension packages for some common tasks, and made these freely available on the Internet. Businesses and engineering teams today are often faced with the problem of making diverse collections of resources work together. We call these programming tasks integration applications. For enterprises, the integration platform is becoming as strategically important as the operating system and database platforms. Tcl is the integration platform of choice because of its speed of use, breadth of functionality, and enterprise-ready features such as thread-safety, internationalization and cross platform deployment. The latest version of Tcl provides all the features an enterprise needs for all integration and scripting needs.

HyperWorks 13.0

Introduction to 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 lighterweight 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 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 1: Introduction to Tcl/Tk

If the string is more than one word, the string must be enclosed in either double quotes (“ “) or braces ({ }). Many commands, including the puts command, accept multiple arguments. If the string is not enclosed in quotes or braces, the individual words are considered arguments. A set of words enclosed in quotes or braces will treated as a single unit. The two options of quotes or braces behave differently and the differences will be discussed in the next section. Example 1.2 puts “This is an example with quotes” puts {This is an example with braces} Output: This is an example with quotes This is an example with braces As mentioned above, a command in Tcl is terminated with a newline or semicolon. Tcl comments are designated with a # at the beginning of the line or after a semicolon. Example 1.3 # An example using a semicolon puts “This is line 1”; puts {This is line 2};#Note after the ; Output: This is line 1 This is line 2

2. Variables and Variable Substitution Unlike C, Tcl does not require that variables be declared before they are used. Tcl variables are simply created when they are first assigned values. Values are assigned using the set command. Although they do not have to be deleted, Tcl variables can be deleted using the unset command. The value stored in a variable can be accessed by prefacing the name of the variable with a dollar sign ("$"). This is known as variable substitution, and is illustrated in the examples below. A variable can be used to store a number, a date, a string, or even another Tcl script. Example 2.1: set software "HyperWorks" puts "The software we are using is $software" Output: The software we are using is HyperWorks

HyperWorks 13.0

Introduction to 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 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 1: Introduction to Tcl/Tk

puts $date Output: 2:3:09 Here variable substitution is used in several places: The values of the variables "month", "day", and "year" are substituted in the set command that assigns the value of the "date" variable, and the value of the "date" variable is then substituted in the line that displays the output. Example 2.5: set foo "puts hi" eval $foo Output: hi In this example, the variable "foo" holds another (small) Tcl script that simply prints the word "hi". The value of the variable "foo" is substituted into an eval command. The eval command takes one or more arguments which together comprise a Tcl script and passes it to the Tcl interpreter.

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

• •

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

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

Introduction to 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 acos asin atan atan2 ceil cos

cosh double exp floor fmod hypot int

log log10 pow rand round sin sinh

sqrt srand tan tanh wide

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

Introduction to HM Customization 10 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 1: Introduction to Tcl/Tk

Example 3.4: expr sin(2) Output: 0.909297 This example shows that the expr statement can be used to evaluate the result of a mathematical function, in this case, the sine of an angle.

4. Command Substitution Just as variable substitution is used to substitute the value of a variable into a Tcl script, command substitution can be used to replace a Tcl command with the result that it returns. Consider the following example: Example 4.1: puts "I am [expr 10*2] years old, and my I.Q. is [expr 100 - 25]" Output: I am 20 years old, and my I.Q. is 75 As this example shows, square brackets are used to achieve command substitution. The text between the square brackets is evaluated as a Tcl script, and its result is then substituted in its place. In this case, command substitution is used to place the results of two mathematical expressions into a string. Command substitution is often used in conjunction with variable substitution, as shown in Example 4.2: Example 4.2: set my_height 6.0 puts "If I was 2 inches taller, I would be [expr $my_height + (2.0 / 12.0)] feet tall" Output: If I was 2 inches taller, I would be 6.16667 feet tall In this example, the value of the variable "my_height" is substituted inside the square brackets before the command is evaluated. This is a good illustration of Tcl's one-pass recursive parsing mechanism. When evaluating a statement, the Tcl interpreter, makes one pass over it, and in doing so makes all the necessary substitutions. Once this is done, the interpreter then evaluates the resulting expression. If, during its pass over the expression, the interpreter encounters square brackets (indicating that command substitution is to be performed), it recursively parses the script inside the square brackets in the same manner.

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

HyperWorks 13.0

Introduction to 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 4 {puts "It could 6 {puts "It could 8 {puts "It could default {puts "It }

be a human."} be a cow."} be an ant."} be a spider."} could be anything."}

Output: It could be a cow.

Introduction to HM Customization 12 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 1: Introduction to Tcl/Tk

The switch statement has two general forms (both of which are described in detail in the manual page), but the form used here is as follows: switch ?options? string {pattern body ?pattern body ...?} The string argument is compared to each of the patterns and if a comparison succeeds, the corresponding body is executed, after which the switch statement returns. The pattern "default", if present, is always matched, and thus its body always executed if none of the earlier comparisons succeed. It is often useful to execute parts of a program repeatedly, until some condition is met. In order to facilitate this, Tcl offers three looping constructs: the while, for, and foreach statements, each of which is shown in the examples below. Example 5.3: for {set i 0} {$i < 5} {incr i 1} { puts "In the for loop, and i == $i" } Output: In the for loop, and i == 0 In the for loop, and i == 1 In the for loop, and i == 2 In the for loop, and i == 3 In the for loop, and i == 4 The general syntax for the for loop is as follows: for init test reinit body The init argument is a Tcl script that initializes a looping variable. In the for loop used in Example 5.3, the looping variable was called "i", and the init argument simply set it to 0. The test argument is a Tcl script which will be evaluated to decide whether or not to enter the body of the for loop. Each time this script evaluates to a true value, the body of the loop is executed. The first time this script evaluates to false, the loop terminates. The reinit argument specifies a script that will be called after each time the body is executed. In Example 5.3, the reinit script increments the value of the looping variable, "i" using the incr command. Thus, the for loop in this example executes its body 5 times, before its test script evaluates to false, causing the loop to terminate. Example 5.4: set i 0 while {$i < 5} { puts "In the while loop, and i == $i" incr i 1 } HyperWorks 13.0

Introduction to 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 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 1: Introduction to Tcl/Tk

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

6. Lists Lists in Tcl provide a simple means by which to group collections of items, and deal with the collection as a single entity. When needed, the single items in the group can be accessed individually. Lists are represented in Tcl as strings with a specified format. As such, they can be used in any place where strings are normally allowed. The elements of a list are also strings, and therefore any form of data that can be represented by a string can be included in a list (allowing lists to be nested within one another). Lists can be created in the following ways, in addition to being represented by a string. by setting a variable to be a list of values set lst {{item 1} {item 2} {item 3}} with the split command set lst [split "item 1.item 2.item 3" "."] with the list command set lst [list "item 1" "item 2" "item 3"] An individual list member can be accessed with the lindex command. The following examples will illustrate many important list commands: Example 6.1: set simple_list “John Joe Mary Susan” puts [lindex $simple_list 0] puts [lindex $simple_list 2] Output: John Mary Example 6.1 creates a simple list of four elements, each of which consists of one word. The lindex command is then used to extract two of the elements in the list: the 0th element and the 2nd element. Note that list indexing is zero-based. It is also important to see that the lindex command, along with most other list commands, takes an actual list as its first argument, not the name of a variable containing a list. Thus the value of the variable "simple_list" is substitued into the lindex command. The items in a list can be iterated through using the foreach command: foreach varName list body As mentioned previously, the foreach command will execute the body code one time for each list item in list. On each pass, varName will contain the value of the next list item.

HyperWorks 13.0

Introduction to 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 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

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 indepth explanations and a complete listing, please refer to the Tcl manual.

HyperWorks 13.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 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

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 builtin 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 builtin Tcl command. Thus, command substitution can be used to substitute the return value of a procedure into another expression. By default, the return value from a procedure is the result of the last command in its body. However, to return another value, the return command may be used. If an argument is given to the return command, then the value of this argument becomes the result of the procedure. The return command may be used anywhere in the body of the procedure, causing the procedure to exit immediately. Example 10.1: proc sum_proc {a b} { return [expr $a + $b] } proc magnitude {num} { if {$num > 0} { return $num } set num [expr $num * (-1)] return $num } set num1 12 set num2 14 set sum [sum_proc $num1 $num2] puts "The sum is $sum" puts "The magnitude of 3 is [magnitude 3]" puts "The magnitude of -2 is [magnitude -2]" Output: The sum is 26 The magnitude of 3 is 3 The magnitude of -2 is 2

HyperWorks 13.0

Introduction to 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 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

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 nonexistent file, the dialog box gives the user an error prompt and requires the user to give an alternative selection. This dialog box does not open a file, it simply returns the filename so that it can be used in your script. Example 1.1 tk_getOpenFile This command creates the GUI in Figure 1 where you can select an existing file from a dialog box:

HyperWorks 13.0

Introduction to 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 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 1: Introduction to Tcl/Tk

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

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

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

2. tk_getSaveFile The procedure tk_getSaveFile pops up a dialog box for the user to select a file to save. This command is usually associated with the Saveas command in the File menu. If the user enters a file that already exists, the dialog box prompts the user for confirmation whether the existing file should be overwritten or not. The dialog itself does not write out the file; it only returns the file name for your script to use. This procedure behaves the same way as the tk_getOpenFile procedure does. It even has the same options available. Below the –title option is shown. Exercise 2.1 set filename [tk_getSaveFile –title “Select a File”] puts $filename Output: C:/Documents and Settings/training/My Documents/test.txt

HyperWorks 13.0

Introduction to 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 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 1: Introduction to Tcl/Tk

Figure 4: GUI from tk_chooseDirectory command.

4. tk_messageBox The procedure tk_messageBox procedure creates and displays a message window with an application-specified message, an icon, and a set of buttons. The buttons, icon, and message are specified with the various options that are available. Please refer to your manual for a complete listing of these options. Example 3.1 illustrates the tk_messageBox command with the message option. This option allows you to specify the message to be displayed in the message box. Example 4.1 tk_messageBox -message "This is the message to be displayed" Output:

Figure 5: GUI from tk_messageBox command.

HyperWorks 13.0

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

Chapter 1: Introduction to Tcl/Tk

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

HyperWorks 13.0

Chapter 2: HyperMesh Process Automation Introduction

Chapter 2

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

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

The macro page it is displayed on Its label Its location and size

HyperWorks 13.0

Introduction to HM Customization 27 Proprietary Information of Altair Engineering, Inc

Chapter 2: HyperMesh Process Automation Introduction

• •

Its help message The macro it calls, and any optional arguments

F !

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

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

The HyperMesh Utility Menu The Utility menu allows you to customize the standard interface to include function buttons, radio options, and text that have HyperMesh-supplied and userdefined macros associated with them. The Utility menu is located on a tab of the Tab area pane(s), and can be shown or hidden from within the View > Browsers > HyperMesh pull-down menu. The Utility menu includes several pages of its own, each dedicated to different tasks. Thus it presents groups of functionalities accessible from a set of pages contained by the Utility tab, although only one set of functions is displayed at a time. Each page is associated with a button at the bottom of the Utility menu; clicking one of these buttons accesses the page associated with it. A macro file (hm.mac) controls the display and available operations of the Utility Menu. Attributes that you can change include: • • • • •

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

When HyperMesh starts, it looks for a macro file named hm.mac in the current directory, HOME directory (UNIX only), or the application’s base directory. If it finds this file, HyperMesh runs it automatically to define the attributes and contents of the Utility Menu. The default hm.mac file sources the following additional macro files: disppage.mac

Populates the Display page of the Utility Menu

Introduction to HM Customization 28 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 2: HyperMesh Process Automation Introduction

geommeshpage.mac globalpage.mac qamodelpage.mac userpage.mac

Populates the Geom/Mesh page of the Utility Menu Creates the button group that allows you to switch pages Populates the QA/Model page of the Utility Menu Populates the User page of the Utility Menu

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

HyperMesh Utility Menu Commands HyperMesh macro commands reside in the default hm.mac file. When you open this file, you will see that it defines the Utility menu contents in order by page. To change a macro on a given page, find that page in the hm.mac file and the macro name that you wish to modify. Attributes you can change on a macro page include: • Buttons to display on that macro page • The location and size of the buttons appearing on a macro page • The label for each button • The help string displayed in the bubble as the mouse is hovered over the button. • The macro called by each button, with optional arguments to pass HyperMesh macros consist of valid command file or templex commands, and are enclosed by the *beginmacro(macroname) and *endmacro() commands. Macros may accept data passed to them using the arguments $1, $2, etc. Each argument specifies where the values should be substituted. The *callmacro() command allows you to call a macro from within another one, which allows you to create groups of standard reusable macros. The following skeleton shows the format of a macro: *beginmacro(macroname) macro command statements go here *endmacro() HyperWorks 13.0

Introduction to HM Customization 29 Proprietary Information of Altair Engineering, Inc

Chapter 2: HyperMesh Process Automation Introduction

In the next Chapter we will go over HyperMesh macros in more detail. Here we will focus on how to add a button to the Utility menu. To activate the macro from HyperMesh, you must create a button on the Utility menu to invoke the macro. Use the *createbutton() command to define the button and its characteristics. The syntax for this command is: *createbutton(page, name, row, column, width, COLOR, helpString, macroName [ , arg1 …]) Where: page:

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

Row 1 Column 0 Figure: Row and Column Designations

Introduction to HM Customization 30 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 2: HyperMesh Process Automation Introduction

Below are two examples on how to create a button. The first example illustrates the button calls needed for a user-created HyperMesh macro: *createbutton(5, “Create force”, -1, 0, 10, GREEN, “Create force on selected nodes”, “createForce_macro”)

F

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

The second example shows the button calls for a user created Tcl script using the “EvalTcl” command: *createbutton(5, “Create force”, -1, 0, 10, GREEN, “Create force on selected nodes”, “EvalTcl”, “create_force.tcl”) For each example, 5 refers to the Userpage, “Create force” is the text on the button, -1 refers to the row position, 0 is the column number, 10 is the column width, GREEN is the color of the button, and “Create force on selected nodes” is the help string. For the HyperMesh macro example, “createForce_macro” is the name of the macro to be evaluated. In the Tcl script example, “EvalTcl” needs to be entered before “create_force.tcl” which is the name of the Tcl file. Notice that the full path for create_force.tcl isn’t given. A full path can be specified if the file isn’t located in one of the predefined paths that HyperMesh searches to find scripts. These paths include installation paths as well as the working directory. Users can add additional search paths using the TCL_INCLUDE environment variable. Relative paths can also be used from these search paths.

F

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

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

Introduction to HM Customization 31 Proprietary Information of Altair Engineering, Inc

Chapter 2: HyperMesh Process Automation Introduction

the navigation area you will find another book named Scripts. This contains all the commands and functions used in HyperMesh.

Figure: Reference Guide in HyperMesh and BatchMesher Online Help

Introduction to HM Customization 32 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 2: HyperMesh Process Automation Introduction

Practical Exercises Exercise 2a Description Add a button to the User Page on the Utility Menu that executes the macro modeltour.tcl. This macro is located in the installation under hm\scripts, so a path is not needed. The name of the button should be “Model Tour”. The help string should be “Explore HyperMesh Session”. The color and location are up to you. HyperMesh commands used *createbutton() TCL/TK commands used none Hints On Windows, the working directory is located in the My Documents folder. Create a new text file called userpage.mac in this location and add the appropriate commands to make the button evaluate the tcl file.

HyperWorks 13.0

Introduction to HM Customization 33 Proprietary Information of Altair Engineering, Inc

Chapter 2: HyperMesh Process Automation Introduction

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

HyperWorks 13.0

Chapter 3: HyperMesh Automation with HyperMesh Macros

Chapter 3

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

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

Command Files During each HyperMesh session, HyperMesh generates a command file named command.cmf. If this file doesn't already exist, then HyperMesh creates it at the start of a session. If the file does already exist, HyperMesh adds the commands for the new session to the end of the original file. HyperMesh command files are standard ASCII files that HyperMesh can read or write. Command files allow you to program a series of procedures or, in the case of a power failure or other unexpected system loss, retrieve an earlier work session. You can use command files in applications that rely on repetitive or iterative steps, or to create demonstrations. Command files follow this syntax: • A command begins with an asterisk (*). • A command ends with the left parenthesis. HyperWorks 13.0

Introduction to HM Customization 35 Proprietary Information of Altair Engineering, Inc

Chapter 3: HyperMesh Automation with HyperMesh Macros



The parameters for a command are separated by commas, ending with the right parenthesis.

The following command illustrates the command syntax. The shrink command is: *shrink(.2) The command name that HyperMesh reads is located between the asterisk and the left parenthesis; in this case, it is the word shrink. The command has one parameter, .2, which is the factor that HyperMesh shrinks the elements (in this example, the elements shrink by 20%, leaving open gaps between them). Commands executed in an active HyperMesh session are not immediately written to the command files. They are stored in memory and are written to the command file during idle time (when HyperMesh is not busy performing user operations).

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

Marks Marks specify groups of entities that are transferred to the command processor. Marks can be created for most entities, and commands are then issued to perform operations on the entities on the mark. HyperMesh allows for two standard marks and a user mark. Standard marks are referenced by the mark IDs 1 and 2. The following example demonstrates how to delete elements using standard marks; assume that you want to delete the elements 50, 51, and 52 from a database. To perform this operation, you must create a mark with these elements and then instruct HyperMesh to delete the mark: *createmark(elements, 1) 50 51 52 *deletemark(elements, 1) This *createmark command populates mark 1 with elements 50, 51, and 52. The *deletemark command deletes the elements contained on mark 1.

Introduction to HM Customization 36 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 3: HyperMesh Automation with HyperMesh Macros

Notice after the *createmark command there are a series of numbers which correspond to the element ids which were added to the mark. These ids will not be consistent from model to model. In order to make a macro useful for multiple models, we can change the selection method. Several options exist to make the *createmark command general enough to work with any model. For example, to select all the currently displayed elements in the model use the command *createmark(elements,1)"by displayed". A mark can also be appended using the *appendmark() command. Imagine from the previous example, we want to delete elements 50, 51, and 52 as well as all the elements adjacent to those elements. To do this, the commands would be as follows: *createmark(elements, 1) 50 51 52 *appendmark(elements, 1) “by adjacent” *deletemark(elements, 1) Another option is to replace the *createmark command with *createmarkpanel. When executed, this command presents the user with a selection panel in the entity specified in the command can be selected.

Planes and Vectors At times, it is necessary to define a vector or plane for a command. HyperMesh allocates two vectors and two planes with the IDs 1 and 2. The vectors and planes can be defined at any time during the processing of a command file or Tcl script. The following example translates node 10 along the x axis by 5 units: *createvector(1, 1.0, 0.0, 0.0) *createmark(nodes, 1) 10 *translatemark(nodes, 1, 1, 5.0) In this case, vector 1 is loaded with the components (1.0,0.0,0.0) that define the global x-axis. Node mark 1 is populated with node 10. These are then passed to the *translatemark command to perform the action. Additionally, a normal and base point are required to define a plane. The next example reflects all displayed elements about a plane that has a normal along the x axis and a base point of (5.0,0.0,0.0): *createplane(1, 1.0, 0.0, 0.0, 5.0, 0.0, 0.0) *createmark(elements, 1) “displayed” *reflectmark(elements, 1, 1) HyperWorks 13.0

Introduction to HM Customization 37 Proprietary Information of Altair Engineering, Inc

Chapter 3: HyperMesh Automation with HyperMesh Macros

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

Common Command File Commands Below is a table with many common command file commands as well as a description of the command. Command Name *appendmark() *beginmacro(name) *callmacro() *createbutton() *createbuttongroup() *createlistpanel()

Description Add additional entities to a mark Start the definition of a Utility Menu macro Call a macro from within another macro Add a button to the Utility Menu Add a button group to the Utility Menu Allow you to interactively select a list of entities Place the entities from the last operation into a *createmarklast() mark *createmarkpanel() Allow you to interactively select entities *createtext() Add text to the Utility Menu End the definition of a macro started with the *endmacro() beginmacro command *enterpanel() Enter the passed HyperMesh panel *includemacrofile() Include the contents of the passed macro file *insertbutton() Insert a button into the Utility Menu *inserttext() Insert text into the Utility Menu *setactivegroup() Set the default selection for a button group *setactivepage() Set the current displayed Utility Menu page Set the color for the Utility Menu button group’s *setbuttongroupactivecolor() current selection indicator For a complete listing of command file commands, please refer to the online help. In the Scripts book under the Reference Guide, there is a topic for Commands and Functions. In this book you will find a complete listing of all the commands available in HyperMesh.

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

HyperWorks 13.0

Chapter 3: HyperMesh Automation with HyperMesh Macros

HyperWorks 13.0

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

Chapter 3: HyperMesh Automation with HyperMesh Macros

HyperMesh Macro Structure As mentioned in the previous chapter, the HyperMesh macro consists of valid command file or templex commands. These commands are enclosed by the *beginmacro() and *endmacro() commands. The following skeleton shows the format of a macro. *beginmacro(macroName) [commands] *endmacro() Macros may accept data passed to them using the arguments $1, $2, etc. Each argument specifies where the values should be substituted. Below is an example to turn on/off all geometry. *beginmacro(ToggleGeom_macro) *displaycollectorwithfilter(comps,$1,””,0,1) *plot() *endmacro() By specifying “none” for $1 in the *createbutton command, the argument is passed to the macro so that all geometry is turned off. The *createbutton command is shown below: *createbutton(5, “Turn off all geometry”, -1, 0, 10, GREEN, “Turn off the display of all geometry”, “ToggleGeom_macro”, “none”)

Process to Create HyperMesh Macros The following is a process to assist you in creating HyperMesh macros. While this procedure does not have to be followed, it is strongly recommended that you follow this procedure as it has been found to be an effective way to create HyperMesh macros. 1. Define the task to be automated. 2. Delete the existing command.cmf file. This file is located in either the start-in directory or the current working directory. 3. Perform the operations in HyperMesh that the script should run. 4. Extract the commands from the command.cmf file. 5. Add the commands to the userpage.mac file. 6. Modify the commands as necessary and add macro wrapper commands *beginmacro and *endmacro. 7. Add the macro button using the *createbutton command that will call the new macro defined in Step 6. Introduction to HM Customization 40 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 3: HyperMesh Automation with HyperMesh Macros

8. Reload the current .mac file into HyperMesh to load the modified userpage.mac. 9. Test the macro.

Example 3.1: Automate Creating a Load Collector The purpose of this example is to become familiar with the general process for creating a HyperMesh macro. This example will use the process described above for creating a HyperMesh macro.

Step 1: Define the task to be automated Create a load collector named forces. A card image does not need to be specified for the collector.

Step 2: Delete the existing command.cmf file Every command executed in HyperMesh is recorded in the command.cmf file. To view only the tasks commands, it is suggested that you delete the command.cmf file before doing the task. After deleting this file, the file is automatically recreated when more commands are executed in HyperMesh. The command.cmf file is located in the My Documents folder on Windows.

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

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

Introduction to HM Customization 41 Proprietary Information of Altair Engineering, Inc

Chapter 3: HyperMesh Automation with HyperMesh Macros

1. From your HyperMesh working directory, open the command.cmf file. 2. Locate the command *collectorcreateonly() at or near the end of the file. You should see a line similar to the following: *collectorcreateonly(loadcols, “forces”, “”,7) This command creates a load collector named “forces” and because the above command as a color id of 7, it has a color of light blue. 3. Copy the *collectorcreateonly() line. 4. From your HyperMesh working directory, open the userpage.mac file. If this file does not already exist, create an empty text file named userpage.mac 5. In the userpage.mac file, on the next blank line from the top, paste the copied line. 6. Save the userpage.mac file.

Step 5: Modify the commands in the userpage.mac file as necessary Do not modify the *collectorcreateonly() command as it does not need to be modified for this example.

Step 6: Add macro wrapper commands Add the *beginmacro() and *endmacro() commands to create the macro as shown below: *beginmacro(macroCreate_LoadCol) *collectorcreateonly(loadcols, “forces”, “”, 7) *endmacro() Note: “macroCreate_LoadCol” is the macro’s name. It links the macro to its button, which you will create in the next step, via the macro name field in the *createbutton() line.

Step 7: Create a button and label for the macro on the Utility menu’s User page Create an activation button in the Utility Menu to execute the macro. Place the button on page 5 (User) of the Utility Menu as that page is dedicated to userdefined macros.

Introduction to HM Customization 42 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 3: HyperMesh Automation with HyperMesh Macros

1. In the userpage.mac file, add the following line at the beginning of the file to create a green button called Create Load Col. Note that the *createbutton command should all be on a single line. It is shown on two lines below simply due to space limitations. *createbutton(5, “Create Load Col”, -1, 0, 10, GREEN, “Create a load collector”, “macroCreate_LoadCol”) 2. Create a label for the button using the *createtext() command as shown below. Add this below the *createbutton command. *createtext(5, “Collectors:”, -1, 0)

Step 8: Save the userpage.mac file The userpage.mac file should look like the following: *createbutton(5, “Create Load Col”, -1, 0, 10, GREEN, “Create a load collector”, “macroCreate_LoadCol”) *createtext(5, “Collectors:”, -1, 0) *beginmacro(macroCreate_LoadCol) *collectorcreateonly(loadcols,"forces","",5) *endmacro() Save the userpage.mac file.

Step 9: Load the userpage.mac file into the current HyperMesh session The userpage.mac file can be loaded into the current HyperMesh session in a couple of different ways. By changing the User Profile, the userpage.mac file gets reloaded. While this method works, if you don’t want to change the User Profile, another method is to either reload the hm.mac file or simply close and reopen HyperMesh. 1. Close HyperMesh and reopen HyperMesh. OR load a different user profile.

Step 10: Test the macro 1. Click on the Utility tab in the tab area and select the User page. Notice the Create Load Col button and the Collectors: label on the User page. HyperWorks 13.0

Introduction to HM Customization 43 Proprietary Information of Altair Engineering, Inc

Chapter 3: HyperMesh Automation with HyperMesh Macros

2. Click the Create Load Col button. 3. Notice in the status bar that the message “The collector was created” appears. 4. Click on the Model tab to view the Model Browser. 5. Notice how there is now a LoadCollectors folder with a single load collector called forces inside of it.

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

Modifying Commands to Create Generalized Macros As mentioned above, simply copying commands from the command.cmf can result in macros that are too restrictive. In order to generalize the macros so that they can be used on multiple models, the *createmark() command will need to be modified. Let’s examine the *createmark() command. This command places entities on a mark (which is a storage buffer). For each entity type there are two marks available, 1 and 2. Once on a mark these entities can be passed to other commands. When the command using the mark is executed, the changes apply to all entities in the mark. When HyperMesh writes the *createmark() command to the command.cmf file, it operates on entity ids making it very restrictive. Even if a selection method such as “displayed” is used, entity ids are listed in the command.cmf file. As a result, we need to modify the command so that it is less restrictive. We can do this by either replacing the entity ids with a selection option (such as “all”, “displayed”, “on plane”, etc) or by replacing the *createmark() command with Introduction to HM Customization 44 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 3: HyperMesh Automation with HyperMesh Macros

the *createmarkpanel() command. The *createmarkpanel() command allows users to interactively select the entities. First let’s look at the first option of modifying the *createmark() command. The syntax for the *createmark() command is: *createmark(entity_type, mark_id) ?options? ?list? entity_type mark_id ?options?

?list?

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

Example: To delete the displayed elements: *createmark(elements, 1) “displayed” *deletemark(elements, 1) The second option is to replace the *createmark() command with the *createmarkpanel() command which allows the user to interactively select the entities. The syntax for the *createmarkpanel() command is: *createmarkpanel(entity_type, mark_id, message) entity_type mark_id message

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

Example: Allow the user to select the elements and then delete the elements: *createmarkpanel(elements, 1, “Select elements to delete”) *deletemark(elements, 1)

HyperWorks 13.0

Introduction to HM Customization 45 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 *createbutton() *createmarkpanel() *translatemark() *beginmacro() *endmacro() TCL/TK commands used none Hints Follow the Process to Create HyperMesh Macros presented in this Chapter. Do all the steps in HyperMesh and extract the appropriate commands from the command.cmf file.

Introduction to HM Customization 46 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 4: Using Tcl to Control the HyperMesh Session

Chapter 4

Using Tcl to Control the HyperMesh Session The macros that have been created thus far are very powerful in their automation of repetitive tasks. However, there are limitations. For example, in the LoadCol macro which creates a load collector called forces, the name of the load collector is hard-coded. If the user wanted to create a load collector with a different name, it would require editing the name in the userpage.mac file. The Tcl scripting language can be utilized to provide support for more advanced tasks. Using the previous example, Tcl could be used to request a name for the load collector from the user and use that information to tell the HyperMesh session to create a load collector with the user provided name.

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

HyperWorks 13.0

Introduction to HM Customization 47 Proprietary Information of Altair Engineering, Inc

Chapter 4: Using Tcl to Control the HyperMesh Session

Macro in userpage.mac file *beginmacro("macroJpeg") *setbackgroundcolor(255,255,255) *setmeshlinecolor(6) *jpegfile() *setbackgroundcolor(0,0,0) *setmeshlinecolor(0) *endmacro()

Tcl Script Not used in Tcl *setbackgroundcolor 255 255 255 *setmeshlinecolor 6 *jpegfile *setbackgroundcolor 0 0 0 *setmeshlinecolor 0 Not used in Tcl

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

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

Basic HyperMesh Input Widgets One of the most basic things that need to be done in a macro is to enter data or text to be used in the HyperMesh macro. For example, imagine we are creating a load collector as we did in the previous chapter. In that example, the name of the load collector was hard-coded into the macro. Using the hm_getstring command, a string value is returned by providing the user with a HyperMesh panel. The syntax is: hm_getstring ?caption? ?message? where both the caption and message are optional arguments. The caption is shown in the panel while the message is shown in the message bar. For example: hm_getstring “Load collector name” “Enter a name for the load collector” produces the following panel and message in HyperMesh Introduction to HM Customization 48 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 4: Using Tcl to Control the HyperMesh Session

Panel produced by hm_getstring

This command can be used with the set Tcl command to assign the string entered in the panel to a variable: set loadname [hm_getstring “Load collector name” “Enter name for load collector”] In addition to getting a string, the hm_getint and hm_getfloat commands can be used to get values by posting a panel in the HyperMesh panel area. The hm_getint command returns a user input integer value while hm_getfloat returns a user input floating point value. Both these commands have the same options as the hm_getstring command. As an example, let’s assign a floating point value to a variable called force: set force [hm_getfloat “Force” “Enter force value”]

Panel produced by hm_getfloat

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

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

Chapter 4: Using Tcl to Control the HyperMesh Session

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

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

Using the Command Window The first step in learning to integrate Tcl scripts into the HyperMesh environment is to learn how to launch scripts from the HyperMesh interface. An interactive Command Window is provided and can be access through the View menu. This Introduction to HM Customization 50 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 4: Using Tcl to Control the HyperMesh Session

launches the Tk Console (TkCon) which is an interactive console which comes with Tk.

The Command Window

In the Command Window, users can evaluate any command that can be issued in Tcl or in HyperMesh through Tcl. Let’s examine a few commands. General Unix command such as ls, pwd, and cd can be used within the Command Window. The ls command will return the directory contents, the pwd command will return the current working directory, and the cd command allows users to change directories. In addition to general UNIX commands, general and HyperMesh specific Tcl commands can be entered. For example, let’s use the HyperMesh specific Tcl command hm_info with the following options: hm_info –appinfo SPECIFIEDPATH TEMPLATES_DIR The above command with the provided options will return the current template directory. Any command that can be issued in Tcl or in HyperMesh through the Tcl command layer can be entered at the Command Window prompt and it will be evaluated. This capability provides the automation tool developer an easy means of testing a concept before writing the full procedure. The Command Window also provides the ability to run Tcl scripts by either using the source command or using the File/Load Menu option. When using the source command, the complete path and filename needs to be given (unless the file is located in the directory the user is currently in within the Command Window). source C:/temp/my_macro.tcl The other option is to use the File/Load Menu. This menu is available in the Command Window by right clicking in the Command Window (shown below). You can also save the session contents in the Command Window using the File/Save Menu option.

HyperWorks 13.0

Introduction to HM Customization 51 Proprietary Information of Altair Engineering, Inc

Chapter 4: Using Tcl to Control the HyperMesh Session

The Command Window Load Menu

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

Example 4.1: Using the Command Window The purpose of this example is to become familiar with using the Command Window for developing in Tcl. In this example, HyperMesh Tcl and core Tcl commands, will be used in the Command Window to determine the number of elements in a component collector for a pre-defined HyperMesh model. The following commands are used in this exercise: Modified HyperMesh commands: • *createmark() HyperMesh Tcl commands • hm_info • hm_getmark Core Tcl commands • list • llength • set • source

Step 1: Launch the Command Window from HyperMesh 1. Open HyperMesh. 2. Go to the View menu and select Command Window.

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

HyperWorks 13.0

Chapter 4: Using Tcl to Control the HyperMesh Session

Step 2: Run operating system commands from the Command Window Run a couple operating system commands to become familiar with entering commands and getting the output. 1. Run the command pwd. The present working directory is returned. 2. Run the command ls A list of the present working 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

HyperWorks 13.0

Introduction to HM Customization 53 Proprietary Information of Altair Engineering, Inc

Chapter 4: Using Tcl to Control the HyperMesh Session

By using the llength Tcl command, the number of entities in the list elemIds can be found. set numElems [llength $elemIds] In the Command Window the value of 390 is returned, which is the number of elements in the component collector upper.

Step 8: Display the element count result Using the puts command, we can print the output of a variable to the Command Window. puts $numElems Again the value returned is 390 which is the number of elements in the component collector upper.

Step 9: Verify the returned number of elements is the same number reported in HyperMesh’s Count panel. 1. 2. 3. 4. 5. 6. 7.

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

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

Step 11: Load the command_window_ex.tcl file into the Command Window. 1. Right click in the Command Window and select File >> Load File. 2. Select the command_window_ex.tcl file. “390” is returned. Introduction to HM Customization 54 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 4: Using Tcl to Control the HyperMesh Session

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

Process to Create a Tcl HyperMesh Macro 1. Define the task. 2. Delete the existing command.cmf file. This file is located in either the start-in directory or the current working directory. 3. Perform the operations in HyperMesh that the script should run. 4. Extract the commands from the command.cmf 5. Create a Tcl script by converting the commands to Tcl format and modifying as necessary (this includes adding additional Tcl commands) 6. Create a new Utility menu macro that runs a Tcl script. 7. Add macro button using *createbutton that calls the macro created in Step 6 with the appropriate Tcl script filename. 8. Reload the current .mac file into HyperMesh to load the modified userpage.mac. 9. Test the macro. This process is nearly identical to developing a HyperMesh Basic macro. The only differences are that the HyperMesh commands must be converted to Tcl format and that Tcl core commands are allowed to introduce control logic to the automation tools.

Example 4.2: Automate Creating Forces with a User Specified Magnitude In this example, we will go through the general process for creating HyperMesh Tcl scripts. The script will automate the creating of forces with a user defined magnitude. The following commands are used in this example: Modified and added HyperMesh commands: • *createmark • *clearmark HyperMesh Tcl commands: • hm_getfloat Core Tcl commands: • set

Step 1: Define the task to be automated. HyperWorks 13.0

Introduction to HM Customization 55 Proprietary Information of Altair Engineering, Inc

Chapter 4: Using Tcl to Control the HyperMesh Session

1. 2. 3. 4.

Create a load collector named forces. Request the user to select the nodes on which to apply a force. Request the user to specify the magnitude of the forces to be created. Create the forces and organize them into the forces collector.

Step 2: Delete the command.cmf file from your working directory. Every command executed in HyperMesh is recorded in the command.cmf file. To view only the task’s commands, it is suggested you delete the command.cmf file before doing the task. After deleting this file, the file is automatically recreated when more commands are executed in HyperMesh.

Steps 3-5: Do the task in HyperMesh to capture its commands to the command.cmf file. Step 3: Retrieve the file c_channel-tcl_vector.hm 1. Open HyperMesh. 2. From File > Open, select the file c_channel-tcl_vector.hm

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

Step 5: Create a force on the beam 1. 2. 3. 4. 5. 6. 7. 8.

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

Introduction to HM Customization 56 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 4: Using Tcl to Control the HyperMesh Session

Step 6: Copy the task’s commands in the command.cmf file and paste them to the create_force.tcl file. 1. Open a text editor and create a new text file named create_force.tcl. Save the file to your HyperMesh working directory (My Documents on Windows). 2. From your HyperMesh working directory, open the command.cmf file. 3. Locate the following four commands at or near the end of the file. *collectorcreateonly(loadcols, “forces”, “”, 7) *loadsize(1,15,0,1) *createmark(nodes,1) 3237 *loadcreateonentity(nodes,1,1,1,0,0,23,0,0,23,0,0,0,0,0) 4. Copy these commands and add them to the text file create_force.tcl

Steps 7-9 Modify and add to the script commands as necessary. Step 7: Modify the code so it is in Tcl syntax To modify the code so that it is in the appropriate Tcl syntax, parentheses and commas need to be replaced with a blank space. This results in the following four lines: *collectorcreate loadcols “forces” “” 7 *loadsize 1 15 0 1 *createmark nodes 1 3237 *loadcreateonentity nodes 1 1 1 0 0 23 0 0 23 0 0 0 0 0

Step 8: Allow the user to select nodes on which to apply a force. Here we are updating the code by adding the *clearmark command and replacing the *createmark command with *createmarkpanel. The *clearmark command clears the node ids that are currently in the mark (if any are currently there). The *createmarkpanel command is used to get user selected nodes using a HyperMesh panel and store them in the buffer. 1. Before the *createmark command, add the following line which clears the node ids currently in mark 1. *clearmark nodes 1 2. Modify the *createmark command to allow users to select the nodes using a HyperMesh panel and store them in the buffer. HyperWorks 13.0

Introduction to HM Customization 57 Proprietary Information of Altair Engineering, Inc

Chapter 4: Using Tcl to Control the HyperMesh Session

*createmarkpanel nodes 1 “Select nodes”

Step 9: Allow the user to specify a force magnitude. Using the hm_getfloat command, the user can enter a value for the magnitude and then using the set command it can be stored as a variable. The variable can then be substituted for the hard coded force magnitude. 1. Get a force magnitude from the user using a HyperMesh panel and store it in a variable. Enter the following line after the *createmarkpanel command. set mag_val [hm_getfloat “Magnitude =” “Enter the force magnitude”]

2. Substitute the hard coded force magnitude with the variable mag_val. *loadcreateonentity nodes 1 1 1 0 0 $mag_val 0 0 $mag_val 0 0 0 0 0

Step 10: Review the script to see if it looks similar to the following: *collectorcreate loadcols “forces” “” 7 *loadsize 1 15 0 1 *clearmark nodes 1 *createmarkpanel nodes 1 “Select nodes” set mag_val [hm_getfloat “Magnitude =” “Enter the force magnitude”] *loadcreateonentity nodes 1 1 1 0 0 $mag_val 0 0 $mag_val 0 0 0 0 0

Step 11: Test the script by running it from the command window 1. Go to the currently open HyperMesh session. 2. Open the file c_channel-tcl_vector.hm. This refreshes the HyperMesh database. The load collector and forces you created earlier no longer exist. 3. Go to the View menu and select Command Window. 4. In the Command Window, type the following and then press Enter: source create_force.tcl A HyperMesh panel with a nodes selector appears. 5. Select node(s) in any manner you wish. 6. Click proceed to continue the 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. Introduction to HM Customization 58 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 4: Using Tcl to Control the HyperMesh Session

Steps 12-14 Test the script from a Utility tab button. Step 12: Create a button on the Utility tab’s User page. 1. In your HyperMesh working directory, open the file userpage.mac. If this file does not already exist, create a text file named userpage.mac. 2. On the next blank line from the top of the file, type the following *createbutton line: *createbutton(5, “Create Force”, -1, 0, 10, YELLOW, “Create a force on selected nodes”, EvalTcl, “create_force.tcl”) 3. Save the userpage.mac file.

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

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

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

HyperWorks 13.0

Introduction to HM Customization 59 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 *createmarkpanel *clearmark hm_getfloat

*collectorcreateonly *movemark *createvector *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 60 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

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_nodelist

hm_getmark

TCL/TK commands used for list set if else

foreach lappend incr elseif

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 13.0

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

Chapter 4: Using Tcl to Control the HyperMesh Session

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

HyperWorks 13.0

Chapter 5: Retrieving Data from HyperMesh Entities

Chapter 5

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

HyperMesh Entities and Their Data Names Data names are generic references to the information that physically defines an entity in the HyperMesh environment. An example of this would be the x, y, and z coordinates that define a node’s location in three-dimensional space. This information is part of the entity’s definition and is consistent for all solvers. It is possible though that these can change from one HyperMesh version to the next. For this reason, please refer to the online help. Information on the data names can be found in the following location: HyperMesh > Reference Guide > Scripts > Creating Scripts > Tcl > Using Data Names Data names are accessed using the hm_getentityvalue command. This command is one of the most common commands used by a developer in the HyperMesh environment. It is used to access the data names and template information associated with an entity. The command will return a value that is either a string or a numeric value, depending on the flag value and the value stored in that field or data name. The syntax for this command is: hm_getentityvalue entity_type name_or_id data_name_string flag ?search_type? HyperWorks 13.0

Introduction to HM Customization 63 Proprietary Information of Altair Engineering, Inc

Chapter 5: Retrieving Data from HyperMesh Entities

The following is an example using hm_getentityvalue: set force_x [hm_getentityvalue loads 12 "comp1" 0] In this example, loads corresponds to the entity_type, 12 is the name_or_id of the load, “comp1” is the data_name_string, and 0 is the flag. The flag can be set to either 0 (indicating a floating value should be returned) or to 1 (indicating that a string should be returned. Using these options, the x component of a force with ID 12 is returned and set to the variable force_x. The table below shows several of the data names for the force load: node comp1 comp2 comp3 magnitude collector

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

Another example for hm_getentityvalue is shown below. This example is a Tcl acript which prompts the user to select several nodes and then displays their x, y, and z coordinates: hm_markclear nodes 1 *createmarkpanel nodes 1 set nodes [hm_getmark nodes 1] if { ! [ Null nodes ] } { foreach node $nodes { set xVal [hm_getentityvalue nodes $node "x" 0] set yVal [hm_getentityvalue nodes $node "y" 0] set zVal [hm_getentityvalue nodes $node "z" 0] tk_messageBox -message "Node $node = $xVal $yVal $zVal" } } In the example above, nodes corresponds to the entity_type, $nodes is a variable which passes the node id, “x”, “y”, or “z” is the data_name_string, and 0 is the flag. Below is a table which shows some of the data names available for nodes. Introduction to HM Customization 64 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 5: Retrieving Data from HyperMesh Entities

id The ID of the node (integer). inputsystem Pointer to the node input system (pointer). outputsystem Pointer to the node output system (pointer). The x coordinate of the node in its local system x (real). The y coordinate of the node in its local system y (real). The z coordinate of the node in its local system z (real). Data names for nodes

F

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

Pointers and Flags Notice that several of the data names in the two tables above are defined as pointers. A pointer is used to directly access another data name. For example, the collector and node data names for force loads are pointers. This means they “point” to the data names available for either collectors or nodes. In order to retrieve any data from a pointer, the data name requested for the particular pointer must also be supplied. The additional data names are separated by a period or dot (.). The following are a few examples on how a pointer is used. To retrieve the node id that load 12 is applied to the following set of commands is used: set node_id [hm_getentityvalue loads 12 "node.id" 0] To retrieve the y coordinate of the node that load 12 is applied to use the following set of commands: set node_id [hm_getentityvalue loads 12 "node.y" 0] To retrieve the load collector name that contains load 12, use the following set of commands: set ld_col [hm_getentityvalue loads 12 "collector.name" 1] All data names for that particular entity are available for reference when using pointers. For the collector name, notice the flag value is set to 1 as the expected return value is a string value as opposed to a numeric value. In the node HyperWorks 13.0

Introduction to HM Customization 65 Proprietary Information of Altair Engineering, Inc

Chapter 5: Retrieving Data from HyperMesh Entities

examples above, the flag value is set to 0, indicating that a floating point number is to be returned. Another example is with component collectors. There is no data name associated with a component collector to get the material name, only the material ID. The following set of commands is used to get the material ID: set matID [hm_getentityvalue comps 12 "materialid" 0] A second set of commands would then be required to get the name of the material with that ID: set matName [hm_getentityvalue mats $matID "name" 1] Alternatively, the component collector has a material pointer data name. From this pointer, any valid material data name can be substituted by separating the pointer and the new data name with a period (.). From the example above the following line can replace the previous two lines: set matName [hm_getentityvalue comps 12 "material.name" 1]

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

Introduction to HM Customization 66 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 5: Retrieving Data from HyperMesh Entities

Example 5.1: Automate Computing the Vector Sum of Forces The purpose of this example is to become familiar with creating HyperMesh Tcl scripts to retrieve data on HyperMesh entities (nodes, elements, loads, etc.). The following HyperMesh commands are modified in this exercise. • *clearmark() • *createmarkpanel() The following HyperMesh Tcl commands are used in this exercise. • hm_getentityvalue • hm_getmark • hm_usermessage • hm_errormessage The following core Tcl commands are used in this exercise. • brackets [ ] • expr • foreach • if • set • return • llength

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

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

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

Introduction to HM Customization 67 Proprietary Information of Altair Engineering, Inc

Chapter 5: Retrieving Data from HyperMesh Entities

Step 4: Allow the user to select the forces. 1. Create a buffer (mark) to store loads selected in the panel by the user. *clearmark loads 1 *createmarkpanel loads 1 “Select forces for resultant” Notice the HyperMesh entity type for force is loads. 2. Retrieve loads from the buffer (mark) and create a list variable. set loads_list [hm_getmark loads 1]

Step 5: Before proceeding to calculate the sum, determine whether or not loads were selected. If none were selected, display a message stating this. By checking the length of the variable $loads_list, it can be determined if any loads have been selected. If the length of the list of loads is equal to 0, this means that no loads have been selected. By using this check within an if statement, a message will be displayed only when no loads are selected and the script will be exited. if { [llength $loads_list] == 0 } { hm_errormessage "No loads selected" return }

Step 6: Initialize variables that store the X, Y and Z components of the vector sum of the selected forces. Initialization is done by setting the variables xsum, ysum, and zsum to 0. set xsum 0 set ysum 0 set zsum 0

Step 7: Loop through the list of selected loads, retrieve their component values, and add them to the total for each component. By using the foreach statement, each load in the list can be extracted and set to the variable load_id. Then, the x component can be retrieved and set to the variable xcomp, the y component can be retrieved and set to the variable ycomp, Introduction to HM Customization 68 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 5: Retrieving Data from HyperMesh Entities

and the z component can be retrieved and set to the variable zcomp. Finally each component is added to the appropriate sum variable using the expr command. foreach load_id $loads_list { set xcomp [hm_getentityvalue LOADS $load_id "comp1" 0] set ycomp [hm_getentityvalue LOADS $load_id "comp2" 0] set zcomp [hm_getentityvalue LOADS $load_id "comp3" 0] set xsum [expr $xsum +$xcomp] set ysum [expr $ysum +$ycomp] set zsum [expr $zsum +$zcomp] }

Step 8: Display the result (components of the resultant). Using the hm_usermessage command, a message is shown in the message bar which reports the x, y, and z components of the resultant force. hm_usermessage “Resultant force: $xsum, $ysum, $zsum”

Step 9: Review your script to see if it looks similar to the following. *clearmark loads 1 *createmarkpanel loads 1 “Select forces for resultant” set loads_list [hm_getmark loads 1] if { [llength $loads_list] == 0 } { hm_errormessage "No loads selected" return } set xsum 0 set ysum 0 set zsum 0 foreach load_id $loads_list { set xcomp [hm_getentityvalue LOADS $load_id "comp1" 0] set ycomp [hm_getentityvalue LOADS $load_id "comp2" 0] set zcomp [hm_getentityvalue LOADS $load_id "comp3" 0] set xsum [expr $xsum +$xcomp] set ysum [expr $ysum +$ycomp] set zsum [expr $zsum +$zcomp] } HyperWorks 13.0

Introduction to HM Customization 69 Proprietary Information of Altair Engineering, Inc

Chapter 5: Retrieving Data from HyperMesh Entities

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

Step 10: Save the sum_force_comps.tcl file. Step 11: Test the script by running it from the Command Window. 1. Open HyperMesh from your HyperMesh working folder. 2. Retrieve the file c_channel-tcl_vector.hm. 3. Go to View >> Command Window to open the Command Window if it 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 bar. 8. Run the script again, but this time, do not select any loads. The message “No loads selected” appears in the message bar.

Step 12: Create a button for the script on the macro menu’s User page. 1. In your HyperMesh working folder, open the file userpage.mac. If this file does not already exist, create a text file named userpage.mac. 2. On the next blank line from the file’s top, type the following *createbutton() line: *createbutton(5,”Sum force comps”,-1,0,10,GREEN,”Sum comps of forces”, ”EvalTcl”, ”sum_force_comps.tcl”) 3. Save the userpage.mac file to your HyperMesh working folder.

Step 13: Test the script by running it from its button on the macro menu. Step 14: The exercise is complete. Close the HyperMesh session.

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

HyperWorks 13.0

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

HyperWorks 13.0

Introduction to HM Customization 71 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_channeltcl_vector.hm. HyperMesh commands used *createmark *translatemark *createelement *currentcollector hm_nodelist hm_getentityvalue

*createvector *createnode *collectorcreate hm_getmark hm_entityinfo

TCL/TK commands used for set elseif

foreach if 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?

Introduction to HM Customization 72 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

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 *clearmark hm_getmark hm_entityinfo

*createnode *hm_nodelist *systemcreate

TCL/TK commands used set foreach lindex

for eval 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.

HyperWorks 13.0

Introduction to HM Customization 73 Proprietary Information of Altair Engineering, Inc

Chapter 5: Retrieving Data from HyperMesh Entities

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

HyperWorks 13.0

Chapter 6: Interfacing with HyperMesh Solver Templates

Chapter 6

Interfacing with HyperMesh Solver Templates Solver specific data created within HyperMesh can be defined, reviewed, and edited in the card images. Card images are an interpretation of the loaded solver template. Each piece of data that defines a card image has a text string (data name) and a numeric attribute ID. An example is the Young’s Modulus for a material. Each solver, and even each different material type for a particular solver, can have a Young’s Modulus attribute and a corresponding data name. These data names and attributes are defined in each solver’s feoutput template. They are unique and are not necessarily consistent between solvers or even between each material within a solver. Templates exist for each solver supported by HyperMesh and are located in subfolders under the /templates/feoutput directory. These templates define every solver specific attribute including data names, attribute IDs, card image formats, and the format of the data upon export. The *defineattribute command is used to define attribute data names and IDs in a template file. There are several different types of attributes including array, double, entity, integer and string. Each of these types is handled in a similar fashion to the examples below. The difference is that each entity type uses an appropriate *attributeupdate command based on its type. There are also a number of hm_attribute commands to query entity attributes.

HyperWorks 13.0

Introduction to HM Customization 75 Proprietary Information of Altair Engineering, Inc

Chapter 6: Interfacing with HyperMesh Solver Templates

Solver Attributes and Card Images A sample card image for an OptiStruct MAT1 material collector is shown below:

Figure 6.1: Card image for MAT1 card in OptiStruct.

For each field in the above card image there is, a corresponding attribute and data name in one the optistruct templates (in /templates/feoutput/common_nas_os/attribs) . An excerpt is shown below for several of the card image fields: *defineattribute(E,1,real,none) *defineattribute(G,2,real,none) *defineattribute(Nu,3,real,none) *defineattribute(Rho,4,real,none) The first argument in the *defineattribute command is the solver data name. The second is the attribute ID and the third is the attribute type. There are 11 different attribute types. Attributes of different types are created and updated with different commands, but the overall concept is the same. Each attribute in the template has a definition similar to these. Additionally, there are card image definitions that define how the card editor is generated inside of HyperMesh for each attribute. For optistruct, these card images are defined in /templates/feoutput/optistruct. An excerpt of the optistruct MAT1 card image is shown below: *menustring("MAT1 ") *menufield(ID,integer,id,8) *menufield(E,real,$E,8) *menudefaultvalue(" ") *menuinitialvalue(210000.0) *menurestrictedvalue(>,0.0) *menufield(G,real,$G,8) *menudefaultvalue(" ") *menuinitialvalue(80769.2) *menurestrictedvalue(>,0.0) Introduction to HM Customization 76 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 6: Interfacing with HyperMesh Solver Templates

*menufield(NU,real,$Nu,8) *menudefaultvalue(" ") *menurestrictedvalue(>,-1.0) *menurestrictedvalue( 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.cmf file and paste them to the create_mat.tcl file. 1. Open a text editor and create a new text file named create_mat.tcl. Save the file to your HyperMesh working folder. 2. From your HyperMesh working folder, open the command.cmf file. 3. Locate the command line *collectorcreate() at or near the end of the file. You should see lines similar to the following. *collectorcreate(materials,"steel","",11) *createmark(materials,2) "steel" *dictionaryload(materials,2,"C:/Altair/hw13.0/templates/feo utput/optistruct/optistruct","MAT1") *attributeupdateint(materials,1,3240,1,2,0,1) *attributeupdatedouble(materials,1,1,1,0,0,210000) *attributeupdatedouble(materials,1,2,1,0,0,80769.2) *attributeupdatedouble(materials,1,3,1,0,0,0.3) *attributeupdatedouble(materials,1,4,1,0,0,7.85e-009) *attributeupdatedouble(materials,1,5,1,0,0,0) *attributeupdatedouble(materials,1,6,1,0,0,0) *attributeupdatedouble(materials,1,7,1,0,0,0) *attributeupdatedouble(materials,1,341,1,0,0,0) *attributeupdatedouble(materials,1,343,1,0,0,0) HyperWorks 13.0

Introduction to HM Customization 85 Proprietary Information of Altair Engineering, Inc

Chapter 6: Interfacing with HyperMesh Solver Templates

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

Steps 6-12: Modify and add to the commands as necessary. Step 6: Modify the code so it is in Tcl syntax. Replace the parentheses and commas with a blank space.

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

materials materials materials materials

1 1 1 1

1 2 3 4

1 1 1 1

1 1 1 1

0 0 0 0

$E $G $NU $RHO

Step 8: Substitute all instances of the hard coded material name steel with the variable mat_name. *collectorcreate materials "$mat_name" "" 7 *createmark materials 2 "$mat_name" Introduction to HM Customization 86 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 6: Interfacing with HyperMesh Solver Templates

Step 9: Once the material is created, retrieve its id from the mark and store it in a variable. Add the following command just below the *createmark line. set mat_id [hm_getmark materials 2]

Step 10: Substitute all instances of the hard coded material id with the variable $mat_id. *attributeupdateint materials $mat_id 3240 *attributeupdatedouble materials $mat_id 1 *attributeupdatedouble materials $mat_id 2 *attributeupdatedouble materials $mat_id 3 *attributeupdatedouble materials $mat_id 4

1 1 1 1 1

2 1 1 1 1

0 0 0 0 0

1 123 45 0.078 90

Step 11: Substitute the hard coded path to the OptiStruct feoutput template with a request for the global template. *dictionaryload materials 2 "[hm_info templatefilename]" "MAT1" This line now assumes the OptiStruct feoutput template has been loaded prior to running the script. If it is not loaded, a “0” is returned.

Step 12: Review your script to see if it looks similar to the following. *collectorcreate materials "$mat_name" "" 7 *createmark materials 2 "$mat_name" set mat_id [hm_getmark materials 2] *dictionaryload materials 2 "[hm_info templatefilename]" "MAT1" *attributeupdateint materials $mat_id 3240 1 2 0 1 *attributeupdatedouble materials $mat_id 1 1 1 0 $E *attributeupdatedouble materials $mat_id 2 1 1 0 $G *attributeupdatedouble materials $mat_id 3 1 1 0 $NU *attributeupdatedouble materials $mat_id 4 1 1 0 $RHO

Step 13: Wrap the code into a Tcl procedure and pass the variables mat_name, E, G, NU and RHO as arguments to it. proc mat_create {mat_name E G NU RHO} { [code] } HyperWorks 13.0

Introduction to HM Customization 87 Proprietary Information of Altair Engineering, Inc

Chapter 6: Interfacing with HyperMesh Solver Templates

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

Step 15: Test the script by running it from the Command Window. 1. Go to the File menu and select New > Model to clear the current session. 2. In the Command Window, type the following and then press Enter. source create_mat.tcl The aluminum material is created.

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

Step 17: Test the script by running it from its button in the Utility menu. Step 18: The exercise is complete. Close the HyperMesh session.

Updating Solver Attributes In addition to creating a card image from scratch, it is also possible to update an existing card image. A procedure to do this is almost identical to the procedure to create a new card image, with the exception that the material is not created and thus the procedure requires a material ID to be passed instead of a material name. proc mat_update { mat_id E Nu Rho } { if {[hm_entityinfo exist mats $mat_id -byid] == 0} { hm_errormessage "Material $mat_id does not exist" return; } else { *createmark materials 2 "by id" "$mat_id"; *dictionaryload materials 2 "[hm_info exporttemplate]" \ Introduction to HM Customization 88 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Chapter 6: Interfacing with HyperMesh Solver Templates

"MAT1"; *attributeupdatedouble materials $mat_id 1 1 1 0 $E; *attributeupdatedouble materials $mat_id 3 1 1 0 $Nu; *attributeupdatedouble materials $mat_id 4 1 1 0 $Rho; return; } }

Exercise 6.3: Automate Defining/Updating Multiple Materials This example will continue to illustrate how to define/update materials.

Step 1: Define the task to be automated. This task is an extension to example 6.2 of this chapter. Automate defining three OptiStruct MAT1 materials with values for the parameters 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 aluminum altairium steel

E 10 1000 2.00E+06

G 20 200 1.00E+06

NU 0.3 0.3 0.3

RHO 40 400 7.80E-09

Step 2: Update the script you created in exercise two of this chapter or update its solution file create_mat_solution.tcl. 1. Break up the create_mat procedure defined in the previous example. Put the update functions ( *attributeupdate… ) into a proc called update_mat and leave the creation functions in the proc create_mat. The create_mat procedure will call the update_mat procedure: proc update_mat {mat_id E *attributeupdatedouble *attributeupdatedouble *attributeupdatedouble *attributeupdatedouble }

G NU RHO} materials materials materials materials

{ $mat_id $mat_id $mat_id $mat_id

1 2 3 4

1 1 1 1

1 1 1 1

0 0 0 0

$E $G $NU $RHO

proc create_mat {mat_name E G NU RHO} { *collectorcreate materials "$mat_name" "" 7 *createmark materials 2 "$mat_name" set mat_id [hm_getmark materials 2] *dictionaryload materials 2 "[hm_info templatefilename]" "MAT1"; HyperWorks 13.0

Introduction to HM Customization 89 Proprietary Information of Altair Engineering, Inc

Chapter 6: Interfacing with HyperMesh Solver Templates

update_mat $mat_id $E $G $NU $RHO } 2. Use a foreach loop to loop through the three materials to be created and set the variables for the material parameters. Then use an if statement to determine if a material with that name already exists. If so update the material using the update_mat procedure. If the material does not exist, create the material. Place these commands in a procedure called main. proc main {} { set materialList [ hm_entitylist materials name ] foreach {materialName E G N R} \ [list "aluminum" "10" "20" "0.3" "40" \ "altairium" "1000" "200" "0.3" "400" \ "steel" "2.0e6" "1.0e6" "0.3" "7.8e-9"] { if {[lsearch $materialList $materialName] == -1 } { create_mat $materialName $E $G $N $R } else { set mat_id [ hm_entityinfo id materials $materialName ]; update_mat $mat_id $E $G $N $R } } }

Step 3: Test the script by running it from the Command Window. Step 4: Test the script by creating a button & running it from its button in the macro menu. If necessary, refer to previous exercises on methods to update the userpage.mac file.

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

Introduction to HM Customization 90 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

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 *collectorcreateonly *attributeupdatedouble hm_getfloat

*createmark *dictionaryload hm_getmark

TCL/TK commands used set if Hints Do the steps in HyperMesh and then extract the commands from the command.cmf file.

HyperWorks 13.0

Introduction to HM Customization 91 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 *dictionaryload *hm_allentitiesinfo TCL/TK commands used proc set foreach

*attributeupdateint *attributeupdatedouble *hm_getentityvalue lindex expr

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

Introduction to HM Customization 92 Proprietary Information of Altair Engineering, Inc.

HyperWorks 13.0

Solutions for Exercises

SOLUTIONS FOR EXERCISES CHAPTER 2 Exercise 2a *createbutton(5, "Model Tour", -1, 0, 10, YELLOW, "Explore HyperMesh Session", "EvalTcl", "modeltour.tcl")

CHAPTER 3 Exercise 3a *createbutton(5,"Translate Elements",-1,0,10,YELLOW,"Translate elements","macroTranslate_elem") *beginmacro(macroTranslate_elem) *createmarkpanel(elements,1,"Select Elements") *createvector(1,0.0000,0.0000,1.0000) *translatemark(elements,1,1,10) *endmacro()

CHAPTER 4 Exercise 4a In userpage.mac file:

*createbutton(5,"Move and Translate Elements",-1,0,10,BLUE,"Move elems to new comp and translate in z dir","EvalTcl","translate_elem.tcl") In TCL File: set user_comp [hm_getstring "Component Name" "Enter a Component Collector Name"] *collectorcreateonly components $user_comp "" 3 *createmarkpanel elements 1 "Elements" *movemark elements 1 $user_comp

HyperWorks 13.0

Introduction to HM Customization 93 Proprietary Information of Altair Engineering, Inc

Solutions for Exercises *clearmark elements 1 *createmark elements 1 "by collector name" $user_comp *createvector 1 0.0 0.0 1.0 set user_distance [hm_getfloat "Translate Distance" "Enter the distance to translate elements in z direction"] *translatemark elements 1 1 $user_distance *clearmark elements 1

Exercise 4b In userpage.mac file:

*createbutton(5,"Create Elem List" -1,0,10,RED,"Create list of elems and their nodes","EvalTcl","elem_list.tcl" In TCL File: hm_markclear elements 1 # Selects all elements and places in the mark *createmark elems 1 all set elemList [ hm_getmark elements 1 ] set i 1 # for every element, find the nodes and centroid coordinates foreach eList $elemList { set nodeIDs [hm_nodelist $eList] set ShortList [list $eList $nodeIDs] # prints every list puts $ShortList # appends a list with all the elements information lappend LongList $ShortList # creates a list with a name SList_1, SList_2, etc for each # element with their nodes and centroid coord set SList_$i $ShortList incr i 1 } # prints the complete list of all the elements information puts $LongList

Introduction to HM Customization 94 Proprietary Information of Altair Engineering, Inc

HyperWorks 13.0

Solutions for Exercises

CHAPTER 5 Exercise 5a proc translatecomps { } { *createmarkpanel components 1 "Select components to be translated" *createmarkpanel vectors 1 "Select translational vector" set dist [hm_getfloat "Translation distance =" "Enter translational distance"] set vect [hm_getmark vectors 1] set xcomp [hm_getentityvalue vectors $vect "xcomp" 0] set ycomp [hm_getentityvalue vectors $vect "ycomp" 0] set zcomp [hm_getentityvalue vectors $vect "zcomp" 0] *createvector 1 $xcomp $ycomp $zcomp *translatemark components 1 1 $dist *clearmark comps 1 *clearmark vectors 1 } translatecomps

Exercise 5b hm_markclear all 1 # Selects all elements and places in the mark *createmark elems 1 all set elemList [ hm_getmark elements 1 ] set i 1 # for every element, find the nodes and centroid coordinates foreach eList $elemList { set nodeIDs [hm_nodelist $eList] set Centroid [hm_entityinfo centroid elements $eList] set ShortList [list $eList $nodeIDs $Centroid] # set each component of the centroid to a variable

HyperWorks 13.0

Introduction to HM Customization 95 Proprietary Information of Altair Engineering, Inc

Solutions for Exercises 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 # create a vector set xComp [ hm_getentityvalue set yComp [ hm_getentityvalue set zComp [ hm_getentityvalue *createvector 1 $xComp $yComp

the normal of the elements and then elems $eList "normalx" 0 ] elems $eList "normaly" 0 ] elems $eList "normalz" 0 ] $zComp

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

# appends a list with all the elements information lappend LongList $SList # creates a list with a name SList_1, SList_2, etc for each element # with their nodes and centroid coord set SList_$i $ShortList incr i 1 # mask nodes *nodecleartempmark

Introduction to HM Customization 96 Proprietary Information of Altair Engineering, Inc

HyperWorks 13.0

Solutions for Exercises

hm_markclear elements 1 # hm_markclear nodes 1 # hm_markclear vector 1 } # prints the complete list of all the elements information # puts $LongList

Exercise 5c ####################################################################### ############################## ##### Solution to Practical Exercise 5c ##### ####################################################################### ############################## ### Use the *createmarkpanel to allow users to select the elements ### Then create a list of the selected element ids ### Finally clear the existing mark (no longer needed as ids have been assigned to a list *createmarkpanel elems 1 "Select Elements to create nodes at the centroid" set elemlist [hm_getmark elems 1] *clearmark elems 1 ### use the llength command to determine the number of element id in the list set ellistlength [llength $elemlist] ### Loop through each element in the list for {set i 0} {$i < $ellistlength} {incr i} { ###assign the current element id to a variable set elemid [lindex $elemlist $i] ### use the foreach command to get the x y z coordinates of the centroid foreach {x y z} [hm_entityinfo centroid elems $elemid] {break}; ### Create a node at the x y z location of the centroid, add it to mark 1, assign the id to a variable and clear the mark eval *createnode $x $y $z 0 0 0

HyperWorks 13.0

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

Solutions for Exercises *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 set set set

N1 N2 N3 N4

[lindex [lindex [lindex [lindex

[ [ [ [

hm_nodelist hm_nodelist hm_nodelist hm_nodelist

$elemid $elemid $elemid $elemid

] ] ] ]

0] 1] 2] 3]

### Create a new system with the origin at the node at the element centroid, and oriented by the x axis and ### xy plane *systemcreate 1 0 $newnode "x" $N2 "xy" $N3 }

CHAPTER 6 Exercise 6a set prop_name [hm_getstring "Name="] if {$prop_name == ""} { hm_errormessage "No name specified" return; } elseif {[hm_entityinfo exist properties $prop_name -byname] == 1} { hm_errormessage "Preoperty already exists" return; } set prop_thick [hm_getfloat "Thickness="] if {$prop_thick == "" || $prop_thick
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF