Tengo scripting language

A calculation script makes use of a scripting language, called Tengo.

Tengo is a scripting language written in Go and with a Go-like syntax. An overview of the basic Tengo syntax can be found here. You can play around with Tengo here .

Input data reference(s) via alias

To access the data of an input data reference, one can use the according alias for the input data reference given in the calculation settings. The alias contains the following properties:

  • Value: the value of the data reference
  • Timestamp: the timestamp of the data reference
  • Tags: the tags of the data reference

Example

This example uses the Value property of an alias _A to access the value of an input data reference and multiplies that value by 2.

return _A.Value * 2

Calculation context helper functions

set_tag: set_tag(tag, value) sets a tag in the result

set_status: set_status(status) sets the status of the result

Accessing Metadata

You can access metadata in different contexts, including metadata for the calculation itself or metadata for inputs. These inputs can be either asset properties or measurements. Additionally, if the input is an asset property, you can also access the metadata of the associated asset.

Accessing Metadata of the Calculation Itself

To access the metadata of the calculation itself, use:

factry.get_metadata("<metadata-key>")

Replace <metadata-key> with the key you need.

Accessing Metadata of Inputs

Inputs can be either measurements or asset properties, and the metadata can be accessed as follows:

  1. Accessing Metadata of Measurements or Asset Properties

    To access a specific metadata key of an input (either a measurement or asset property):

    factry.get_input_metadata("<input-alias>", "<metadata-key>")
    

    Replace <input-alias> with the alias of the input data and <metadata-key> with the key you need.

    To access all metadata of an input:

    metadata := factry.get_input_metadata("<input-alias>")
    

    You can then retrieve specific keys:

    metadata["<metadata-key>"]
    
  2. Accessing Metadata of the Asset (When Input is an Asset Property)

    If the input is an asset property, you can also access the metadata of the associated asset:

    • To access a specific metadata key of the associated asset:

      factry.get_input_asset_metadata("<input-alias>", "<metadata-key>")
      
    • To access all metadata of the associated asset:

      metadata := factry.get_input_asset_metadata("<input-alias>")
      

      Retrieve a specific key as needed:

      metadata["<metadata-key>"]
      

Standard Tengo libraries

A list of standard Tengo libraries that are supported are listed below.

math

Defines some mathematic constants and functions.

More info

times

Defines some basic time based constants and functions.

More info

  • time_weekday: times.time_weekday(t time) returns an integer that represents the day of the week of a given timestamp. The numeric representation of weekdays start from 0 with Sunday and end at 6 with Saturday.

Simple shift calculation

tz := "Europe/Brussels"
ts := times.to_location(_A.Timestamp, tz)
diw := times.time_weekday(ts) // numeric representation of the day of week
hid := times.time_hour(ts) // hour of the day

if diw >= 0.0 && diw <= 5.0 && hid >= 5.0 && hid < 13.0 {
  return 1.0
}

if diw >= 0.0 && diw <= 5.0 && hid >= 13.0 && hid < 21.0 {
  return 2.0
}

if diw >= 0.0 && diw <= 5.0 && hid >= 21.0 && hid < 5.0 {
   return 3.0
}

if diw >= 6.0 && diw <= 7.0 && hid >= 5.0 && hid < 17.0 {
  return 4.0
}

if diw >= 6.0 && diw <= 7.0 && hid >= 17.0 && hid < 5.0 {
  return 4.0
}

rand

Defines functions to generate random values.

More info

text

Defines string manipulation and formatting functions.

More info

enum

Defines some functions to work with enumerables.

More info

Factry Tengo libraries

We’ve added some custom libraries on top of the existing libraries to allow for more versatile scripts.

local

Local allows to save variables in a local context specific to a particular calculation. Only this calculation script can store/retrieve the value across all script executions. The key Context is reserved for the calculation context and can’t be used with these functions.

An overview of the available functions:

get: local.get(key) retrieves a value from the local context by its key.

set: local.set(key, value) sets a value in the local context by its key.

This example retrieves a previously set value from the local context. If the value does not exist, a default value 0.0 is used. After adding 1.0 to the result, the value is set again in the local context and returned as output by the script.

previous := float(local.get("previous"),0.0)
result := previous + 1.0
local.set("previous", result)
return result

global

Global allows to save variables in a global context accessible to all calculation scripts. Any calculation script can store/retrieve the value across all scripts executions. An overview of the available functions:

get: global.get(key) retrieves a value from the global context by its key.

set: global.set(key, value) sets a value in the global context by its key.

util

Util provides custom functions for basic operations which are not available or incomplete in the standard Tengo library.

is_equal: checks whether 2 objects are equal, providers better handling of undefined values

Simple boolean comparison

if is_equal(_A.Value, true) {
  return _B.Value
}

return _C.Value

Comparing numeric types, in this example _A.Value is of type float

return is_equal(_A.Value, 12)

units

Units provides simple unit conversion. Its main datatype is the Value, which represents a number with a given unit.
When a Value is returned from a script, it is automatically converted to the bare number.
All functions that accept the name of a unit accept the the shorthand of the unit, the singular or plural form of the unit name, and varying spellings of the unit name, eg. m, meter, meters, metre, metres.

convert:

  • units.convert(input, unit) converts the input into a Value. If input is
    a number, a new Value is returned with the given unit. If the input is
    already a Value, the input is converted into the given unit.
    Conversions can be done between different magnitudes, e.g. meter to kilometer, and between different systems, e.g. Celsius to Fahrenheit, or meters to feet.
  • units.convert(input, from, to) converts the given number from one unit into another, returning a number.

float: units.float(value) returns the number stored in the Value.

find: units.find(unit) returns the unit object for the given unit. The unit object can be used to add units to numbers, or to convert between units.

Supported units

Unit Names
attopascal attopascal,aPa,attopascals
femtopascal femtopascal,fPa,femtopascals
picopascal picopascal,pPa,picopascals
nanopascal nanopascal,nPa,nanopascals
micropascal micropascal,μPa,micropascals
millipascal millipascal,mPa,millipascals
centipascal centipascal,cPa,centipascals
decipascal decipascal,dPa,decipascals
pascal pascal,Pa,pascals
decapascal decapascal,daPa,decapascals
hectopascal hectopascal,hPa,hectopascals
kilopascal kilopascal,kPa,kilopascals
megapascal megapascal,MPa,megapascals
gigapascal gigapascal,GPa,gigapascals
terapascal terapascal,TPa,terapascals
petapascal petapascal,PPa,petapascals
exapascal exapascal,EPa,exapascals
microbar microbar,μbar,microbars
millibar millibar,mbar,millibars
centibar centibar,cbar,centibars
bar bar,bars
millimeter of Mercury millimeter of Mercury,mmmHg,millimeter of Mercurys
centimeter of Mercury centimeter of Mercury,cmmHg,centimeter of Mercurys
meter of Mercury meter of Mercury,mmHg,meters of Mercury,meters of Mercury
inch of Mercury inch of Mercury,inHg,inch of Mercurys
millimeter of Water Column millimeter of Water Column,mmmH2O,millimeter of Water Columns
centimeter of Water Column centimeter of Water Column,cmmH2O,centimeter of Water Columns
meter of Water Column meter of Water Column,mmH2O,meters of Water Column,meters of Water Column
inch of Water Column inch of Water Column,inH2O,inch of Water Columns
newton per square meter newton per square meter,N/m²,newton per square meters
pound-force per square inch pound-force per square inch,psi,pound-force per square inchs
standard atmosphere standard atmosphere,atm,standard atmospheres,standard atmospheres
technical atmosphere technical atmosphere,at,technical atmospheres,technical atmospheres
torr torr,Torr,torrs
barye barye,Ba,baryes,baryes
Unit Names
attosecond attosecond,as,attoseconds
femtosecond femtosecond,fs,femtoseconds
picosecond picosecond,ps,picoseconds
nanosecond nanosecond,ns,nanoseconds
microsecond microsecond,μs,microseconds
millisecond millisecond,ms,milliseconds
centisecond centisecond,cs,centiseconds
decisecond decisecond,ds,deciseconds
second second,s,seconds
decasecond decasecond,das,decaseconds
hectosecond hectosecond,hs,hectoseconds
kilosecond kilosecond,ks,kiloseconds
megasecond megasecond,Ms,megaseconds
gigasecond gigasecond,Gs,gigaseconds
terasecond terasecond,Ts,teraseconds
petasecond petasecond,Ps,petaseconds
exasecond exasecond,Es,exaseconds
minute minute,min,minutes
hour hour,hr,hours
day day,d,days
fortnight fortnight,fortnights
month month,months
year year,yr,years
decade decade,decades
score score,scores
century century,centurys
millennium millennium,millenniums
planck time planck time,𝑡ₚ,planck times
Unit Names
bit bit,b,bits
kilobit kilobit,kb,kilobits
megabit megabit,Mb,megabits
gigabit gigabit,Gb,gigabits
terabit terabit,Tb,terabits
petabit petabit,Pb,petabits
exabit exabit,Eb,exabits
Unit Names
nibble nibble,nibbles
byte byte,B,bytes
kilobyte kilobyte,KB,kilobytes
kibibyte kibibyte,KiB,kibibytes
megabyte megabyte,MB,megabytes
mebibyte mebibyte,MiB,mebibytes
gigabyte gigabyte,GB,gigabytes
gibibyte gibibyte,GiB,gibibytes
terabyte terabyte,TB,terabytes
tebibyte tebibyte,TiB,tebibytes
petabyte petabyte,PB,petabytes
pebibyte pebibyte,PiB,pebibytes
exabyte exabyte,exabytes
exbibyte exbibyte,EiB,exbibytes
zettabyte zettabyte,zettabytes
zebibyte zebibyte,ZiB,zebibytes
yottabyte yottabyte,yottabytes
yobibyte yobibyte,YiB,yobibytes
Unit Names
attojoule attojoule,aJ,attojoules
femtojoule femtojoule,fJ,femtojoules
picojoule picojoule,pJ,picojoules
nanojoule nanojoule,nJ,nanojoules
microjoule microjoule,μJ,microjoules
millijoule millijoule,mJ,millijoules
joule joule,J,joules
kilojoule kilojoule,kJ,kilojoules
megajoule megajoule,MJ,megajoules
gigajoule gigajoule,GJ,gigajoules
terajoule terajoule,TJ,terajoules
petajoule petajoule,PJ,petajoules
exajoule exajoule,EJ,exajoules
zettajoule zettajoule,ZJ,zettajoules
yottajoule yottajoule,YJ,yottajoules
calorie calorie,cal,calories
electronvolt electronvolt,eV,electronvolts
watt-hour watt-hour,Wh,watt-hours
kilowatt-hour kilowatt-hour,kWh,kilowatt-hours
megawatt-hour megawatt-hour,MWh,megawatt-hours
gigawatt-hour gigawatt-hour,GWh,gigawatt-hours
terawatt-hour terawatt-hour,TWh,terawatt-hours
petawatt-hour petawatt-hour,PWh,petawatt-hours
Unit Names
watt watt,W,watts
kilowatt kilowatt,kW,kilowatts
megawatt megawatt,MW,megawatts
gigawatt gigawatt,GW,gigawatts
terawatt terawatt,TW,terawatts
petawatt petawatt,PW,petawatts
exawatt exawatt,EW,exawatts
zettawatt zettawatt,ZW,zettawatts
yottawatt yottawatt,YW,yottawatts
Unit Names
celsius celsius,C
fahrenheit fahrenheit,F
kelvin kelvin,K
Unit Names
attoliter attoliter,al,attolitre,attoliters
femtoliter femtoliter,fl,femtolitre,femtoliters
picoliter picoliter,pl,picolitre,picoliters
nanoliter nanoliter,nl,nanolitre,nanoliters
microliter microliter,μl,microlitre,microliters
milliliter milliliter,ml,millilitre,milliliters
centiliter centiliter,cl,centilitre,centiliters
deciliter deciliter,dl,decilitre,deciliters
liter liter,l,litre,liters
decaliter decaliter,dal,decalitre,decaliters
hectoliter hectoliter,hl,hectolitre,hectoliters
kiloliter kiloliter,kl,kilolitre,kiloliters
megaliter megaliter,Ml,megalitre,megaliters
gigaliter gigaliter,Gl,gigalitre,gigaliters
teraliter teraliter,Tl,teralitre,teraliters
petaliter petaliter,Pl,petalitre,petaliters
exaliter exaliter,El,exalitre,exaliters
customary fluid ounce customary fluid ounce,customary fluid ounces
fluid ounce fluid ounce,fl oz,floz,fluid ounces
fluid pint fluid pint,fl pt,fluid pints
fluid quart fluid quart,fl qt,fluid quarts
fluid gallon fluid gallon,fluid gallons
pint pint,pt,pints
quart quart,qt,quarts
gallon gallon,gal,gallons
Unit Names
attometer attometer,am,attometre,attometers
femtometer femtometer,fm,femtometre,femtometers
picometer picometer,pm,picometre,picometers
nanometer nanometer,nm,nanometre,nanometers
micrometer micrometer,μm,micrometre,micrometers
millimeter millimeter,mm,millimetre,millimeters
centimeter centimeter,cm,centimetre,centimeters
decimeter decimeter,dm,decimetre,decimeters
meter meter,m,metre,meters
decameter decameter,dam,decametre,decameters
hectometer hectometer,hm,hectometre,hectometers
kilometer kilometer,km,kilometre,kilometers
megameter megameter,Mm,megametre,megameters
gigameter gigameter,Gm,gigametre,gigameters
terameter terameter,Tm,terametre,terameters
petameter petameter,Pm,petametre,petameters
exameter exameter,Em,exametre,exameters
angstrom angstrom,Å,angstroms,angstroms
inch inch,in,inches,inches
foot foot,ft,feet,feet
yard yard,yd,yards
mile mile,mi,miles
furlong furlong,fur,furlongs
league league,lea,leagues
Unit Names
attogram attogram,ag,attograms
femtogram femtogram,fg,femtograms
picogram picogram,pg,picograms
nanogram nanogram,ng,nanograms
microgram microgram,μg,micrograms
milligram milligram,mg,milligrams
centigram centigram,cg,centigrams
decigram decigram,dg,decigrams
gram gram,g,grams
decagram decagram,dag,decagrams
hectogram hectogram,hg,hectograms
kilogram kilogram,kg,kilograms
megagram megagram,Mg,megagrams
gigagram gigagram,Gg,gigagrams
teragram teragram,Tg,teragrams
petagram petagram,Pg,petagrams
exagram exagram,Eg,exagrams
drachm drachm,dr,drachms
grain grain,gr,grains
ounce ounce,oz,ounces
pound pound,lb,pounds
slug slug,slugs
stone stone,st,stones
ton ton,t,tons

Examples


// Convert 1000 meters to kilometers
// 1. convert the number 1000 to a Value with unit "m"
meters := units.convert(1000, "m")
// 2. convert the Value to kilometers
kilometers := units.convert(meters, "km")
// 3. return the number stored in the Value
// note that this conversion is not necessary, as the result is automatically converted to a number
kilometersFloat := units.float(kilometers)
return kilometersFloat

// Convert 20 degrees Celsius to Kelvin, and convert 30 degrees Celsius to Fahrenheit
celsius := units.find("C")
kelvin := units.find("K")
fahrenheit := units.find("F")
twentyC := celsius(20)
thirtyC := celsius(30)

twentyK := units.convert(twentyC, kelvin)
thirtyF := units.convert(thirtyC, fahrenheit)
return [units.float(twentyK), units.float(thirtyF)]

// Convert 1000 meters to kilometers
// 1. convert the number 1000 from "m" to "km"
kilometers := units.convert(1000, "metre", "kilometer")
// 2. return the number
return kilometers

if97

IF97 provides functions for calculating thermodynamic properties of steam and water according to the IAPWS IF97 specification. This module uses names for thermodynamic quantities as defined on page 3 of the specification PDF .

All IF97 functions take either a regular number or a units.Value unit-aware value as input. Units will be converted where needed. Return values are also unit.Value objects.

massDensity: if97.massDensity(temp, pressure) returns the mass density (kg/m^3) as a function of temperature (K) and pressure (Pa)

specificEnthalpy: if97.specificEnthalpy(temp, pressure) returns the specific enthalpy (J/kg) as a function of temperature (K) and pressure (Pa)

specificEntropy: if97.specificEntropy(temp, pressure) returns the specific entropy (J/kg/K) as a function of temperature (K) and pressure (Pa)

specificInternalEnergy: if97.specificInternalEnergy(temp, pressure) returns the specific internal energy (J/kg) as a function of temperature (K) and pressure (Pa)

isobaricHeatCap: if97.isobaricHeatCap(temp, pressure) returns the mass constant-pressure heat capacity (J/kg/K) as a function of temperature (K) and pressure (Pa)

isochoricHeatCap: if97.isochoricHeatCap(temp, pressure) returns the mass constant-volume heat capacity (J/kg/K) as a function of temperature (K) and pressure (Pa)

speedSound: if97.speedSound(temp, pressure) returns the speed of sound (m/s) as a function of temperature (K) and pressure (Pa)

derivMassDensityPressure: if97.derivMassDensityPressure(temp, pressure) returns (d(rho)/d(p))T (kg/m³/Pa) as a function of temperature (K) and pressure (Pa)

viscosity: if97.viscosity(temp, pressure) returns the viscosity (Pa-s) as a function of temperature (K) and pressure (Pa)

thermalConductivity: if97.thermalConductivity(temp, pressure) returns the thermal conductivity (W/m-K) as a function of temperature (K) and pressure (Pa)

prandtl: if97.prandtl(temp, pressure) returns the Prandtl number (dimensionless) as a function of temperature (K) and pressure (Pa)

satLiquidMassDensity: if97.satLiquidMassDensity(pressure) returns the saturated liquid mass density (kg/m^3) as a function of pressure (Pa)

satVaporMassDensity: if97.satVaporMassDensity(pressure) returns the saturated vapor mass density (kg/m^3) as a function of pressure (Pa)

satLiquidSpecificEnthalpy: if97.satLiquidSpecificEnthalpy(pressure) returns the saturated liquid specific enthalpy (J/kg) as a function of pressure (Pa)

satVaporSpecificEnthalpy: if97.satVaporSpecificEnthalpy(pressure) returns the saturated vapor specific enthalpy (J/kg) as a function of pressure (Pa)

satLiquidSpecificEntropy: if97.satLiquidSpecificEntropy(pressure) returns the saturated liquid specific entropy (J/kg/K) as a function of pressure (Pa)

satVaporSpecificEntropy: if97.satVaporSpecificEntropy(pressure) returns the saturated vapor specific entropy (J/kg/K) as a function of pressure (Pa)

satLiquidMassInternalEnergy: if97.satLiquidMassInternalEnergy(pressure) returns the saturated liquid mass internal energy (J/kg) as a function of pressure (Pa)

satVaporMassInternalEnergy: if97.satVaporMassInternalEnergy(pressure) returns the saturated vapor mass internal energy (J/kg) as a function of pressure (Pa)

satLiquidIsobaricHeatCap: if97.satLiquidIsobaricHeatCap(pressure) returns the saturated liquid isobaric heat capacity (J/kg/K) as a function of pressure (Pa)

satVaporIsobaricHeatCap: if97.satVaporIsobaricHeatCap(pressure) returns the saturated vapor isobaric heat capacity (J/kg/K) as a function of pressure (Pa)

satLiquidIsochoricHeatCap: if97.satLiquidIsochoricHeatCap(pressure) returns the saturated liquid isochoric heat capacity (J/kg/K) as a function of pressure (Pa)

satVaporIsochoricHeatCap: if97.satVaporIsochoricHeatCap(pressure) returns the saturated vapor isochoric heat capacity (J/kg/K) as a function of pressure (Pa)

satLiquidSpeedSound: if97.satLiquidSpeedSound(pressure) returns the saturated liquid speed of sound (m/s) as a function of pressure (Pa)

satVaporSpeedSound: if97.satVaporSpeedSound(pressure) returns the saturated vapor speed of sound (m/s) as a function of pressure (Pa)

satLiquidViscosity: if97.satLiquidViscosity(pressure) returns the saturated liquid viscosity (Pa-s) as a function of pressure (Pa)

satVaporViscosity: if97.satVaporViscosity(pressure) returns the saturated vapor viscosity (Pa-s) as a function of pressure (Pa)

satLiquidThermalCond: if97.satLiquidThermalCond(pressure) returns the saturated liquid thermal conductivity (W/m-K) as a function of pressure (Pa)

satVaporThermalCond: if97.satVaporThermalCond(pressure) returns the saturated vapor thermal conductivity (W/m-K) as a function of pressure (Pa)

satLiqPrandtl: if97.satLiqPrandtl(pressure) returns the saturated liquid Prandtl number (dimensionless) as a function of pressure (Pa)

satVaporPrandtl: if97.satVaporPrandtl(pressure) returns the saturated vapor Prandtl number (dimensionless) as a function of pressure (Pa)

satTemp: if97.satTemp(pressure) returns the saturation temperature (K) as a function of pressure (Pa)

satPressure: if97.satPressure(temp) returns the saturation pressure (Pa) as a function of temperature (K)

surfaceTension: if97.surfaceTension(temp) returns the surface tension (N/m) as a function of temperature (K)

backwardEnthalpyTemp: if97.backwardEnthalpyTemp(pressure, specific_enthalpy) returns the temperature (K) as a function of pressure (Pa) and specific enthalpy (J/Kg)

backwardEnthalpyMassDensity: if97.backwardEnthalpyMassDensity(pressure, specific_enthalpy) returns the mass density (kg/m^3) as a function of pressure (Pa) and specific enthalpy (J/kg)

backwardEntropyTemp: if97.backwardEntropyTemp(pressure, specific_entropy) returns the temperature (K) as a function of pressure (Pa) and specific entropy (J/kg/K)

backwardEntropyMassDensity: if97.backwardEntropyMassDensity(pressure, specific_entropy) returns the mass density (kg/m^3) as a function of pressure (Pa) and specific entropy (J/kg/K)

backwardPressure: if97.backwardPressure(specific_enthalpy, specific_entropy) returns the pressure (Pa) as a function of specific enthalpy (J/kg) and specific entropy (J/kg/K)

backwardTemp: if97.backwardTemp(specific_enthalpy, specific_entropy) returns the temperature (K) as a function of specific enthalpy (J/kg) and specific entropy (J/kg/K)

backwardEntropyEnthalpy: if97.backwardEntropyEnthalpy(pressure, specific_entropy) returns the specific enthalpy (J/kg) as a function of pressure (Pa) and specific entropy (J/kg/K)

backwardEnthalpyEntropy: if97.backwardEnthalpyEntropy(pressure, specific_enthalpy) returns the specific entropy (J/kg/K) as a function of pressure (Pa) and specific enthalpy (J/kg)

qualitySpecificEnthalpy: if97.qualitySpecificEnthalpy(pressure, vapor_quality) returns the specific enthalpy (J/kg) as a function of pressure (Pa) and vapor quality (%)

qualitySpecificInternalEnergy: if97.qualitySpecificInternalEnergy(pressure, vapor_quality) returns the specific internal energy (J/kg) as a function of pressure (Pa) and vapor quality (%)

qualitySpecificEntropy: if97.qualitySpecificEntropy(pressure, vapor_quality) the specific entropy (J/kg/K) as a function of pressure (Pa) and vapor quality (%)

qualitySpecificVolume: if97.qualitySpecificVolume(pressure, vapor_quality) returns the specific volume (m^3) as a function of pressure (Pa) and vapor quality (%)

qualityMassDensity: if97.qualityMassDensity(pressure, specific_enthalpy) returns the mass density (kg/m^3) as a function of pressure (Pa) and vapor quality (%)

specificEnthalpyQuality: if97.specificEnthalpyQuality(pressure, specific_enthalpy) returns the vapor quality (%) as a function of pressure (Pa) and specific enthalpy (J/kg)

specificInternalEnergyQuality: if97.specificInternalEnergyQuality(pressure, specific_internal_energy) returns the vapor quality (%) as a function of pressure (Pa) and specific internal energy (J/kg)

specificEntropyQuality: if97.specificEntropyQuality(pressure, specific_entropy) returns the vapor quality (%) as a function of pressure (Pa) and specific entropy (J/kg/K)

massDensityQuality: if97.massDensityQuality(pressure, mass_density) returns the vapor quality (%) as a function of pressure (Pa) and mass density (kg/m^3)

specificVolumeQuality: if97.specificVolumeQuality(pressure, specific_volume) returns the vapor quality (%) as a function of pressure (Pa) and specific volume (m^3)