Skip to content

combine_weight_vectors

yohou.utils.weighting.combine_weight_vectors(*arrays, n)

Combine weight vectors multiplicatively and normalize.

Filters out None inputs, multiplies the remaining arrays element-wise, then normalizes so the result sums to n.

Parameters

Name Type Description Default
*arrays ndarray or None

Weight arrays to combine. None entries are ignored.

()
n int

Target sum after normalization (typically the number of rows).

required

Returns

Type Description
ndarray or None

Combined, normalized weight array, or None if all inputs are None.

Raises

Type Description
ValueError

If the combined product sums to zero.

Source Code

Show/Hide source
def combine_weight_vectors(*arrays: np.ndarray | None, n: int) -> np.ndarray | None:
    """Combine weight vectors multiplicatively and normalize.

    Filters out ``None`` inputs, multiplies the remaining arrays
    element-wise, then normalizes so the result sums to ``n``.

    Parameters
    ----------
    *arrays : numpy.ndarray or None
        Weight arrays to combine.  ``None`` entries are ignored.
    n : int
        Target sum after normalization (typically the number of rows).

    Returns
    -------
    numpy.ndarray or None
        Combined, normalized weight array, or ``None`` if all inputs are
        ``None``.

    Raises
    ------
    ValueError
        If the combined product sums to zero.

    """
    valid = [a for a in arrays if a is not None]
    if not valid:
        return None
    combined = valid[0].copy()
    for a in valid[1:]:
        combined = combined * a
    if combined.sum() == 0:
        raise ValueError("Combined weights sum to zero: all weighted elements have zero weight")
    return combined * (n / combined.sum())