Code Edit Dialog
Applicability: Cranium, Synapse (core versions 0317+)
(Click here for previous documentation)

Cranium and Synapse provide an internal programming language that enables you to enter new estimation technique models and new constraint functions for use in designs and selections. The code written in this language is entered using the Code Edit dialog.

1
The Code control is the large edit box in which you enter code.
2
The list of available functions. Some functions are only available for certain model types. For example, the Technique() function is applicable for estimation models but not for design constraint functions.
3
The documentation for the selected function.
4
The Default Args button inserts default code into the Code edit control. Pressing the Default Args button is typically the first step when entering a new estimation technique.
5
The Std Units button displays the standard units for all known properties. All estimation techniques assume input variables, e.g., temperature and pressure, are in standard units and must output property estimates in standard units.
6
The Insert button a menu listing commands for inserting common names and values:
  • Chemical Calculation: activates a dialog listing the names of all chemical calculations in the current document.
  • Mixture Calculation: activates a dialog listing the names of all mixture calculations in the current document.
  • Technique Name: activates a dialog listing the names of all techniques in the current document.
  • Chemical Name: activates a dialog listing the names of all chemicals in the current document.
  • Element Name: activates a dialog listing the names of all elements in the current document.
  • Mixture Name: activates a dialog listing the names of all mixtures in the current document.
  • Group Name: activates a dialog listing the names of all groups in the current document.
  • Property Name: activates a dialog listing the names of all properties known to the application.
  • Date and Time: inserts the current date and time into the dialog's code edit control.
  • Constants: activates the submenu which enables you to insert common constants into the dialog's code edit control.
7
The Compile button compiles the code and reports any errors.
MKS Modeling Language

The modeling language used by Cranium and Synapse is easy to learn and use. The language is extremely similar to many of today’s modern programming languages such as C++ and Java. Some of the language's key aspects include:

  • Every argument and variable must have a declared type. (The language is strongly typed.)
  • Every variable must be declared before being used.
  • Each model is composed of a series of statements with each statement ending with a semicolon.
  • Code is case sensitive meaning xyz and XYZ are considered to be two different variables.
  • The source code you enter is compiled into a rapidly executable set of instructions.
  • Spaces, tabs, and carriage returns are used primarily for readability and are ignored by the compiler.
  • Control statements provide for if-then-else conditions and looping.
  • Library functions are available for mathematical operations.
  • Array indices are zero-based meaning the first element of the array xyz is accessed by writing xyz[0].

However, because the modeling language is tailored to the task of physical property estimation there are some differences with conventional languages including:

  • A model returns either TRUE or FALSE.
  • A model assigns a resulting value, using the SetResult function.
  • A library of physical property oriented functions is available. (Note that the library functions available are dependent upon the type of model being created. For example, the library function "Technique()" can be used when coding estimation technique models but not when coding selection functions.)

To further explain the language's concepts, we use the example of entering a new technique to estimate a chemical's critical temperature. The new technique's model is:

Tc = 95.3 + 1.22 * Tb
(01)

The final code is shown in the listing to the right. The following sections document each line of our example code.

// Argument declarations string technique, chemical; // Argument functions technique = Technique(); chemical = Chemical(); // Variable declarations double tb, tc; string prop; int err; // Retrieve boiling point prop = "Boiling Point"; tb = CProp(chemical, prop, 0, 0, err); if( err != 0 ) return FALSE; // Calculate estimate tc = 95.3 + 1.22 * tb; // Assign estimate SetResult(tc); // Successful return TRUE;
Comments

The MKS modeling language allows you to specify two types of comments. The double forward slash comment

// Variable declarations

ignores all following text up to and including the next carriage return. The multiple line comment ignores all text between the characters /* and */.

/* All of this text is ignored */
Declarations

The declaration section accomplishes the task of declaring all variables before they are used. Cranium and Synapse use four types of variables: double, string, bool and int. The type double is used for all floating point numbers. Almost all computations are performed on variables of type double. The string type is used for all character text. Names of properties, chemicals, mixtures, techniques, and groups are stored in variables of type string. The bool type is used for storing TRUE/FALSE values. Boolean control variables are often needed to direct the logic within models. The int type is used for all integers. Counts and indices are typically stored in variables of type int.

Our example code contains two declaration sections.

// Argument declarations string technique, chemical;

These variables are used to store the names of a technique and a chemical. This declaration is part of the "default arguments" section of the code. The default arguments section can be automatically inserted using the Default Args button found in the Code Edit dialog.

The second set of declarations includes the variables we will use to compute our estimate.

// Variable declarations double tc, tb; string prop; int err;

You can declare one or more variables in a single statement. You can also have any number of declaration statements. For example, the first declaration statement could be rewritten as two statements.

// Variable declarations double tc; double tb; string prop; int err;

Cranium allows you to declare one and two dimensional arrays of any type. The syntax of array declaration is the same as a variable declaration followed by a dimensional specification. Dimensional specifications must be integer constants enclosed by brackets.

// Array declarations double params[8], bips[50][50];

A declaration can be placed anywhere within a model although it is common to place all declarations near the code’s beginning.

Variable Names

All variable names must start with a letter. Following this starting letter can be any quantity and combination of letters (a through z and A through Z) and numbers (0 through 9).

// Valid variable names x123 = s1a2b3c - verylongvariable12345;
Strings

A string is a sequence of characters surrounded by double quotation marks. Strings are widely used in code as names of chemicals, mixtures, groups, etc.

// Retrieve boiling point prop = "Boiling Point";
Library Functions

The MKS modeling language has a number of library functions available for use in models. Some functions return values. Some functions do not return values. Some functions modify their arguments.

// Boiling point prop = "Boiling Point"; tb = CProp(chemical, prop, 0, 0, err); if( err != 0 ) return FALSE;

The CProp function, shown in the above code, is commonly used and is a good example of library function usage. CProp takes five arguments: a chemical’s name; the name of a physical property; the temperature value; the pressure value; an error variable. CProp returns either a data value or estimate.

In addition to returning a value, a library function may also modify one or more of its arguments. For example, the CProp function takes the error variable, err, as its fifth argument. This variable is assigned an integer value indicating the success of the function. A value of zero indicates no errors occurred.

Tip: Always check the assigned error value

Many library functions use an error variable to indicate execution success or failure. If no errors occur, the variable is assigned a value of 0. If an error does occur, the variable is assigned a non-zero value. The meaning of this value is documented in the function description shown at the bottom of the Code Edit dialog.

If-Then-Else Statement

If-then-else statements have two general forms:

  • if( test ) expression1;
  • if( test ) expression1; else expression2;

The test must evaluate to either TRUE or FALSE. If the test evaluates to TRUE then expression1 is executed. If the test evaluates to FALSE then expression1 is skipped and the else clause’s expression2 is executed if it is present.

// Single expression if statement if( err != 0 ) return FALSE;

The expressions contained within an if-then-else statement can themselves be if-then-else statements.

// Multiple nested if statements if( tb > 250.0 ) if( tm > 150 ) return FALSE;

Multi-statement expressions must be enclosed in braces.

// Multi-statement if expressions if( temp < params[0] ) { // Set error and return SetError("Temperature too low."); return FALSE; }
SetResult and Return Statements

All models produce two values. One value is a number representing either a property estimate, an estimation error or a constraint function value. The SetResult function assigns this value. The other value returned is either TRUE or FALSE indicating the model's applicability or its successful execution. The return statement assigns this value.

// Assign estimate SetResult(tc); // Successful return TRUE;

Typically a model will have only one SetResult function and several return statements. However, there is no restriction on the number of SetResult functions which may occur within a model.

For and While Statements

Iteration or looping is a very common operation in estimation techniques. Many techniques iterate through all groups in a molecular structure or all components in a mixture. The MKS modeling language provides two iteration statements.

The for statement has the general form:

    for( initialize; test; increment ) expression;

The initialize clause assigns the starting value to the iteration variable. The test clause is executed before each iteration to determine if the loop should continue. The increment clause is executed after each iteration to prepare the iteration variable for the next loop. For example, the following code collects and totals group contributions.

// Total group contributions for( i = 0; i < n; i = i + 1 ) { // Retrieve the contribution contrib = Contribution(technique, groups[i], "", "", err); if( err != 0 ) return FALSE; // Total contributions total = total + contrib * occurs[i]; }

In this example, i is the iteration variable and n is the number of groups. The code iterates for each group exiting once all n groups have been processed. The error variable is checked on each iteration. If any group does not have a contribution (error varaible not equal to 0), the code exits returning FALSE indicating failure.

The while statement is very similar to the for statement. The while statement has the general form:

  • while( test ) expression;

The iteration continues executing the expression until the test clause evaluates to FALSE. Rewriting the previous example using while would result in the following code.

// Total group contributions while( n > 0 ) { // Decrement index n = n - 1; // Retrieve the contribution contrib = Contribution(technique, groups[n], "", "", err); if( err != 0 ) return FALSE; // Total contribution total = total + contrib * occurs[n]; }
Example: Enter a new model for the critical temperature

In the documentation for the Text Export Dialog, a new model for the critical temperature was developed using the regression tools of Microsoft Excel.

Tc = 95.3 + 1.22 * Tb
(02)

The following steps detail how to create a new estimation technique based upon this new equation.

  1. Open a knowledge base document. (Open a "working" document or create a copy of a document (see here) if you are just experimenting with this functionality.)
  2. Change to the Techniques Chapter. (See documentation on Navigation Overview for details on navigating chapters and pages.)
  3. Create a new Technique entity by pressing the "+" button in the menubar or executing the "Add New Page" command found on the Edit menu. A new, blank Technique page will be added to the current document.
  4. Click the left mouse button in the new technique's identifier pane and enter a new name for the technique.
  5. Click the left mouse button on the Descriptive information Section's Property field's edit control. Select "Critical Temperature" from the displayed dialog and press the Save button. The selected property will be displayed in the field.
  6. Scroll to the Model Information Section and click the left mouse button on the Estimation Model field's large edit control. The application will activate the Estimation Model Edit dialog.
  7. Press the dialog's Default Args button. The application will insert the appropriate default arguments for the property being estimated. (Note that if you did not previously enter a value for the property being estimated, the application will display an error message because it needs to know which property is being estimated before it can display the Code Edit dialog.)

    The Technique() function returns the name of the technique to which code belongs. This name is used by other functions for retrieving parameters, groups and contributions. Similarly, the Chemical() function returns the name of the chemical currently being estimated. This name is used by other functions for retrieving property values and molecular structure.

  8. Enter the declarations for the variables we will use to calculate the property estimate. It is very common to write some initial declarations and then return to add more declarations as your code develops.
    // Variable declarations double tb, tc; string prop; int err;
  9. The new model requires a value for the chemical's normal boiling point. We will use the CProp function to retrieve this value. Type the following, incomplete code into the Code Edit dialog.
    // Retrieve boiling point prop =
  10. Press the Properties button. The application will activate the Properties Dialog displaying a list of known physical properties.
  11. Select "Boiling Point" and press the dialog's Insert button. The property's name will be inserted into the edit control. Add a semicolon to the end of the line and then the additional code shown below.

    Note that we test the CProp function's error variable. If the function could not retrieve a value for the normal boiling point, the value of the variable err will equal zero. If err is equal to zero then the model returns FALSE stopping the execution.

  12. Enter the code that will perform the actual calculation of the critical temperature.
    // Calculate estimate tc = 95.3 + 1.22 * tb;

    Cranium and Synapse check all internal operations. If an improper operation is performed, e.g., a division by zero, the execution of the model is stopped and a value of FALSE is returned.

  13. We now must assign the result of our calculation using the SetResult function. Add the following code.
    // Assign estimate SetResult(tc);
  14. Finally, we must indicate that the calculations were performed successfuly by returning TRUE.
    // Successful return TRUE;
  15. Now that all the code has been entered, press the dialog's Save button. The application will first compile the code reporting any errors. If the code compiles successfully, the application will store the code into the current knowledge base.
  16. Select the Evaluate Technique from the chapter's Commands menu. The application will execute the newly entered estimation technique on every chemical in the current knowledge base and display an analysis of the results. (See the documentation Technique Evalutation Dialog for details on estimation technique evaluation.)
Tip: Always convert to standard units

Many published estimation techniques generate estimates in non-standard units. For these techniques it is best to develop the model as published. Then, just before you assign the result using the SetResult function, convert the estimate to standard units. For example:

// Molecular weight for conversion prop = "Molecular Weight"; mw = CProp(chemical, prop, 0, 0, err); if( err != 0 ) return FALSE; // Gas constant (J/kg-mol K) r = 8314.472; // Convert to standard units cp = r * cp / mw;
Example: Code Error Dialog

When you press the Code Edit dialog's Save button or Test button, Cranium and Synapse will compile the code and report any errors detected. These detected errors are displayed in the Code Error dialog.

  1. Click the left mouse button on the estimation model we created above to load the code into the Code Edit dialog.
  2. Change the calculation line to:
    // Calculate estimate tc = 95.3 + 1.22 * tbb;

    Note that the boiling point variable, "tbb", is misspelled. The variable should be "tb" as specified in the declarations.

  3. Press the Save or Test button. The application will activate the Code Error dialog displaying the error.
  4. Press the dialog's Goto Error button. The Code Edit dialog will highlight the term causing the error.
  5. Correct the error and press the dialog's Save button. Or, press the dialog's Cancel button to discard all changes.
Related Documentation
Topic Description
Getting Started using Synapse provides a quick tour of Synapse's capabilities including examples of chemical product design.
Getting Started using Cranium provides a quick tour of Cranium's capabilities including a discussion of structure editing.
Estimating Chemical Properties a short video demonstrating how to estimate the physical properties of chemicals using either Synapse or Cranium.
Estimating Mixture Properties a short video demonstrating how to estimate the physical properties of mixtures using either Synapse or Cranium.