Skip to content

unaiverse.streams.streamlib

Tests, demos and tutorials need a stream that produces data without a sensor or a dataset behind it. The classes of this module are BufferedStream subclasses that compute each sample when the replay asks for it. An agent offers one of them to other peers like any other stream (see Data streams):

from unaiverse.streams.streams import Stream
from unaiverse.streams.streamlib import Sin

agent.add_streams([Stream.create(Sin(freq=0.1, phase=0., delta=1.), name="temperature", delta=1.)])
Class Produces
AllHotLabelStream A constant (1, n) vector of ones whose components are named by labels.
Random Uniform random tensors in [0, std).
Sin Samples of a sine wave.
Square Samples of a square wave.
CombSin Samples of a sum of sines with random or given frequencies and amplitudes.
SmoothHFHA, SmoothHFLA, SmoothLFLA, SmoothLFHA CombSin presets with three sines.
SquareHFHA, SquareHFLA, SquareLFHA, SquareLFLA Square presets.

The generators share the replay of BufferedStream. At each clock cycle the first call to get advances an index (0, 1, 2, ...) and the class computes the sample of that index. Because the constructor calls restart(), the index starts from 0 at the first read. The tag of a sample is the current clock cycle minus the cycle at which the replay of the uuid None started. The buffers stay empty. len(stream) is 0 and the generators never read the samples stored with set.

In Sin, Square and CombSin the argument delta is the time step of the signal and sample i is the value of the function at time i * delta. The description has a separate delta that paces the stream on the network and it stays -1. Use Stream.create(..., delta=...) to pace the stream on the network.

AllHotLabelStream

AllHotLabelStream(labels: list[str], device: device = device('cpu'))

Bases: BufferedStream

Source code in unaiverse/streams/streamlib.py
def __init__(self, labels: list[str],
             device: torch.device = torch.device('cpu')) -> None:
    """Initialize an AllHotLabelStream with the given label names.

    Args:
        labels: List of label strings to associate with the all-ones tensor.
        device: PyTorch device to place the tensor on (default: CPU).
    """
    super().__init__(props=DataProps(name=AllHotLabelStream.__name__,
                                     data_type="tensor",
                                     data_desc="dummy stream",
                                     tensor_shape=(1, len(labels)),
                                     tensor_labels=labels,
                                     tensor_dtype=str(torch.float),
                                     tensor_labeling_rule="geq0.5"),
                     is_static=True)

    self.set(torch.ones((1, len(labels)), dtype=torch.float32, device=device))
    self.restart()

A static stream that always returns the vector torch.ones((1, len(labels))) in which every label is active. It serves as a constant target or as a placeholder label stream.

Argument Type Default Meaning
labels list[str] The names of the components.
device torch.device torch.device("cpu") The device of the stored tensor.

The description is a float tensor stream named "AllHotLabelStream" (data_desc="dummy stream") of shape (1, len(labels)) with the labels and the rule "geq0.5". The stream is static (is_static=True).

>>> s = AllHotLabelStream(["cat", "dog"])
>>> s.get(), s.props.to_text(s.get())          # after the clock has run a cycle
(tensor([[1., 1.]]), 'cat, dog')

Random

Random(std: float, shape: tuple[int, ...] | None = (1,), device: device = device('cpu'))

Bases: BufferedStream

Source code in unaiverse/streams/streamlib.py
def __init__(self, std: float, shape: tuple[int, ...] | None = (1,),
             device: torch.device = torch.device('cpu')) -> None:
    """Initialize a Random stream.

    Args:
        std: Scale factor applied to the uniformly-sampled values (standard-deviation-like).
        shape: Shape of the output tensor (default: ``(1, )``).
        device: PyTorch device to place the tensor on (default: CPU).
    """
    super().__init__(props=DataProps(name="rand",
                                     data_type="tensor",
                                     data_desc="stream of random numbers",
                                     tensor_shape=shape,
                                     tensor_dtype=str(torch.float)))
    self.std = std
    self.device = device
    self.restart()

A stream of tensors drawn from a uniform distribution. Each sample is std * torch.rand(shape). The values lie in [0, std). The docstring of the class calls them zero-centred but the code never subtracts the mean.

Argument Type Default Meaning
std float The width of the interval of the values.
shape tuple[int, ...] (1,) The shape of each sample. Every entry must be an int. The annotation allows None but Random(std, shape=None) fails with AssertionError because a tensor stream needs a shape.
device torch.device torch.device("cpu") The device of the samples.

The description is a torch.float32 tensor stream named "rand" with tensor_shape=shape. A new tensor is drawn at each step of the replay.

>>> Random(2.0, shape=(1, 3)).get()
tensor([[0.8936, 1.6556, 1.7417]])

Sin

Sin(freq: float, phase: float, delta: float, device: device = device('cpu'))

Bases: BufferedStream

Source code in unaiverse/streams/streamlib.py
def __init__(self, freq: float, phase: float, delta: float,
             device: torch.device = torch.device('cpu')) -> None:
    """Initialize a Sin stream.

    Args:
        freq: Frequency of the sine wave in Hz.
        phase: Phase offset in units of full periods (0 = no offset, 1 = full period offset).
        delta: Time step between consecutive samples in seconds.
        device: PyTorch device to place the tensor on (default: CPU).
    """
    super().__init__(props=DataProps(name="sin",
                                     data_type="tensor",
                                     data_desc="stream of samples from the sin function",
                                     tensor_shape=(1, 1),
                                     tensor_dtype=str(torch.float)))
    self.freq = freq
    self.phase = phase
    self.period = 1. / self.freq
    self.delta = delta
    self.device = device
    self.restart()

A stream of samples of a sine wave. Sample i is the (1, 1) float tensor sin(2 * pi * freq * t) with t = i * delta + phase / freq.

Argument Type Default Meaning
freq float The frequency in Hz. 0 raises ZeroDivisionError.
phase float The phase as a fraction of a period. With 0 the wave starts at zero and with 0.25 at its peak.
delta float The time in seconds between two samples of the signal.
device torch.device torch.device("cpu") The device of the samples.

The description is named "sin" with shape (1, 1) and dtype torch.float32. The attributes freq, phase, period (1 / freq), delta and device hold the arguments.

>>> s = Sin(freq=0.25, phase=0., delta=1.)
>>> [round(s.get().item(), 3) for _ in range(4)]       # one get per clock cycle
[0.0, 1.0, -0.0, -1.0]

Square

Square(freq: float, ampl: float, phase: float, delta: float, device: device = device('cpu'))

Bases: BufferedStream

Source code in unaiverse/streams/streamlib.py
def __init__(self, freq: float, ampl: float, phase: float, delta: float,
             device: torch.device = torch.device('cpu')) -> None:
    """Initialize a Square wave stream.

    Args:
        freq: Frequency of the square wave in Hz.
        ampl: Amplitude of the square wave.
        phase: Phase offset in units of full periods.
        delta: Time step between consecutive samples in seconds.
        device: PyTorch device to place the tensor on (default: CPU).
    """
    super().__init__(props=DataProps(name="square",
                                     data_type="tensor",
                                     data_desc="stream of samples from the square function",
                                     tensor_shape=(1, 1),
                                     tensor_dtype=str(torch.float)))
    self.freq = freq
    self.ampl = ampl
    self.phase = phase
    self.period = 1. / self.freq
    self.delta = delta
    self.device = device
    self.restart()

A stream of samples of a square wave. Sample i is the (1, 1) float tensor ampl * (-1) ** floor(2 * freq * t) with t = i * delta + phase / freq. The value is ampl in the first half of each period and -ampl in the second.

Argument Type Default Meaning
freq float The frequency in Hz. 0 raises ZeroDivisionError.
ampl float The amplitude.
phase float The phase in periods.
delta float The time in seconds between two samples of the signal.
device torch.device torch.device("cpu") The device of the samples.

The description is named "square" with shape (1, 1) and dtype torch.float32.

>>> s = Square(freq=0.5, ampl=2., phase=0., delta=0.5)
>>> [s.get().item() for _ in range(4)]                  # one get per clock cycle
[2.0, 2.0, -2.0, -2.0]

CombSin

CombSin(f_cap: float | list, c_cap: float | list, order: int, delta: float, device: device = device('cpu'))

Bases: BufferedStream

Source code in unaiverse/streams/streamlib.py
def __init__(self, f_cap: float | list, c_cap: float | list, order: int, delta: float,
             device: torch.device = torch.device('cpu')) -> None:
    """Initialize a CombSin stream.

    Args:
        f_cap: Maximum frequency cap (float) for random sampling, or an explicit list of frequencies.
        c_cap: Amplitude cap (float) for random coefficient sampling, or an explicit list of coefficients.
        order: Number of sine components to combine.
        delta: Time step between consecutive samples in seconds.
        device: PyTorch device to place the tensor on (default: CPU).
    """
    super().__init__(props=DataProps(name="combsin",
                                     data_type="tensor",
                                     data_desc="stream of samples from combined sin functions",
                                     tensor_shape=(1, 1),
                                     tensor_dtype=str(torch.float)))
    if isinstance(f_cap, float):
        self.freqs = f_cap * torch.rand(order)
    elif isinstance(f_cap, list):
        self.freqs = torch.tensor(f_cap)
    else:
        raise Exception(f"expected float or list for f_cap, not {type(f_cap)}")
    self.phases = torch.zeros_like(self.freqs)
    if isinstance(c_cap, float):
        self.coeffs = c_cap * (2 * torch.rand(order) - 1)
    elif isinstance(c_cap, list):
        self.coeffs = torch.tensor(c_cap)
    else:
        raise Exception(f"expected float or list for c_cap, not {type(c_cap)}")

    # Check all the dimensions
    assert len(self.coeffs) == len(self.freqs), \
        (f"specify the same number of coefficients and frequencies (got {len(self.coeffs)} "
         f"and {len(self.freqs)} respectively).")

    self.delta = delta
    self.device = device
    self.restart()

A stream of samples of a sum of sines. Sample i is the (1, 1) float tensor sum_k coeffs[k] * sin(2 * pi * freqs[k] * t) with t = i * delta.

Argument Type Default Meaning
f_cap float or list A float draws order frequencies uniformly in [0, f_cap). A list gives the frequencies directly.
c_cap float or list A float draws order coefficients uniformly in [-c_cap, c_cap). A list gives the coefficients directly.
order int The number of sines drawn for a float cap. It is ignored for a list.
delta float The time in seconds between two samples of the signal.
device torch.device torch.device("cpu") Stored in device.

A cap that is neither a float nor a list raises a plain Exception. An int counts as neither and CombSin(5, 1.0, 3, 0.1) fails with "expected float or list for f_cap, not <class 'int'>". Write 5.0. Frequencies and coefficients of different lengths fail with AssertionError. The attributes freqs, coeffs and phases (zeros) are 1-dimensional tensors. The description is named "combsin".

SmoothHFHA

SmoothHFHA(device: device = device('cpu'))

Bases: CombSin

Source code in unaiverse/streams/streamlib.py
def __init__(self, device: torch.device = torch.device('cpu')) -> None:
    """Initialize a SmoothHFHA stream.

    Args:
        device: PyTorch device to place the tensor on (default: CPU).
    """
    freqs = [0.11, 0.07, 0.05]
    coeffs = [0.8, 0.16, 0.16]
    super().__init__(f_cap=freqs, c_cap=coeffs, order=3, delta=0.1, device=device)
    assert self.props is not None
    self.props.set_name("smoHfHa")

A CombSin preset with frequencies [0.11, 0.07, 0.05], coefficients [0.8, 0.16, 0.16] and delta=0.1. The highest frequency has the largest coefficient and the amplitude is large. The description is renamed "smoHfHa". The only argument is device.

FEATURES class-attribute instance-attribute

FEATURES = ['3sin', 'hf', 'ha']

['3sin', 'hf', 'ha']: three sines, high frequency, high amplitude. Each preset tags its signal with a FEATURES list so that experiments can compare the presets.

SmoothHFLA

SmoothHFLA(device: device = device('cpu'))

Bases: CombSin

Source code in unaiverse/streams/streamlib.py
def __init__(self, device: torch.device = torch.device('cpu')) -> None:
    """Initialize a SmoothHFLA stream.

    Args:
        device: PyTorch device to place the tensor on (default: CPU).
    """
    freqs = [0.11, 0.07, 0.05]
    coeffs = [0.4, 0.08, 0.08]
    super().__init__(f_cap=freqs, c_cap=coeffs, order=3, delta=0.1, device=device)
    assert self.props is not None
    self.props.set_name("smoHfLa")

A CombSin preset with frequencies [0.11, 0.07, 0.05], coefficients [0.4, 0.08, 0.08] and delta=0.1. The highest frequency has the largest coefficient and the amplitude is small. The description is renamed "smoHfLa".

FEATURES class-attribute instance-attribute

FEATURES = ['3sin', 'hf', 'la']

['3sin', 'hf', 'la'].

SmoothLFLA

SmoothLFLA(device: device = device('cpu'))

Bases: CombSin

Source code in unaiverse/streams/streamlib.py
def __init__(self, device: torch.device = torch.device('cpu')) -> None:
    """Initialize a SmoothLFLA stream.

    Args:
        device: PyTorch device to place the tensor on (default: CPU).
    """
    freqs = [0.11, 0.07, 0.05]
    coeffs = [0.08, 0.08, 0.4]
    super().__init__(f_cap=freqs, c_cap=coeffs, order=3, delta=0.1, device=device)
    assert self.props is not None
    self.props.set_name("smoLfLa")

A CombSin preset with frequencies [0.11, 0.07, 0.05], coefficients [0.08, 0.08, 0.4] and delta=0.1. The lowest frequency has the largest coefficient and the amplitude is small. The description is renamed "smoLfLa".

FEATURES class-attribute instance-attribute

FEATURES = ['3sin', 'lf', 'la']

['3sin', 'lf', 'la'].

SmoothLFHA

SmoothLFHA(device: device = device('cpu'))

Bases: CombSin

Source code in unaiverse/streams/streamlib.py
def __init__(self, device: torch.device = torch.device('cpu')) -> None:
    """Initialize a SmoothLFHA stream.

    Args:
        device: PyTorch device to place the tensor on (default: CPU).
    """
    freqs = [0.11, 0.07, 0.05]
    coeffs = [0.16, 0.16, 0.8]
    super().__init__(f_cap=freqs, c_cap=coeffs, order=3, delta=0.1, device=device)
    assert self.props is not None
    self.props.set_name("smoLfHa")

A CombSin preset with frequencies [0.11, 0.07, 0.05], coefficients [0.16, 0.16, 0.8] and delta=0.1. The lowest frequency has the largest coefficient and the amplitude is large. The description is renamed "smoLfHa".

FEATURES class-attribute instance-attribute

FEATURES = ['3sin', 'lf', 'ha']

['3sin', 'lf', 'ha'].

SquareHFHA

SquareHFHA(device: device = device('cpu'))

Bases: Square

Source code in unaiverse/streams/streamlib.py
def __init__(self, device: torch.device = torch.device('cpu')) -> None:
    """Initialize a SquareHFHA stream.

    Args:
        device: PyTorch device to place the tensor on (default: CPU).
    """
    super().__init__(freq=0.06, phase=0.5, ampl=1.0, delta=0.1, device=device)
    assert self.props is not None
    self.props.set_name("squHfHa")

A Square preset with freq=0.06, ampl=1.0, phase=0.5 and delta=0.1. The description is renamed "squHfHa". The only argument is device.

FEATURES class-attribute instance-attribute

FEATURES = ['square', 'hf', 'ha']

['square', 'hf', 'ha'].

SquareHFLA

SquareHFLA(device: device = device('cpu'))

Bases: Square

Source code in unaiverse/streams/streamlib.py
def __init__(self, device: torch.device = torch.device('cpu')) -> None:
    """Initialize a SquareHFLA stream.

    Args:
        device: PyTorch device to place the tensor on (default: CPU).
    """
    super().__init__(freq=0.06, phase=0.5, ampl=0.5, delta=0.1, device=device)
    assert self.props is not None
    self.props.set_name("squHfLa")

A Square preset with freq=0.06, ampl=0.5, phase=0.5 and delta=0.1. The description is renamed "squHfLa".

FEATURES class-attribute instance-attribute

FEATURES = ['square', 'hf', 'la']

['square', 'hf', 'la'].

SquareLFHA

SquareLFHA(device: device = device('cpu'))

Bases: Square

Source code in unaiverse/streams/streamlib.py
def __init__(self, device: torch.device = torch.device('cpu')) -> None:
    """Initialize a SquareLFHA stream.

    Args:
        device: PyTorch device to place the tensor on (default: CPU).
    """
    super().__init__(freq=0.03, phase=0.5, ampl=1.0, delta=0.1, device=device)
    assert self.props is not None
    self.props.set_name("squLfHa")

A Square preset with freq=0.03, ampl=1.0, phase=0.5 and delta=0.1. The description is renamed "squLfHa".

FEATURES class-attribute instance-attribute

FEATURES = ['square', 'lf', 'ha']

['square', 'lf', 'ha'].

SquareLFLA

SquareLFLA(device: device = device('cpu'))

Bases: Square

Source code in unaiverse/streams/streamlib.py
def __init__(self, device: torch.device = torch.device('cpu')) -> None:
    """Initialize a SquareLFLA stream.

    Args:
        device: PyTorch device to place the tensor on (default: CPU).
    """
    super().__init__(freq=0.03, phase=0.5, ampl=0.5, delta=0.1, device=device)
    assert self.props is not None
    self.props.set_name("squLfLa")

A Square preset with freq=0.03, ampl=0.5, phase=0.5 and delta=0.1. The description is renamed "squLfLa".

FEATURES class-attribute instance-attribute

FEATURES = ['square', 'lf', 'la']

['square', 'lf', 'la'].