Cost Functions

A Cost Function represents the computation of a cost metric from a vector of inputs called a Sample. In general, a cost function produces some metric value that can be minimized or maximized depending on the problem space.

Samples

Cost Functions operate over samples, which are vectors of static and signal inputs to the system. A sample is created by decomposing the vector of float values produced by the Optimizer based on the inputs declared in the TestOptions object used to run the test. The static attribute on the Sample object provides access to the set of named static inputs, while the signals attribute allows users to access the named signal inputs. The SampleLike type captures the set of values that can be converted into a Sample object.

Results

Base Class

The cost function interface is defined in the CostFunc[C, E] class, which users can be extended to create their own implementations. The type variable C represents the cost value computed by the optimizer, and the type variable E represents the type of the annotation data in the return value. The only required method to implement is the evaluate() method, which should take as a parameter a Sample and return a Result value.

 1from staliro import CostFunc, Sample, Result
 2
 3
 4class Foo(CostFunc[float, str]):
 5    def __init__(self):
 6        ...
 7
 8    def evaluate(self, sample: Sample) -> Result[float, str]:
 9        ...
10
11
12class Bar(CostFunc[tuple[float, float], dict[str, int]]):
13    def __init__(self):
14        ...
15
16    def evaluate(self, sample: Sample) -> Result[tuple[float, float], dict[str, int]]:
17        ...

Decorator

A cost function can also be created by applying the costfunc() decorator to a function that accepts a sample and returns a Result value.

import staliro

@staliro.costfunc()
def costfunc(sample: staliro.Sample) -> staliro.Result[float, str]:
    return staliro.Result(value=0.0, extra="foo")

costfunc.evaluate(...)  # Result(0.0, "foo")

The function can also return a value other than a Result, in which case a new Result value is created with the value attribute set to the functions return value and the extra attribute set to None.

import staliro

@staliro.costfunc
def costfunc(sample: staliro.Sample) -> float:
    return 0.0

costfunc.evaluate(...)  # Result(0.0, None)