Skip to content

moplayground.utils

The config reader, Pareto-front statistics, progress callbacks and plots, and rotation utilities.

moplayground.utils.config

Single access point between YAML config files and the moplayground package.

Classes:

Name Description
MOConfig

Functions:

Name Description
check_same_env

Raise ValueError unless every config deploys the same environment.

MOConfig

Bases: Config

Attributes:

Name Type Description
default_scalarization ndarray

Objective weights used to scalarize the reward when algorithm: ppo.

gaitlib_path

Gait library directory (NaviGait only), or None if not set.

sampling_params dict

Sampling settings: alpha, k, sampling, warmup_frac.

ppo_network_params dict

Network settings for PPO.

morlax_network_params dict

Network settings for MORLAX (hypernetwork + target MLP shapes).

amor_network_params dict

Network settings for AMOR.

objectives list

Reward keys per objective, one list per reward dimension.

num_objectives int

Number of objectives (length of the reward vector).

objective_labels

Display names for the objectives, or None if not set.

Source code in src/moplayground/utils/config.py
class MOConfig(mm.Config):

    @property
    def default_scalarization(self) -> np.ndarray:
        """Objective weights used to scalarize the reward when ``algorithm: ppo``."""
        return np.array(self.cfg.env_config.reward.optimization.default_scalarization)

    @property
    def gaitlib_path(self):
        """Gait library directory (``NaviGait`` only), or ``None`` if not set."""
        return self.cfg.get('gaitlib_path')

    @property
    def sampling_params(self) -> dict:
        """Sampling settings: ``alpha``, ``k``, ``sampling``, ``warmup_frac``."""
        return self.cfg.learning_params.sampling_params.to_dict()

    @property
    def ppo_network_params(self) -> dict:
        """Network settings for PPO."""
        return self.cfg.learning_params['ppo_network_params'].to_dict()

    @property
    def morlax_network_params(self) -> dict:
        """Network settings for MORLAX (hypernetwork + target MLP shapes)."""
        return self.cfg.learning_params[f'morlax_network_params'].to_dict()

    @property
    def amor_network_params(self) -> dict:
        """Network settings for AMOR."""
        return self.cfg.learning_params[f'amor_network_params'].to_dict()

    @property
    def objectives(self) -> list:
        """Reward keys per objective, one list per reward dimension."""
        return list(self.cfg.env_config.reward.optimization.objectives)

    @property
    def num_objectives(self) -> int:
        """Number of objectives (length of the reward vector)."""
        return len(self.cfg.env_config.reward.optimization.objectives)

    @property
    def objective_labels(self):
        """Display names for the objectives, or ``None`` if not set."""
        labels = self.cfg.env_config.reward.optimization.get('labels')
        return None if labels is None else list(labels)

default_scalarization property

default_scalarization: ndarray

Objective weights used to scalarize the reward when algorithm: ppo.

gaitlib_path property

gaitlib_path

Gait library directory (NaviGait only), or None if not set.

sampling_params property

sampling_params: dict

Sampling settings: alpha, k, sampling, warmup_frac.

ppo_network_params property

ppo_network_params: dict

Network settings for PPO.

morlax_network_params property

morlax_network_params: dict

Network settings for MORLAX (hypernetwork + target MLP shapes).

amor_network_params property

amor_network_params: dict

Network settings for AMOR.

objectives property

objectives: list

Reward keys per objective, one list per reward dimension.

num_objectives property

num_objectives: int

Number of objectives (length of the reward vector).

objective_labels property

objective_labels

Display names for the objectives, or None if not set.

check_same_env

check_same_env(cfgs)

Raise ValueError unless every config deploys the same environment.

Compares env and the full env_config section. Use this before evaluating several runs together (e.g. eval.pareto.get_morlax_fronts with a list of run directories).

Source code in src/moplayground/utils/config.py
def check_same_env(cfgs):
    """Raise ``ValueError`` unless every config deploys the same environment.

    Compares ``env`` and the full ``env_config`` section. Use this before
    evaluating several runs together (e.g. ``eval.pareto.get_morlax_fronts``
    with a list of run directories).
    """
    cfgs = list(cfgs)
    if len(cfgs) <= 1:
        return
    ref = cfgs[0]
    for i, c in enumerate(cfgs[1:], start=1):
        if c.env != ref.env:
            raise ValueError(
                f"Config[{i}] env={c.env!r} does not match config[0] env={ref.env!r}; "
                f"all configs must deploy the same environment."
            )
        if c.env_config.to_dict() != ref.env_config.to_dict():
            raise ValueError(
                f"Config[{i}] env_config differs from config[0]; "
                f"all configs must deploy the same environment."
            )

moplayground.utils.pareto

Functions:

Name Description
project_to_simplex

Euclidean projection of v onto the probability simplex.

closest_points

Index into points of the nearest (Euclidean) neighbor of each target.

corner_tradeoffs

Indices of the tradeoffs nearest each one-hot corner of the simplex.

get_nondominated
hypervolume_from_nondominated

Compute the hypervolume of a non-dominated front in minimization space.

sparsity_from_normalized_nondominated
get_pareto_statistics

Compute hypervolume and sparsity for a set of objective vectors.

project_to_simplex

project_to_simplex(v)

Euclidean projection of v onto the probability simplex.

Source code in src/moplayground/utils/pareto.py
def project_to_simplex(v):
    """Euclidean projection of ``v`` onto the probability simplex.
    """
    v = np.asarray(v, dtype=float).reshape(-1)
    sorted_v = np.sort(v)[::-1]
    cumulative = np.cumsum(sorted_v)
    support = np.arange(1, v.size + 1)
    # Largest support size whose sorted entry still clears the running threshold.
    rho = support[sorted_v - (cumulative - 1.0) / support > 0][-1]
    theta = (cumulative[rho - 1] - 1.0) / rho
    return np.maximum(v - theta, 0.0)

closest_points

closest_points(points, targets)

Index into points of the nearest (Euclidean) neighbor of each target.

Parameters:

Name Type Description Default
points

(n_points, dim) array searched over.

required
targets

(dim,) or (n_targets, dim) query point(s).

required

Returns:

Type Description

(n_targets,) integer indices into points.

Source code in src/moplayground/utils/pareto.py
def closest_points(points, targets):
    """Index into ``points`` of the nearest (Euclidean) neighbor of each target.

    Args:
        points: ``(n_points, dim)`` array searched over.
        targets: ``(dim,)`` or ``(n_targets, dim)`` query point(s).

    Returns:
        ``(n_targets,)`` integer indices into ``points``.
    """
    return cKDTree(np.asarray(points)).query(np.atleast_2d(targets))[1]

corner_tradeoffs

corner_tradeoffs(tradeoffs)

Indices of the tradeoffs nearest each one-hot corner of the simplex.

Source code in src/moplayground/utils/pareto.py
def corner_tradeoffs(tradeoffs):
    """Indices of the tradeoffs nearest each one-hot corner of the simplex.
    """
    tradeoffs = np.asarray(tradeoffs)
    return closest_points(tradeoffs, np.eye(tradeoffs.shape[1]))

get_nondominated

get_nondominated(F, epsilon=None)
Source code in src/moplayground/utils/pareto.py
def get_nondominated(F, epsilon=None):
    nds = NonDominatedSorting(epsilon=epsilon)
    front_indices = nds.do(-F, only_non_dominated_front=True)
    return front_indices

hypervolume_from_nondominated

hypervolume_from_nondominated(F_min, ref_point=None)

Compute the hypervolume of a non-dominated front in minimization space.

Parameters:

Name Type Description Default
F_min

(n_points, n_objectives) array of points in minimization space (i.e. negated objective values).

required
ref_point

(n_objectives,) upper bound in that same minimization space; a point not strictly below it on every axis contributes nothing. Defaults to the origin.

None

Returns:

Type Description

Hypervolume as a float, computed by pymoo.indicators.hv.HV.

Source code in src/moplayground/utils/pareto.py
def hypervolume_from_nondominated(F_min, ref_point=None):
    """Compute the hypervolume of a non-dominated front in minimization space.

    Args:
        F_min: ``(n_points, n_objectives)`` array of points in
            minimization space (i.e. negated objective values).
        ref_point: ``(n_objectives,)`` upper bound in that same minimization
            space; a point not strictly below it on every axis contributes
            nothing. Defaults to the origin.

    Returns:
        Hypervolume as a float, computed by ``pymoo.indicators.hv.HV``.
    """
    if ref_point is None:
        ref_point = np.zeros(F_min.shape[1])

    hv = HV(ref_point=np.asarray(ref_point, dtype=float))
    hypervolume = hv(F_min)
    return hypervolume

sparsity_from_normalized_nondominated

sparsity_from_normalized_nondominated(F_min_norm)
Source code in src/moplayground/utils/pareto.py
def sparsity_from_normalized_nondominated(F_min_norm):
    spacing = SpacingIndicator()
    sparsity = spacing(F_min_norm)
    return sparsity

get_pareto_statistics

get_pareto_statistics(F, ref_point=None)

Compute hypervolume and sparsity for a set of objective vectors.

Parameters:

Name Type Description Default
F

(n_points, n_objectives) array of objective vectors (higher is better).

required
ref_point

(n_objectives,) reference in the same maximization space as F; an objective at or below it contributes no hypervolume. Defaults to the origin.

None

Returns:

Type Description

Tuple (hypervolume, sparsity).

Source code in src/moplayground/utils/pareto.py
def get_pareto_statistics(F, ref_point=None):
    """Compute hypervolume and sparsity for a set of objective vectors.

    Args:
        F: ``(n_points, n_objectives)`` array of objective vectors
            (higher is better).
        ref_point: ``(n_objectives,)`` reference in the same maximization space
            as ``F``; an objective at or below it contributes no hypervolume.
            Defaults to the origin.

    Returns:
        Tuple ``(hypervolume, sparsity)``.
    """
    F_max = F[get_nondominated(F)]
    F_norm = normalize(F_max.copy())

    # Convert to minimization
    F_min = -F_max.copy()
    F_min_norm = -F_norm.copy()

    if F_min_norm.shape[0] == 1:
        # Sparsity always needs 2 points to calculate
        F_min_norm = np.repeat(F_min_norm, 2, axis=0)
    # The reference is negated alongside the front to stay in minimization space.
    return (
        hypervolume_from_nondominated(
            F_min, None if ref_point is None else -np.asarray(ref_point, dtype=float)
        ),
        sparsity_from_normalized_nondominated(F_min_norm)
    )

moplayground.utils.plotting

Classes:

Name Description
MOTrainingPlottingInfo
MOProgress

Multi-objective progress callback for mm.train(progress_cls=...).

Functions:

Name Description
default_coloring
plot_pareto

Plot a pareto frontier.

plot_sequential_paretos
plot_sequential_hypervolume

MOTrainingPlottingInfo dataclass

Methods:

Name Description
save

Attributes:

Name Type Description
start_time float
times list
iterations list
paretos list
tradeoffs list
labels list
hypervolumes list
sparsities list
Source code in src/moplayground/utils/plotting.py
@dataclass(frozen=False)
class MOTrainingPlottingInfo:
    start_time    : float
    times         : list = field(default_factory=list)
    iterations    : list = field(default_factory=list)
    paretos       : list = field(default_factory=list)
    tradeoffs    : list = field(default_factory=list)
    labels        : list = field(default_factory=list)
    hypervolumes  : list = field(default_factory=list)
    sparsities    : list = field(default_factory=list)

    def save(self, save_dir, create_time=True):
        pad = [np.nan] if create_time else []
        pd.DataFrame(
            {
                'times': [self.start_time] + self.times if create_time else self.times,
                'iters': [0] + self.iterations if create_time else self.iterations,
                'hypervolume': pad + self.hypervolumes,
                'sparsity': pad + self.sparsities,
            }
        ).to_csv(save_dir)

start_time instance-attribute

start_time: float

times class-attribute instance-attribute

times: list = field(default_factory=list)

iterations class-attribute instance-attribute

iterations: list = field(default_factory=list)

paretos class-attribute instance-attribute

paretos: list = field(default_factory=list)

tradeoffs class-attribute instance-attribute

tradeoffs: list = field(default_factory=list)

labels class-attribute instance-attribute

labels: list = field(default_factory=list)

hypervolumes class-attribute instance-attribute

hypervolumes: list = field(default_factory=list)

sparsities class-attribute instance-attribute

sparsities: list = field(default_factory=list)

save

save(save_dir, create_time=True)
Source code in src/moplayground/utils/plotting.py
def save(self, save_dir, create_time=True):
    pad = [np.nan] if create_time else []
    pd.DataFrame(
        {
            'times': [self.start_time] + self.times if create_time else self.times,
            'iters': [0] + self.iterations if create_time else self.iterations,
            'hypervolume': pad + self.hypervolumes,
            'sparsity': pad + self.sparsities,
        }
    ).to_csv(save_dir)

MOProgress

Bases: Progress

Multi-objective progress callback for mm.train(progress_cls=...).

Records the eval Pareto front each epoch, writes hypervolume/sparsity to save_dir/progress.csv, and plots the fronts when there are 2 objectives. labels names the objectives on the plot axes; pass it with functools.partial(MOProgress, labels=...) since mm.train builds the callback itself.

Methods:

Name Description
load
plot_progress

Attributes:

Name Type Description
training_data
times
Source code in src/moplayground/utils/plotting.py
class MOProgress(mm.Progress):
    """Multi-objective progress callback for ``mm.train(progress_cls=...)``.

    Records the eval Pareto front each epoch, writes hypervolume/sparsity to
    ``save_dir/progress.csv``, and plots the fronts when there are 2 objectives.
    ``labels`` names the objectives on the plot axes; pass it with
    ``functools.partial(MOProgress, labels=...)`` since ``mm.train`` builds the
    callback itself.
    """

    def __init__(self, save_dir, total_timesteps=None, run=None, labels=None):
        super().__init__(save_dir, total_timesteps, run)
        self.training_data = MOTrainingPlottingInfo(
            start_time = time.time(),
            labels     = list(labels) if labels is not None else [],
        )
        # mm.train reads ``self.times`` for its jit/train timings
        self.times = self.training_data.times

    def load(self, before=None):
        # progress.csv holds hypervolume/sparsity, not the fronts the plots need
        raise NotImplementedError('MOProgress cannot resume a run yet')

    def plot_progress(
        self,
        num_steps       : int,
        metrics         : dict,
    ):
        # print current itme
        tz = ZoneInfo("America/New_York")
        now = datetime.now(tz)
        print(now.strftime("%Y-%m-%d %H:%M:%S %Z"))

        # save data from iteration
        self.training_data.iterations.append(num_steps)
        self.training_data.paretos.append(metrics['reward'])
        self.training_data.tradeoffs.append(metrics['tradeoff'])
        self.training_data.times.append(time.time())

        # pareto statistics of the current front, logged natively as scalars
        hv, sp = get_pareto_statistics(np.asarray(metrics['reward']))
        self.training_data.hypervolumes.append(float(hv))
        self.training_data.sparsities.append(float(sp))
        self.training_data.save(self.save_dir / 'progress.csv')
        log = {"pareto/hypervolume": float(hv), "pareto/sparsity": float(sp)}

        # 2 objectives: the frontier itself is still worth a picture
        if np.asarray(metrics['tradeoff']).shape[-1] == 2:
            fig, axs = plot_sequential_paretos(
                ax_titles   = self.training_data.iterations,
                paretos     = self.training_data.paretos,
                tradeoffs  = self.training_data.tradeoffs,
                objectives  = self.training_data.labels or None
            )
            fig.savefig(self.save_dir / 'progress.svg')
            plt.close(fig)
            if self.run:
                with open(self.save_dir / 'progress.svg', "r") as f:
                    log["reward_plot"] = wandb.Html(f.read())

        if self.run:
            self.run.log(log, step=num_steps)

training_data instance-attribute

training_data = MOTrainingPlottingInfo(start_time=time.time(), labels=list(labels) if labels is not None else [])

times instance-attribute

times = self.training_data.times

load

load(before=None)
Source code in src/moplayground/utils/plotting.py
def load(self, before=None):
    # progress.csv holds hypervolume/sparsity, not the fronts the plots need
    raise NotImplementedError('MOProgress cannot resume a run yet')

plot_progress

plot_progress(num_steps: int, metrics: dict)
Source code in src/moplayground/utils/plotting.py
def plot_progress(
    self,
    num_steps       : int,
    metrics         : dict,
):
    # print current itme
    tz = ZoneInfo("America/New_York")
    now = datetime.now(tz)
    print(now.strftime("%Y-%m-%d %H:%M:%S %Z"))

    # save data from iteration
    self.training_data.iterations.append(num_steps)
    self.training_data.paretos.append(metrics['reward'])
    self.training_data.tradeoffs.append(metrics['tradeoff'])
    self.training_data.times.append(time.time())

    # pareto statistics of the current front, logged natively as scalars
    hv, sp = get_pareto_statistics(np.asarray(metrics['reward']))
    self.training_data.hypervolumes.append(float(hv))
    self.training_data.sparsities.append(float(sp))
    self.training_data.save(self.save_dir / 'progress.csv')
    log = {"pareto/hypervolume": float(hv), "pareto/sparsity": float(sp)}

    # 2 objectives: the frontier itself is still worth a picture
    if np.asarray(metrics['tradeoff']).shape[-1] == 2:
        fig, axs = plot_sequential_paretos(
            ax_titles   = self.training_data.iterations,
            paretos     = self.training_data.paretos,
            tradeoffs  = self.training_data.tradeoffs,
            objectives  = self.training_data.labels or None
        )
        fig.savefig(self.save_dir / 'progress.svg')
        plt.close(fig)
        if self.run:
            with open(self.save_dir / 'progress.svg', "r") as f:
                log["reward_plot"] = wandb.Html(f.read())

    if self.run:
        self.run.log(log, step=num_steps)

default_coloring

default_coloring(tradeoff)
Source code in src/moplayground/utils/plotting.py
def default_coloring(tradeoff):
    # Map a tradeoff (or batch of tradeoffs) to an RGB color
    tradeoff = np.asarray(tradeoff, dtype=float)
    pad = max(0, 3 - tradeoff.shape[-1])
    if pad:
        tradeoff = np.pad(tradeoff, [(0, 0)] * (tradeoff.ndim - 1) + [(0, pad)])
    return tradeoff[..., :3]

plot_pareto

plot_pareto(ax: Axes, pareto: ndarray, colors: str | ndarray = None, objective: list[str] = None, connect: bool = False, show_dominated: bool = True, nondominated_alpha: float = 1.0, dominated_alpha: float = 1.0, nondominated_s: int = 20, dominated_s: int = 8, outline_nondominated: float = 0.0, label: str = None, set_lims: bool = True, label_fontsize: int = 16, special_idxs: ndarray = None, special_marker: str = '*', connect_line_color: str | ndarray = 'black', **plot_kwargs)

Plot a pareto frontier.

colors is a single matplotlib color or per-point color. RGB(A) label names the front in the legend; set_lims zooms to the nondominated front.

Source code in src/moplayground/utils/plotting.py
def plot_pareto(
    ax                    : plt.Axes,
    pareto                : np.ndarray,
    colors                : str | np.ndarray = None,
    objective             : list[str] = None,
    connect               : bool = False,
    show_dominated        : bool = True,
    nondominated_alpha    : float = 1.0,
    dominated_alpha       : float = 1.0,
    nondominated_s        : int = 20,
    dominated_s           : int = 8,
    outline_nondominated  : float = 0.0,
    label                 : str = None,
    set_lims              : bool = True,
    label_fontsize        : int = 16,
    special_idxs          : np.ndarray = None,
    special_marker        : str = '*',
    connect_line_color    : str | np.ndarray = 'black',
    **plot_kwargs
):
    """
    Plot a pareto frontier.

    ``colors`` is a single matplotlib color or per-point color. RGB(A)
    ``label`` names the front in the legend; 
    ``set_lims`` zooms to the nondominated front.
    """
    # TODO: this doesn't work for 3d fronts
    num_objs = pareto.shape[1]
    if num_objs not in (2, 3):
        raise NotImplementedError(f'Only 2D and 3D paretos are supported for plotting, yours has {num_objs}')

    if objective is None: objective = [''] * num_objs
    c = np.asarray(colors) if isinstance(colors, (list, tuple, np.ndarray)) else colors
    nd_idx = get_nondominated(pareto)
    d_idx = np.setdiff1d(np.arange(pareto.shape[0]), nd_idx)
    clip = {'axlim_clip': True} if num_objs == 3 else {}

    if show_dominated:
        # dominated points
        ax.scatter(
            *(pareto[d_idx].T),
            s       = dominated_s,
            alpha   = dominated_alpha,
            **_decide_color_kwargs(c, d_idx),
            **clip,
            **plot_kwargs,
        )


    # non-dominated points
    ax.scatter(
        *(pareto[nd_idx].T),
        alpha         = nondominated_alpha,
        zorder        = 1,
        s             = nondominated_s,
        edgecolors    = 'black',
        linewidths    = outline_nondominated,
        label         = label,
        **_decide_color_kwargs(c, nd_idx),
        **clip,
        **plot_kwargs,
    )

    if(special_idxs is not None):
        # non-dominated points
        ax.scatter(
            *(pareto[special_idxs].T),
            alpha         = nondominated_alpha,
            zorder        = 1,
            s             = nondominated_s*20,
            edgecolors    = 'black',
            linewidths    = outline_nondominated,
            label         = label,
            **_decide_color_kwargs(c, special_idxs),
            **clip,
            **{**plot_kwargs, 'marker': special_marker},
        )

    if connect:
        if num_objs == 3:
            raise NotImplementedError('connect is 2D only; a 3D front is a surface')
        pts = pareto[nd_idx]
        ax.plot(
            *(pts[np.argsort(pts[:, 0])].T),
            zorder        = 0,
            color         = connect_line_color,
        )


    if set_lims:
        ax.set_xlim((0.95 * np.min(pareto[nd_idx, 0]), 1.05 * np.max(pareto[nd_idx, 0])))
        ax.set_ylim((0.95 * np.min(pareto[nd_idx, 1]), 1.05 * np.max(pareto[nd_idx, 1])))
        if num_objs == 3:
            ax.set_zlim((1.00 * np.min(pareto[nd_idx, 2]), 1.05 * np.max(pareto[nd_idx, 2])))

    ax.set_xlabel(objective[0], fontsize=label_fontsize)
    ax.set_ylabel(objective[1], fontsize=label_fontsize)
    if num_objs == 3:
        ax.set_zlabel(objective[2], fontsize=label_fontsize)

    return ax

plot_sequential_paretos

plot_sequential_paretos(ax_titles: list[str], paretos: ndarray, tradeoffs: ndarray = None, objectives: list[str] = None)
Source code in src/moplayground/utils/plotting.py
def plot_sequential_paretos(
    ax_titles: list[str],
    paretos: np.ndarray,
    tradeoffs: np.ndarray = None,
    objectives: list[str] = None
):
    if len(ax_titles) != len(paretos) != len(tradeoffs):
        raise Exception('Incompatible lengths of input arrays')

    if tradeoffs is None: tradeoffs = np.zeros_like(paretos)
    if objectives is None: objectives = [''] * paretos[0].shape[1]

    nrows, ncols = mm.get_subplot_grid(len(ax_titles))
    fig, axs = plt.subplots(nrows=nrows, ncols=ncols)
    if type(axs) == np.ndarray: axs = axs.flatten()
    else: axs = [axs]

    paretos = np.array(paretos)
    tradeoffs = np.array(tradeoffs)
    xlim   = np.array((np.min(paretos[..., 0]), np.max(paretos[..., 0])))
    ylim   = np.array((np.min(paretos[..., 1]), np.max(paretos[..., 1])))
    border = np.array([-1., 1.])
    xlim   = xlim + border * np.abs(xlim[1] - xlim[0]) * 0.1
    ylim   = ylim + border * np.abs(ylim[1] - ylim[0]) * 0.1
    for ax, x, y, d in zip(axs, ax_titles, paretos, tradeoffs):
        ax = plot_pareto(ax, y, default_coloring(d), objectives, set_lims=False)
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
        ax.set_title(x)

    fig.set_size_inches((4 * ncols, 4 * nrows))
    fig.tight_layout()

    return fig, ax

plot_sequential_hypervolume

plot_sequential_hypervolume(iterations: list[int] | ndarray, paretos: ndarray)
Source code in src/moplayground/utils/plotting.py
def plot_sequential_hypervolume(
    iterations: list[int] | np.ndarray,
    paretos: np.ndarray
):
    fig, ax = plt.subplots()
    hvs = []
    sps = []
    for p in paretos:
        hv, sp = get_pareto_statistics(np.array(p.block_until_ready()))
        hvs.append(hv)
        sps.append(sp)
    ax2 = ax.twinx()
    ax.plot(iterations, hvs, label='Hypervolume')
    ax2.plot(iterations, sps, 'r-', label='Sparsity')
    fig.set_size_inches((10, 7))
    ax.set_xlabel('Iterations')
    ax.set_ylabel('Hypervolume')
    ax2.set_ylabel('Sparsity')
    ax.legend()
    ax2.legend()
    return fig, ax

moplayground.utils.geometry

Functions:

Name Description
euler2quat

Convert euler angles (roll, pitch, yaw) to a quaternion (w, x, y, z).

quat2euler

Convert a quaternion (w, x, y, z) to euler angles (roll, pitch, yaw).

rotx

Rotation matrix around x axis

roty

Rotation matrix around y axis

rotz

Rotation matrix around z axis

rotmat

Rotation matrix from euler angles (roll, pitch, yaw), same convention as euler2quat.

quat_mul

Multiplies two quaternions.

angle2quat

Provides a quaternion that describes rotating around axis by angle.

quat_conjugate

Returns the conjugate of a quaternion.

extract_yaw

Extracts the yaw angle from a quaternion.

solve_transform

Solves the transformation, T, between two qpos for the form

apply_transform

Applies the offset transform to the qpos

quat_rotate_vector

Rotate vector v by quaternion q.

inv_transform

Computes the inverse of the offset transform to the qpos

quat_dist
quat_rotate

Rotate vector v (3,) using unit quaternion q (w,x,y,z).

decide_quat

Attributes:

Name Type Description
FREE3D_POS
FREE3D_VEL

FREE3D_POS module-attribute

FREE3D_POS = 7

FREE3D_VEL module-attribute

FREE3D_VEL = 6

euler2quat

euler2quat(_np, euler_angles)

Convert euler angles (roll, pitch, yaw) to a quaternion (w, x, y, z).

Intrinsic x-y-z convention: the rotation is Rx(roll) @ Ry(pitch) @ Rz(yaw), matching rotmat and inverted by quat2euler.

Source code in src/moplayground/utils/geometry.py
def euler2quat(_np, euler_angles):
    """Convert euler angles (roll, pitch, yaw) to a quaternion (w, x, y, z).

    Intrinsic x-y-z convention: the rotation is ``Rx(roll) @ Ry(pitch) @ Rz(yaw)``,
    matching ``rotmat`` and inverted by ``quat2euler``.
    """
    roll = euler_angles[0]
    pitch = euler_angles[1]
    yaw = euler_angles[2]

    cy = _np.cos(yaw * 0.5)
    sy = _np.sin(yaw * 0.5)
    cp = _np.cos(pitch * 0.5)
    sp = _np.sin(pitch * 0.5)
    cr = _np.cos(roll * 0.5)
    sr = _np.sin(roll * 0.5)

    w = cr * cp * cy - sr * sp * sy
    x = sr * cp * cy + cr * sp * sy
    y = cr * sp * cy - sr * cp * sy
    z = cr * cp * sy + sr * sp * cy
    q = _np.array([w, x, y, z]) 
    q = decide_quat(_np, q)
    return q

quat2euler

quat2euler(_np, q)

Convert a quaternion (w, x, y, z) to euler angles (roll, pitch, yaw).

Inverse of euler2quat (intrinsic x-y-z, Rx @ Ry @ Rz).

Source code in src/moplayground/utils/geometry.py
def quat2euler(_np, q):
    """Convert a quaternion (w, x, y, z) to euler angles (roll, pitch, yaw).

    Inverse of ``euler2quat`` (intrinsic x-y-z, ``Rx @ Ry @ Rz``).
    """
    w, x, y, z = q
    t0 = +2.0 * (w * x - y * z)
    t1 = +1.0 - 2.0 * (x * x + y * y)
    X = _np.arctan2(t0, t1)

    t2 = +2.0 * (w * y + x * z)
    t2 = _np.clip(t2, -1.0, 1.0)
    Y =  _np.arcsin(t2)

    t3 = +2.0 * (w * z - x * y)
    t4 = +1.0 - 2.0 * (y * y + z * z)
    Z =  _np.arctan2(t3, t4)

    return _np.array([X, Y, Z])

rotx

rotx(_np, theta)

Rotation matrix around x axis

Source code in src/moplayground/utils/geometry.py
def rotx(_np, theta):
    """Rotation matrix around x axis"""
    c = _np.cos(theta)
    s = _np.sin(theta)
    return _np.array([[1, 0, 0],
                      [0, c, -s],
                      [0, s, c]])

roty

roty(_np, theta)

Rotation matrix around y axis

Source code in src/moplayground/utils/geometry.py
def roty(_np, theta):
    """Rotation matrix around y axis"""
    c = _np.cos(theta)
    s = _np.sin(theta)
    return _np.array([[c, 0, s],
                      [0, 1, 0],
                      [-s, 0, c]])

rotz

rotz(_np, theta)

Rotation matrix around z axis

Source code in src/moplayground/utils/geometry.py
def rotz(_np, theta):
    """Rotation matrix around z axis"""
    c = _np.cos(theta)
    s = _np.sin(theta)
    return _np.array([[c, -s, 0],
                      [s, c, 0],
                      [0, 0, 1]])

rotmat

rotmat(_np, angles)

Rotation matrix from euler angles (roll, pitch, yaw), same convention as euler2quat.

Source code in src/moplayground/utils/geometry.py
def rotmat(_np, angles):
    """Rotation matrix from euler angles (roll, pitch, yaw), same convention as ``euler2quat``."""
    return rotx(_np, angles[0]) @ roty(_np, angles[1]) @ rotz(_np, angles[2])

quat_mul

quat_mul(_np, u, v)

Multiplies two quaternions.

Parameters:

Name Type Description Default
u

(4,) quaternion (w,x,y,z)

required
v

(4,) quaternion (w,x,y,z)

required

Returns:

Type Description

A quaternion u * v.

Source code in src/moplayground/utils/geometry.py
def quat_mul(_np, u, v):
    """Multiplies two quaternions.

    Args:
      u: (4,) quaternion (w,x,y,z)
      v: (4,) quaternion (w,x,y,z)

    Returns:
      A quaternion u * v.
    """
    return _np.array([
        u[0] * v[0] - u[1] * v[1] - u[2] * v[2] - u[3] * v[3],
        u[0] * v[1] + u[1] * v[0] + u[2] * v[3] - u[3] * v[2],
        u[0] * v[2] - u[1] * v[3] + u[2] * v[0] + u[3] * v[1],
        u[0] * v[3] + u[1] * v[2] - u[2] * v[1] + u[3] * v[0],
    ])

angle2quat

angle2quat(_np, axis, angle)

Provides a quaternion that describes rotating around axis by angle.

Parameters:

Name Type Description Default
axis

(3,) axis (x,y,z)

required
angle

() float angle to rotate by

required

Returns:

Type Description

A quaternion that rotates around axis by angle

Source code in src/moplayground/utils/geometry.py
def angle2quat(_np, axis, angle):
    """Provides a quaternion that describes rotating around axis by angle.

    Args:
      axis: (3,) axis (x,y,z)
      angle: () float angle to rotate by

    Returns:
      A quaternion that rotates around axis by angle
    """
    s, c = _np.sin(angle * 0.5), _np.cos(angle * 0.5)
    quat = _np.insert(axis * s, 0, c)
    quat = decide_quat(_np, quat)
    return quat

quat_conjugate

quat_conjugate(_np, q)

Returns the conjugate of a quaternion.

Parameters:

Name Type Description Default
q

(4,) quaternion (w,x,y,z)

required

Returns:

Type Description

A quaternion that is the conjugate of q.

Source code in src/moplayground/utils/geometry.py
def quat_conjugate(_np, q):
    """Returns the conjugate of a quaternion.

    Args:
      q: (4,) quaternion (w,x,y,z)

    Returns:
      A quaternion that is the conjugate of q.
    """
    conj = _np.array([q[0], -q[1], -q[2], -q[3]])
    return decide_quat(_np, conj)

extract_yaw

extract_yaw(_np, quat)

Extracts the yaw angle from a quaternion.

Parameters:

Name Type Description Default
quat

(4,) quaternion (w,x,y,z)

required

Returns:

Type Description

The yaw angle in radians.

Source code in src/moplayground/utils/geometry.py
def extract_yaw(_np, quat):
    """Extracts the yaw angle from a quaternion.

    Args:
      quat: (4,) quaternion (w,x,y,z)

    Returns:
      The yaw angle in radians.
    """
    w, x, y, z = quat
    yaw = _np.arctan2(2.0 * (w*z + x*y), 1.0 - 2.0 * (y**2 + z**2))

    # Reconstruct yaw-only quaternion
    half_yaw = yaw / 2.0
    cy = _np.cos(half_yaw)
    sy = _np.sin(half_yaw)

    # Pure yaw quaternion (rotation around z axis)
    q_yaw = _np.array([cy, 0.0, 0.0, sy])  # [w, x, y, z]
    q_yaw = decide_quat(_np, q_yaw)
    return q_yaw

solve_transform

solve_transform(_np, qpos_des, qpos_act, reset_yaw=False, cmd_yaw_offset=None)

Solves the transformation, T, between two qpos for the form qpos_des = qpos_act @ T

Source code in src/moplayground/utils/geometry.py
def solve_transform(_np, qpos_des, qpos_act, reset_yaw=False, cmd_yaw_offset=None):
    """Solves the transformation, T, between two qpos for the form
    qpos_des = qpos_act @ T"""
    xyz_des  = qpos_des[:3]
    xyz_act  = qpos_act[:3]
    quat_act = qpos_act[3:FREE3D_POS]
    quat_des = qpos_des[3:FREE3D_POS]

    if reset_yaw:
        quat_diff = quat_mul(_np, quat_conjugate(_np, quat_des), quat_act)
        yaw_quat_act = extract_yaw(_np, quat_diff)
    else:
        if cmd_yaw_offset is not None:
            yaw_quat_act = angle2quat(_np, _np.array([0.0, 0.0, 1.0]), cmd_yaw_offset)
        else:
            quat_diff = quat_mul(_np, quat_conjugate(_np, quat_des), quat_act)
            yaw_quat_act = extract_yaw(_np, quat_diff)
        # yaw_quat_act = angle2quat(_np, _np.array([0.0, 0.0, 1.0]), cmd_yaw_offset)
        # yaw_quat_act = _np.array([1.0, 0.0, 0.0, 0.0])
    offset_quat = yaw_quat_act
    # R = quat2rot(_np, offset_quat)
    xyz_des_rot = quat_rotate_vector(_np, offset_quat, xyz_des)
    offset_xyz = _np.hstack((xyz_act[:2] - xyz_des_rot[:2], [0]))
    offset_quat = decide_quat(_np, offset_quat)
    return _np.hstack((offset_xyz, offset_quat))

apply_transform

apply_transform(_np, qpos, offset)

Applies the offset transform to the qpos

Source code in src/moplayground/utils/geometry.py
def apply_transform(_np, qpos, offset):
    """Applies the offset transform to the qpos"""
    # quit()
    # new_qpos = quat_rotate_vector(_np, quat_conjugate(_np, offset[3:FREE3D_POS]), qpos[:3])
    new_qpos = quat_rotate_vector(_np, offset[3:FREE3D_POS], qpos[:3])
    # new_xyz = new_qpos + offset[:3]
    # print(offset[:3])
    # input()
    new_xyz = new_qpos[:3] + offset[:3]
    new_quat = quat_mul(_np, offset[3:FREE3D_POS], qpos[3:FREE3D_POS])
    new_quat = decide_quat(_np, new_quat)
    return _np.hstack((new_xyz, new_quat))

quat_rotate_vector

quat_rotate_vector(np, q, v)

Rotate vector v by quaternion q. q: array-like, shape (4,) [w, x, y, z] v: array-like, shape (3,) Returns rotated vector as np.ndarray, shape (3,)

Source code in src/moplayground/utils/geometry.py
def quat_rotate_vector(np, q, v):
    """
    Rotate vector v by quaternion q.
    q: array-like, shape (4,) [w, x, y, z]
    v: array-like, shape (3,)
    Returns rotated vector as np.ndarray, shape (3,)
    """
    q = np.array(q, dtype=float)
    v = np.array(v, dtype=float)

    # Normalize quaternion (optional but recommended)
    q = q / np.linalg.norm(q)

    w, x, y, z = q
    q_vec = np.array([x, y, z])

    # Quaternion * vector formula (optimized)
    uv = np.cross(q_vec, v)
    uuv = np.cross(q_vec, uv)
    return v + 2 * (w * uv + uuv)

inv_transform

inv_transform(_np, offset)

Computes the inverse of the offset transform to the qpos

Source code in src/moplayground/utils/geometry.py
def inv_transform(_np, offset):
    """Computes the inverse of the offset transform to the qpos"""
    new_xyz = -offset[:3]
    new_quat = quat_conjugate(_np, offset[3:FREE3D_POS])
    new_quat = decide_quat(_np, new_quat)
    return _np.hstack((new_xyz, new_quat))

quat_dist

quat_dist(_np, q1, q2)
Source code in src/moplayground/utils/geometry.py
def quat_dist(_np, q1, q2):
    q1 = _np.array(q1)
    q2 = _np.array(q2)
    dot = _np.abs(_np.dot(q1, q2))
    dot = _np.clip(dot, -1.0, 1.0)  # numerical safety
    angle = 2 * _np.arccos(dot)
    return angle  # in radians

quat_rotate

quat_rotate(_np, q, v)

Rotate vector v (3,) using unit quaternion q (w,x,y,z).

Source code in src/moplayground/utils/geometry.py
def quat_rotate(_np, q, v):
    """Rotate vector v (3,) using unit quaternion q (w,x,y,z)."""
    q_v = _np.array([0, *v])
    return quat_mul(_np, quat_mul(_np, q, q_v), quat_conjugate(_np, q))[1:]

decide_quat

decide_quat(_np, quat)
Source code in src/moplayground/utils/geometry.py
def decide_quat(_np, quat):
    cond = quat[0] >= 0
    return _np.where(cond, quat, -quat)