# Copyright 2025-2026 Thousand Brains Project
# Copyright 2023-2024 Numenta Inc.
#
# Copyright may exist in Contributors' modifications
# and/or contributions to the work.
#
# Use of this source code is governed by the MIT
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
from __future__ import annotations
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from typing import Any, ClassVar, Literal
import numpy as np
import numpy.typing as npt
from tbp.monty.geometry import GazeDirection, OrientationMatrix, SurfacePoseVectors
[docs]
class Message:
"""Message class used as message packages passed in Monty using CMP.
The cortical messaging protocol (CMP) is used to pass messages between Monty
components and makes sure we can easily set up arbitrary configurations of them.
This class makes it easier to define the CMP in one place and defines the content
and structure of messages passed between Monty components. It also contains some
helper functions to access and modify the message content.
States are represented in this format but can be interpreted by the receiver in
different ways:
Observed states: states output by sensor modules
Hypothesized states: states output by learning modules
Goals: motor output of learning modules
Attributes:
location: 3D vector representing the location
morphological_features: dictionary of morphological features. Should include
pose_vectors of shape (3,3) and pose_fully_defined (bool).
non_morphological_features: dictionary of non-morphological features.
confidence: message confidence. In range [0,1].
pass_message: boolean indicating whether the message should be delivered to
the receiver (as opposed to withheld, e.g. on motor-only steps).
sender_id: string identifying the sender of the message.
sender_type: string identifying the type of sender. Can be "SM" or "LM".
process_features_in_lm: boolean indicating whether the receiving learning
module should process the message's features, as opposed to treating it
as a location-only message that only syncs the receiver's sense of the
sensor location. Note that the message may still carry features even when
this is False (e.g. so the motor system can use them).
"""
[docs]
def __init__(
self,
# TODO: Consider changing to VectorXYZ
location: npt.NDArray[np.float64] | None,
morphological_features: dict[str, Any],
non_morphological_features: dict[str, Any],
confidence: float,
pass_message: bool,
sender_id: str,
sender_type: Literal["SM", "LM"],
process_features_in_lm: bool,
):
"""Initialize a message."""
self.location = location
# QUESTION: Divide into pose_dependent and pose_independent features instead?
self.morphological_features = morphological_features
self.non_morphological_features = non_morphological_features
self.confidence = confidence
self.pass_message = pass_message
self.sender_id = sender_id
self.sender_type = sender_type
self.process_features_in_lm = process_features_in_lm
self._set_allowable_sender_types()
if self.process_features_in_lm:
self._check_all_attributes()
def __repr__(self):
"""Return a string representation of the object."""
location = np.round(self.location, 3) if self.location is not None else None
repr_string = (
f"Message from {self.sender_id}:\n"
f" Location: {location}.\n"
f" Morphological Features: \n"
)
if self.morphological_features is not None:
for feature in self.morphological_features:
feat_val = self.morphological_features[feature]
if isinstance(feat_val, np.ndarray):
feat_val = np.round(feat_val, 3)
if feature == "pose_vectors":
feat_val = np.round(feat_val.value, 3)
repr_string += f" {feature}: \n"
for vector in feat_val:
repr_string += f" {vector}\n"
else:
repr_string += f" {feature}: {feat_val}\n"
repr_string += " Non-Morphological Features: \n"
if self.non_morphological_features is not None:
for feature in self.non_morphological_features:
feat_val = self.non_morphological_features[feature]
if isinstance(feat_val, (np.ndarray, np.float64)):
feat_val = np.round(feat_val, 3)
repr_string += f" {feature}: {feat_val}\n"
repr_string += (
f" Confidence: {self.confidence}\n"
f" Pass Message: {self.pass_message}\n"
f" Sender Type: {self.sender_type}\n"
)
return repr_string
def _set_allowable_sender_types(self):
"""Set the allowable sender types of this Message class."""
self.allowable_sender_types = ("SM", "LM")
[docs]
def is_from_sm(self) -> bool:
return self.sender_type == "SM"
[docs]
def set_displacement(self, displacement, ppf=None):
"""Add displacement (represented as dict) to message.
TODO S: Add this to message or in another place?
"""
self.displacement = {
"displacement": displacement,
}
if ppf is not None:
self.displacement["ppf"] = ppf
[docs]
def get_feature_by_name(self, feature_name):
if feature_name in self.morphological_features:
feature_val = self.morphological_features[feature_name]
elif feature_name in self.non_morphological_features:
feature_val = self.non_morphological_features[feature_name]
else:
raise ValueError(f"Feature {feature_name} not found in message.")
return feature_val
[docs]
def surface_normal(self) -> npt.NDArray[np.float64]:
"""Return the SurfacePoseVectors surface normal vector.
Raises:
ValueError: If message does not have SurfacePoseVectors
"""
if "pose_vectors" not in self.morphological_features:
raise ValueError("Message does not have SurfacePoseVectors")
# TODO: Replace with match statement
pose_vectors = self.morphological_features["pose_vectors"]
if isinstance(pose_vectors, SurfacePoseVectors):
return pose_vectors.surface_normal
raise ValueError("Message does not have SurfacePoseVectors")
[docs]
def get_pose_vectors(self):
"""Return the pose vectors."""
return self.morphological_features["pose_vectors"]
[docs]
def curvature_directions(
self,
) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
"""Return the curvature direction vectors.
Raises:
ValueError: If message does not have SurfacePoseVectors
"""
if "pose_vectors" not in self.morphological_features:
raise ValueError("Message does not have SurfacePoseVectors")
# TODO: Replace with match statement
pose_vectors = self.morphological_features["pose_vectors"]
if isinstance(pose_vectors, SurfacePoseVectors):
return (
pose_vectors.principal_curvature_1,
pose_vectors.principal_curvature_2,
)
raise ValueError("Message does not have SurfacePoseVectors")
[docs]
def get_on_object(self):
"""Return whether we think we are on the object or not.
This is currently used in the policy to stay on the object.
"""
if "on_object" in self.morphological_features:
return self.morphological_features["on_object"]
# TODO: Use depth values to estimate on_object (either threshold or large
# displacement)
return True
def _check_all_attributes(self):
assert "pose_vectors" in self.morphological_features, (
"pose_vectors should be in morphological_features but keys are "
f"{self.morphological_features.keys()}"
)
assert isinstance(
self.morphological_features["pose_vectors"],
(SurfacePoseVectors, OrientationMatrix, GazeDirection),
), (
"pose_vectors must be an instance of SurfacePoseVectors, OrientationMatrix,"
" or GazeDirection but type is "
f"{type(self.morphological_features['pose_vectors'])}"
)
assert "pose_fully_defined" in self.morphological_features
assert isinstance(self.morphological_features["pose_fully_defined"], bool), (
"pose_fully_defined must be a boolean but type is "
f"{type(self.morphological_features['pose_fully_defined'])}"
)
if self.location is not None:
assert self.location.shape == (3,), (
f"Location must be a 3D vector but shape is {self.location.shape}"
)
assert self.confidence >= 0 and self.confidence <= 1, (
f"Confidence must be in [0,1] but is {self.confidence}"
)
assert isinstance(self.pass_message, bool), (
f"pass_message must be a boolean but is {type(self.pass_message)}"
)
assert isinstance(self.process_features_in_lm, bool), (
"process_features_in_lm must be a boolean but is "
f"{type(self.process_features_in_lm)}"
)
assert isinstance(self.sender_id, str), (
f"sender_id must be string but is {type(self.sender_id)}"
)
assert self.sender_type in self.allowable_sender_types, (
f"sender_type must be SM or LM but is {self.sender_type}"
)
[docs]
class Goal(Message):
"""Specialization of :class:`Message` for goals with null (None) values allowed.
Specialized form of message that still adheres to the cortical messaging protocol,
but can have null (None) values associated with the location and morphological
features.
Used by goal generators (GSGs) to communicate goals to other GSGs, and
to motor actuators.
The message variables generally have the same meaning as for the base
:class:`Message` class, and they represent the target values for the receiving
system. Thus if a goal specifies a particular object ID (non-morphological feature)
in a particular pose (location and morphological features), then the receiving
system should attempt to achieve that state.
Note however that for the goal, the confidence corresponds to the conviction
with which a GSG believes that the current goal should be acted upon. Float
bound in [0.0, 1.0].
"""
[docs]
def __init__(
self,
location: npt.NDArray[np.float64] | None,
morphological_features: dict[str, Any] | None,
non_morphological_features: dict[str, Any] | None,
confidence: float,
pass_message: bool,
sender_id: str,
sender_type: str,
process_features_in_lm: bool,
goal_tolerances: dict[str, Any] | None,
info: dict[str, Any] | None = None,
):
"""Initialize a goal.
Args:
location: the location to move to in global/body-centric coordinates, or
`None` if the location is not specified as part of the goal.
For example, this may be a point on an object's surface or a location
nearby from which a sensor would have a good view of the target point.
morphological_features: dictionary of morphological features or `None`.
For example, it may include pose vectors, whether the pose is fully
defined, etc.
non_morphological_features: a dictionary containing non-morphological
features at the target location or `None`.
confidence: a float between 0 and 1 representing the confidence in the goal.
pass_message: a boolean indicating whether the goal should be delivered to
the receiver.
sender_id: the ID of the sender of the goal (e.g., `"LM_0"`).
sender_type: the type of sender of the goal (e.g., `"GSG"`).
process_features_in_lm: a boolean indicating whether the receiving
learning module should process the goal's features, as opposed to
treating it as carrying only a target location.
goal_tolerances: Dictionary of tolerances that GSGs use when determining
whether the current state of the LM matches the driving goal
or `None`. As such, a GSG can send a goal with more or less
strict tolerances if certain elements of the message (e.g. the location
of a mug vs its orientation) are more or less important.
info: Optional metadata for logging purposes.
"""
self.goal_tolerances = goal_tolerances
self.info = info or {}
super().__init__(
location,
morphological_features,
non_morphological_features,
confidence,
pass_message,
sender_id,
sender_type,
process_features_in_lm,
)
def _set_allowable_sender_types(self):
"""Set the allowable sender types of this Message class."""
self.allowable_sender_types = ("GSG", "SM")
def _check_all_attributes(self):
"""Overwrite base attribute check to also allow for None values."""
if self.morphological_features is not None:
assert "pose_vectors" in self.morphological_features, (
"pose_vectors should be in morphological_features but keys are "
f"{self.morphological_features.keys()}"
)
assert isinstance(
self.morphological_features["pose_vectors"],
(SurfacePoseVectors, OrientationMatrix, GazeDirection),
), (
"pose_vectors must be an instance of SurfacePoseVectors, "
"OrientationMatrix, or GazeDirection but type is "
f"{type(self.morphological_features['pose_vectors'])}"
)
assert "pose_fully_defined" in self.morphological_features
assert (
isinstance(self.morphological_features["pose_fully_defined"], bool)
) or self.morphological_features["pose_fully_defined"] is None, (
"pose_fully_defined must be a boolean or None but type is "
f"{type(self.morphological_features['pose_fully_defined'])}"
)
if self.location is not None:
assert self.location.shape == (3,), (
f"Location must be a 3D vector but shape is {self.location.shape}"
)
assert self.confidence >= 0 and self.confidence <= 1, (
f"Confidence must be in [0,1] but is {self.confidence}"
)
assert isinstance(self.pass_message, bool), (
f"pass_message must be a boolean but is {type(self.pass_message)}"
)
assert isinstance(self.sender_id, str), (
f"sender_id must be string but is {type(self.sender_id)}"
)
assert self.sender_type in self.allowable_sender_types, (
f"sender_type must be in {self.allowable_sender_types} but is "
f"{self.sender_type}"
)
# info is optional, but it must be a dictionary.
assert isinstance(self.info, dict), "info must be a dictionary"
[docs]
def encode_goal(goal: Goal) -> dict[str, Any]:
"""Encode a goal into a dictionary.
Args:
goal: The goal to encode.
Returns:
A dictionary containing the goal's attributes.
"""
return {
"location": goal.location,
"morphological_features": goal.morphological_features,
"non_morphological_features": goal.non_morphological_features,
"confidence": goal.confidence,
"pass_message": goal.pass_message,
"process_features_in_lm": goal.process_features_in_lm,
"sender_id": goal.sender_id,
"sender_type": goal.sender_type,
"goal_tolerances": goal.goal_tolerances,
"info": goal.info,
}
[docs]
def location_mean(messages: Sequence[Message]) -> npt.NDArray[np.float64] | None:
"""Compute the mean location across messages.
Args:
messages: Sequence of Message objects.
Returns:
The mean of the messages' locations, or None if no message has a location.
"""
locations = [m.location for m in messages if m.location is not None]
if not locations:
return None
return np.mean(locations, axis=0)
[docs]
@dataclass(frozen=True)
class AttentionRegion:
"""A sequence of locations, each carrying an attention weight.
Attributes:
locations: (N, 3) body-frame locations.
weights: (N,) attention weight associated with each location.
"""
locations: npt.NDArray[np.floating]
weights: npt.NDArray[np.floating]
MIN_WEIGHT: ClassVar[float] = -1.0
MAX_WEIGHT: ClassVar[float] = 1.0
def __post_init__(self) -> None:
"""Coerce the arrays and check they describe the same N locations.
Raises:
ValueError: If ``locations`` is not (N, 3) or ``weights`` is not
(N,) for the same N.
"""
locations = np.asarray(self.locations)
if locations.ndim != 2 or locations.shape[1] != 3:
raise ValueError(
f"locations must be of shape (N, 3), got {locations.shape}."
)
weights = np.asarray(self.weights)
if weights.ndim != 1:
raise ValueError(f"weights must be of shape (N,), got {weights.shape}.")
if len(locations) != len(weights):
raise ValueError(
"locations and weights must describe the same number of points, "
f"got {len(locations)} locations and {len(weights)} weights."
)
# frozen: assign through the base class.
object.__setattr__(self, "locations", locations)
object.__setattr__(self, "weights", weights)
[docs]
@classmethod
def empty(cls) -> AttentionRegion:
"""Return a region consisting of zero locations and weights.
Returns:
The empty region.
"""
return cls(np.empty((0, 3)), np.empty(0))
[docs]
@classmethod
def concat(cls, regions: Iterable[AttentionRegion]) -> AttentionRegion:
"""Join regions into one, keeping their order.
Args:
regions: Zero or more regions to join.
Returns:
One region holding every location of every input region, in order, with
their associated weights.
"""
regions = list(regions)
if not regions:
return cls.empty()
return cls(
np.concatenate([region.locations for region in regions]),
np.concatenate([region.weights for region in regions]),
)
def __len__(self) -> int:
"""Return the number of locations in the region."""
return len(self.locations)