Skip to content

vehicle

cosmic_warp.core.vehicle

Vehicle configuration and properties.

VehicleConfig

Physical properties of the spacecraft.

VehicleManager

VehicleManager(
    num_envs: int,
    device: str = "cuda",
    num_bodies: int = 1,
    states: array = None,
)

Manages vehicle configurations for parallel entities (envs * bodies).

Parameters:

Name Type Description Default
num_envs int

Number of parallel environments

required
device str

Compute device

'cuda'
num_bodies int

Number of bodies per environment

1
states array

The simulator's State array, so a new mass_dry can be checked against the current masses (None: no check)

None
Source code in cosmic_warp/core/vehicle.py
def __init__(self, num_envs: int, device: str = "cuda", num_bodies: int = 1,
             states: wp.array = None):
    """
    Args:
        num_envs: Number of parallel environments
        device: Compute device
        num_bodies: Number of bodies per environment
        states: The simulator's State array, so a new mass_dry can be
            checked against the current masses (None: no check)
    """
    self.num_envs = num_envs
    self.num_bodies = num_bodies
    self.num_entities = num_envs * num_bodies
    self.device = device
    self._states = states
    self.configs = wp.zeros(self.num_entities, dtype=VehicleConfig, device=device)
    # Host mirrors of the configured dry masses and inertia tensors, so
    # configuration checks and the randomizer's nominal values need no
    # device read. Randomized values are not mirrored. inertia_version
    # changes whenever the configured inertia does.
    self.mass_dry_host = np.zeros(self.num_entities)
    self.inertia_host = np.zeros((self.num_entities, 3, 3))
    self.inertia_version = 0
    # Default: a 1 kg cube (inertia mass/6 per axis), no magnetic dipole
    self.set_config(mass_dry=1.0, inertia=np.eye(3) / 6.0, area_drag=1.0,
                    cd=2.2, magnetic_dipole=[0.0, 0.0, 0.0])

set_config

set_config(
    *,
    mass_dry: float = None,
    inertia: list = None,
    area_drag: float = None,
    cd: float = None,
    magnetic_dipole: list = None,
    env_ids: list = None,
    body_ids: list = None,
    entity_ids: list = None,
) -> None

Set vehicle configuration for specific or all entities.

Only the fields given are checked and written; None leaves a field unchanged for the selected entities. A new simulator starts with a 1 kg cube: mass_dry 1, inertia diag(1/6), area_drag 1, cd 2.2, no magnetic dipole.

Parameters:

Name Type Description Default
mass_dry float

Dry mass (without propellant) [kg], > 0 and at most the current mass of every selected entity that has been reset

None
inertia list

Inertia tensor [kg*m^2] as 3x3 list/tuple; must be symmetric, positive definite and satisfy the triangle inequality of a rigid body

None
area_drag float

Cross-sectional area for drag [m^2], >= 0

None
cd float

Drag coefficient, >= 0

None
magnetic_dipole list

Residual magnetic dipole moment in body frame [A*m^2] as [mx, my, mz]

None
env_ids list

List of environment indices to configure (None = all)

None
body_ids list

List of body indices to configure (None = all bodies)

None
entity_ids list

Optional flat entity indices (env_id * num_bodies + body_id)

None
Source code in cosmic_warp/core/vehicle.py
def set_config(
    self,
    *,
    mass_dry: float = None,
    inertia: list = None,
    area_drag: float = None,
    cd: float = None,
    magnetic_dipole: list = None,
    env_ids: list = None,
    body_ids: list = None,
    entity_ids: list = None
) -> None:
    """
    Set vehicle configuration for specific or all entities.

    Only the fields given are checked and written; None leaves a field
    unchanged for the selected entities. A new simulator starts with a
    1 kg cube: mass_dry 1, inertia diag(1/6), area_drag 1, cd 2.2, no
    magnetic dipole.

    Args:
        mass_dry: Dry mass (without propellant) [kg], > 0 and at most the
            current mass of every selected entity that has been reset
        inertia: Inertia tensor [kg*m^2] as 3x3 list/tuple; must be
                 symmetric, positive definite and satisfy the triangle
                 inequality of a rigid body
        area_drag: Cross-sectional area for drag [m^2], >= 0
        cd: Drag coefficient, >= 0
        magnetic_dipole: Residual magnetic dipole moment in body frame [A*m^2]
                         as [mx, my, mz]
        env_ids: List of environment indices to configure (None = all)
        body_ids: List of body indices to configure (None = all bodies)
        entity_ids: Optional flat entity indices (env_id * num_bodies + body_id)
    """
    if mass_dry is not None:
        mass_dry = validation.scalar("mass_dry", mass_dry, positive=True)
    if area_drag is not None:
        area_drag = validation.scalar("area_drag", area_drag, minimum=0.0)
    if cd is not None:
        cd = validation.scalar("cd", cd, minimum=0.0)
    if inertia is not None:
        inertia = validation.inertia("inertia", inertia)
        inertia_mat = wp.mat33d(*inertia.ravel())
        inertia_inv = wp.mat33d(*np.linalg.inv(inertia).ravel())
    else:
        inertia_mat = inertia_inv = wp.mat33d()
    if magnetic_dipole is not None:
        mag_dipole_vec = wp.vec3d(*validation.vec3("magnetic_dipole", magnetic_dipole))
    else:
        mag_dipole_vec = wp.vec3d()

    entity_ids = expand_entity_ids(self.num_envs, self.num_bodies, env_ids, body_ids, entity_ids)
    if entity_ids is None:
        entity_ids = list(range(self.num_entities))
    if len(entity_ids) == 0:
        return

    if mass_dry is not None:
        self._check_state_masses(np.full(len(entity_ids), mass_dry), entity_ids)
        self.mass_dry_host[entity_ids] = mass_dry
    if inertia is not None:
        self.inertia_host[entity_ids] = inertia
        self.inertia_version += 1

    wp.launch(
        kernel=_set_config_kernel,
        dim=len(entity_ids),
        inputs=[
            self.configs,
            wp.array(entity_ids, dtype=wp.int32, device=self.device),
            int(mass_dry is not None),
            float(mass_dry or 0.0),
            int(inertia is not None),
            inertia_mat,
            inertia_inv,
            int(area_drag is not None),
            float(area_drag or 0.0),
            int(cd is not None),
            float(cd or 0.0),
            int(magnetic_dipole is not None),
            mag_dipole_vec
        ],
        device=self.device
    )

set_config_per_entity

set_config_per_entity(
    *,
    mass_dry: ndarray | array | None = None,
    inertia: ndarray | array | None = None,
    area_drag: ndarray | array | None = None,
    cd: ndarray | array | None = None,
    magnetic_dipole: ndarray | array | None = None,
) -> None

Set vehicle configuration per entity from batched arrays (e.g. for Monte Carlo parameter dispersions).

Each argument holds one value per entity, num_envs * num_bodies of them: a NumPy array or nested list of numbers, or a Warp array of the field's dtype on the simulator's device (used as-is; anything else is copied to the device). None leaves that field unchanged. The inverse inertia tensor is computed in-kernel from inertia. Values are checked as in set_config (Warp arrays are copied to the host for the check) before anything is written.

Parameters:

Name Type Description Default
mass_dry ndarray | array | None

Dry masses [kg], shape (num_entities,); Warp: float64

None
inertia ndarray | array | None

Inertia tensors [kg*m^2], shape (num_entities, 3, 3); Warp: mat33d of shape (num_entities,)

None
area_drag ndarray | array | None

Drag areas [m^2], shape (num_entities,); Warp: float64

None
cd ndarray | array | None

Drag coefficients, shape (num_entities,); Warp: float64

None
magnetic_dipole ndarray | array | None

Dipole moments [A*m^2], shape (num_entities, 3); Warp: vec3d of shape (num_entities,)

None
Source code in cosmic_warp/core/vehicle.py
def set_config_per_entity(
    self,
    *,
    mass_dry: "np.ndarray | wp.array | None" = None,
    inertia: "np.ndarray | wp.array | None" = None,
    area_drag: "np.ndarray | wp.array | None" = None,
    cd: "np.ndarray | wp.array | None" = None,
    magnetic_dipole: "np.ndarray | wp.array | None" = None
) -> None:
    """
    Set vehicle configuration per entity from batched arrays (e.g. for
    Monte Carlo parameter dispersions).

    Each argument holds one value per entity, num_envs * num_bodies of
    them: a NumPy array or nested list of numbers, or a Warp array of the
    field's dtype on the simulator's device (used as-is; anything else is
    copied to the device). None leaves that field unchanged. The inverse
    inertia tensor is computed in-kernel from `inertia`. Values are
    checked as in set_config (Warp arrays are copied to the host for the
    check) before anything is written.

    Args:
        mass_dry: Dry masses [kg], shape (num_entities,); Warp: float64
        inertia: Inertia tensors [kg*m^2], shape (num_entities, 3, 3);
            Warp: mat33d of shape (num_entities,)
        area_drag: Drag areas [m^2], shape (num_entities,); Warp: float64
        cd: Drag coefficients, shape (num_entities,); Warp: float64
        magnetic_dipole: Dipole moments [A*m^2], shape (num_entities, 3);
            Warp: vec3d of shape (num_entities,)
    """
    n = self.num_entities
    fields = {   # name: (values, Warp dtype, host row shape, value check)
        "mass_dry": (mass_dry, wp.float64, (), _at_least("mass_dry", 0.0, positive=True)),
        "inertia": (inertia, wp.mat33d, (3, 3),
                    lambda h: validation.inertia("inertia", h)),
        "area_drag": (area_drag, wp.float64, (), _at_least("area_drag", 0.0)),
        "cd": (cd, wp.float64, (), _at_least("cd", 0.0)),
        "magnetic_dipole": (magnetic_dipole, wp.vec3d, (3,), _finite("magnetic_dipole")),
    }
    device = self.configs.device
    host, arrays = {}, {}
    for name, (values, dtype, row, check) in fields.items():
        if values is None:
            arrays[name] = wp.empty(0, dtype=dtype, device=device)
            continue
        if isinstance(values, wp.array):
            if values.dtype != dtype or values.shape != (n,):
                raise ValueError(
                    f"{name} must be a Warp array of {dtype.__name__} with shape "
                    f"({n},), got {values.dtype.__name__} {values.shape}")
            if values.device != device:
                raise ValueError(f"{name} is on {values.device}, the simulator on {device}")
            host[name] = values.numpy().astype(np.float64).reshape((n, *row))
            arrays[name] = values
        else:
            host[name] = validation.numeric_array(name, values, (n, *row))
            arrays[name] = None   # uploaded once every field has passed
        check(host[name])
    if "mass_dry" in host:
        self._check_state_masses(host["mass_dry"], np.arange(n))
    for name, array in arrays.items():
        if array is None:
            arrays[name] = wp.array(host[name], dtype=fields[name][1], device=device)

    wp.launch(
        kernel=_set_config_per_entity_kernel,
        dim=n,
        inputs=[self.configs, *arrays.values()],
        device=self.device
    )
    if "mass_dry" in host:
        self.mass_dry_host[:] = host["mass_dry"]
    if "inertia" in host:
        self.inertia_host[:] = host["inertia"]
        self.inertia_version += 1