Calculation Formulas
About Calculation Formulas
The Historian Administrator contains an Insert Function Wizard designed to help you with "building" syntax within your calculation formula. Using the wizard is optional. You can type in any valid VBScript code directly into the Calculation pane. You can also cut and paste code into the Calculation pane from any other text source. For more information, refer to Building Calculation Formulas Using the Wizard.
General Guidelines for Designing a Calculation Formula
This section describes guidelines you should follow when building your calculation formulas.
Identify Time Intensive Calculations
Use the Calculation Execution Time
property of each tag to identify time-intensive queries. In the Historian Administrator, look for the Execution Time on the Calculation tab for an estimate of how long, on average, it takes the calculation for a tag to execute (since the time the collector was started or restarted).
You can also include that column when you export tags to Excel using the Excel Add-In. For more information on exporting tags with the Excel Add-In, refer to the Exporting Tags section of the Using the Historian Excel Add-In manual.
You can also include that column (AverageCollectionTime) when you query the ihTags table using the Historian OLE DB Provider. Sorting by this column will let you find them fast.
Troubleshoot Issues with Large Configurations
If the timestamps of your raw samples appear slightly old, do not assume that the Calculation Collector has stopped working. It is possible that the Calculation Collector is just running behind.
For instance, if you have a report rate of 15,000 but the newest raw sample that you see is 20-30 minutes old, wait 1-2 minutes and review the newest raw sample again. If the Calculation Collector really stopped, the newest raw sample will be unchanged. If it did change, then the engine is still running, but is lagging behind.
If the collector overrun count is increasing, then the collector is dropping samples and the load needs to be decreased.
Error Handling in VBScript
Start each script with the On Error Resume Next statement so that errors are trapped. If you use this statement, the script runs even if a run-time error occurs. You can then implement error handling in your VBScript.
It is a good practice to include statements in your VBScript that catch errors when you run the script. If there is an unhandled error, a value of 0 with a bad data quality, is stored. When you catch an error in the VBScript, consider including a statement in your calculation that sets the Quality=0 when the error occurs. (The 0 value means that the quality is bad.) If you do not specifically include this setting in your script, Historian stores a good data quality point (Quality=100), even if an error has occurred in your formula. If Quality=100 is not appropriate for your application, consider setting the Quality to 0.
You cannot use the On Error GoTo
Label statement for error handling, as it is not supported in VBScript. As a workaround, you can write code in the full Visual Basic language and then place it in a .DLL so that you can call it from within your VBScript using the CreateObject
function. For examples of calculations that use the CreateObject
function, see Examples of Calculation Formulas.
Unsupported VBScript Functions
MsgBox
InputBox
Milliseconds not Supported in VBScript
The CDate()
function does not support the conversion of a time string with milliseconds in it. Anytime you use the CDate()
function, a literal time string, or a time string with a shortcut, do not specify milliseconds in the time criteria. Milliseconds are not supported in VBScript.
You cannot use milliseconds in times passed into built-in functions such as the PreviousTime
and NextValue
functions. For example, you cannot loop through raw samples with millisecond precision.
Notes on VBScript Time Functions
Using the VBScript time functions such as Now, Date, or Time can lead to unexpected results, especially in recalculation or recovery scenarios. To avoid these issues, use the CurrentTime
built-in function provided by Historian, instead of Now, Date, or Time. For example, the VBScript Now is always the clock time of the computer and is likely not useful when recalculating or recovering data for times in the past. However, the "Now" time shortcut is equivalent to CurrentTime
and can be used as input to the other built in functions.
Using Quotation Marks in VBScript
Result = CurrentValue("TagCost""s")
In this example, note the double quote that appears before the letter s in the TagCost"s name in the formula.
Avoiding Circular References in VBScript
Do not use circular references in calculation formulas. For instance, if the tag name is Calc1
, a formula with a circular reference would be Result=CurrentValue("Calc1")
. Whether the tag is polled or unsolicited, you get a bad value back using the circular reference.
Uninterrupted Object Method Calls
Object method calls are not interrupted. It is possible to exceed the Calculation Timeout setting if you have a method call that takes a long time to execute. The Calculation Timeout error still occurs, but only after the method completes.
Help for VBScript
You can get detailed Help for VBScript by referencing the Microsoft documentation on the MSDN web site. A VBScript User's Guide and Language Reference is available here: http://msdn.microsoft.com/en-us/library/t0aew7h6.aspx
Creating a Calculation Formulation
Notes on Deleted Tags in Calculation Formulas
You can reference a deleted tag in a calculation formula, without an error appearing. For instance, you could enter a formula such as Result=CurrentValue("DeletedTag")
, where DeletedTag
is the name of the deleted tag. You can do this because when you delete a tag, Historian removes deleted tags from the Tag Database (so you cannot browse for it), but it retains the data for that tag in the archive.
However, it is recommended that you do not reference deleted tag names in your calculation formulas, because if the archive files are removed with the data for the deleted tag, the calculation will not work properly.
Calculation Pane Functions
In addition to the VBScript language, there are several built-in functions provided with the Calculation Collector that you can enter in the Calculation Pane. You can type in most of these built-in functions manually or use the wizard to insert them. For a list of the built-in functions, see the Built-In Functions section. For samples, refer to the Examples of Built-In Functions section.
There are two predefined global values called Result and Quality. These global values control the value and quality of the output sample. If the Result is not set in the formula, then no sample is stored.
Built-in Functions
In the following table, tagname
refers to any Historian tag. Time
refers to the actual time; this time can include absolute and relative time shortcuts. See the Date/Time Shortcuts and Relative Date/Time Shortcuts sections for more information.
See the following table for the built-in function names and descriptions.
Function Name | Description |
---|---|
CurrentValue(tagname) |
The value of tagname interpolated to the calculation execution time. The CurrentValue function returns 0 if the quality is 0 (bad). This is true if you initialized it to 0, or if a previous call failed, which would also set it to 0. |
CurrentQuality(tagname) |
The current quality (0=bad or 100=good) of tagname . |
CurrentTime |
The calculation execution time, which becomes the timestamp of the stored value. For real time processing of polled tags, the calculation execution time is the time that the trigger fired. For unsolicited tags, the calculation execution time is the timestamp delivered with the subscription. Note: When a calculation tag runs and a result is assigned, the timestamp of the result is the time that the calculation began running, not the time that it finished.
For recovery of polled or unsolicited tags, the calculation execution time is the time that the calculation would have fired if the collector was running. |
PreviousValue(tagname, Time) |
The value of the raw sample prior to Time for tagname .This is similar to performing a |
PreviousQuality(tagname, Time) |
The quality (0=bad or 100=good) of the raw sample before Time for tagname .This is similar to performing a |
PreviousGoodValue(tagname, Time) |
The good value of the raw sample prior to Time for tagname .This is similar to performing a |
PreviousGoodQuality(tagname, Time) |
The good quality (0=bad or 100=good) of the raw sample before Time for tagname .This is similar to performing a |
PreviousTime(tagname, Time) |
The timestamp of the raw sample before Time for tagname .This is similar to performing a |
PreviousGoodTime(tagname, Time) |
The good timestamp of the raw sample before Time for tagname .This is similar to performing a |
NextValue(tagname, Time) |
The value of the raw sample after Time for tagname .This is similar to performing a |
NextQuality(tagname, Time) |
The quality (0=bad or 100=good) of the raw sample after Time for tagname .This is similar to performing a |
NextTime(tagname, Time) |
The timestamp of the raw sample after Time for tagname .This is similar to performing a |
NextGoodValue(tagname, Time) |
The value of the good raw sample after Time for tagname . This is similar to performing a |
NextGoodQuality(tagname, Time) |
The quality (100=good) of the raw sample after Time for tagname .This is similar to performing a |
NextGoodTime(tagname, Time) |
The timestamp of the good raw sample after Time for tagname. This is similar to performing a |
InterpolatedValue(tagname, Time) |
The value of tagname , interpolated to the Time passed in. |
Calculation |
Non-filtered calculated data query that returns a single value, similar to the Excel Add-In. For a list of the calculation mode, refer to Calculation Modes section in the Getting Started with Historian guide. |
AdvancedCalculation |
Non-filtered calculated data query that returns a single value, similar to the Excel Add-In. For a list of the calculation mode, refer to Calculation Modes in the Getting Started with Historian guide. |
AdvancedFilteredCalculation |
Advanced Filtered calculated data query that returns a single value, similar to the Excel Add-In. |
FilteredCalculation |
Filtered calculated data query that returns a single value, similar to the Excel Add-In. |
LogMessage(string_message) |
Allows you to write messages to the Calculation or Server-to-Server Collector log file for debugging purposes. The collector log files are located in the Historian\LogFiles folder. Note: The
LogMessage function is the only function that does not appear in the wizard. |
GetMultiFieldValue(Variable, FieldName) |
Returns the value of the field identified by the FieldName . The variable holds the current value of all the fields of a multi-field tag. You must read the tag into a variable before using this function. The CurrentValue() function is used to read all fields into the variable. You can then use the GetMultiFieldValue function to access the value one field.The value of the |
GetMultiFieldQuality(Variable, FieldName) |
Returns the quality (0=bad or 100=good) of the field identified by the Fieldname . The variable holds the current value of all the fields of a multi-field tag. You must read the tag into a variable before using this function. The CurrentValue() function is used to read all fields into the variable. You can then use the GetMultiFieldQuality function to access the field quality.If the user defined type has a "Store Individual Quality" specified, then you get the field quality. Otherwise, you get the sample quality. The value of the |
SetMultiFieldValue(Variable, FieldName, Value, Quality) |
Sets the value and the quality for a field identified by the FieldName .You can use this function to construct a multifield value containing values for each field, then use "result=syntax to store the value in Historian. |
You cannot use microseconds for any of the built-in calculation functions.
User-Defined Functions
In addition to the many functions included with the calculation collector, Historian provides the ability to create custom calculation functions. After a custom calculation function has been created, it is available for use with other calculations.
Functions are useful as shortcuts for large blocks of source code. By creating a function out of commonly used calculation formulas, you can save time and effort instead of typing a few lines of calculation formula every time you want to perform the same operation, it is compressed to a single line.
Function functionname (variable list)
[calculation formulas]
End Function
The operations the function performs are contained within the Function / End Function statements. If you need to send data to the function a tagname, for example you simply create a variable in the function's parameters to receive the data. Multiple variables must be separated by commas. These variables exist only within the function.
The following is an example of a function. This function, named checkValue()
, looks at a tag and assigns it an alarm if it is over a specified value.
Function checkValue (tagname,sourcename,value)
If CurrentValue(tagname) > value Then
Set AlarmObj = new Alarm
AlarmObj.SubConditionName = "HI"
AlarmObj.Severity = 750
AlarmObj.NewAlarm
"alarmname", "Simulated", "tagname", "Now"
checkValue = true
Else
checkValue = false
End If
End Function
To call the function once it has been created, use the following syntax in your calculation formula:
alm_set = checkValue("DD098.FluidBalance","FluidBalance_ALM",5000)
If the function returns a true value (the alarm was set), the alm_set variable will be set to true
. If it did not set the alarm, the alm_set variable will be set to false
.
Creating a User-Defined Function
Inserting a User-Defined Function
Date/Time Shortcuts
The following table outlines the date/time shortcuts that you can use in calculation formulas. If Historian accepts an abbreviation for the shortcut, in addition to the full shortcut, the abbreviation appears in bold in the following table.
Shortcut | Description |
---|---|
Now | Now (the time and date that you execute the query) |
Today | Today at midnight |
Yesterday | Yesterday at midnight |
BOY | First day of year at midnight |
EOY | Last day of year at midnight |
BOM | First day of month at midnight |
EOM | Last day of month at midnight |
Relative Date/Time Shortcuts
Optionally, you can add or subtract relative times to the absolute times listed in the following table. The following table outlines the relative time shortcuts. If Historian accepts an abbreviation for the shortcut, in addition to the full shortcut, the abbreviation appears in bold in the following table.
Shortcut | Description |
---|---|
Second | Second |
Minute | Minute |
Hour | Hour |
Day | Day |
Week | Week |
Examples of Built-in Functions
Example 1: Counting the Number of Bad Quality Samples
This example shows how to loop through samples of tag named C2 to count the number of bad quality samples.
Dim count, starttime, endtime, tagquality count=0
StartTime=CurrentTime EndTime=DateAdd("n",-1,StartTime) Do while StartTime>EndTime
TagQuality=PreviousQuality("C2",StartTime)
startTime=PreviousTime("C2",StartTime) IF TagQuality=0 THEN
count=count + 1
END IF loop Result=count
Example 2: Counting the Number of Collected Digital 1s For a Tag
The following example counts the number of collected digital 1s for a tag so that, for instance, you can determine how many times a pump is turned ON and OFF.
Dim count, starttime, endtime,tagquality,TagValue
count=0
StartTime=CurrentTime
EndTime=DateAdd("h",-1,StartTime)
On error resume next
Do while StartTime>=EndTime
TagValue=PreviousValue("FIX.DI.F_CV",StartTime)
TagQuality=PreviousQuality("FIX.DI.F_CV",StartTime)
startTime=PreviousTime("FIX.DI.F_CV",StartTime)
IF TagQuality=100 AND TagValue=1 then
count=count + 1
END IF
loop
Result=count
Example3: Determining the Trigger When Using Multiple Trigger Tags
The following example shows how to determine which tag triggered the calculation, from a list of two possible trigger tags. The example compares the two trigger tags and determines which one has the newest raw sample. This method of getting the newest raw sample can also be used determine if a remote collector is sending data or is disconnected from the server.
In the example that follows, archive compression is disabled for both of these tags.
dim timetag1
dim timetag2
dim tag1
dim tag2
tag1 = "BRAHMS.AI1.F_CV"
tag2 = "BRAHMS.AI2.F_CV"
' Get the timestamp of the newest raw sample for tag1:
timetag1 = previousTime(tag1, CurrentTime)
' Get the timestamp of the newest raw sample for tag2:
timetag2 = previousTime(tag2, CurrentTime)
if timetag1 > timetag2 then
' If tag1 triggered me, then:
result = 1 else
' If tag2 triggered me, then:
result = 2
end if
Example 4: Using Array or Multifield data in Calculation
You can create tags of arrays and multifield types and use the Calculation collector and Server to Server Collector and Distributor with these tags.
- Arrays
- To use the Array data as input to a calculation formula you can use the name of the array tag like "Array1" or the individual element of the array like "Array1[4]". For example, if you have an array tag "Array1" of floating point values and a calculation tag "FloatCalc1" of float data type, then you can use the array as input to calculate a float value.
result = currentvalue("Array1[4]")+5
Youcan use Calculation() function to read the array tag as shown in the following code.
Result = Calculation("Array1","Average","Now 1Minute","Now",Quality)
In this example, the calculation tag should be an array tag because the average of an array is an array, not a single value. Each element is averaged over the time range. Since an average of an integer or float array is a floating point value, the calculation tag must be a single or double float array.
If you want to find the minimum of array elements in a given time, then use vbscript code to compute and store the result in a Float tag as shown.
if CurrentValue("Array1[0]") < CurrentValue("Array1[1]") then Result = CurrentValue("Array1[0]") else Result = CurrentValue("Array1[1]") end if
- Multifield
- If you have a user-defined type "MySample" with fields "r;FloatVal" and "r;IntVal" you can create
Tag1
and use the value of one field in an Integer Calc Tag. The destination tag is not a multifield tag.result = currentvalue("Tag1.IntVal")+5
Example 5: Storing Array or Multifield data in Calculation tags
- Array
- If your calculation tag is an array tag, then you can copy the entire array values into it. For example, you can copy the entire values from
Array1
intoArray2
using the given code.result = CurrentValue("Array1")
You can take an array value collected from a field device and adjust the values before storing it in another array tagArray2
using this code:dim x x=CurrentValue("Array1") x(1) = x(1)+10 result = x
You can simply construct an array value inside your formula and store it inArray2
, for example:dim MyArray(2)' The 2 is the max index not the size MyArray(0)=1 MyArray(1)=2 MyArray(2)=3 result = MyArray
- Multifield
- You can have the Calculation Collector combine collected data into a multifield tag. Create a calculation
Tag1
using the user-defined Type "MySample," then use this formula to fill in the fields:Dim InputValue, myval,x,y ' get the current value of another multifield tag InputValue = CurrentValue("tag1") ' get the values of each of the fields x = GetMultiFieldValue(InputValue, "IntVal") y = GetMultiFieldValue(InputValue, "floatval") ' store the field values in this tag SetMultiFieldValue myval,"IntVal",x,100 SetMultiFieldValue myval,"floatval",y,100 Result = myval
Example 6: Using Array or Multifield data to trigger calculation
- Array
- You can use the array tag as a trigger tag for your float or array calculation tags. For example, you can use
Array1
as a trigger so that when it changes, the"CalcArray1"
tag will be updated. You cannot use an individual array element such as"Array1[3]"
as a trigger, you must use the entire array tag as the trigger tag. - Multifield
- You can use a multifield tag as a trigger tag by either using the tagname
"Tag1"
or tagname with the field name"Tag1.FloatVal"
.
Example 7: Sending Array or Multifield data to a Remote Historian
- Array
- You can use the Server to Server Collector or Server to Server Distributor to send array data to a destination Historian. If the destination Historian is version 6.0 or later, you can simply browse the tags and add them.
You cannot send an array to the older versions of archiver (Pre 6.0 versions) as these archivers will store the array tags as a blob data type in the destination and you will not be able to read them. However, you can send individual elements of an array to these archivers, for example,
result = currentvalue("Array1 [4]")
. - Multifield
- The destination needs to be Historian 6.0 or above to store a multifield tag but you can send individual fields to a pre Historian 6.0 archiver.
For multifield tags, you must create the User Defined Type manually at the destination
You can write an entire multified tag data sample in one write or you can create multiple tags in the destination, one for each field you want to copy. For example, if you have one tag
"Tag1"
with two fields"FloatVal"
and"IntVal"
on a source archiver, then you can create two tags ("Tag1.FloatVal"
and"Tag1.IntVal"
) on the destination.Note: If you change a field name or add or remove fields you must update your collection and your destination tags.
Example 8: Reading and writing a Multifield tag using MultiField functions
The following example shows how to read an entire multifield tag, using the GetMultiFieldValue
function and to write the value to a field in another tag using the SetMultiFieldValue
function.
Dim CurrMultifieldValue
' Read the value of a multi field tag into a variable
CurrMultifieldValue = CurrentValue("MyMultifieldTag")
' Read the field value of multifield tag into the temporary variable
F1 = GetMultiFieldValue(CurrMultifieldValue, "Temperature Field")
' Perform a calculation on the value
Celcius = (F1 32)/ 9* 5
' Set the calculated value to another field of the multifield tag
SetMultiFieldValue(CurrMultifieldValue, "Temperature Field Celcius", Celcius, 100)
result = CurrMultifieldValue
Building Calculation Formulas Using the Wizard
The wizard contains several pre-defined functions. For more information on these functions, see Types of Functions Supported by the Wizard. You are not limited to using only these functions. You can also use these functions without the wizard.
Types of Functions Supported by the Wizard
The following table describes the types of actions supported by the Wizard.
Type of Action | Available Functions for the Action |
---|---|
Insert a Value |
|
Insert a Calculation |
|
Insert a Timestamp |
|
Check Data Quality |
|
Set Data Quality |
|
Add Data Value | None |
Insert a Tagname | Tagname |
Insert an Alarm Calculation |
|
Insert a Multifield Operation |
|
Verifying the Syntax of a Calculation Formula
Perform a syntax check to make sure that your formula is constructed correctly and executes. The syntax check does not identify invalid (misspelled or deleted) tagnames in the dependency list. It does not check all branches of a calculation; it only tests the calculation formula based upon the logic and current values. It also may not return the same result as the collected value.
If you have a syntax error, a dialog appears detailing the error, as shown in the following figure.