Using Custom Functions
This page describes how custom functions are registered and how to use them with the PowerTSM .NET API in ad hoc calculations. It also explains how to create your own custom functions.
Registration
Section titled “Registration”Custom functions can be registered in the .NET API in two ways:
- Direct registration (
.csfiles): Load functions explicitly usingUseCustomFunctionmethod - CustomFunctions path (
.dllor.csxfiles): Place files in the configured custom functions path (HAKOM:TSM:Calculation:Formulas:CustomFunctions)
Loading Custom Functions
Section titled “Loading Custom Functions”For .cs files, custom functions must be loaded explicitly using the UseCustomFunction method in conjunction with the class name of the custom function when creating an instance of ITsm.
// Not necessary for standard functions!var tsm = ITsm.Create( (container) => container.UseCustomFunction<SomeCustomFunction>());Ad Hoc Calculations
Section titled “Ad Hoc Calculations”After creating an instance of ITsm, use it to specify the formula to be calculated and the repository from which the time series data will be read. To execute the calculation, invoke the method Calculate<T> from ITsm.Calculator.
var tsm = ITsm.Create()
// Define formulavar formula = tsm.Formulas.Create("BestValue([SomeTimeSeriesName], [AnotherTimeSeriesName])");
// Define from which repository to read the data fromvar repositoryName = "SomeRepositoryName"
var calculationOptions = tsm.Calculator.CalculationOptions.Create( true, FunctionType.StepRight(), tsm.Intervals.Create( IntervalType.Hour() ));
// Define the period for which data will be readvar from = new DateTimeOffset(2025, 01, 01, 00, 00, 00, TimeSpan.Zero);var to = start.AddHours(6);
var timeSeriesDataReadingOptionsFactory = tsm.Container.Resolve<ITimeSeriesDataReadingOptionsFactory>();var timeSeriesDataReadingOptions = timeSeriesDataReadingOptionsFactory.Create( Period.Create(from, to));
var result = await tsm.Calculator.Calculate<double>( formula, calculationOptions, timeSeriesDataReadingOptions, repositoryName, CancellationToken.None);
var listOfResultDataPoints = await result.ToListAsync()Creating Custom Functions
Section titled “Creating Custom Functions”Users can create their own custom functions to implement specific calculation logic tailored to their business requirements. A custom function is a class that implements one of the ICustomFunction interfaces from HAKOM.TSM.Net.Api.Calculation.Formulas.CustomFunctions and carries a CustomFunctionName attribute.
Supported Formats
Section titled “Supported Formats”- Precompiled DLLs (
.dllfiles): Compiled .NET assemblies containing custom function implementations - C# Script files (
.csxfiles): Raw C# code files that are compiled at runtime - C# Source files (
.csfiles): Must be registered directly in the .NET API
All three formats contain the same class. The format only decides how the class reaches PowerTSM: .dll and .csx files are placed in the custom functions folder, while a .cs file is compiled into your own application and registered with UseCustomFunction.
Anatomy of a Custom Function
Section titled “Anatomy of a Custom Function”A custom function class consists of four parts:
| Part | Purpose |
|---|---|
[CustomFunctionName("TariffCost")] |
The name the formula calls. Required, and it must be a valid C# identifier. nameof(MyClass) is a convenient way to keep name and class in sync. |
ICustomFunction<…> |
The interface that declares the parameter types and the return type. |
Evaluate(DateTimeOffset calculationTime, …) |
Called for every timestamp of the calculation. Contains the actual logic. |
PerformBeforeCalculation(…) |
Called once, before the first Evaluate of a calculation. |
Optionally, the class can implement Initialize to receive the calculation context. Because ICustomFunction declares it as a default interface member, it has to be implemented explicitly, as Task ICustomFunction.Initialize<TValue>(...).
Choosing the Interface
Section titled “Choosing the Interface”The interface is chosen by parameter count. ICustomFunction<TResult> takes no parameters, ICustomFunction<TParameter1, TResult> takes one, ICustomFunction<TParameter1, TParameter2, TResult> takes two, and so on up to nine parameters. The last type argument is always the return type.
| Formula call | Interface |
|---|---|
MyFunction() |
ICustomFunction<double> |
MyFunction(2.0) |
ICustomFunction<double, double> |
MyFunction([in1], [in2]) |
ICustomFunction<ITimeSeriesData<double>, ITimeSeriesData<double>, ITimeSeriesData<double>> |
MyFunction([a], [b], [c], …) |
ICustomFunction<ITimeSeriesData<double>[], ITimeSeriesData<double>> with a params array |
Declare a parameter as double when only the number matters, and as ITimeSeriesData<double> when the function needs the flag or the timestamp of the input as well. The same choice applies to the return type: returning double produces results flagged as Valid, while returning ITimeSeriesData<double> lets the function set the flag itself.
Collections work too. A parameter of type List<double> can be filled directly from the formula, as in SumList(new List<double> { 1, 2, 3 }).
The Calculation Context
Section titled “The Calculation Context”The context passed to Initialize gives access to everything the calculation knows:
| Member | Content |
|---|---|
TimeSeriesDataFactory |
Creates result data points from a time, a value and a flag |
ArithmeticOperations |
Arithmetic on the calculated value type |
CalculationOptions |
The options the referenced time series are read with |
ReadingOptions |
The requested properties of the result |
RootTimeSeriesReference |
The time series the formula is assigned to, if any |
SourceTimeSeries |
All time series referenced in the formula, in the order they appear |
GetService<T>() / TryGetService<T>() |
Any registered service, for example IFlagPriorityProvider |
Example: A Two-Rate Tariff
Section titled “Example: A Two-Rate Tariff”A consumption time series has to be priced with a two rate tariff: a peak rate on working days between 08:00 and 20:00, and an off peak rate at all other times. The rule depends on the timestamp of each data point and on two prices that should not be baked into the code, which is a typical case for a custom function.
Because the function declares its consumption parameter and its result as data points rather than plain values, the calculated cost can carry the flag of the consumption it was derived from: an estimated consumption produces an estimated cost.
using HAKOM.TSM.Net.Api.Calculation.Formulas.CustomFunctions;using HAKOM.TSM.Net.Api.Data.TimeSeries;using System;using System.Threading.Tasks;
[CustomFunctionName("TariffCost")]public sealed class TariffCost : ICustomFunction<ITimeSeriesData<double>, double, double, ITimeSeriesData<double>>{ private ITimeSeriesDataFactory? _timeSeriesDataFactory;
Task ICustomFunction.Initialize<TValue>(ICustomFunctionContext<TValue> context) { _timeSeriesDataFactory = context.TimeSeriesDataFactory; return Task.CompletedTask; }
public ITimeSeriesData<double> Evaluate( DateTimeOffset calculationTime, ITimeSeriesData<double> consumption, double peakRate, double offPeakRate ) { if (_timeSeriesDataFactory is null) throw new InvalidOperationException("Initialize has not been called yet.");
var isWorkingDay = calculationTime.DayOfWeek != DayOfWeek.Saturday && calculationTime.DayOfWeek != DayOfWeek.Sunday; var isPeak = isWorkingDay && calculationTime.Hour >= 8 && calculationTime.Hour < 20;
var rate = isPeak ? peakRate : offPeakRate;
// The cost is only as trustworthy as the consumption it is based on, // so the flag of the input is carried over to the result. return _timeSeriesDataFactory.Create( calculationTime, consumption.Value * rate, consumption.Flag ); }
public Task PerformBeforeCalculation( ITimeSeriesData<double> consumption, double peakRate, double offPeakRate ) => Task.CompletedTask;}Called as TariffCost([Consumption], 0.32, 0.19), it produces:
| Timestamp | Consumption |
Result |
|---|---|---|
| Tuesday, 09:00 | 10 | valid | 3.2 | valid |
| Tuesday, 22:00 | 10 | valid | 1.9 | valid |
| Sunday, 09:00 | 10 | valid | 1.9 | valid |
| Tuesday, 09:00 | 10 | estimated | 3.2 | estimated |
Using the Function from a .cs File
Section titled “Using the Function from a .cs File”Register the class when creating the ITsm instance, then use its name in a formula:
Register and calculate with a custom function
Section titled “ Register and calculate with a custom function”var tsm = ITsm.Create( (container) => container.UseCustomFunction<TariffCost>());
var formula = tsm.Formulas.Create("TariffCost([Consumption], 0.32, 0.19)");Using the Function from a .csx File
Section titled “Using the Function from a .csx File”For a script file, save the same class as a .csx file in the custom functions folder. No registration call is needed, and the file can be added or changed while the application is running.
Script files are compiled with a minimal set of references: the .NET runtime basics and the PowerTSM assemblies. Additional assemblies have to be requested in the script itself with an #r directive, for example:
Reference an additional assembly in a script
Section titled “ Reference an additional assembly in a script”#r "System.Linq"
using System.Linq;Using the Function from a .dll File
Section titled “Using the Function from a .dll File”Compile the class into a class library that references the PowerTSM NuGet package (see Installing the .NET API), then copy the resulting .dll into the custom functions folder. The assembly is loaded per calculation, so replacing the file takes effect without restarting the application.