Skip to content

MannWhitneyU

Use MannWhitneyU for a two-sided permutation test of rank separation between two groups. Its statistic is the area under the receiver operating characteristic curve (AUROC): how often a target value ranks above a source value, with ties counting as half. It does not say whether anyone is worse off.

Question Does the target-versus-source rank probability differ from 0.5?
Inputs source reference values; target values under review
Run Call (); optionally set permutation settings with .set_permutation(...)
statistic AUROC, with source labeled 0 and target labeled 1
alternative two-sided
import numpy as np
import samesame as ss

source = np.array([0.10, 0.22, 0.28, 0.35])
target = np.array([0.30, 0.42, 0.55, 0.61])

test = ss.MannWhitneyU(source, target)
test = test.set_permutation(seed=np.random.default_rng(12345))
shift = test()
print(shift.pvalue, shift.statistic)

Expected output: p-value 0.056 and AUROC 0.94. Target values usually rank higher in these eight observations; the result does not show that outcomes got worse.

Null and statistic

The test labels source as 0 and target as 1. Its statistic is the empirical AUROC. It shuffles group labels while keeping values and any supplied weights fixed. An AUROC above 0.5 means target values tend to rank higher; below 0.5 means source values tend to rank higher.

The test checks rank separation, not every possible difference between distributions, and it does not test harm.

Edge cases

  • Ties use tie-group masses with 0.5 weight. No jitter is needed.
  • extra["null"] is a read-only array of evaluated statistics. It can be shorter than the requested n_permutations when SciPy enumerates all possible arrangements.
  • extra["n_permutations"] holds the requested count.
  • The package does not implement inference="asymptotic". The call raises NotImplementedError. Use scipy.stats.mannwhitneyu(..., method="asymptotic") for that null.

Reference

samesame.MannWhitneyU

Bases: _TwoSampleBase

Test for rank separation between two groups.

Its statistic is the probabilistic index: the probability that a target value exceeds a source value, with ties counting as half. The two-sided test checks whether this index differs from 0.5. It can detect rank separation, but it does not test every possible distributional difference or say whether anyone is worse off.

Parameters:

Name Type Description Default
source NDArray[float64]

Reference scores with shape (n_source,).

required
target NDArray[float64]

Scores under review with shape (n_target,).

required
inference Literal['permutation', 'asymptotic']

"permutation" permutes labels with scores and weights fixed. It is the default. "asymptotic" is not implemented. A call with it raises and points to scipy.stats.mannwhitneyu. Configure permutation randomness with :meth:set_permutation.

'permutation'
Notes

The test labels source as 0 and target as 1. Its statistic is empirical AUROC, equivalent to the Mann–Whitney rank statistic scaled to [0, 1]. The permutation null assumes group labels are exchangeable for the pooled scores. The test checks whether the probabilistic index differs from 0.5, including the weighted form when .overlap() weights exist.

See Also

Dsos : One-sided tail-weighted test in a defined harm direction. DeLong : Paired comparison of two models' AUROCs.

Examples:

>>> import numpy as np
>>> import samesame as ss
>>> test = ss.MannWhitneyU(np.array([0.1, 0.2]), np.array([0.4, 0.5]))
>>> test = test.set_permutation(seed=np.random.default_rng(12345))
>>> result = test()
>>> result.test_name
'Mann-Whitney U (permutation)'
Source code in src/samesame/_two_sample.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
class MannWhitneyU(_TwoSampleBase):
    """Test for rank separation between two groups.

    Its statistic is the probabilistic index: the probability that a
    ``target`` value exceeds a ``source`` value, with ties counting as
    half. The two-sided test checks whether this index differs from ``0.5``.
    It can detect rank separation, but it does not test every possible
    distributional difference or say whether anyone is worse off.

    Parameters
    ----------
    source :
        Reference scores with shape ``(n_source,)``.
    target :
        Scores under review with shape ``(n_target,)``.
    inference :
        ``"permutation"`` permutes labels with scores and weights fixed.
        It is the default. ``"asymptotic"`` is not implemented. A call
        with it raises and points to ``scipy.stats.mannwhitneyu``.
        Configure permutation randomness with :meth:`set_permutation`.

    Notes
    -----
    The test labels ``source`` as ``0`` and ``target`` as ``1``. Its
    statistic is empirical AUROC, equivalent to the Mann–Whitney rank
    statistic scaled to ``[0, 1]``. The permutation null assumes group
    labels are exchangeable for the pooled scores. The test checks whether
    the probabilistic index differs from ``0.5``, including the weighted
    form when `.overlap()` weights exist.

    See Also
    --------
    Dsos : One-sided tail-weighted test in a defined harm direction.
    DeLong : Paired comparison of two models' AUROCs.

    Examples
    --------
    >>> import numpy as np
    >>> import samesame as ss
    >>> test = ss.MannWhitneyU(np.array([0.1, 0.2]), np.array([0.4, 0.5]))
    >>> test = test.set_permutation(seed=np.random.default_rng(12345))
    >>> result = test()
    >>> result.test_name
    'Mann-Whitney U (permutation)'
    """

    _TEST_NAME: Literal["Mann-Whitney U (permutation)", "D-SOS (permutation)"] = (
        "Mann-Whitney U (permutation)"
    )
    _ALTERNATIVE: Literal["two-sided", "greater"] = "two-sided"

    def __call__(self) -> TestResult:
        """Run the test for the selected ``inference``.

        Returns
        -------
        TestResult
            It holds ``test_name="Mann-Whitney U (permutation)"`` and
            ``alternative="two-sided"``. ``statistic`` equals empirical
            AUROC with ``source`` labeled ``0`` and ``target`` labeled
            ``1``. ``extra`` carries read-only ``"null"`` and
            ``"n_permutations"``.

        Raises
        ------
        NotImplementedError
            If ``inference="asymptotic"``. Use
            ``scipy.stats.mannwhitneyu`` with ``method="asymptotic"``
            instead. This package implements only the permutation null.
        """
        if self._inference != "permutation":
            raise NotImplementedError(
                "inference='asymptotic' is not implemented for MannWhitneyU; "
                "use scipy.stats.mannwhitneyu(..., method='asymptotic') instead"
            )
        return self._run_label_permutations(
            _empirical_auroc, _ascending_order, _mann_whitney_null
        )

__call__()

Run the test for the selected inference.

Returns:

Type Description
TestResult

It holds test_name="Mann-Whitney U (permutation)" and alternative="two-sided". statistic equals empirical AUROC with source labeled 0 and target labeled 1. extra carries read-only "null" and "n_permutations".

Raises:

Type Description
NotImplementedError

If inference="asymptotic". Use scipy.stats.mannwhitneyu with method="asymptotic" instead. This package implements only the permutation null.

Source code in src/samesame/_two_sample.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
def __call__(self) -> TestResult:
    """Run the test for the selected ``inference``.

    Returns
    -------
    TestResult
        It holds ``test_name="Mann-Whitney U (permutation)"`` and
        ``alternative="two-sided"``. ``statistic`` equals empirical
        AUROC with ``source`` labeled ``0`` and ``target`` labeled
        ``1``. ``extra`` carries read-only ``"null"`` and
        ``"n_permutations"``.

    Raises
    ------
    NotImplementedError
        If ``inference="asymptotic"``. Use
        ``scipy.stats.mannwhitneyu`` with ``method="asymptotic"``
        instead. This package implements only the permutation null.
    """
    if self._inference != "permutation":
        raise NotImplementedError(
            "inference='asymptotic' is not implemented for MannWhitneyU; "
            "use scipy.stats.mannwhitneyu(..., method='asymptotic') instead"
        )
    return self._run_label_permutations(
        _empirical_auroc, _ascending_order, _mann_whitney_null
    )