Skip to content
Documentation

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.

Custom functions can be registered in the .NET API in two ways:

  1. Direct registration (.cs files): Load functions explicitly using UseCustomFunction method
  2. CustomFunctions path (.dll or .csx files): Place files in the configured custom functions path (HAKOM:TSM:Calculation:Formulas:CustomFunctions)

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>()
);

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 formula
var formula = tsm.Formulas.Create("BestValue([SomeTimeSeriesName], [AnotherTimeSeriesName])");
// Define from which repository to read the data from
var repositoryName = "SomeRepositoryName"
var calculationOptions = tsm.Calculator.CalculationOptions.Create(
true,
FunctionType.StepRight(),
tsm.Intervals.Create(
IntervalType.Hour()
)
);
// Define the period for which data will be read
var 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()

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.

  • Precompiled DLLs (.dll files): Compiled .NET assemblies containing custom function implementations
  • C# Script files (.csx files): Raw C# code files that are compiled at runtime
  • C# Source files (.cs files): 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.

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>(...).

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 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

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

Register the class when creating the ITsm instance, then use its name in a formula:

flask 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)");

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:

flask Reference an additional assembly in a script

Section titled “ Reference an additional assembly in a script”
#r "System.Linq"
using System.Linq;

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.

© 2026 Volue.Version v0.6.38017 November 2026