Skip to content

Vector2D

SUMMARY

A vector in 2D space.

python
from telekinesis import datatypes
vector2d = datatypes.Vector2D([1.0, 2.0])
API Reference
Complete API documentation for Vector2D, including parameters, attributes, and methods.
View Reference →

Parameters

ParameterTypeDefaultDescription
datanp.ndarray | list | tupleRequiredArray-like data of shape (2,).

Raises

ExceptionCondition
TypeErrordata can't be converted to a float32 array (e.g. non-numeric elements)
ValueErrordata's rank isn't 1, its shape isn't (2,), or it contains a non-finite value (NaN/Inf)

Attributes

AttributeTypeDescription
shape_specClassVar[tuple[int, ...]]Class-level shape spec, (2,).
datanp.ndarrayThe wrapped vector. Reading it returns a copy, so mutating the result doesn't affect the Vector2D; assigning a new value re-validates it the same way as construction.
shapetuple[int, ...]Always (2,).
ndimintAlways 1.
dtypenp.dtypeAlways float32.
sizeintAlways 2.

Methods

MethodTypeDescription
Vector2D.coerce(value)Vector2DConverts array-like data into a Vector2D. Accepts a np.ndarray, list, or tuple of shape (2,). If value is already a Vector2D, it is returned unchanged.
to_numpy(copy=True)np.ndarrayReturns the vector as a plain array. With the default copy=True you get an independent copy; pass copy=False to get a direct reference to the internal array instead, so mutating it also mutates the Vector2D.
copy()Vector2DReturns a new, independent Vector2D with the same data.

Operators

OperationBehavior
v1 == v2True only if other is exactly a Vector2D (not a subclass, not another datatype) with element-equal data. False for anything else.
len(v)Always 2 (length of the single axis).
np.asarray(v)Returns a copy of data as an np.ndarray; NumPy functions accept a Vector2D directly.

Visualization

python
import rerun as rr

# Your code block
# ....

rr.init("vector2d_example", spawn=True)
datatypes.visualize(vector2d, entity_path="/vector2d", label="Vector2D")

Example

python
"""Demonstrates the Telekinesis Vector2D datatype."""

import time

import numpy as np
import rerun as rr
from loguru import logger

from telekinesis import datatypes


def vector2d_example():
    """Demonstrate creation, inspection, operations, visualization, and serialization."""

    # ======================= Create ============================================
    vector2d = datatypes.Vector2D([1.0, 2.0])
    logger.info(f"Created Vector2D: {vector2d}")

    # ======================= Inspect ===========================================
    logger.info(f"data={vector2d.data}")
    logger.info(f"shape={vector2d.shape}")
    logger.info(f"ndim={vector2d.ndim}")
    logger.info(f"dtype={vector2d.dtype}")
    logger.info(f"size={vector2d.size}")

    # ======================= Operations =========================================
    vector2d.data = [3.0, 4.0]
    logger.info(f"Updated Vector2D: {vector2d}")

    vector2d_copy = vector2d.copy()
    logger.info(f"Copied Vector2D: {vector2d_copy}")

    vector2d_numpy = vector2d.to_numpy(copy=True)
    logger.info(f"NumPy Vector2D: {vector2d_numpy}")

    numpy_array = np.asarray(vector2d)
    logger.info(f"NumPy array: {numpy_array}")

    sum_with_numpy = vector2d + np.array([1.0, 1.0])
    logger.info(f"Sum of Vector2D with NumPy array: {sum_with_numpy}")

    norm = np.linalg.norm(vector2d)
    logger.info(f"Norm (np.linalg.norm): {norm}")

    # ======================= Visualize =========================================
    rr.init("vector2d_example", spawn=True)
    datatypes.visualize(vector2d, entity_path="/vector2d", label="Updated Vector2D")

    # ======================= Serialize / Deserialize ===========================
    start = time.perf_counter()
    serialized = datatypes.serialize(vector2d)
    serialization_ms = (time.perf_counter() - start) * 1000

    start = time.perf_counter()
    deserialized = datatypes.deserialize(serialized)["param_0"]
    deserialization_ms = (time.perf_counter() - start) * 1000

    logger.info(f"Deserialized Vector2D: {deserialized}")
    logger.info(f"Round-trip successful: {vector2d == deserialized}")
    logger.info(f"Serialization time: {serialization_ms:.3f} ms")
    logger.info(f"Deserialization time: {deserialization_ms:.3f} ms")


if __name__ == "__main__":
    vector2d_example()

See also Vectors2D for batches of 2D vectors.