Skip to content

unaiverse.streams.streamproxy

The processor of an agent reads several input streams and writes several output streams. These streams change from one request to the next. A StreamProxy is a named, ordered group of streams bound to one interaction uuid. The actions of an agent read and write through four proxies instead of accessing the streams directly:

Proxy Bound to
agent.stdin The inputs of the processor. process reads them with stdin.get(uuid=uuid, requested_by="process").
agent.stdtar The targets of learning. learn reads them with stdtar.get(uuid=uuid, requested_by="learn").
agent.stdext The streams that come from the environment (a camera for instance).
agent.stdout The outputs of the processor. process writes the whole output tuple with stdout.set(outputs, data_tag=tag, uuid=uuid).

The agent builds the four proxies in its constructor. stdtar, stdext and stdout start empty. stdin is created with a replace_none_samples_with list that holds one entry per positional input of the processor. The entry is the default value of that parameter in the forward signature of the processor (None when the parameter has no default). An optional input that receives no sample therefore reaches the processor as its default value.

The agent then binds the proxies. Before each behavior runs, set_default_stream_binding binds stdin to the input streams of the processor, stdtar to nothing, stdext to the environment streams and stdout to the output streams. It binds them with the uuid of the system interaction (Custom.SYSTEM_INTERACTION_UUID) and uses the streams of the private network when the agent runs the behavior of a world and those of the public network otherwise. When the interaction manager runs an interaction that names streams, it rebinds stdin, stdtar and stdext to the streams of the interaction with its uuid and moves stdout to that uuid with bind_uuid_only. A proxy can also hold plain values in place of streams. An interaction uses them to bind its default arguments and its data samples under keys such as <default_pos_0>. See Data streams and Agents.

The keys of a proxy are the keys of the dictionary passed to its last bind. For streams these keys are user hashes ("<peer id>:<name>"). Each entry can also be reached by its bare name (the part of the key after the last :). When two streams share a bare name, that name refers to the first one. len(proxy) is the number of bound entries, iteration yields the bound objects, "name" in proxy tests a key or a bare name and proxy[key] is proxy.get(key). str(proxy) groups the names by peer: "PEER:a,b", "owner:<default_pos_0>" or "no-streams".

from unaiverse.streams.streams import Stream
from unaiverse.streams.streamproxy import StreamProxy

a, b = Stream(name="a", data_type="text"), Stream(name="b", data_type="text")
px = StreamProxy({"PEER:a": a, "PEER:b": b})
px.set("a", "hi")
px.get("a"), px.get("PEER:a"), px.get(0), px.get()     # 'hi', 'hi', 'hi', ['hi', None]

StreamProxy

StreamProxy(streams: dict[str, Stream | object] | None = None, replace_none_samples_with: list | None = None)
Source code in unaiverse/streams/streamproxy.py
def __init__(self, streams: dict[str, Stream | object] | None = None,
             replace_none_samples_with: list | None = None):
    """Create a Stream proxy.

    Args:
        streams: Optional dict mapping stream name to stream object.
        replace_none_samples_with: Optional list of values to be used when streams return None (warning: they are
            applied in-order). It does not apply when getting with 'all_uuids', where None samples are stripped
            by the get function in the actual streams.
    """
    self._streams: dict[str, Stream | object] = streams if streams is not None else {}
    self._stream_list: list = list(self._streams.values())
    self._streams_by_name_only: dict[str, Stream | object] = {}
    for stream_hash, stream_obj in self._streams.items():
        name_only = StreamProxy.__get_name_only(stream_hash)
        if name_only not in self._streams_by_name_only:  # In case of collision, the first name wins
            self._streams_by_name_only[name_only] = stream_obj
    self._uuid: str | None = None

    self.replace_none_samples_with_list: list | None = replace_none_samples_with
    self.replace_none_samples_with: dict[str, object] = {}
    self.__enable_replacers_or_none_samples()
Argument Type Default Meaning
streams dict[str, Stream \| object] or None None The initial entries by key. A value that is not a Stream is a plain value returned as it is. The dictionary is used without a copy.
replace_none_samples_with list or None None Values returned in place of a None sample (one per position). Entry i replaces the sample of the entry at position i. Replacement does not apply with all_uuids=True.

The proxy keeps the original list in replace_none_samples_with_list and at each bind rebuilds from it the dictionary replace_none_samples_with that maps each key to its replacement. The default uuid is None until a bind gives one.

bind

bind(streams: dict[str, Stream | object], uuid: str | None = None)
Source code in unaiverse/streams/streamproxy.py
def bind(self, streams: dict[str, Stream | object], uuid: str | None = None):
    """Rebind this proxy to a different set of streams (different from the ones used when building it).

    Args:
        streams: Dict mapping stream name to stream object.
        uuid: The default UUID to look for when doing get/set.
    """
    self._streams = streams.copy()  # Shallow copy
    self._stream_list = list(streams.values())
    self._streams_by_name_only = {}
    for stream_hash, stream_obj in self._streams.items():
        name_only = StreamProxy.__get_name_only(stream_hash)
        if name_only not in self._streams_by_name_only:  # In case of collision, the first name wins
            self._streams_by_name_only[name_only] = stream_obj
    if uuid is not None:
        self._uuid = uuid

    self.__enable_replacers_or_none_samples()

Replaces the bound entries with a shallow copy of streams and rebuilds the bare-name index and the replacements. A uuid that is not None becomes the default uuid of get, set and get_tag. A uuid of None keeps the previous default.

add_new_bind

add_new_bind(stream_hash: str, stream: Stream) -> None
Source code in unaiverse/streams/streamproxy.py
def add_new_bind(self, stream_hash: str, stream: Stream) -> None:
    """Register an additional stream under the given hash, if not already bound.

    Args:
        stream_hash: The key (typically a user hash) to associate with the stream.
        stream: The Stream object to add.
    """
    if stream_hash not in self._streams:
        self._streams[stream_hash] = stream
        self._stream_list.append(stream)
        name_only = StreamProxy.__get_name_only(stream_hash)
        if name_only not in self._streams_by_name_only:  # In case of collision, the first name wins
            self._streams_by_name_only[name_only] = stream

    self.__enable_replacers_or_none_samples()

Adds stream under stream_hash when that key is not bound yet. An existing key is left as it is. The bare name is indexed when it is free and the replacements are rebuilt.

bind_uuid_only

bind_uuid_only(uuid: str | None) -> None
Source code in unaiverse/streams/streamproxy.py
def bind_uuid_only(self, uuid: str | None) -> None:
    """Set the default UUID used by get/set when the caller does not pass one."""
    self._uuid = uuid

Replaces the default uuid with uuid (None included) and keeps the bound entries.

clear_data

clear_data(uuid: str | None)
Source code in unaiverse/streams/streamproxy.py
def clear_data(self, uuid: str | None):
    """Remove all the currently existing data from the bind streams (not the interactions)."""

    for stream_obj in self._stream_list:
        stream_obj.clear_data(uuid=uuid)

Calls clear_data(uuid=uuid) on every bound entry. The interactions are kept. A plain value among the entries raises AttributeError.

clear_all_data

clear_all_data()
Source code in unaiverse/streams/streamproxy.py
def clear_all_data(self):
    """Remove all the currently existing data from the bind streams (not the interactions)."""

    for stream_obj in self._stream_list:
        stream_obj.clear_all_data()

Calls clear_all_data() on every bound entry. As with clear_data, a plain value among the entries raises AttributeError.

enable

enable() -> None
Source code in unaiverse/streams/streamproxy.py
def enable(self) -> None:
    """Enable all streams in this proxy stream, allowing data to be set."""
    for stream_obj in self._stream_list:
        stream_obj.enable()

Calls enable() on every bound entry.

disable

disable() -> None
Source code in unaiverse/streams/streamproxy.py
def disable(self) -> None:
    """Disable all streams in this proxy, preventing data from being set."""
    for stream_obj in self._stream_list:
        stream_obj.disable()

Calls disable() on every bound entry. The agent disables stdin for a processor driven by a person.

get

get(key: str | int | None = None, requested_by: str | None = None, uuid: str | None = None, all_uuids: bool = False, data_type: str | None = None)
Source code in unaiverse/streams/streamproxy.py
def get(self, key: str | int | None = None, requested_by: str | None = None, uuid: str | None = None,
        all_uuids: bool = False, data_type: str | None = None):
    """Get data from a stream.

    Args:
        key: Stream name (str), index (int), or None to retrieve from all streams.
        requested_by: The identifier of who requests access to the stream data (default: None).
        uuid: UUID of the interaction to retrieve data for (default: None, that will use the default-bind UUID).
        all_uuids: If True, data from all the existing UUIDs (no matter what) are returned.
            It is valid if and only if paired with the selection of a specific data_type or of key.
        data_type: The string name of the data type of interest. If multiple streams with the same data_type
            are bind, the first found one is returned.

    Returns:
        The data from the requested stream, or None if no new data is available (it is a list if key = None).
        If all_uuids is True, returns a wild list of tuples (data, data_tag).
    """
    if len(self._stream_list) == 0:
        return None

    if uuid is None:
        uuid = self._uuid

    if all_uuids and (not data_type and not key):
        raise GenException("You can only ask for all UUIDs if you also also specify a "
                           "stream name (key) or a data type")

    if key and data_type:
        raise GenException("You can only specify a stream name (key) or a data type, not both")

    if key is None:
        found_at_least_one = False
        ret = []
        for i, s in enumerate(self._stream_list):
            if isinstance(s, Stream):
                if data_type and (s.props is None or s.props.data_type != data_type):
                    continue
                data = s.get(requested_by, uuid, all_uuids)  # This might will be None if requested multiple times
                data = self.__replace_none_samples_if_possible(data, i)
                if data is not None:
                    found_at_least_one = True
                ret.append(data)
            else:
                ret.append(s)  # This will always be not-None (well, unless None is the actual value)
        return ret if found_at_least_one else None
    elif isinstance(key, int):
        if isinstance(self._stream_list[key], Stream):
            data = self._stream_list[key].get(requested_by, uuid, all_uuids)
            data = self.__replace_none_samples_if_possible(data, key)
            return data
        else:
            return self._stream_list[key]  # Static, given value
    elif key in self._streams:
        stream = self._streams[key]
        if isinstance(stream, Stream):
            data = stream.get(requested_by, uuid, all_uuids)
            data = self.__replace_none_samples_if_possible(data, key)
            return data
        else:
            return stream  # Default value
    elif key in self._streams_by_name_only:
        stream = self._streams_by_name_only[key]
        if isinstance(stream, Stream):
            data = stream.get(requested_by, uuid, all_uuids)
            data = self.__replace_none_samples_if_possible(data, key)
            return data
        else:
            return stream  # Static, given value
    else:
        raise GenException(f"Unknown stream/key: {key}"
                           f"\n{self._stream_list}\n{self._streams}\n{self._streams_by_name_only}")

Reads samples from the bound streams.

Argument Type Default Meaning
key str, int or None None A key, a bare name or a position. None reads every entry.
requested_by str or None None Passed to Stream.get. Each distinct requested_by receives each sample once.
uuid str or None None The interaction. None uses the default uuid.
all_uuids bool False Passed to Stream.get. It is accepted only together with a key or a data_type.
data_type str or None None With key=None, reads only the streams of this data type. It cannot be combined with a key.

With a key the result is the sample of that entry (or the plain value) after replacement. With key=None the result is a list with one element per entry (plain values included). It is None instead when every stream returned None. The list form holds for a proxy with a single stream too: get() returns ['hi'], not 'hi'. An unknown key raises GenException("Unknown stream/key: ..."), a combination of key and data_type raises GenException and an empty proxy returns None.

Three behaviors of the current version follow from the code:

  • The check on all_uuids tests the truth value of key. get(0, all_uuids=True) raises GenException because the position 0 is false.
  • A replacement looked up through a bare name raises KeyError because the replacements are keyed by full key. get("a") on the example of replace_none_samples_with fails when the stream of "a" has no sample. The calls get(0) and get("PEER:a") return the replacement.
  • A replacement looked up by position beyond the end of the list raises IndexError.
>>> pr = StreamProxy({"P:a": Stream(name="a"), "P:b": Stream(name="b")},
...                  replace_none_samples_with=["DEF_A", "DEF_B"])
>>> pr.get(0), pr.get("P:b"), pr.get()
('DEF_A', 'DEF_B', ['DEF_A', 'DEF_B'])

add_interaction

add_interaction(interaction) -> None
Source code in unaiverse/streams/streamproxy.py
def add_interaction(self, interaction) -> None:
    """Register an interaction on all bound streams.

    Args:
        interaction: The Interaction object to register.
    """
    for s in self._stream_list:
        s.add_interaction(interaction)

Calls add_interaction(interaction) on every bound entry. A plain value raises AttributeError.

has_interaction

has_interaction(uuid: str | None) -> bool
Source code in unaiverse/streams/streamproxy.py
def has_interaction(self, uuid: str | None) -> bool:
    """Check whether all bound streams have an interaction for the given UUID.

    Args:
        uuid: The UUID to look up.

    Returns:
        True if every bound stream has an interaction for that UUID, False otherwise.
    """
    for s in self._stream_list:
        if not isinstance(s, Stream):
            continue
        if not s.has_interaction(uuid):
            return False
    return True

True when every bound stream has an interaction for uuid. Plain values are skipped and a proxy without streams returns True.

get_interaction

get_interaction(uuid: str | None) -> object | None
Source code in unaiverse/streams/streamproxy.py
def get_interaction(self, uuid: str | None) -> object | None:
    """Retrieve the interaction for the given UUID from the first stream that has one.

    Args:
        uuid: The UUID of the interaction to retrieve.

    Returns:
        The Interaction object if found, else None.
    """
    if not self.has_interaction(uuid):
        return None

    for s in self._stream_list:
        if not isinstance(s, Stream):
            continue
        interaction = s.get_interaction(uuid)
        if interaction is not None:
            return interaction  # This will happen at the 1st iteration for the way "has_interaction" is implemented
    return None  # This will never happen, since we already ensured that it "has_interaction"

Returns the interaction of uuid taken from the first bound stream when has_interaction(uuid) is True. It returns None otherwise.

set

set(key_or_data, data=None, data_tag: int = -1, uuid: str | None = None, force: bool = False)
Source code in unaiverse/streams/streamproxy.py
def set(self, key_or_data, data=None, data_tag: int = -1, uuid: str | None = None, force: bool = False):
    """Set data on a stream.

    Usage (example for stdin - it could be other StreamProxy's):
        - ``self.stdin.set(data)`` — when there is only one stream
        - ``self.stdin.set(stream_name, data)`` — by name
        - ``self.stdin.set(stream_index, data)`` — by index

    Args:
        key_or_data: Stream name/index if ``data`` is also provided, the data itself
            for the single-stream case, or a list of values to set on all streams at once.
        data: The data to set (when ``key_or_data`` is a name/index).
        data_tag: Custom integer tag for the sample (default: -1, meaning auto-tag).
        uuid: UUID of the interaction for which data is being set (default: None, that will use the
            default-bind UUID)
        force: Boolean flag to force the set operation also on disabled streams
    """
    if len(self._stream_list) == 0:
        stack_str = '\n'.join(traceback.format_stack())
        log.error(stack_str)
        raise GenException("No streams bound to this StreamProxy")

    if uuid is None:
        uuid = self._uuid

    if isinstance(key_or_data, (list, tuple)):
        if len(key_or_data) != len(self._stream_list):
            raise GenException(f"The list of stream values to set must have the same length of the stream list "
                               f"in this proxy "
                               f"({len(key_or_data)} != {len(self._stream_list)})")
        for i, data in enumerate(key_or_data):
            s = self._stream_list[i]
            if isinstance(s, Stream):
                s.set(data, data_tag, uuid=uuid, force=force)
            else:
                self._stream_list[i] = data
                key_at_index = next(islice(self._streams, i, None))
                self._streams[key_at_index] = data
                name_only = StreamProxy.__get_name_only(key_at_index)
                self._streams_by_name_only[name_only] = data
        return key_or_data
    elif isinstance(key_or_data, int):
        s = self._stream_list[key_or_data]
        if isinstance(s, Stream):
            return s.set(data, uuid=uuid, force=force)
        else:
            self._stream_list[key_or_data] = data
            key_at_index = next(islice(self._streams, key_or_data, None))
            self._streams[key_at_index] = data
            name_only = StreamProxy.__get_name_only(key_at_index)
            self._streams_by_name_only[name_only] = data
            return data
    elif key_or_data in self._streams:
        s = self._streams[key_or_data]
        if isinstance(s, Stream):
            return s.set(data, data_tag, uuid=uuid, force=force)
        else:
            self._streams[key_or_data] = data

            # We need to keep this fresh in the other data structures
            key_to_pos_in_stream_list = {k: i for i, k in enumerate(self._streams)}
            p = key_to_pos_in_stream_list[key_or_data]
            self._stream_list[p] = data
            name_only = StreamProxy.__get_name_only(key_or_data)
            self._streams_by_name_only[name_only] = data
            return data
    elif key_or_data in self._streams_by_name_only:
        stream = self._streams_by_name_only[key_or_data]
        if isinstance(stream, Stream):
            return stream.set(data, data_tag, uuid=uuid, force=force)
        else:
            # We guess the full name and call set again using it
            for i, full_name in enumerate(self._streams.keys()):
                name_only = StreamProxy.__get_name_only(full_name)
                if name_only == key_or_data:
                    return self.set(full_name, data, data_tag, uuid, force)
            raise GenException(f"Unknown stream: {key_or_data}")
    else:
        raise GenException(f"Unknown stream: {key_or_data}")

Writes samples on the bound streams.

Argument Type Default Meaning
key_or_data list, tuple, int or str A list or tuple writes one value per entry in order. An int or a str selects one entry by position, key or bare name.
data any None The sample for a single entry.
data_tag int -1 The tag passed to Stream.set. A negative value lets the stream choose.
uuid str or None None The interaction. None uses the default uuid.
force bool False Passed to Stream.set. With True the sample is written on disabled streams too.

A list must have exactly one value per entry (GenException otherwise). Each stream receives its value with the same data_tag and the method returns the list. When key_or_data selects a single entry, the method returns the result of Stream.set (the Data or None). When that entry is a plain value, the proxy replaces it with the new value in its three internal indexes (by key, by position and by bare name) and returns the new value. An empty proxy logs the call stack and raises GenException("No streams bound to this StreamProxy"). An unknown key raises GenException("Unknown stream: ...").

The docstring documents set(data) for a proxy with a single stream. In the current version data is looked up as a key and the call raises GenException("Unknown stream: ..."). Write set(0, data) or set([data]). The call by position set(index, data, data_tag) ignores data_tag and the stream tags the sample with the clock. The forms by key and by list pass the tag.

get_tag

get_tag(key: str | int | None = None, uuid: str | None = None) -> int
Source code in unaiverse/streams/streamproxy.py
def get_tag(self, key: str | int | None = None, uuid: str | None = None) -> int:
    """Return the data tag for the given stream key and UUID.

    Args:
        key: Stream name (str), index (int), or None to return the max tag across all streams.
        uuid: UUID of the interaction to query (default: None, that will use the default-bind UUID).

    Returns:
        The integer data tag, or -1 if not applicable.

    Raises:
        GenException: If no streams are bound or the key is not found.
    """
    if len(self._stream_list) == 0:
        raise GenException("No streams bound to this StreamProxy")

    if uuid is None:
        uuid = self._uuid

    if key is None:
        ret = []
        for s in self._stream_list:
            if isinstance(s, Stream):
                data_tag = s.get_tag(uuid)
                if data_tag is None:
                    return -1
                ret.append(data_tag)
            else:
                ret.append(-1)
        if len(ret) == 0:
            return -1
        return max(ret)
    elif isinstance(key, int):
        if isinstance(self._stream_list[key], Stream):
            return self._stream_list[key].get_tag(uuid)
        else:
            return -1  # Default value
    elif key in self._streams:
        if self._streams[key] is not None:
            stream = self._streams[key]
            if isinstance(stream, Stream):
                tag = stream.get_tag(uuid)
                return tag if tag is not None else -1
            else:
                return -1
        else:
            return -1  # Default value
    else:
        raise GenException(f"Unknown stream: {key}")

Returns the tag of the current sample of one entry or of the whole proxy.

Argument Type Default Meaning
key str, int or None None A full key or a position. None returns the largest tag among the entries.
uuid str or None None The interaction. None uses the default uuid.

With key=None the result is -1 as soon as one stream has no sample for the uuid. Plain values count as -1. A position returns the tag of that stream (None when it has no sample) or -1 for a plain value. A full key returns the tag or -1. The agent reads stdin.get_tag(uuid=uuid) and copies the tag to the outputs. An empty proxy raises GenException. Unlike get and set, this method refuses a bare name with GenException("Unknown stream: ...").

clear

clear() -> None
Source code in unaiverse/streams/streamproxy.py
def clear(self) -> None:
    """Reset all bound streams by setting their data to None."""
    self.set([None] * len(self))

Calls set([None] * len(proxy)). Every stream stores an empty sample for the default uuid and every plain value becomes None.

items

items()
Source code in unaiverse/streams/streamproxy.py
def items(self):
    """Iterate over ``(stream_name, stream)`` pairs for all bound streams.

    Returns:
        An iterator of ``(key, value)`` pairs.
    """
    for key, value in self._streams.items():
        yield key, value

Yields the (key, entry) pairs in binding order.

values

values()
Source code in unaiverse/streams/streamproxy.py
def values(self):
    """Iterate over the bound streams.

    Returns:
        An iterator.
    """
    yield from self._streams.values()

Yields the bound entries in binding order.

names property

names: list[str]

The list of the bound keys in binding order. For streams these are user hashes.