Flowfront - Main page  
 


Contact Flowfront

How to advertise
Learn about our advertisers
Subscribe to Flowfront


www.plasticszone.com


www.moldflow.com

 

tips & techniques

Working with the Moldflow Plastics Insight API Tools

By David Rieffel, Product Engineer, Siegel-Robert, Inc., St. Louis, MO

Motivation for using the API

I am going to recount my motivation for using the MPI® API tools, and hopefully, it will become yours as well. Ask yourself these questions:

  • Has your arm, wrist, or hand ached at the end of the day because you are performing the same repetitive clicks in MPI all day long?
  • Have you ever wished the mesh editing tools were just a little more powerful or behaved in a different manner?
  • Have you ever wanted to create your own analysis result?
  • Is there some missing functionality for which you cannot wait for the next software release (for an enhancement that may or may not be there)?

If you answered "Yes" to any of these questions, then the Moldflow Plastics Insight® (MPI) API (Application Programming Interface) most likely is the solution to your problems.

Where to begin?

Before that question can be answered, ask yourself, "What is my programming background?" If you have a lot of experience with C++, Visual Basic, or Visual Basic Script (VBS), then you probably can jump right into programming, and this article won't help you much. My experience has its roots in FORTRAN (with a very little bit of C++), so that is where my perspective on learning and using the API is based.

I believe that the best way to start to learn the API is not to start programming at all. I started by using the Record Macro command in MPI/Synergy to do simple tasks, such as move and copy, and reviewed the resulting VBS file to see how the code worked. Another good place to start is to look at other users' scripts (the simple ones at first) to see how they handle the flow of information and various API calls.

A word about reference materials. Here are a few good sources for getting help on the API and writing scripts:

  • Obtain a free VBScript editor at: http://www.koansoftware.com/freeware/VBSeditor.zipThe Microsoft VBS reference is at: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/vbscripttoc.aspWithin MPI: Help > Contents > Application Programming Interface (API) > API Command Reference (the Compound List is a good place to start)Check out the following Lunchtime Luminaries Seminars on the Moldflow Community Center (MCC) available from the Get Trained > Training Resources selection:
    • Introduction to the MPI 4.0 Application Programming Interface (API)
    • Advanced API Topics
    Exchange macros with other users on the MCC with the Get Files > Macro Exchange selection.
  • Discuss your problems with other users through the MCC with the Talk to MPI Users selection.

I am a big fan of the MCC. With people posting scripts on the MCC to solve problems, reduce modeling time, and analyze results better, there is a huge potential to affect the efficiency of Moldflow users. A similar potential exists with the Talk to MPI Users forum on the MCC. These are great resources, and I recommend using them.


Simple beginnings

I used the Record Macro command to generate this code (Figure 1). I band-selected around some nodes and elements and copied them by 0,0,1. Then I band-selected around some other nodes and elements and moved them by 0,0,1. Easy enough, right?

1   Set Synergy = CreateObject("synergy.Synergy")
2   Set Modeler = Synergy.Modeler()
3   Set EntList = Modeler.CreateEntityList()
4   Set Vector = Synergy.CreateVector()
5   EntList.SelectFromString "N279 N278 N281 T427 T428 T668 "
6   Vector.SetXYZ 0, 0, 1
7   Modeler.Translate EntList, Vector, True, 1, False
8   Set Modeler = Synergy.Modeler()
9   Set EntList = Modeler.CreateEntityList()
10  Set Vector = Synergy.CreateVector()
11  EntList.SelectFromString "N386 N387 N388 N389 T685 T686 T687 "
12  Vector.SetXYZ 0, 0, 1
13  Modeler.Translate EntList, Vector, False, 1, False
        

Figure 1. Script resulting from using the Record Macro command.

Upon opening the saved VBS macro file, look at Line 1 and say, "What does this line do, and what is Set?" From a FORTRAN background I was, and still am, used to working with numerical, logical, and string data types. Generally, FORTRAN is not used to interface with other programs. I use FORTRAN just for basic processing of data files. So now we need to talk about object oriented programming (OOP) and what is an object. (NOTE: This is my understanding of objects, not the textbook definitions.)

Objects are entities that MPI/Synergy exposes through its OLE/Automation interface. The Set statement links the VBS variable to the MPI/Synergy program objects, and we use those VBS variables to control MPI/Synergy. In this example:

  • Line 1 creates the Synergy variable and links it to the main application object in MPI/Synergy (the MPI/Synergy program).
  • Line 2 creates the Modeler variable and links it to the Modeler object in MPI/Synergy. (Modeler is an object that provides modeling operations.)
  • Line 3 tells the Modeler object to create an empty entity list (which is an object) and links it to the EntList variable. q Line 4 tells the Synergy object to create an empty vector (which is an object) and links it to the Vector variable.
  • Line 5 finally instructs MPI/Synergy to do something with all these objects that have been created! Selected nodes and triangles from the study populate the empty entity list, EntList.
  • Line 6 sets the dimensions of the vector to copy along into the Synergy Vector.
  • Line 7 translates the EntList, by Vector, and copies the EntList (True).
  • Lines 8-13 perform the same operations as Lines 2-7, but the selected nodes and triangles are only moved and not copied.


Make it more flexible

While using the Record Macro command is a good first step, the resulting script is not very flexible. Let's modify it to allow any vector to be specified for copying selected entities (Figure 2).

1   Set Synergy = CreateObject("synergy.Synergy")
2   Set Modeler = Synergy.Modeler()
3   Set EntList = Modeler.CreateEntityList()
4   Set Vector = Synergy.CreateVector()
5   'EntList.SelectFromString "N279 N278 N281 T427 T428 T668 "
6
7   VectorString = Inputbox("Enter a translation vector." & vblf & "Separate the numbers by 		spaces.")
8   'msgbox(vectorstring)
9
10  'take the vector string "VectorString" and separate it into an array.
11  VectorArray = Split(VectorString)
12
13  'Vector.SetXYZ 0, 0, 0.25
14  'set the vecot using the vector array.
15  Vector.SetXYZ VectorArray(0), VectorArray(1), VectorArray(2)
16
17  msgbox("Select the entities in the model which you wish to copy.")
18
19  Set SD = Synergy.StudyDoc()
20  'Modeler.Translate EntList, Vector, True, 1, False
21  Modeler.Translate SD.Selection, Vector, True, 1, False
        

Figure 2. Modified script based on a recorded macro.

First, delete Lines 8-13 and comment out Lines 5-7 of the original script (comment lines begin with a single quote mark and are not executed when the script is run). Next, add an input box so a string of numbers can be entered to represent the vector for entities to be copied along (Line 7 in the modified script).

As a test, I added a message box (Line 8 in this example) to output the vector entered in the input box. When writing code, I find it best to write a small segment of code and then output some of the results to a message box to verify that the script is behaving correctly. This message box isn't necessary to run the final script, so I commented it out.

To continue, split the string into an array (Line 11) and then set the Vector variable to the array components (Line 15). Line 17 is a message box that prompts the user to select the entities to be copied. Line 19 links the variable SD to the StudyDoc object of the MPI/Synergy program (StudyDoc is the object used to query and manipulate studies). Finally, Line 21 translates and copies the entities that have been selected inside MPI/Synergy.

I made two programming mistakes in my first attempt at writing this code:

  • On Line 15, I initially used a square bracket, [, where I should have used a parenthesis, (, and I got the following error:
    	Script:  C:\MPI_4_1_Projects\scripts\mv_del2.vbs
    	Line:    15
    	Char:    26
    	Error:   Expected end of statement
    	Code:    800A0401
    	Source:  Microsoft VBScript compilation error
    	    
  • On Line 19, I initially omitted the Set statement, and I got this error:
    	Script:  C:\MPI_4_1_Projects\scripts\mv_del2.vbs
    	Line:    19
    	Char:    1
    	Error:   Object doesn't support this property or method: 'SD'
    	Code:    800A01B6
    	Source:  Microsoft VBScript runtime error
    	    

In both cases, the error message identifies the line and the character where the error originates.

From my perspective, this example is not too difficult. Remembering the first time I tried to write a script, that experience was rather excruciating and painful. I didn't, and to some extent still don't, understand object-oriented programming. It took me a full two days to get my first try at a script to run. The second, third, and fourth scripts didn't fare much better.

So you say, "I'm not going to spend days writing scripts, what a waste of time!" or "Learning to write VBS is too difficult." It is not a waste of time. Rather, it's an investment. Portions of the simple coding get copied and modified slightly to create a new, more powerful code. Then, you can begin to tackle more difficult things, such as querying entity properties, putting scripts into Excel, and the like.

The more experience you gain, the quicker you will be able to create more powerful scripts.


Looking at a bit of code

For a more in-depth example, let's look at the main code of the mav.vbs script found on the Macro Exchange area of the MCC (Figure 3). The mav.vbs script moves or copies entities between a set of nodes. This script requires the user to pre-select entities before running the script.

36  '///////////////////	Main Code	//////////////////////////////////////
37  Set Syn = CreateObject("synergy.Synergy")
38  
39	If syn.studydoc.selection.size = 0 Then
40	  msgbox("Sorry, you have not selected anything to move/copy. Quiting Script.")
41	  Set syn = Nothing 
42	  wscript.quit
43	End If
44
45  Set syn = Nothing 
46	
47	flag = inputbox("Copy objects?"&vbLf&_ 
48				"1   for yes,"&vbLf&_ 
49				"0   for no",,0)
50
51	If (flag = 1) Then
52	  num_copies = inputbox("Enter number of copies",,"1")
53	End If
54
55  Set Syn = CreateObject("synergy.Synergy")
56  Set MoveList = Syn.StudyDoc.Selection
57	Syn.StudyDoc.Selection = Syn.Modeler.CreateEntityList()
58
59	
60	If (flag = 1) Then
61		msgbox("Select, at least, two nodes for the copying vector."&vbLf&vbLf&_
62		"The first node will be the base node and "&vbLf&_
63		"all the following nodes will be copied to."&vbLf&vbLf&_
64		"Remember,use 'Ctrl' and banded selection, the script sorts out the nodes.")
65	Else
66		msgbox("Select two nodes for the moving vector.")
67	End If
68
69	Set NodeList = FUNGetSelection(Syn.StudyDoc.Selection,Syn.Modeler,Syn.StudyDoc)
70
71	If NodeList.Size < 2 Then
72	  msgbox("Less than two nodes selected.  Quiting script.")
73	  WScript.Quit
74	End If
75	
76	
77  ' ---- Deactivate the Local Coordinate Systems.
78 Syn.Modeler.ActivateLCS Nothing, False, "LCS"
        

Figure 3. Part 1 of the main code of the mav.vbs script.

Line 37 uses the Set command to link the Syn variable to the MPI/Synergy program.

In the previous examples, extra variables and Set statements were created to access objects in the MPI/Synergy program. In this instance, however, I didn't want to create all these extra variables. Instead, the object and its method invocation are piggybacked onto the Syn object. Study.Doc.Selection (Line 39) returns a list of entities selected inside MPI/Synergy as an EntList object. An EntList object corresponds to an ordered list of model entities. It also has a public attribute, Size, which tells how many things are selected. So in short, this line tells the script how many things are selected inside MPI/Synergy.

Line 40 displays a message box if no entities have been selected. In Line 41, setting the value of Syn to "Nothing" terminates the life of the Syn variable. It is important to terminate the life of a variable when it is no longer useful. (Consult the archived Lunchtime Luminaries session for more on this topic.) In Line 42, Wscript.quit terminates the script.

Line 47 allows the user to specify whether the objects are to be moved or copied. Line 52 prompts the user to input the number of copies, if necessary.

Line 56 moves the entities that were pre-selected to the MoveList variable. Line 57 empties the selection. This is because the Study.Doc.Selection variable is needed to select the nodes to move along.

Lines 60-67 prompt the user to select nodes. The prompt displayed to the user depends on whether the script was previously instructed to move or to copy the pre-selected entities (the MoveList).

In Line 69, FUNGetSelection is a function that takes a selection and separates out the nodes. If the user band-selects around a node, the selection can include associated triangles, curves, etc. This function weeds out the unwanted selected entities (e.g., triangles).

Note these warnings:

  • Nodal boundary conditions should not be included in your selection. The function does not look for nodal boundary conditions in the list. It would be an easy fix to solve this problem, but instead I just remember not to select those types of entities.
  • This FUNGetSelection function has been copied into other scripts. The function has been modified from script to script, depending on how it is required to interact with the main code. So, if you copy this function from my code into yours, be careful to modify it to fit your purpose.

Line 71 checks to see that at least two nodes have been selected.

Line 78 deactivates local coordinate systems. This script won't move things properly if any are active.

Let's continue our examination of the mav.vbs code (Figure 4).

79
80	
81	scale=InputBox("Enter the distance to move (or '###%' to enter a percent",,"100%")
82	
83	If (flag = 1) Then
84	  last = Nodelist.Size - 1
85	Else
86	  last = 1
87	End If
88	
89	
90	SUBGetCoord Syn.StudyDoc.GetNodeCoord(NodeList.Entity(0)), VecA  
91	For i = 1 To last
92  	  SUBGetCoord Syn.StudyDoc.GetNodeCoord(NodeList.Entity(i)), VecB
93	  SUBSubtract VecB, VecA, VecB
94	  If UCase(Right(scale,1)) = "%" Then
95	    SUBScale VecB, Mid(scale,1,Len(Scale)-1)/100.0, Offset
96	  Else
97	    SUBNormalize VecB, VecB
98	    SUBScale VecB, Scale, Offset
99	  End If
100
101	Set Vector_1 = Syn.CreateVector()
102	  Vector_1.SetXYZ Offset(0), Offset(1), Offset(2)
103	  Syn.Modeler.Translate MoveList,Vector_1,flag,num_copies,False
104	Next
105	
106	Syn.StudyDoc.Selection = Syn.Modeler.CreateEntityList()
107	Set Nodelist = Nothing
108	Set Movelist = Nothing
109	Set syn = Nothing
110	
        

Figure 4. Part 2 of the main code of the mav.vbs script.

Line 81 prompts the user to enter the distance or a percentage of the distance between the selected nodes, along the vector to move/copy the entities.

Lines 83-87 determine the last node in the list. Because arrays are indexed from 0, the script takes the size and subtracts 1. If the script is moving entities and the user accidentally selected more than two nodes to define the vector, the point to move to is set to the second node found in the selection list.

In Line 90, SUBGetCoord is a subroutine that takes the node coordinates and places them in the vector VecA. Nodelist.Entity(0) is the base coordinate for moving/copying the selected entities.

Lines 91-104 loop on the second to the nth node.

Line 92 gets the coordinates of the destination node and puts them in vector VecB. (See Line 90.)

In Line 93, SUBSubtract is a subroutine that subtracts two vectors.

In Lines 94-99, the If loop determines if you wanted to use a percentage or an actual distance to specify the actual movement dimension.

In Line 95, SUBScale is a subroutine that scales input (VecB) to the decimal percentage that was input on Line 81 and outputs it into the vector Offset.

In Line 97, SUBNormalize is a subroutine that normalizes the displacement vector. The SUBScale subroutine in Line 98 works the same as in Line 95.

Lines 101-102 put the Offset values into another vector.

Finally, In Line 103, the script moves/copies the selection.

Lines 106-109 clear the selection and end the lives of the variables.

Of course, it is possible that my code could be simplified. However, with most of my scripts, once it works, I don't like to mess with it too much. As the old saying goes, "If it ain't broke, don't fix it."


The API in use

Now, let's look at an example of using the API to create a manifold system on a part. This example uses three scripts that are available on the Macro Exchange area of the MCC. Using the scripts helps to minimize repetitive tasks involved in accomplishing this modeling task manually.

First, we start with a midplane model of a simple part (Figure 5) on which we would like to place five drops. A model of a generic drop is available in another MPI study (Figure 6). Note that it's good modeling practice to create different types of entities on different layers (for example, one layer to hold part nodes, another layer to hold part triangle elements, another layer to hold beam elements, and so on), to make it easier to view and operate on desired entities.

Note: MPI users who wish to try this example for themselves may download the injection_part.sdy and generic_drop.sdy files from the Macro Exchange area of the MCC.

Click to zoom in Click to zoom in
Figure 5. The model of the generic part given in injection_part.sdy. Figure 6. The model of the generic drop given in generic_drop.sdy.

Node 637 in the lower left corner of Figure 5 is at 0,0,0 and the rest of the nodes shown are locations where the additional drops are required. Add the generic drop to the injection part study. Now make sure the Manifold layer is turned off, select all the beams, and turn off the Drop layers (Figure 7).

Click to zoom in
Figure 7. The drop has been added to the part study.

Use the mav.vbs script to copy the generic drop.

Type mav at the command prompt to run the script. Use the copy option, and specify 1 copy. Using the Ctrl key, first select N637 and then band-select around the five nodes on the part. Select OK on the message box, and accept the 100% default for the distance. Upon turning the Drop layer on, the display will show that the generic drop has been copied to the five part nodes that were previously selected (Figure 8). Entities that are selected, whether their layer is shown or not, will be copied. The copied entities will be created on the layers on which the parent entity resides.

Click to zoom in
Figure 8. Using the mav.vbs script, the drop has been copied to each of the selected part nodes.

Use the scn_v2.vbs script to create nodes where the drops intersect the manifold plane.

To complete the manifold system, turn off all the layers except the Manifold Nodes and the Drop Nodes. Select the two manifold nodes, N639 and N641; these two nodes are used to represent a vector in space. Using the Ctrl key, band-select around the nodes for the outer drops in sets to create additional 3D vectors: N676 and N677, N684 and N685, N660 and N661, N652 and N653, in this order (Figure 9). Type scn_v2 at the command prompt to create the nodes where the drops will intersect the manifold and where the manifold forms a T-intersection. Use the Global Merge command to merge coincident nodes.

Click to zoom in
Figure 9. Select pairs of nodes in order to identify where new nodes will be created on the manifold plane.

Use the beam.vbs script to add beam elements between nodes.

Select the manifold beam to be duplicated. Type beam at the command prompt, then select the nodes between which to create the manifold beam. Run the script again to create the annular beams between the drops and the manifold. See Figure 10.

Click to zoom in
Figure 10. The completed model of the part with the manifold and drops added.

Scripts for just about anything

Scripts can be created for most of the commonly used tasks in MPI/Synergy. I have scripts for just about all of the meshing tools. I can project nodes to a plane and match nodes on a Fusion mesh. I have scripts to adjust the aspect ratios of elements, merge individually selected node sets, and control the look of the post-processing. For the most part, the only limits you have are your programming capability and your determination to create the scripts.

A word about selections

With the API, a script can query entities selected inside MPI/Synergy. The response is in the form of EntList, as described above. It is important to realize how the order and type of selection used affects the final pattern and content of EntList.

The pattern and order of data passed from the MPI/Synergy program to the recorded VBS macro script can affect the results based on how the script is coded. Figure 11 shows the different results that occur by band-selecting around Node 7, Node 13, and then Nodes 7 and 13.

Figure 11. Entities selected as a result of band-selecting different nodes or a pair of nodes.

The first thing to note is that any time a banded selection is made, the entity (or query) list is created, or appended, in a Node, Beam, Triangle, Curve, or Nodal Boundary Condition order.

The second thing to note is that using the Ctrl key to append to the section adds entities in the same order, and items can also occur multiple times in a selection list, as shown with T9 and T12 in Figure 11. (This is why using Ctrl+M to rotate or translate objects can move an entity 2-3 times farther than intended because it exists in the selection list more than once!)

Now, taking the result from above and using the Shift key to deselect T5 will result in the EntList being reordered and duplicate entities removed, as shown in Figure 12. Depending on how the script is coded, this can have an undesired effect on the result.

Figure 12. Deselecting an entity using the Shift key changes the order of the EntList and removes duplicate entities.

Using the Ctrl key to deselect preserves the pattern of the EntList and removes only the deselected entity throughout the selection (Figure 13).

Figure 13. Deselecting an entity using the Ctrl key preserves the order of the EntList and removes only the deselected entity.

The end of the beginning

Now you have a general idea about the types of problems that the API can help you solve. You have a list of a few good references, and you have reviewed some examples of a recorded macro, how to modify a recorded macro to make it more flexible, and how to put scripts to work in a modeling task. You were given a brief overview of pattern and order in which entities are selected inside MPI/Synergy — recognizing the pattern of selection could help you to sort data for looping scripts.

Don't forget that the MCC is a great resource. Get out there and start using the API! Download someone else's script and modify it or post your own script on the MCC. If you have problems, ask for help on the Talk to MPI Users section of the MCC and post your code there.

What's in the future?

I am thinking about writing a script to create the clamp tonnage plot for a part oriented in car position. I may also create a script for growing valve gate drops. I'm currently working on a script for creating a more in-depth recommended ram speed output.