Skip to content

resolve_dict_weights

yohou.utils.weighting.resolve_dict_weights(weight_dict, keys, default=1.0)

Map a {key: weight} dict to an aligned numpy array.

For each element in keys, looks up the corresponding weight in weight_dict. Missing keys receive default. If the dict contains the wildcard key "*", its value overrides default (e.g., {"*": 0.0, 1: 2.0} gives step 1 weight 2.0 and all others weight 0.0). The "*" key is consumed and never looked up in keys.

Parameters

Name Type Description Default
weight_dict dict

Mapping from key values to weights.

required
keys ndarray or list

Key values to look up, one per element.

required
default float

Weight for keys not present in weight_dict.

1.0

Returns

Type Description
ndarray

Weight array aligned to keys.

Source Code

Show/Hide source
def resolve_dict_weights(
    weight_dict: dict,
    keys: np.ndarray | list,
    default: float = 1.0,
) -> np.ndarray:
    """Map a ``{key: weight}`` dict to an aligned numpy array.

    For each element in ``keys``, looks up the corresponding weight in
    ``weight_dict``.  Missing keys receive ``default``.  If the dict
    contains the wildcard key ``"*"``, its value overrides ``default``
    (e.g., ``{"*": 0.0, 1: 2.0}`` gives step 1 weight 2.0 and all
    others weight 0.0).  The ``"*"`` key is consumed and never looked up
    in ``keys``.

    Parameters
    ----------
    weight_dict : dict
        Mapping from key values to weights.
    keys : numpy.ndarray or list
        Key values to look up, one per element.
    default : float, default=1.0
        Weight for keys not present in ``weight_dict``.

    Returns
    -------
    numpy.ndarray
        Weight array aligned to ``keys``.

    """
    effective_default = weight_dict.get("*", default)
    lookup = {k: v for k, v in weight_dict.items() if k != "*"}
    return np.array([lookup.get(k, effective_default) for k in keys], dtype=np.float64)