You are on page 1of 67

Introduction to TK Solver

Universal Technical Systems, Inc.

Introduction to TK Solver
This document begins with a rapid tour of TK Solvers interface, solvers and programming features as might be used in a training session. TK Solver can do such a broad variety of things that its best to be equipped with the fundamentals rather than try to master the concepts from working examples. A given problem might be solved in a variety of ways paper and pencil, calculator, spreadsheet, programming language, math program but TK Solver is the best way to build a versatile solution. That is, once a problem has been solved by building a mathematical model TK, related problems can be solved with very little additional effort. That will be a recurring theme of this introduction. At its core, TK Solver is a rule-based problem solving and math modeling environment that combines equation solving, unit conversion, interpolation tables, and user-defined procedures. The rule-based features can be accessed from a variety of problem solving and application building shells.

A List Solver can be used to repeatedly process the math model over ranges of inputs to generate tables and plots of solutions. The list solver can also be used in Monte Carlo simulations, filtering distributions of random numbers through the rules and summarizing the results. An Optimizer can be used to repeatedly process the math model until some target solution is achieved, subject to bounds and constraints on any variables and expressions. An Excel Toolkit allows any of the objects (variables, units, lists, plots) from a TK model to be interactively linked within a spreadsheet. These objects can also be linked interactively with custom desktop and web-based applications created using other programming languages.

www.uts.us.com

The Interface
TK Solver manages different types of objects on worksheets. The object types are rules, variables, lists, units, plots, tables, formats, and comments. Together, the objects can form a mathematical model. The worksheet structure is accessible via the TK Navigation Bar. (If you do not see the Navigation Bar, click on the View menu to activate it.)

Double-click on the icon or description of the sheet you need to access. If objects are already present in a TK model, the Navigation Bar displays + symbols beside the sheet icons. Click on the + to expand the display and show the objects on that sheet. If you double-click on an object in the Navigation Bar, TK displays its attributes or properties.

www.uts.us.com

You can also access an objects properties directly from the worksheets, holding both the keys Ctrl-D, or by right-clicking on the object. TK also provides access to existing objects in a model via the Object Bar.

From the left, the Object Bar icons access functions, lists, plot definitions, table definitions, and format definitions. The Object Bar also provides quick access to existing plots, tables and comments. Use the Navigation Bar to access TK sheets and create new objects. Use the Object Bar to access existing objects.

Navigation Mode vs. Edit Mode


When you type information into a TK sheet, TK goes into edit mode. You see a single blinking cursor at the data entry point. During this time, many of the icons and functionality of TKs interface are inaccessible. You will see that the icons become grayed out. You cannot change to a different sheet when you are in edit mode.

When you have completed entry of the information in a particular field, the blinking cursor disappears and the current field is completely highlighted. You are now in navigation mode. When you are in navigation mode you have free access to all the icons, menus and interface functionality. TK Solver is a Tool Kit full of many solvers that all work together under your direction. Here is a list of those solvers. Direct Solver Iterative Solver Procedure Processor Differential Equations Integrator List Solver Optimizer TK Library of Root-Finders Excel Tool Kit

www.uts.us.com

TKs Direct Solver performs inverse mathematical operations and inverts functions in an equation to solve for a single unknown. If an equation contains more than one unknown, the Direct Solver skips it and moves on. When it solves an equation, it applies what it learns to subsequent equations, making additional passes through the rules to solve previously bypassed equations and checking for inconsistencies. For example, given inputs for any two of the three variables in the following equation, TKs Direct Solver will solve for the remaining variable. tand(theta/2) = radius/height, or in TKs MathLook view,
tand theta 2 = radius height

The Direct Solver makes your life easier by allowing you to enter your equations in any sequence and without having to isolate the unknowns to left of the equals sign. TKs Iterative Solver works with the Direct Solver to solve equations where the unknown cannot be isolated or to solve systems of simultaneous equations. The Iterative Solver sends a guess value to the Direct Solver, which works its way through the equations until it detects an inconsistency in one of the equations. The Direct Solver then tells the Iterative Solver how much of an inconsistency it found. The Iterative Solver keeps sending the Direct Solver new guesses until the inconsistency is very close to zero. The Iterative Solver can work with multiple guess variables if necessary. For example, the following set of equations can be solved using TKs Iterative Solver, if inputs are given for theta and volume.
tand theta 2 1 3 = radius height radius 2 height

volume =

The Iterative Solver can also be used to solve problems involving more complex functions that are otherwise non-invertible. For example, the Iterative Solver can be used to determine the upper limit (x2) of the following integral, given the lower limit (x1), such that a desired area is achieved. Area = Integral("1-sin(x)*cos(x),x",x1,x2) Similarly, the Iterative Solver can backsolve the following rule to determine the pressure at which water vapor, at a given temperature, will have a given density. Rho = $density(1,water,T,T,P,P)

www.uts.us.com

TK Solver also includes a Procedure Language that allows for solving problems in a sequence of steps. The procedure language is used to create user-defined subroutines called Procedure Functions. Procedure Functions can be called as a subroutine by the Direct Solver to do specific tasks such as stepping through a range of inputs, filling lists, performing summations or products, etc. Procedure functions allow you to add any algorithms to a TK model. Given an input value for C, the following procedure loops through a series of calculations, returning the final value of S and generating a list called XYZ with the cosines of each of the 100 intermediate values of s. S=0 For I = 1 to 100 S = S + (C-I/1000)^-2 XYZ[I] = cos(S) Next I Suppose we need the output of this procedure to be 2.75 and we need to know the value of C required to make that happen. The Iterative Solver handles it easily. Some TK built-in functions automatically generate lists of solutions. For example, TK includes a collection of integrators for solving differential equations. There is also a Wizard to help set up the differential equations, initial conditions, solution tables, and plots. As with procedure functions, the Iterative Solver can be used to backsolve these integrators to achieve desired results. Here is TKs solution to the following differential equations, where y1(0)=0 and y2(0)=0.2.
y` = y 1 2 y` = 1 - y 1 2 2 y -y 2 1

Solution 1 3 2 1 0 -1 -2 -3 0 2 4 6 8 10 12 14 16 18 20

www.uts.us.com

Element 1 2 3 4 5 6 7 Element 541 542 543 544 545 546 547

ODE_x1 0 .092603848 .187649488 .282441726 .377411345 .472887231 .569168717 ODE_x1 19.8392069 19.8694777 19.8986642 19.9267374 19.953833 19.9800655 20

ODE_y11 0 .019377624 .041039322 .064403466 .089522341 .116423086 .145114274 ODE_y11 -.29388033 -.23649045 -.17937409 -.12274748 -.066495 -.01052269 .0330106

ODE_y12 .2 .21849121 .237275272 .255589567 .273262503 .290057758 .305677834 ODE_y12 1.86533685 1.92670722 1.98741169 2.04697566 2.10527704 2.16216518 2.20546338

TK also includes a List Solver that will repeatedly run the entire math model, using lists of values for any of the input variables. This is one way to generate tables and plots of results. The List Solver can be set up manually or through the use of a Wizard. The List Solver will call on the Direct and Iterative Solvers at each step of the process. Here is set of TK rules used to solve fluid flow problems.
density = $DENSITY3 , fluid , 'T , T , 'P , P) ( viscosity = $VISCOSITY 3 , fluid , 'T , T , 'P , P) ( w q= density V= 4 q 2 D V D density viscosity = - 4 log f f density V deltap = D 16.085 L 2 eps + 44.4 D 1.255 NRe f

NRe= 1

www.uts.us.com

Here is a plot of the pressure drop vs. the tube diameter.


1000 pressure drop [psi] 300 100 30 10 3 1 .3 .1 1 1.5 2 2.5 3 3.5 4 tube diameter [in]

List Solving can also be used to run through a series of random numbers from various probability distributions. This is called Monte Carlo Simulation. TKs Simulation Wizard can be used to set up all the required parameters and evaluate the results. The TK Optimizer repeatedly solves a TK model until a set of objectives are met. This can involve finding a minimum or maximum value subject to sets of bounds and constraints on any of the variables in the model. The Optimizer can call on the Direct and Iterative Solvers at each step of the process.

www.uts.us.com

The Optimizer can also be used as an alternative to the Iterative Solver for backsolving a model to determine how an input must be changed so that one of the outputs results in a desired value. TK Solver includes a Library of pre-programmed procedures you can merge into your own models. The Library, accessed via the Applications menu, includes hundreds of tools divided into various categories.

The TK Library tools can be used to solve specific problems within a math model, freeing the other solvers to tackle other tasks. The Library tools also add to the available rootfinders in TK. Here is a quick summary of the root-finders in the TK Library. Quadratic Equations Cubic Equations Quartic Equations Nth Order Polynomial Equations by Bairstows Method Bisection Method False Position Method Newtons Method

www.uts.us.com

You can see these tools in action by loading the examples from the TK Library before merging in one of the tools. Finally, the TK-Excel Toolkit provides another level of solving power. The TK-Excel Toolkit allows you to run any number of TK models as subroutines within an Excel spreadsheet. The TK cells can also be referenced from other cells in Excel. The outputs from one model can be linked to the inputs in other models. The linked TK models can be called to List Solve to generate tables of solutions that can also be linked with Excel. The Excel Solver add-in can be used to optimize the results from this entire combination. Heres a portion of linked spreadsheet showing some TK variables and a plot.

www.uts.us.com

Practice
Lets begin with some practice with the interface. Launch the program.

Opening Sheets and Creating Objects


1. The toolbar automates several of the menu commands. You can see tool tips by moving the pointer over the icons. 2. The Navigation Bar provides fast access to the various sheets. Double click on a sheet name to open it. Sheets can be minimized or maximized by clicking on the icons in the upper right corner of each window. Alternatively, windows can be closed by clicking the button in the upper right corners. 3. Open the Plot Sheet. Enter p1 in the name column. 4. Move to the second row on the Plot Sheet and enter plot2. Now there are 2 objects. FACT: TK sheets can hold up to 32,000 objects if necessary!

5. Cursor down to the third row on the Plot Sheet and try to enter 2ndplot. When you try to enter it, TK displays an error message. 2ndplot is an invalid name. 6. Click the Context-Sensitive Help button. In this case, TK displays complete information about how to enter names, what characters are valid in names, and other related information. You can also search for other Help topics. When you are finished exploring Help, close it and return to TK. 7. Press Esc to remove your entry or edit the name so TK can accept it. 8. Press Home to move to the top of the Plot Sheet. Home and End move you to the top and bottom of a sheet. 9. Move the cursor to the Plot Type column. Notice that if you double click in this field, a pull-down appears. Many different TK fields behave this way. In this case, choose Line Chart. (As a shortcut, you can also type the first character of the choice you want.) At this point, you have a Line Chart named p1 but you don't have any contents for it yet (data, labels, scales, etc.).

www.uts.us.com

10

Opening Subsheets and Editing Object Attributes


1. Click the right mouse button or press CTRL-D to open the subsheet for the p1 Line Chart. Subsheets contain object definitions. 2. Enter abc as the X-Axis List name. TK created the object automatically on the List Sheet. Look at the Navigation bar and see that a + is now shown beside the List Sheet icon, indicating the sheet now has content.
Display Scale: Display Zero Axes: Display Grid: Display Legend: Line Chart Scaling: Title: Subtitle: X-Axis Label: Y-Axis Label: X-Axis Minimum, Maxi Y-Axis Minimum, Maxi Annotation-Text List: Yes None No No Linear

3. Open the subsheet for the list abc (CTRL-D or right mouse click on the list name in the plot subsheet or use the Navigation Bar). A list of values can be entered here in the subsheet. Enter 1, then cursor down and enter 2, then 3, then 4, then 5 under the Value heading. The element column automatically updates to let you know which line you are on. Most sheets dont have line numbers, however you can look in the lower left corner of the TK screen and it is displayed regardless of where you are in the program.
Element 1 2 3 4 5 Value 1 2 3 4 5

4. Close the list subsheet. 5. Cursor down below the Y-Axis field and enter xyz as the name of the Y-Axis List.
Y-Axis xyz Style Lines Color Blue Thickness 1 Type Solid Characte *

www.uts.us.com

11

6. Open the subsheet for xyz and enter the values 2, 4, 7, 23, 89 in the first five rows, then close the subsheet.
Element 1 2 3 4 5 Value 2 4 7 23 87

7. Use the Commands menu and select Display Plot or press F7. TK used the objects we defined and created a plot by connecting the X,Y coordinates with lines. Heres the plot.
90 80 70 60 50 40 30 20 10 0 1 1.5 2 2.5 3 3.5 4 4.5 5

8. Use the Navigation Bar to view the contents of the List Sheet. The List Sheet is the storage place for any lists which have been created or imported from spreadsheet or ASCII files. TK automatically placed the names abc and xyz on the List Sheet as soon as we defined them on the plot subsheet. 9. Move the cursor over the xyz list and open the subsheet. This works in every sheet, allowing you to check or define contents. There are several ways of viewing subsheets. The object bar along the top provides pull-downs for each type of object. Close the subsheet. 10. Next, open the Table Sheet using either the Navigation Bar. The Table Sheet is the place where tables are defined and stored. Just like the Plot Sheet or any other sheet, we can define several tables on the Table Sheet. Tables are collections of lists. 11. Enter t1 as the name of the first table then open the subsheet to further define this new object.

www.uts.us.com

12

12. Enter the names of the two lists we previously created, abc and xyz. By default, TK assigns column widths of 10.
List abc xyz Format Width Heading 10 10

13. Press CTRL-D or the Right Mouse Button to open the Interactive Table Subsheet, t1.
Element 1 2 3 4 5 abc 1 2 3 4 5 xyz 2 4 7 23 87

14. These are the same values we entered earlier. Let's add another data point to our plot. Move the cursor to the 6th row in the abc list and enter 6. Cursor over to the xyz list and add another value by entering 8.5^2. TK evaluates this expression for us. In fact, there is a calculator in every TK input field. Click on the down arrow in the upper right corner of the subsheet to iconize the subsheet. 15. Use the Object Bar or Press F7 to bring the plot window to the top again. It now displays all six pairs of data points.
90 80 70 60 50 40 30 20 10 0 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6

16. Pull down the Window menu and select Cascade. This will help you see all the sheets and subsheets you have open. You might also try the Tile option. 17. Close all the Windows using the Windows Menu.

www.uts.us.com

13

18. Use the tables listing in the Object Bar to open the table t1. The Object Bar saves you the trouble of finding and opening individual sheets. It also helps keep the interface from getting too cluttered when youre working with many different types of objects. 19. Use the Navigation Bar to open the Plot Sheet. Highlight the first plot name, p1. Use the View Menu and select Properties. There is also an icon available or you can press ALT-ENTER to view properties. You can also click the right mouse button. Click on the tack in the upper left corner of the properties box to keep it on the screen as you move from object to object.

20. Any entries made in the Properties Box are automatically placed into the corresponding object subsheets and will directly affect the object. Press F7 to bring the plot p1 up on the screen. Click the Y-Log selection in the Properties Box. The plot updates.
100 50 20 10 5 2 1 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6

www.uts.us.com

14

Equation Solving
We begin with a very simple problem. 1. Enter the equation a+b = c*d on the Rule Sheet. TK automatically places the variable names on the Variable Sheet. Variable names are case sensitive -- a and A are not the same in TK. Also notice that TK placed a "*" symbol in the status column next to the equation. Move the cursor over the * and note that the status bar at the bottom of the screen reads, "Unsatisfied." You may also click and drag on the column separator to expand a column. Equations are also displayed in MathLook view at the bottom of the screen. If the MathLook view is not displayed, use the View menu to activate it. 2. Activate the Variable Sheet and enter values of 2, 3, and 4 in the input column for the variables a, b, and c. We now have one equation and one unknown. Press F9 to solve or use the Commands Menu or toolbar icon. TK displays the value of d, 1.25, in the output column. Also, the * disappeared from the Rule Sheet and rule is marked as Satisfied. Look at the lower right corner of the screen. TK displays the memory available along with an "OK" message. OK appears after solving. If any changes are made to the Rule or Variable Sheets, TK changes the OK to F9 as a reminder. 3. Switch to the Variable Sheet and enter 1.5 as an input for d. Notice that the OK indicator has changed to F9. Cursor to the input field for the variable a and press Spacebar and Enter to blank out the value. Again, we have one equation and one unknown. Press F9 to solve. The solution for a appears in the output column. 4. Switch back to the Rule Sheet and place the cursor over the equation. Press F5 or double-click to change to edit mode. Edit the rule to read a+b = b*c . 5. Switch to the Variable Sheet and enter inputs of 2 and 3 for a and c and blank out any other input values. We have one equation and one unknown. Press F9 and...no solution. If an unknown appears more than once in a rule, TKs Direct Solver cannot solve it. 6. Move the cursor to the status column of the variable b and type G or double-click and choose Guess to indicate that b will have an initial guess. By default, TK places the last value entered as the guess value or 0 if no value has been entered yet. We can enter any value we choose as a guess. Press F9 again and a solution is found, b=1. TKs Iterative Solver sent the guess value to the Direct Solver. The Direct Solver detected an inconsistency and reported the value back to the Iterative Solver. The Iterative Solver sent a new guess value and the process was repeated until the Direct Solver no longer detected the inconsistency. 7. Switch back to the Rule Sheet and enter a second equation, a/b + 1 = c. This is a different version of the previous rule and none of the variables appears more than once. Press F9 and TK solves for b directly with no guess needed.

www.uts.us.com

15

Now lets practice with multiple equations. Keep in mind that the same process is used. TK will use solutions from equations in trying to solve other equations. In general, though, TK cannot solve an equation directly if it has more than one unknown or the unknown appears more than once. 1. Use File New to reset all the sheets for the next lesson. 2. Enter the following equations on the Rule Sheet. y1 = 3*x^2 y2 = x*LN(x) + 20*x 3. Switch to the Variable Sheet, enter 50 as an input for y1 and solve. Success. The first equation has only one unknown, x, which appears only once. Once x is known from the first rule, the value is used in the second rule to solve for y2. 4. Now give y2 an input of 50, blank y1 and solve. No solution. In this case, the first equation has two unknowns so TK skips it. The second rule has only one unknown, x, but it appears more than once so TK cannot solve for it directly. Try a guess for x and solve again. Success. Try a different guess for y1 and solve again. Success again. What happens when we guess? The purpose of guessing is to temporarily reduce the number of unknowns in an equation to one. TK can then solve the equation and move on to others if necessary. Eventually, TK will find an inconsistency in one of the rules and will then iterate on the guess value until the inconsistency is sufficiently small (less than 1E-6 by default). 5. Add a third rule, y1 = y2. Blank out any input values. We now have three equations and three unknowns but none of the equations has only one unknown so we'll need to use a guess and iterate. Does it matter which variable we guess? See for yourself. Some guesses lead to error conditions. In this case, if TK tries a value of x which is less than or equal to zero, it will report an error. The second rule includes the expression LN(x) which is not defined for negative x values. 6. At this point, let's save our work. Use the File Menu to Save As the file name WORK1. TK saves all the sheets in one file. Use File New to reset all the sheets.

www.uts.us.com

16

Special Topic: Understanding TKs Accuracy


1. Enter the rule a = a+1. Switch to the Variable Sheet, enter an input of 1 for a and solve. TK reports an error. TKs Direct Solver detects an inconsistency because 1 is relatively different from 2. 2. Now change the input value to 1E7 and solve again. No error. The two sides of the equation are within TKs Comparison Tolerance. 3. Use the Options Menu and choose Settings. Change the Comparison Tolerance setting to 1E-9 and solve again. This time TK notices the difference. In practice, the default Comparison Tolerance of 1E-6 works quite well. However, if you are working with problems involving very small or very large values, you may need to adjust this setting. 4. Use File New to reset and we'll move on.

Guiding the Iterative Solver


1. Load the WORK1 file. 2. Activate the Rule Sheet and double-click in the status column of the third rule to cancel it so that the two original equations are the only ones used. 3. Enter 50 as the input for y2 and blank any other inputs if there are any. As we saw before, if we try solving at this point TKs Direct Solver will fail. A guess is required to launch the Iterative Solver. We can automate that process. 4. One of the properties for a variable is a first guess value. If the Direct Solver does not make progress, TK looks for first guesses for any of the output variables and launches the Iterative Solver automatically. Enter a value of 1 as the first guess property value for x. Notice that TK places an F in the status column for the variable.
Status: F First Guess: 1

Now when we solve, the Iterative Solver is automatically triggered.


Status F Input Name x y1 y2 Output Unit 2.39537704 17.2134935 Comment

50

www.uts.us.com

17

Educated Guesses
Remove the first guess from the x properties. For some problems the guess value must be chosen carefully and may need to change as one or more of the inputs change. This can be accomplished by introducing an iteration trigger variable and then adding a rule to specify the required relationship. In this case, consider the following equation. y1 = y1g * y2 If y1g is assigned a first guess value of 1, then y1 will start the iteration process with the same value as y2. What if we want to guess that y1 is half of y2? Use the rule y1 = y1g * y2/2 As you can see, the extra rule can involve any expression you like.

Real Solutions Only, Please


If a guess is provided but is not sufficient to solve a problem, TK simply moves the guess value to the output field. This may lead you to believe that solved the problem for you, however, it is merely one of an infinite number of possible solutions. In situations where a default first guess is supplied as a variable property, you may not even realize that the Iterative Solver was triggered. You can turn off automatic iteration via the Settings menu. Under that condition, guesses must be provided manually by changing the status for one or more variables. If you have used a guess trigger variable, you can use conditional expressions to control when it will be used to relate two variables. For example, If given(y2) then y1 = y1g * y2/2 else y1g = 1 In this case, the guess will only be triggered if an input is provided for y2.

www.uts.us.com

18

The Optimizer A Different Approach to Equation Solving


The Optimizer can also be used to find solutions to problems like these. It takes a bit more effort to set up but it provides more control in the form of bounds and constraints that are not available with the Iterative Solver. To use the Optimizer, you must have a license for the Premium Version of TK Solver. 1. Load the WORK1 file. 2. Activate the Rule Sheet and double-click in the status column of the third rule to cancel it so that the two original equations are the only ones used. 3. Input a value of 1 for the variable x, blank any other inputs and solve.
Status Input 1 Name x y1 y2 Output 3 20 Unit Comment

4. Suppose we want to determine the value of x that results in an output of 50 for y2. Pull down the Wizards menu and launch the Optimizer Wizard. Select y2 as the objective variable, with the goal to reach a value of 50. Click Next.

www.uts.us.com

19

5. Select x as the decision variable. In this case, there are no bounds required, so we leave the >= and <= fields blank. Click Next.

6. In this case, there are no additional constraints, so click Finished to launch the Optimizer, then click Exit to close the Wizard and view the solution in TK.

www.uts.us.com

20

Here is the variable sheet showing the results from the Optimizer.
Status Input Name 2.39537704 x y1 y2 Output 17.2134934 49.9999999 Unit Comment

The Optimizer works as a shell around TK Solver, repeatedly trying new input values, solving (F9) and observing the results until the goal is achieved. The Optimizer uses the current values of the decision variables as initial guesses. Different starting points may result in different solutions. Additional constraints can be added to guide the Optimizer in finding a particular solution. There is a second way of accessing the Optimizer set up screen Commands, Setup Optimizer.

The Wizard offers a series of screens to guide you while the Commands option provides a more concise interface. Use whichever you prefer. In either case, once you have set up the Optimizer for a particular TK model, the configuration is saved with the model. This means that if you make changes to the model, you can automatically re-run the Optimizer by pressing F11 without having to go through the set up process each time. 7. Edit the second rule as follows: y2 = x*LN(x) + 15*x

www.uts.us.com

21

8. Press F11 and the Optimizer finds the new value of x.


Status Input Name 3.09957119 x y1 y2 Output 28.8220247 50.0000004 Unit Comment

Equation Solving Summary


Direct Solver: One equation, one unknown appearing just once Automatically inverts functions wherever possible Uses results from equations in trying to solve others Makes multiple passes through the rules until no progress can be made Iterative Solver: Sends guess values to the Direct Solver and receives inconsistencies back Iterates on the guess values until the inconsistencies are relatively small First guesses can be assigned as variable properties Guess triggers can be added for educated guesses Optimizer: Repeatedly runs a model until an objective is achieved Initial inputs are used as starting guesses Allows for bounds on any of the decision variables Allows for constraints on any expressions in the model

Quiz/Practice Problem
Solve the following equations for x and y, for A = 3.9 and B = 0.75: A = exp(x) + x*y B = sin(x*y) + x + y 1. Use the Iterative Solver. Does it matter which variable you guess? Do all guess values lead to the same solution? 2. Use the Optimizer. You can use either A or B as the target variable and add the value of the other variable as a constraint. Use x and y as the decision variables. Do all guess values lead to the same solution? The solution values for x are 1.466498, 2.031738, and 2.206181. Did you find all three? Now lets see how we can use TK Solver to investigate sets of equations like these using ranges of input values in tables and plots.

www.uts.us.com

22

List Solving
List Solving is the repeated processing of the rules over ranges of inputs stored in lists. Any model that can solved once can also be list solved. Here are the steps required: Make sure the model solves once using typical input values. Associate lists with inputs and outputs (and guesses if necessary). Fill the input (and guess) lists with values. Use the List Solve command. Lets try it. Load the WORK1 file again with the following two equations. y1 = 3*x^2 y2 = x*LN(x) + 20*x We will use TK to List Solve and create a table and plot showing how y1 and y2 vary as x goes from 1 to 10. 1. Enter 2 as the input for x, blank any other inputs, and solve.
Status Input 2 Name x y1 y2 Output 12 41.3862944 Unit Comment

2. Associate lists with each of the three variables by double-clicking in the Status column and choosing List. You can also type an L to assign List status to a variable. It is a toggle, turning the list status on and off. 3. Move to the input field for x, click the Commands menu, and choose List Fill.

www.uts.us.com

23

4. Choose Linear and Fill By Step, First Element 1, Step Size .2, First Value 1, and Last Value 10. Then click the Fill List button. 5. Use the Object Bar or Navigation Bar to view the 46 values in the x list. 6. Click the Commands menu and choose List Solve or press F10. TK solves the rules 46 times, using each of the x values as inputs and storing the results for y1 and y2 in the associated lists. 7. Use the Navigation Bar to open the Plot Sheet. Create a new plot called p1 and specify that x is the x-axis list and y1 and y2 are the y-axis lists. View the plot via the Object Bar or using the Commands menu.
300 250 200 150 100 50 0 1 2 3 4 5 6 7 8 9 10

8. Edit the properties of the plot to add labels and indicate which line is which.
300 250 200 1 2 2 1 2 2 1 2 3 4 5 x 6 7 8 9 10 1

y1 and y2

150 100 50 2 01 1

9. Follow similar steps to create a table displaying the three lists together.

www.uts.us.com

24

The List Solve Wizard


The previous example took us through all the steps involved in using List Solving to generate plots and tables of solutions. Good news many of these steps have been automated via the List Solver Wizard. 1. Use File New to reset TK and enter the rule y = sind(x) on the rule sheet. 2. Enter an input of 30 for x on the variable sheet and solve (F9). 3. Use the Wizards menu to launch the List Solver Wizard. As you can see, the first step is to make the model solves for a single value and you have already done that.

www.uts.us.com

25

4. Press Next to continue to step 2, variable selection. In this example, we have just one input and output to choose from but you can store as many outputs as you like. It is during this step that TK is associating lists with the selected variables.

5. Click Next to proceed to step 3, filling the input list. Choose Linear and Fill By Step, with Step Size 3, First Value 0 and Last Value 360.

www.uts.us.com

26

6. Click Next to go to the 4th and final step, naming the resulting table and plot.

7. Click Next to close the wizard and view the table and plot.
1 .8 .6 .4 .2 y 0 -.2 -.4 -.6 -.8 -1 0 50 100 150 200 x 250 300 350 400

Heres a portion of the table. The Wizard saves a lot of keystrokes and mouse clicks!
Element 1 2 3 4 5 6 7 8 9 10 11 x 0 3 6 9 12 15 18 21 24 27 30 y 0 .052335956 .104528463 .156434465 .207911691 .258819045 .309016994 .35836795 .406736643 .4539905 .5

www.uts.us.com

27

List Solving with Iteration


If iteration is required during List Solving, you must do one of the following: provide a list of guesses (variable status LG). provide a default guess value on the variable subsheet (variable status L). extrapolate -- use the previous solution as the next guess (advanced). This topic is covered in detail in the Advanced Training document but the concepts arent particularly difficult. Guess extrapolation in list solving involves the use of the ELT and PLACE functions to determine the current element number during list solving and place the current value into the subsequent element where it can be used as the next guess. Here is an example, assuming the status for variable x is LG. place(x,elt()+1) = x If the x list has an initial guess in element 1, this rule will place the computed value into element 2. Higher order guess extrapolation is also possible using similar logic.

Units and Conversions


Open the View Properties Dialog for this section. Be sure to click the thumbtack icon in that form to keep it visible. 1. Enter the rule area = length * width . 2. Switch to the Variable Sheet and enter input values of 3 for length and 4 for width. Solve and TK tells us that area is 12. The units are implied by the equation.

www.uts.us.com

28

3. Let's tell TK to do the calculation in inches. Move to the unit column and enter in for both length and width and in^2 for area. See the properties for the variable area. Both the display and calculation units are listed as in^2.

4. Open the Unit Sheet and define a unit conversion. In the From column, enter in. In the To column, enter cm. In the Multiply By column, enter 2.54.
From in To cm Multiply By 2.54 Add Offset Comment

5. Go to the Variable Sheet and enter cm as the unit for length. TK automatically changes the value in the input field. The calculation unit is still inches (in) but the display is now centimeters (cm).

www.uts.us.com

29

6. Change the display unit for area to cm^2. TK places a ? symbol next to the value. This indicates that TK does not know the conversion from in^2 to cm^2.

7. Go to the Unit Sheet and enter a second conversion from in^2 to cm^2. Enter 2.54^2 in the Multiply By column. Go to the Variable Sheet to see that TK has made the conversion. 8. Go back to the Unit Sheet and define some more conversions: cm to mm (enter 10) cm^2 to mm^2 (enter 100) ft to in (enter 12) ft^2 to in^2 (enter 144) ft to cm (TK automatically calculates this factor!) 9. Use the File Menu, select Save Window and save the Unit Sheet to a file called areaunit. Later, we can merge this information into another model instead of retyping it. 10. Switch back to the Variable Sheet and associate lists with each of the variables. (Remember how to do this?) Go to the List Sheet. The associated lists have the same display and calculation units as the variables on the Variable Sheet. 11. Go back to the Variable Sheet and change the display unit for area to mm^2. TK does the conversion. Now return to the List Sheet and see that the list is still in the original units. The units are linked only during creation of the list. Any changes to either the variables' or the list's units are done independently.

www.uts.us.com

30

12. Use the Applications Menu to access the TK Library and select the Utilities Section. Then select the Units section and merge one of the Unit Sheets into the current model.

Summary:
Your initial entry in the Unit field assigns both the calculation and display units to the variable. Subsequent entries change only the display unit. Units are not like variables. They are simply text strings. TK does not recognize that in^2 means "inches squared." Conversion factors work in both directions. If in to cm is defined, then TK can also convert cm to in. Conversion factors can be chained. Given in to cm and cm to mm, TK knows in to mm. There are no built-in unit conversion factors. You must define your own or merge in a Unit Sheet which was previously created. See the TK Library or Units Import Wizard. Lists can also have calculation and display units. Associated lists initially take on the display and calculation units of the variables. However, subsequent changes ARE NOT linked. Open the View Properties Dialog to get a better view of the units for all variables.

If you make an error when initially entering a unit, DO NOT type over the mistake. TK will interpret the initial entry as the calculation unit and then attempt to convert to the second entry as the display unit. Blank the field using Edit Cut or use the spacebar.

www.uts.us.com

31

TK Unit Wizards
The Object Units Summary Wizard provides a listing of all possible units which are available for a particular variable. The wizard displays the calculation and display units for the variable along with a listing of units. You just pick the one you want and TK updates the Variable Sheet. Rumor has it that TK6 will make this wizard obsolete The Global Units Summary Wizard allows for global switching of units throughout the Variable Sheet. You can define unit groupings (such as US and Metric) and swap between them. The Units Import Wizard presents categories of units to load into TKs Units Sheet.

www.uts.us.com

32

Review Exercise
Enter the following equations on the Rule Sheet. loan = price - down X = loan*(r/(1-(1+r)^-n)) pk = X*((1+r)^-(n-k)-(1+r)^-(n-k+1))/r ik = X - pk T = X*n Ti = T - loan You may recognize these formulas as those used for evaluating consumer loans. Here the variable sheet after reorganizing and the addition of comments.
==================== VARIABLE SHEET ============================= St Input---- Name--- Output--- Unit----- Comment----------------price Price down Down payment loan Loan amount r Interest rate X Monthly payment n Number of monthly payment T Total of all payments Ti Total interest paid k Payment to be studied pk Principal paid in kth payment ik Interest paid in kth payment

In this example, units play an important role. As implied by the equations, the variable r is being calculated as the monthly interest rate in decimal form. Unfortunately, we don't usually think in these terms. Instead, we talk about annual rates in percents. Enter monthly as the unit for the variable r. Go to the Unit Sheet and add the following conversion. monthly to %/yr (enter 1200 for the conversion factor) Go back to the Variable Sheet and change the display unit for r to %/yr. Let's try it out on a few sample problems. Given: price = 24000 down = 6000 r = 10 (%/yr) n = 48 (this is the term of the loan, in months) k = 1 (this is the current month number)

www.uts.us.com

33

1. What is the monthly payment and total interest on this loan? 2. The buyer can only afford payments of $425 per month. What interest rate would make this possible? What change does this make in the total cost of the loan? 3. The buyer negotiates the deal at 9% interest. What monthly payment did they settle for? List solve and set up a table showing the principal and interest paid in each of the 48 payments. Show these curves on both a line chart and a bar chart. Try the stacked bar option. Save the file with the name Loan.

Formats
Numeric Formats are TK objects just like lists and tables. Formats can be assigned to variables or lists or columns in tables. A format can be assigned as the Global Format in the Options menu. This format will then be assigned to all variables, lists and tables unless another format is specifically designated for those objects. For practice, create a format and assign it to a variable.

Comments
Comments are also TK objects. Comments have several unique features. They can be linked by using an asterisk within a comment. For example, if a comment includes the text *uts, you can navigate directly from the current comment to the uts comment using a right-click. Comments on the List Sheet have a dual role in that they are used as the plot legend text for those lists. We suggest that before you save a TK model, create a comment displaying the author, date, and some description of what the model does. The next time the model is opened, the comment will be a nice summary.

www.uts.us.com

34

MathLook
The MathLook View at the bottom of the TK screen automatically formats whichever rule or function statement is highlighted in the current sheet. You can right-click in the MathLook View to copy the equation to paste into another program. TK Solver also includes a MathLook Sheet that formats multiple rules and can also include other graphics images. Highlight rules on the rule sheet or functions and copy them. Then paste them into MathLook and you will see them formatted. MathLook is not intended for use as a report writer but rather a utility for converting formulas and collecting graphics prior to copying and pasting into reports.

Report Writing
There are two approaches you can take in producing reports based on TK models. 1. Copy and paste into Word or Excel. or 2. Use the TK Report Writer (File Create Report). Option 1 has several advantages. You have complete control over what goes into the report. If you Paste Special with the Paste Link option, the TK objects in the document will automatically update when you make changes to the model. You can insert text wherever you like. Option 1 was used to create these training documents. Option 2 can be more efficient, especially if you intend to include many different TK objects in the report. The resulting report can be converted to an .RTF file that can be subsequently edited in Word but many of the graphical objects dont make it cleanly through the conversion process so you may need to copy and paste those manually.

www.uts.us.com

35

Sample Exercise
Create a TK Solver model using the following formulas. volume = 1/3 * pi() * radius^2 * height radius^2 + height^2 = slant^2 surface = pi() * radius * slant tand(theta/2) = radius/height Assign units to each of the variables using in as the base unit of length and deg for the angle. Merge in a unit sheet from the TK Library. Input 20 for the volume and 3 for the radius and solve. Use the List Solve Wizard to generate a table and plot of surface vs. radius as the radius ranges from 1 to 5 in steps of 0.2. Assign formats to the columns of the table as well as the variables on the variable sheet. Use the Optimizer to determine the radius resulting in the minimum surface value. Copy the equations into MathLook. Add a comment to the model, organize the sheets and save the file as CONE. Create a report using File-Create Report. Copy the variable sheet and paste special, linking as a TKW Document Object in Word. Change the inputs in TK and solve. Check to see that the variable sheet updated in Word. Try the same process with the plot.
Sample 80 70
surface

+ + + + + + + + 1 1.5 + + + + + + + 2 2.5 3 + + + + +

60 + 50 40 30

3.5

4.5

radius [in]

www.uts.us.com

36

Linking TK Solver Models with Excel


TK Solver models can be linked with Excel spreadsheets for several purposes. You can use Excel to build a custom interface/report for the TK model. You can use Excel as a dashboard for linking multiple TK models together, where the results of one model might be used as inputs in others. You can use TK Packager with a linked spreadsheet to create and distribute applications to end users with access to Excel (but not necessarily TK). The prerequisites for linking are as follows: The TK model file must be saved. The model must be configured with a particular set of inputs and outputs. You cannot link a model that has no inputs or outputs. The model must solve without the use of a guess on the variable sheet. Default first guesses on variable subsheets are ok. Guesses based on other input variables can also be programmed in TK and triggered by default first guesses on variable subsheets. If list solving is required, the variable sheet must include the proper configuration. The TK model must not include any of the following functions: PROMPT, QUERY, MENU. All such data gathering should be done in Excel. The TK model may include the error trapping functions (ERRMSG, DEBUG, PAUSEMSG) but they will be ignored in Excel. Any reporting of messages should be programmed in the Excel interface.

The TK Solver-Excel Toolkit installs as an Excel Add-in under the Tools menu. A set of optional toolbar icons is available as well. For this exercise, we start with a new spreadsheet. With A1 as the active cell we click the Insert TK Model icon from the toolbar. The Toolkit prompts for the name of the file. Use the CONE model.

www.uts.us.com

37

We will load the cone model but before we do, we confirm the configuration of the TK variable sheet as we will need it for use in Excel. When it solves as expected, we save it and it is ready for linking.
Status L Input 3 Name radius height slant volume surface angle Output 2.12206591 3.67466512 34.6329028 109.452237 Unit in in in in^3 in^2 deg Comment

20 L

The Wizard automatically displays those variables with inputs. If you choose not to link any of these input variables, they will act like constants in the model. You will not be able to change them from Excel. In this exercise, we will use all the inputs and outputs.

www.uts.us.com

38

Click Next to accept the inputs and then the outputs.

Because this model is set up for list solving, the link will solve for the variables on the variable sheet and also list solve. The next two forms allow you to link plots and tables. Since our model has a plot, we will link it. It is important to note that the tables and plots are not editable within Excel. If you would like to edit the data you must follow a separate process for linking the underlying lists. For now, click Next to accept the default links until you come to the form with options involving units, comments, and formats.

www.uts.us.com

39

In this exercise, we will include the units from the TK model since our model has no comments.

You are strongly advised to avoid the use of the TK formats when linking to Excel. By accepting the formatted values, you are in effect losing the accuracy of the actual calculations. This will have a serious impact on all subsequent calculations, including optimizations performed by the Excel Solver. It is best to format the values in Excel and the full precision of the TK calculations will be retained. For this reason, the Link Wizard defaults to no for the use of TK formatting. When you click the Finish button, the variables and plot appear. Here are the variables.

Input
radius volume

Value

Unit

Output
height slant surface angle

Value
2.122066 3.674665 34.6329 109.4522

Unit
in in in^2 deg

3 in 20 in^3

These variables are now directly linked with the TK Solver model. Try changing the radius value from 3 to 4 and watch the outputs update.

Input
radius volume

Value

Unit

Output
height slant surface angle

Value
1.193662 4.174306 52.45587 146.7682

Unit
in in in^2 deg

4 in 20 in^3

The Value column of the output variables contains formulas that link to TK. Here is the formula for the height output... =TKSolverGetValue("height",TKHidden!$A$11:$A$12) If you type over these formulas the link is destroyed.

www.uts.us.com

40

The Unit column provides a listing of available units for each variable, inputs and outputs. These are the units from the TK Unit Sheet that are chained to the calculation unit for each variable.

Input
radius volume

Value

Unit

Output
height slant surface angle

Value
1.193662 4.174306 52.45587 146.7682

Unit
in in in^2 deg

101.6 mm 20 in^3

You can reference these linked cells from other formulas in Excel. If you intend to do so, you should NOT include TKs unit conversion feature when you link the model. Your Excel formulas will not update in the proper units when the TK variable units are changed. Heres a simple example. Suppose you add a formula in Excel for calculating the mass of the cone. Your formula would be a function of the volume. Assuming you have used MathLook for Excel to youre your cells, your formula might appear something like =volume*density . Input
radius volume density

Value

Unit

Output
height slant surface angle mass

Value
1.193662 4.174306 52.45587 146.7682 1400

Unit
in in in^2 deg

4 in 20 in^3 70 lb/in^3

If you ask TK to switch the volume unit from in^3 to ft^3, the value will decrease by a factor of 12^3. Then the mass value will also decrease by the same factor which would be confusing. The TK cells all maintain unit integrity but the new Excel formulas you may add do not. If you linked the units and then change your mind later, you can lock them up again in Excel using the Excel Toolkit Locking Option. Click the List Link icon to link the radius and surface lists from the CONE model. When the form appears, note the two tabs for inputs and outputs. Double-click in the range field for the radius list and Excel will prompt for the cell location where the radius list will begin.

You can click directly in the spreadsheet and Excel will fill the form for you. Repeat the process for the output list, surface. Then click the OK button at the bottom of the list link form and the lists will appear. Change the value of the volume in the spreadsheet and watch the surface list update. Save the spreadsheet, then close it and return to TK Solver and File New to reset TK.

www.uts.us.com

41

Review Exercise
This sample involves water flowing though a tube. The resulting math model will compute the pressure drop due to friction as the water flows through the tube. We will add unit conversions, a table, a plot, and then link it to Excel. Here are the equations to be used, starting with the fluid property functions:
Rule density = $satldens(3,'water,'T,T) viscosity = $viscosity(3,'water,'T,T,'D,density) q = w/density V = 4*q/(pi()*D^2) NRe = V*D*density/viscosity 1/sqrt(f) = -4*log(eps/(3.7*D)+(1.255/(NRe*sqrt(f)))) deltap/L = f*density*V^2/(D*16.085) gradient = deltap/L

Here is the resulting variable sheet, with comments and units and sample inputs. A default first guess of .001 works well for the friction factor, f. Do you understand why a guess is required to solve for f?
St Input Name Output Unit Comment Friction Loss in a Straight Pipe Isothermal Turbulent Flow Fluid temperature Fluid density Fluid viscosity Inside pipe diameter Pipe roughness Pipe length Volumetric rate of flow Weight rate of flow Linear velocity Reynolds number Friction factor Pressure drop due to friction Pressure drop gradient

60

0.2 0.0006 20 0.1

T density viscosity D eps L q w V NRe f deltap gradient

62.36 0.000753

6.236 3.183 52702 0.007127 27.996 1.4

oF lb/ft^3 lb/ft-s ft ft ft ft^3/s lb/s ft/s

lbf/ft^2 lbf/ft^3

Use the Units Import Wizard to load up the Unit Sheet.

www.uts.us.com

42

Use the List Solve Wizard to create a table and plot of D and deltap as D goes from 0.1 to 0.5. Change the plot scaling to Y-log.
10000 3000 1000 300 100 deltap 30 10 3 1 .3 .1 .1 .15 .2 .25 .3 D [ft] .35 .4 .45 .5

Save the model and link it with Excel.


Input Value Unit Comment
T D eps L q 60 0.2 0.0006 20 0.1 oF ft ft ft ft^3/s Fluid temperature Inside pipe diameter Pipe roughness Pipe length Volumetric rate of flow

Output Value
density viscosity w V NRe f deltap gradient 62.36407361 0.000753331 6.236407361 3.183098862 52702.18965 0.007126549 27.99580516 1.399790258

Unit
lb/ft^3 lb/ft-s lb/s ft/s

Comment

Fluid density Fluid viscosity Weight rate of flow Linear velocity Reynolds number Friction factor lbf/ft^2 Pressure drop lbf/ft^3 Pressure drop gradient

www.uts.us.com

43

Here is the table after linking to Excel. You can also link the lists interactively.

Lists are a special type of object. The most important trait is that their length can vary. Because of this, their location in Excel must be handled more carefully. The first step is to identify which lists to link as inputs.

www.uts.us.com

44

Check the box next to the list name to link as an input. Then click in the List Range area and click the browse icon. The wizard waits for you to click a cell in Excel and fills the cell range for you.

This part of the process can be tricky because there are so many fields popping up on your screen. Repeat the same process for the output list, deltap. If you need to move the lists after linking, you can cut and paste them to a new location. For example, its probably best to store the lists to the right of the variables and plots. That way, you can format the column widths without affecting the other linked objects. You can test the list links the same way you tested the variables. Try changing the second element in the D list from 0.12 to 0.11. You will see the corresponding deltap value update. When you link lists you are linking a lot more cells to TK, so you can expect the solution process to slow a bit. Keep this in mind as you design your applications. You dont want to link long lists unless they are absolutely required in Excel. And remember that the Excel Solver will repeatedly update the entire list in solving for any variable, so that will perform slower if long lists are linked.
Input:D
0.1 0.12 0.14 0.16 0.18 0.2 0.22 0.24 0.26 0.28 0.3 0.32 0.34 0.36 0.38 0.4 0.42 0.44 0.46 0.48 0.5

Output:deltap
1034.208213 396.961586 177.3807319 88.58682568 48.16188887 27.99580516 17.17724184 11.01933525 7.337679122 5.043363515 3.562070549 2.575987095 1.901810258 1.429936547 1.092720397 0.84722386 0.665501445 0.52895225 0.424941894 0.344729602 0.282166314

www.uts.us.com

45

Now that you have these lists in Excel, you can format them as you like. You can also use the Excel graphing capability as an alternative to those in the TK Solver model. Click the Insert menu and select Chart to start the process.
Pressure Drop
10000 1000 deltap 100 10 1 0 0.1 D 0.1 0.2 0.3 0.4 0.5 0.6

Linking Several TK Models with Excel


You may link more than one TK model to a single Excel spreadsheet. In fact, this is an excellent way to do process modeling. The results from one model can be used as the inputs for another, with everything linked and communicating within Excel. You can also link a single model two or more times to view as multiple cases for comparison. To link a second model, just position the cursor in a cell with room for your incoming variables and then launch the wizard by clicking on the Insert TK Model icon. Test this with a simple TK Solver model with a single equation such as a+b = c. Link it twice in a single spreadsheet. Reference the output from the first link in a formula for one of the inputs to the second link. Heres an example.

Input
a1 b1

Value
2 4

Output
c1

Value
6

Input
a2 b2

Value
3 4

Output
c2

Value
7

www.uts.us.com

46

The underlying TK model has the equation a+b = c with inputs for a and b and an output for c. After linking the model twice, we edited the variable names in Excel and added a formula linking the output for c1 to the input for a2, =f3/2, where f3 is the cell containing the output for c1. The shading is added for illustration only. Obviously, if you have formulas this simple you can easily put them into a single TK Solver model. However, the process works the same regardless of the complexity of the underlying TK models.

Functions
TK Functions can be classified as either built-in or user-defined.

Listings of Available Built-in Functions


There are several ways to access listings of TKs built-in functions the Help utility, the Wizards tab of the Navigation Bar, and the CTRL-F or CTRL-SPACE hot keys while editing equations. 1. Reset TK and open the Help utility to the Table of Contents. Open the Functions and Wizards section and then select Built-in Functions. All the categories are displayed. Click on any group for further descriptions. Close the Help window when you are finished browsing it.

www.uts.us.com

47

2. Click on the Wizards tab at the bottom of the Navigation Bar and then select Function Wizard for another listing of function categories. We will put these wizards to work later in this training session. When you are finished browsing this list, click the Sheets tab.

www.uts.us.com

48

3. Begin typing y = on the rule sheet and then press ctrl-f or ctrl-space and you will get an alphabetical listing of all the built-in functions. Note that those functions that start with special characters are at the top of the list.

When you select a function from the list, TK automatically enters it and displays a tool tip with a listing of the required value types. You will learn more about value types later. For now, press Escape to clear the rule.

www.uts.us.com

49

TK Function Vocabulary
The words in italics below have special meanings with respect to TK. 1. Enter the equation y = Log(x). The variable x is the argument of the function and the variable y is the result. Because Log is an invertible function, TKs Direct Solver can solve for y given x or to solve for x given y. Log is a built-in function which means that it is always available whenever we are working in TK. 2. Switch to the Variable Sheet and enter 7, a numeric value, as the input for x and solve. The log function requires a numeric value as its argument and it returns a numeric value as its result. 3. TK variables can also have symbolic values. Enter the word red as the input for x. Note that TK automatically places an apostrophe in front of the word. Without the apostrophe, the expression would look just like a variable so the apostrophe is TKs way of differentiating between variable names and symbolic values. Symbolic values are sometimes called strings or string values. Symbolic values start with an apostrophe if there is just one word or are surrounded by double quotes if there are multiple words. 4. Solve again. TK reports an error, "Invalid Symbolic Computation". The log function cannot process a symbolic value. 5. Cursor down and enter red as the name of a third variable. Enter 10 as its input value. Now enter red as the input value of x again. TK replaces the word red with the value of the variable named red. 6. The rule y = Log(x) includes a function reference. Functions can also be called. Switch to the Rule Sheet and enter the rule call log(x;y) on the second line. The semicolon separates the argument variable from the result variable. Function calls have the same effect as function references but they allow for 0 to 20 result variables whereas function references can only have 1 or 2 result variables. We will see the importance of function calls later. Solve to verify that the second rule is OK. 7. Click File New to reset the sheets and then enter the rule y = sum(x). Sum is also a builtin function. The function sum returns the sum of a list of numeric values. The argument variable x must have a symbolic value which refers to the name of a list. 8. Go to the List Sheet and create a list called abc. Open the subsheet for abc and enter the values 10, 20, 30, and 40. Go to the Variable Sheet and enter abc as the value for x. TK converts it to the symbolic value abc. Solve (F9) to see the result. Note that even though the rule processed a list of values, List Solving was not necessary. Remember that List Solving is the repeated process of rules on the rule sheet using lists of values associated with one or more inputs. In this example, we only need TK to process the rule sheet one time.

www.uts.us.com

50

Function Wizards
The Wizards tab of the Navigation Bar presents a complete collection of wizards to help with using any of the TK built-in functions. You are presented with all the available options for each function and you fill in the blanks for everything you know about the inputs. There is a Help button which takes you directly to the online help related to the function. Once you have everything entered, click the Build Rule button and TK shows you what the expression will look like in TK. At that point, you can either click OK to paste the expression into the current field in TK or copy (CTRL-C) and paste (CTRL-V) the expression wherever you need it.

Rule Functions
If you have one or more rules that you intend to use repeatedly in one or more TK models you should consider the use of Rule Functions. Once created, Rule Functions can be saved and merged into other applications as needed. Rule functions can referenced repeatedly within other rules. Theres a nice example in the TK Library showing the efficiency of using rule functions. Go to the Engineering Examples section and study the Circuit Design model. The functions ser and par really simplify the rule sheet for that model.

www.uts.us.com

51

Practice Problem:
TK Solver includes built-in functions for converting between rectangular and polar coordinates. The following example uses a rule function to extend this concept to allow for conversions to spherical coordinates. 1. Go to the Function Sheet and enter stord (short for spherical to rectangular) as the name of the function. Cursor to the Type column and enter R to define stord as a rule function then open the subsheet and enter the equations: (x,y) = ptord(r,theta) (z,r) = ptord(rho,phi) The "d" suffix after the trig functions indicates that the calculation is done in degrees. The ptord function is a built-in function for converting between polar and rectangular coordinates with angles measured in degrees. 2. Enter rho,phi,theta in the Argument Variables field. Enter x,y,z in the Result Variables field. This maps the local variables with whatever expressions are used in referencing this rule function. 3. Activate the Rule Sheet and enter the following rule: call stord(rho,phi,theta;x1-x0,y1-y0,z1-z0) The variables and expressions in this rule are mapped to the local variables in the stord function according to their position. Those variables preceding the semicolon are mapped by position to the three Argument Variables in the function. Similarly, the three Result Variables in the function are mapped to the three expressions in the rule. For example, the expression x1-x0 is mapped to the local variable x. 4. Enter the following inputs on the variable sheet and solve. rho=1; theta=-110; phi=26; x0=.5; y0=.7; z0=1 The stord function solves for the local variables x, y, and z and then TK computes x1, y1, and z1 on the Rule Sheet...just like a built-in function. 5. Go to the Rule Sheet and highlight the rule. Press CTRL-D and TK opens the stord function subsheet. Another way to quickly access a user-defined function is via the functions icon f(x) on the Object Bar. Once in the subsheet, use the Commands menu and select Examine or click the Examine icon (it looks like a magnifying glass) to invoke the Examine Command.

www.uts.us.com

52

The Examine Command is used to evaluate an expression from anywhere in a TK model. It is especially useful for debugging functions by evaluating local variables. You can use it to check values, call functions, etc. Examine the value of the local variable r. That variable represents the projection of the distance rho onto the x,y plane. 6. Use the File Menu to Save the Window to a file called stordfun. The other sheets are not saved. The stord function might be useful in other models in the future and we will be able to merge it and use it as we would a built-in function.

Procedure Functions
Procedure functions (procedures) supplement TKs rule-based capabilities with sequential programming and processing. Procedures are called as subroutines from the rule sheet or from other functions. Procedures cannot call rules from the rule sheet. Procedures can not call on the Direct or Iterative Solvers to solve equations, however those solvers CAN repeatedly process procedures during an iterative process. Here is a complete listing of all the types of statements you can use in procedures. An ASSIGNMENT statement has the form variable_name = expression or list_element = expression or (name1, name2) = expression resulting in a pair of values where name1 and name2 can be names of variables or list element identifiers or one of each. For example, XYZ[i] represents the ith element of the list XYZ. Assignment statements allow either = or := for the assignment operator. You may also call functions in procedure statements. A GOTO statement has the form goto label_name . A LABEL statement has the form label_name: . A RETURN statement has the form return . A FOR-NEXT loop construct has the form FOR var_name = expression1 TO expression2 {STEP expression3} {statements} NEXT {var_name} where expression1 and expression2 must evaluate to numeric values and the optional expression3 must evaluate to a non-zero numeric value (defaults to 1). The optional statements inside the loop can include other correctly nested for-next loops.

www.uts.us.com

53

A CONTINUE statement has the form CONTINUE {variable_name} and takes control to the NEXT statement of the current loop, or to the NEXT statement of a loop at a higher level specified by the optional variable_name. An EXIT statement has the form EXIT {variable_name} and takes control to the statement after the NEXT statement of the current loop, or to the statement after the NEXT statement of a loop at a higher level specified by the optional variable_name.

Practice Problem:
1. Reset all the sheets and open the Function Sheet. We will create a function which computes a factorial. Activate the Function Sheet and create a Procedure Function named fact. 2. Open the subsheet for fact and enter the information as shown below.
==================== PROCEDURE FUNCTION: fact ================= Comment: Computes factorials Parameter Variables: Input Variables: n Output Variables: z S Statement------------------------------------------------------------z = 1 If OR(n=0,n=1) then return for i = 2 to n z = i*z next i

The Comment field helps us identify the contents of the function. There is one Input Variable and one Output Variable. These work in a similar fashion as Argument and Result Variables in Rule Functions. We use them to map values of local variables to the rest of the model. 3. Go to the Rule Sheet and enter c = fact(x). The two variables in this rule are mapped to the variables in the function x is mapped to n and c is mapped to z. 4. Go to the Variable Sheet and enter 13 as the input for x and solve. Change x to 20 and solve again. 5. Enter an input value of 172 for x and solve again. An error! Open the fact subsheet and insert the following line in the first row to trap the error and provide a more helpful error message: if n>170 then call errmsg(Function fact is not valid for n>170) 6. Suppose you also need the procedure to generate a list (called facts) of the factorials up to and including the nth. Insert the following as the first statement in the procedure. Call blank(facts)

www.uts.us.com

54

This will clear the facts list of any values from a previous run. Then insert the following statement just below the line z = 1 to place a 1 in the first element of the facts list. facts[1] = 1 Then insert the following statement just below the z = z*i statement. facts[i] = z This places the current value of z into the ith element of the facts list. 7. Suppose you would like to use different lists to store the factorials on different runs. You can make the list name a variable by removing the apostrophe in each of the three statements it is used. For example, facts[i] becomes facts[i]. Then add facts to the list of input variables in the function. n,facts This tells the function that the value of the variable facts will be passed into the function. The name of the list will be an input to the function. The procedure will then place the values into that list. 8. Edit the rule on the rule sheet, adding a second input variable. c = fact(x,facts) 9. Switch to the variable sheet and enter the name of the list you would like to use to store the factorials. When you solve (F9), TK generates the list on the list sheet. Change the inputs (x and facts) and solve again. A new value of c is displayed on the variable sheet and a new list is generated on the list sheet. The TK Solver Library contains hundreds of procedures in various groupings. The Library contains both Tools and Examples. The examples show the tools in action. You can merge the tools into your own TK applications. For example, there is a file in the Statistics section of the TK Library that computes factorials, combinations, permutations, and arrangements, for inputs of any size. The functions in that model utilize special arbitrary length integer calculation algorithms and represent large numbers as multiple list elements.

www.uts.us.com

55

List Functions
List Functions allows us to create look-up tables with or without interpolation. List functions relate the elements of two lists. The mapping options are Table, Step, Linear, and Cubic, with the last two providing interpolation. 1. Start with a fresh set of TK Sheets. Go to the Function Sheet and create a List Function named f. Open the subsheet. List Functions require two lists of values and a mapping option. If the lists were previously defined in the TK model, the values will automatically appear within the function. 2. Enter color as the name of the Domain List and code as the name of the Range List.
==================== LIST FUNCTION: f ============================ Comment: Domain List: color Mapping: Table Range List: code Element-- Domain------- Range--------------1 'red 100 2 'white 200 3 'blue 300

3. Enter the values red, white, blue in the Domain column and 100, 200, 300 in the Range column. 4. Test the function using the Examine Command with the expression f('blue). TK should return the value 300. Close the Examine form. 5. Go to the Rule Sheet and enter the rule y = f(x) . The argument of the function, x, is mapped to the Domain and the result, y, is mapped to the Range. Switch to the Variable Sheet and enter 200 as the input for y. TK solves for x as the value 'white. 6. Open the function subsheet. Change the mapping option to Linear. Change the values in the color column to 1,2,3,4,5. Then change the values in the Range column to 2,4,7,23,87. TK will now interpolate within the given values. 7. Go to the Variable Sheet and enter 3.25 for x, blank y and solve. TK interpolates between 7 and 23 in the range list and provides the answer. Go back to the function subsheet, change the mapping option to Cubic and solve again. 8. Go to the Plot Sheet and create a line chart called f. Open the subsheet and enter color as the X-Axis List and code as the Y-Axis list twice -- one with Lines and one with Curves. When you plot (F7), you can see the difference between linear and cubic interpolation.

www.uts.us.com

56

A Closer Look: Passing Values to and from Functions


We have already seen that variables in equations can be mapped with local variables in functions according to their position in the list of arguments and results for rule functions and inputs and outputs for procedure functions. List functions always have one input mapped to the domain list and one output mapped to the range list. Values can also be passed to and from functions directly via list elements. For example, Place(y,1) = temperature This equation places the value of the variable temperature into the 1st element of the list y. That list element can be accessed from anywhere else in the TK model. So a rule function might include the rule T = y[1] List elements are accessible anywhere in TK and can be used to bypass the passing of variables as function arguments. Parameter variables provide a means of passing values directly from the Variable Sheet to a function. This is useful for two reasons. First, since functions can call or reference other functions, you may need an efficient means of getting a value to a deeply nested function without having to pass the value through each of the intermediate functions. Second, some functions assume that another function will have a specific number of inputs as they process them. Additional values can be passed into the function using Parameter Variables. Examples of built-in functions that reference other functions: Numerical Integration: INTEGRAL, INTEGRAL_2FIX, INTEGRAL_3VAR Differential Equation Integrators: ODE_RK4, ODE_RK5Adapt, ODE_RK5FINAL INTEGRAL_2VAR, INTEGRAL_3FIX,

ODE_BS,

ODE_STIFFR,

ODE_STIFFBS,

TK Library tools also reference other functions. For example, various root finders repeatedly reference a function as they iterate to a solution. The Optimization section of the Library includes tools which repeatedly reference functions until a max or min is found. These tools pass inputs to the function but rely on parameter variables for passing constants from the Variable Sheet throughout the process.

www.uts.us.com

57

Review Problem
Just as we can find the square root of a variable or collate a list, we can also use TK to process functions. The TK Library has many tools for these tasks. The most commonly used tools are in the areas of differentiation, integration, optimization, and root finding. For example, we can differentiate a function with respect to its input variable. Likewise, we can find the input to a function which leads to result of zero, and so that input is a root of the function. To further clarify, note that we do not differentiate variables or lists -- we differentiate functions. Given y = f(x), we do not integrate y from 0 to 1, we integrate f(x) as x ranges from 0 to 1. With this in mind, it is clear that we cannot integrate or differentiate a TK variable; we need to define a function and then process that. For example, suppose we have an equation such as y = cos(a*x)/cosh(b*x) and we are interested in studying the relationship between x and y as a and b remain constant. Our first step is to enter the equation on TKs Rule Sheet along with sample inputs on the Variable Sheet. Lets use a = 3 and b = 0.75. x will vary between 0 and 2*pi(). Well list solve and generate a plot.
St L L Input 1 3 .75 Name Output y -.76465998 x a b
y = cos(a*x)/cosh(b*x) a = 3, b = 0.75 1 .8 .6 .4 .2 0 -.2 -.4 -.6 -.8

www.uts.us.com

58

Now lets study the slope of the function at various values of x. To do this, we use the built-in differentiation tool from the TK Library. Select the tool called diff13 from the Mathematics section under DIFFINT and merge it into the current model.

The diff13 function requires 3 inputs and produces 1 output, as noted in the subsheet. The procedure features a single statement which evaluates the function at two points near the point of interest and then divides by the total interval, 2*h. The value of h should be relatively small, say 1E-3. The built-in function APPLY is the key to this procedure. APPLY allows the name of the function to be a variable value. APPLY(sqrt,9) = 3 and APPLY(log,10) = 1. So, if we have an expression APPLY(fun,x) , the value of the variable fun refers to the name of the function to apply to the value of x . In our model, we need to create a function for diff13 to process. The easiest way to do this is to copy the rule on the Rule Sheet and create a Rule Function on the Function Sheet. Call it bounce . Open the subsheet for bounce and paste the rule into the function.
y = cos(a*x)/cosh(b*x)

Enter a,b for the Parameter Variables, x for the Argument Variable, and y for the Result Variable.
Parameter Variables: a,b Argument Variables: x Result Variables: y

www.uts.us.com

59

Hmmm... Why are a and b listed as parameters and not arguments? The answer is that we want to differentiate the function with respect to x, while a and b remain constant. The diff13 procedure processes functions with one argument and one result (i.e. y = f(x)). Since the bounce function includes 4 variables, two of them must be passed in directly from the Variable Sheet as parameters. Enter the reference to diff13 on the Rule Sheet and solve.
Rule y = cos(a*x)/cosh(b*x) slope = diff13('bounce,x,1E-3) Input Name Output y -.76465998 1 x 3 a .75 b slope .03725461

So we see that the slope of the bounce function is .03725 at x = 1. For a plot of the derivative, change the status of slope to L and List Solve. Then add slope to the list of y-axis list names in the current plot.
y = cos(3*x)/cosh(0.75*x) (d = dy/dx) 2 1.5 1 .5 0d -.5 -1 -1.5 -2 -2.5 -3 0

d d d d d

Lets see if we can find the value of x at which the bounce function is minimized. To do this, set the slope value to 0 and guess the value of x.
Input Name Output y -.7647552 x .994893071 3 a .75 b 0 slope

Success. By guessing near the appropriate spots indicated by the plot, we could compute the locations of each of the local minimums and maximums in this fashion.

www.uts.us.com

60

The TK Solver Library

The TK Library is accessed via the Applications Menu. It is a collection of TK files. Some of the files contain a single user-defined function. Some contain just unit conversions. These simple files are generally classified as tools. Some of the files contain complete examples, with many objects of all types. Or in the case of many the statistics files, there may be many functions merged together to solve a particular problem such as for curve-fitting. These are sometimes referred to as applications. Tools are intended to be merged into your models while Examples and Applications are intended to be used on their own and could cause confusion if merged into another file. Lets look at examples of each of the three types of Library files.

www.uts.us.com

61

Use the Library Menu to go to Utilities List Manipulation Tools and load the first tool there, reverse. A single function appears on the function sheet.
Name reverse Type Procedure Arguments 1;0 Comment Reversing the order of elements in a list

It is a procedure function, processing a single input. Open the subsheet to see the algorithm.
Statement ; Description: The function reverses the order of elements in a list. ; Notation: L name of the list to be reversed n:= length(L) n1:= n + 1 if n>count(L) goto blanks for i=1 to n/2 ; good for lists without blanks j:= n1 - i (L[i],L[j]):= (L[j],L[i]) next i return blanks: for i=1 to n/2 ; an alternative treatment of lists with blanks j:= n1 - i tempi:= elt(L,i,'blank) tempj:= elt(L,j,'blank) if tempi='blank then call blank(L,j) else L[j]:= tempi if tempj='blank then call blank(L,i) else L[i]:= tempj next i

The procedure includes comments to help us understand its use. We can see that it requires the name of the list to be reversed as the only input. Create a small list on the list sheet and call the function to try it. Lets try another example. Open the Library Menu again and go to Statistics Distributions and Random Numbers and load the Normal selection. Several functions appear on the function sheet.
Name normPDF normCDF inormCDF Type Rule Rule Rule Arguments 3;1 3;1 3;1 Comment Normal distribution, PDF Normal distribution, CDF Normal distribution, Inverse CDF

Open the second one, normCDF, and observe the rules within.
Rule ; Notation: x independent variable ; m mean ; sd standard deviation ; CDF Cumulative Density; probability of observing a value <= x. CDF = (1+erf((x-m)/sd/sqrt(2)))/2

www.uts.us.com

62

There are four lines of comments and just a single equation. We see that the function requires three inputs and returns one output. Enter a rule on the rule sheet to reference this function and try solving it with some sample values. Alternatively, you can use TKs Examine Command to process the function without entering a rule. Try that too. Next, well look at some examples from the Library. Open the Library Menu and go to Mathematics Roots of Equations Examples and select Polynomial Equations. When the example loads, we see a rule sheet with comments and a single function call, along with a table in the lower portion of the screen with sample coefficients for a 10th order polynomial. The Bairstow function could be loaded independently as a tool but this example shows it in action. Solve and observe the updated table with the ten roots of the polynomial.
Element 1 2 3 4 5 6 7 8 9 10 11 Coeff .32432 .00565 .27196 .37294 .60025 .17577 .58748 .64068 .91559 .81142 .09197 Roots: Re -.13119217 -.7710957 -.2298646 -.2298646 -.86702428 -.86702428 .557944363 .557944363 .98137792 .98137792 Im 0 0 .934845084 -.93484508 .689535261 -.68953526 1.17374496 -1.173745 .704417983 -.70441798

Checking the Object Bar, we see that there is also a plot of the solutions in the complex plane.
Roots of a Polynomial Equation in the Complex Plane 1.25 x 1 x .75 .5 Imaginary .25 0 -.25 -.5 -.75 -1 -1.25 -1 -.8 -.6 -.4 x x x -.2 0 .2 .4 .6 .8 1 x x x x x

Real Components

www.uts.us.com

63

Many of the tools in the TK Library are illustrated by examples like this one. For another example, use the Library Menu to go to Utilites Graphics Utilities Examples and select General purpose graphics. When the file loads, we see a Comment Sheet describing how to use the functions (tools) featured in the Example. Solve the model and view the plots.
UTS trucks carrying TK

Lets check the function sheet to see all the tools in this example.
Name ASPECT masterC masterT mastermasterT body window TK erase vector line box circle ellipse scale mirror translate rotate append Type Procedure Procedure Procedure Rule List List List Procedure Procedure Procedure Procedure Procedure Procedure Procedure Procedure Procedure Procedure Procedure Arguments 3;0 2;0 2;0 0;0 1;1 1;1 1;1 2;0 4;0 6;0 6;0 7;0 8;0 4;0 1;0 4;0 5;0 4;0 Comment scaling x coordinates Master graph generator, calibrate circle Master graph generator, truck Composite truck truck body truck window TK on truck slate eraser vector generator line generator box generator circle generator ellipse generator picture scaling mirroring parallel translation rotation merging two pictures

www.uts.us.com

64

Some of the functions are specific to the example and some are generic tools used for generating and processing data points. Lets take a look at the rotate function.
Statement ; Notation: x,y names of lists of the picture coordinates ; x0,y0 center of rotation ; phi angle of rotation (in degrees) ; Description: Transforms the picture coordinates by rotating them around ; a given point sin:= sind(phi) cos:= cosd(phi) for i=1 to length(x) X:= elt(x,i,'blank) if X='blank goto next X:= X - x0 Y:= y[i] - y0 x[i]:= X*cos - Y*sin + x0 y[i]:= X*sin + Y*cos + y0 next: next i

The function requires five inputs as described by the comments. The coordinates are assumed to be in two lists. The function updates those lists. Now lets look at an application from the TK Library. Go to Statistics Curve Fitting and select Polynomial Regression. The application loads with comments to help get you started. There is also a table with sample data set up to solve for the best fitting 2nd order polynomial. Solve and the table fills.
Element 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 X 1.2 1.5 1.8 2.1 2.4 2.7 3 3.3 3.6 3.9 Y 42 34 30 29 28 24 15 6 .8 .5 residuals +2.355E0 -2.525E0 -3.015E0 -1.155E-1 +3.173E0 +3.852E0 -8.091E-2 -3.624E0 -2.978E0 +2.958E0 SUMMARY order N Syx adj R2 p b0 b1 b2 b3 b4 b5 b6 b7 b8 STATS 2 10 3.30976647 .948171138 .000104221 48.2339394 -4.5611111 -2.1632997 0 0 0 0 0 0

www.uts.us.com

65

There are also plots. Here is the plot of the data with the polynomial curve.
Polynomial Regression 45 40 35 30 25 Y 20 15 10 5 0 -5 1 1.5 2 2.5 X 3 3.5 4 + + + + + + + + + +

Try changing to a 4th order polynomial and observe the changes.

www.uts.us.com

66

You might also like