Skip to content

Hypothesis Testing

TestResult dataclass

Base class for hypothesis test results.

Source code in pycircstat2/hypothesis.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
@dataclass(frozen=True)
class TestResult:
    """Base class for hypothesis test results."""

    def asdict(self) -> dict[str, Any]:
        """Return result data as a dictionary."""
        from dataclasses import asdict

        return asdict(self)

    def significance(self, attr: str = "pval") -> Optional[str]:
        """Return significance stars for the requested p-value attribute."""

        if not hasattr(self, attr):
            return None

        value = getattr(self, attr)
        if value is None:
            return None

        try:
            return significance_code(float(value))
        except (TypeError, ValueError):
            return None

asdict()

Return result data as a dictionary.

Source code in pycircstat2/hypothesis.py
85
86
87
88
89
def asdict(self) -> dict[str, Any]:
    """Return result data as a dictionary."""
    from dataclasses import asdict

    return asdict(self)

significance(attr='pval')

Return significance stars for the requested p-value attribute.

Source code in pycircstat2/hypothesis.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def significance(self, attr: str = "pval") -> Optional[str]:
    """Return significance stars for the requested p-value attribute."""

    if not hasattr(self, attr):
        return None

    value = getattr(self, attr)
    if value is None:
        return None

    try:
        return significance_code(float(value))
    except (TypeError, ValueError):
        return None

rayleigh_test(alpha=None, w=None, r=None, n=None, B=1, seed=2046, verbose=False)

Rayleigh's Test for Circular Uniformity.

  • H0: The data in the population are distributed uniformly around the circle.
  • H1: The data in the population are not disbutrited uniformly around the circle.
\[ z = n \cdot r^2 \]

and

\[ p = \exp(\sqrt{1 + 4n + 4(n^2 - R^2)} - (1 + 2n)) \]

This method is for ungrouped data. For testing uniformity with grouped data, use chisquare_test() or scipy.stats.chisquare().

Parameters:

Name Type Description Default
alpha Optional[ndarray]

Angles in radian.

None
w Optional[ndarray]

Frequencies of angles.

None
r Optional[float]

Resultant vector length from descriptive.circ_mean().

None
n Optional[int]

Sample size.

None
B int

Number of bootstrap samples for p-value estimation.

1
seed SeedLike

Seed used to initialize the random number generator for bootstrap resampling when B > 1. Accepts integers, sequences of integers, numpy.random.Generator, numpy.random.BitGenerator, numpy.random.SeedSequence or None. Defaults to 2046.

2046
verbose bool

Print formatted results.

False

Returns:

Type Description
RayleighTestResult

A dataclass containing:

  • r: float
    • Resultant vector length.
  • z: float
    • Test statistic (Rayleigh's Z).
  • pval: float
    • Classical p-value based on the asymptotic formula.
  • bootstrap_pval: float or None
    • Bootstrap p-value (if computed, i.e., B > 1); otherwise, None.
Reference

P625, Section 27.1, Example 27.1 of Zar, 2010

Source code in pycircstat2/hypothesis.py
374
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
def rayleigh_test(
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    r: Optional[float] = None,
    n: Optional[int] = None,
    B: int = 1,
    seed: SeedLike = 2046,
    verbose: bool = False,
) -> RayleighTestResult:
    r"""
    Rayleigh's Test for Circular Uniformity.

    - H0: The data in the population are distributed uniformly around the circle.
    - H1: The data in the population are not disbutrited uniformly around the circle.

    $$ z = n \cdot r^2 $$

    and

    $$ p = \exp(\sqrt{1 + 4n + 4(n^2 - R^2)} - (1 + 2n)) $$

    This method is for ungrouped data. For testing uniformity with
    grouped data, use `chisquare_test()` or `scipy.stats.chisquare()`.

    Parameters
    ----------

    alpha: np.array or None
        Angles in radian.

    w: np.array or None.
        Frequencies of angles.

    r: float or None
        Resultant vector length from `descriptive.circ_mean()`.

    n: int or None
        Sample size.

    B: int
        Number of bootstrap samples for p-value estimation.

    seed: SeedLike
        Seed used to initialize the random number generator for bootstrap resampling
        when ``B > 1``. Accepts integers, sequences of integers, ``numpy.random.Generator``,
        ``numpy.random.BitGenerator``, ``numpy.random.SeedSequence`` or ``None``.
        Defaults to 2046.

    verbose: bool
        Print formatted results.

    Returns
    -------
    RayleighTestResult
        A dataclass containing:

        - r: float
            - Resultant vector length.
        - z: float
            - Test statistic (Rayleigh's Z).
        - pval: float
            - Classical p-value based on the asymptotic formula.
        - bootstrap_pval: float or None
            - Bootstrap p-value (if computed, i.e., B > 1); otherwise, None.

    Reference
    ---------
    P625, Section 27.1, Example 27.1 of Zar, 2010
    """

    if B <= 0:
        raise ValueError("`B` must be a positive integer.")

    if r is None:
        if alpha is None:
            raise ValueError("If `r` is None, then `alpha` (and optionally `w`) is required.")
        alpha = np.asarray(alpha, dtype=float)
        if alpha.size == 0:
            raise ValueError("`alpha` must contain at least one angle.")
        if w is None:
            w = np.ones_like(alpha, dtype=float)
        else:
            w = np.asarray(w, dtype=float)
            if w.shape != alpha.shape:
                raise ValueError("`w` must have the same shape as `alpha`.")
        n_total = float(np.sum(w))
        if n_total <= 0:
            raise ValueError("Sample size inferred from `w` must be positive.")
        if not np.isclose(n_total, round(n_total)):
            raise ValueError("Rayleigh's test requires integer sample sizes when weights are used.")
        n = int(round(n_total))
        r = circ_r(alpha, w)
    else:
        r = float(r)

    if n is None or n <= 0:
        raise ValueError("Sample size `n` must be provided and positive when `r` is given.")

    if not (0.0 <= r <= 1.0):
        raise ValueError("`r` must lie in the interval [0, 1].")

    R = n * r
    z = n * r**2  # eq(27.2)

    pval = np.exp(np.sqrt(1 + 4 * n + 4 * (n**2 - R**2)) - (1 + 2 * n))  # eq(27.4)

    bootstrap_pval: Optional[float]
    if seed is True and verbose is False:
        warnings.warn(
            "Passing `verbose` as a positional argument is deprecated; use keyword arguments.",
            DeprecationWarning,
            stacklevel=2,
        )
        verbose = bool(seed)
        seed = 2046

    if B > 1:
        rng = _init_rng(seed)
        uniforms = rng.uniform(0.0, 2 * np.pi, size=(B, n))
        unit_vectors = np.exp(1j * uniforms)
        resultant_lengths = np.abs(np.sum(unit_vectors, axis=1))
        bootstrap_stats = (resultant_lengths**2) / n
        bootstrap_pval = float((np.count_nonzero(bootstrap_stats >= z) + 1) / (B + 1))
    else:
        bootstrap_pval = None

    if verbose:
        print("Rayleigh's Test of Uniformity")
        print("-----------------------------")
        print("H0: ρ = 0")
        print("HA: ρ ≠ 0")
        print("")
        print(f"Test Statistics  (ρ | z-score): {r:.5f} | {z:.5f}")
        print(f"P-value: {pval:.5f} {significance_code(pval)}")
        if B > 1 and bootstrap_pval is not None:
            print(
                f"Bootstrap P-value: {bootstrap_pval:.5f} {significance_code(bootstrap_pval)}"
            )

    return RayleighTestResult(r=r, z=z, pval=pval, bootstrap_pval=bootstrap_pval)

chisquare_test(w, verbose=False)

Chi-Square Goodness of Fit for Circular data.

  • H0: The data in the population are distributed uniformly around the circle.
  • H1: THe data in the population are not disbutrited uniformly around the circle.

For method is for grouped data.

Parameters:

Name Type Description Default
w ndarray

Frequencies of angles

required
verbose bool

Print formatted results.

False

Returns:

Type Description
ChiSquareTestResult

A dataclass containing:

  • chi2: float
    • The chi-squared test statistic.
  • pval: float
    • The p-value of the test.
Note

It's a wrapper of scipy.stats.chisquare()

Reference

P662-663, Section 27.17, Example 27.23 of Zar, 2010

Source code in pycircstat2/hypothesis.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
def chisquare_test(w: np.ndarray, verbose: bool = False) -> ChiSquareTestResult:
    """Chi-Square Goodness of Fit for Circular data.

    - H0: The data in the population are distributed uniformly around the circle.
    - H1: THe data in the population are not disbutrited uniformly around the circle.

    For method is for grouped data.

    Parameters
    ----------
    w: np.ndarray
        Frequencies of angles

    verbose: bool
        Print formatted results.

    Returns
    -------
    ChiSquareTestResult
        A dataclass containing:

        - chi2: float
            - The chi-squared test statistic.
        - pval: float
            - The p-value of the test.

    Note
    ----
    It's a wrapper of scipy.stats.chisquare()

    Reference
    ---------
    P662-663, Section 27.17, Example 27.23 of Zar, 2010
    """
    from scipy.stats import chisquare

    frequencies = np.asarray(w, dtype=float)
    if frequencies.ndim != 1 or frequencies.size == 0:
        raise ValueError("`w` must be a one-dimensional array with at least one element.")
    if np.any(frequencies < 0):
        raise ValueError("`w` must contain non-negative frequencies.")

    res = chisquare(frequencies)
    chi2 = res.statistic
    pval = res.pvalue

    if verbose:
        print("Chi-Square Test of Uniformity")
        print("-----------------------------")
        print("H0: uniform")
        print("HA: not uniform")
        print("")
        print(f"Test Statistics (χ²): {chi2:.5f}")
        print(f"P-value: {pval:.5f} {significance_code(pval)}")

    return ChiSquareTestResult(chi2=chi2, pval=pval)

V_test(angle, alpha=None, w=None, mean=None, r=None, n=None, verbose=False)

Modified Rayleigh Test for Uniformity versus a Specified Angle.

  • H0: The population is uniformly distributed around the circle (i.e., H0: ρ=0)
  • H1: The population is not uniformly distributed around the circle (i.e., H1: ρ!=0), but has a mean of certain degree.

Parameters:

Name Type Description Default
angle Union[int, float]

Angle in radian to be compared with mean angle.

required
alpha Optional[ndarray]

Angles in radian.

None
w Optional[ndarray]

Frequencies of angles.

None
mean Optional[float]

Circular mean from descriptive.circ_mean(). Needed if alpha is None.

None
r Optional[float]

Resultant vector length from descriptive.circ_mean(). Needed if alpha is None.

None
n Optional[int]

Sample size. Needed if alpha is None.

None
verbose bool

Print formatted results.

False

Returns:

Type Description
VTestResult

Dataclass containing the test statistic V, the normalized statistic u, and the p-value.

Reference

P627, Section 27.1, Example 27.2 of Zar, 2010

Source code in pycircstat2/hypothesis.py
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
def V_test(
    angle: Union[int, float],
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    mean: Optional[float] = None,
    r: Optional[float] = None,
    n: Optional[int] = None,
    verbose: bool = False,
) -> VTestResult:
    """
    Modified Rayleigh Test for Uniformity versus a Specified Angle.

    - H0: The population is uniformly distributed around the circle (i.e., H0: ρ=0)
    - H1: The population is not uniformly distributed around the circle (i.e., H1: ρ!=0),
        but has a mean of certain degree.

    Parameters
    ----------
    angle: float or int
        Angle in radian to be compared with mean angle.

    alpha: np.array or None
        Angles in radian.

    w: np.array or None.
        Frequencies of angles.

    mean: float or None
        Circular mean from `descriptive.circ_mean()`. Needed if `alpha` is None.

    r: float or None
        Resultant vector length from `descriptive.circ_mean()`. Needed if `alpha` is None.

    n: int or None
        Sample size. Needed if `alpha` is None.

    verbose: bool
        Print formatted results.

    Returns
    -------
    VTestResult
        Dataclass containing the test statistic `V`, the normalized statistic `u`,
        and the p-value.

    Reference
    ---------
    P627, Section 27.1, Example 27.2 of Zar, 2010
    """

    angle = float(angle)

    if mean is None or r is None or n is None:
        if alpha is None:
            raise ValueError("If `mean`, `r`, or `n` is None, then `alpha` (and optionally `w`) is required.")
        alpha = np.asarray(alpha, dtype=float)
        if alpha.size == 0:
            raise ValueError("`alpha` must contain at least one angle.")
        if w is None:
            w = np.ones_like(alpha, dtype=float)
        else:
            w = np.asarray(w, dtype=float)
            if w.shape != alpha.shape:
                raise ValueError("`w` must have the same shape as `alpha`.")
        n = int(np.sum(w))
        if n <= 0:
            raise ValueError("Sample size inferred from `w` must be positive.")
        mean, r = circ_mean_and_r(alpha, w)
    else:
        mean = float(mean)
        r = float(r)
        if n <= 0:
            raise ValueError("`n` must be positive.")

    if not (0.0 <= r <= 1.0):
        raise ValueError("`r` must lie in the interval [0, 1].")

    R = n * r
    V = R * np.cos(angmod(mean - angle, bounds=[-np.pi, np.pi]))  # eq(27.5)
    u = V * np.sqrt(2.0 / n)  # eq(27.6)
    pval = float(norm.sf(u))

    if verbose:
        print("Modified Rayleigh's Test of Uniformity")
        print("--------------------------------------")
        print("H0: ρ = 0")
        print(f"HA: ρ ≠ 0 and μ = {angle:.5f} rad")
        print("")
        print(f"Test Statistics: {V:.5f}")
        print(f"P-value: {pval:.5f} {significance_code(pval)}")

    return VTestResult(V=V, u=u, pval=pval)

one_sample_test(angle, alpha=None, w=None, lb=None, ub=None, verbose=False)

To test whether the population mean angle is equal to a specified value, which is achieved by observing whether the angle lies within the 95% CI.

  • H0: The population has a mean of μ (μ_a = μ_0)
  • H1: The population mean is not μ (μ_a ≠ μ_0)

Parameters:

Name Type Description Default
angle Union[int, float]

Angle in radian to be compared with mean angle.

required
alpha Optional[ndarray]

Angles in radian.

None
w Optional[ndarray]

Frequencies of angles

None
lb Optional[float]

Lower bound of circular mean from descriptive.circ_mean_ci().

None
ub Optional[float]

Upper bound of circular mean from descriptive.circ_mean_ci().

None
verbose bool

Print formatted results.

False
Reference

P628, Section 27.1, Example 27.3 of Zar, 2010

Source code in pycircstat2/hypothesis.py
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
def one_sample_test(
    angle: Union[int, float],
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    lb: Optional[float] = None,
    ub: Optional[float] = None,
    verbose: bool = False,
) -> OneSampleTestResult:
    """
    To test whether the population mean angle is equal to a specified value,
    which is achieved by observing whether the angle lies within the 95% CI.

    - H0: The population has a mean of μ (μ_a = μ_0)
    - H1: The population mean is not μ (μ_a ≠ μ_0)

    Parameters
    ----------

    angle: float or int
        Angle in radian to be compared with mean angle.

    alpha: np.array or None
        Angles in radian.

    w: np.array or None.
        Frequencies of angles

    lb: float
        Lower bound of circular mean from `descriptive.circ_mean_ci()`.

    ub: float
        Upper bound of circular mean from `descriptive.circ_mean_ci()`.

    verbose: bool
        Print formatted results.

    Reference
    ---------
    P628, Section 27.1, Example 27.3 of Zar, 2010
    """

    angle = float(angle)

    if lb is None or ub is None:
        if alpha is None:
            raise ValueError("If `lb` or `ub` is None, then `alpha` (and optionally `w`) is required.")
        alpha = np.asarray(alpha, dtype=float)
        if alpha.size == 0:
            raise ValueError("`alpha` must contain at least one angle.")
        if w is None:
            w = np.ones_like(alpha, dtype=float)
        else:
            w = np.asarray(w, dtype=float)
            if w.shape != alpha.shape:
                raise ValueError("`w` must have the same shape as `alpha`.")
        lb, ub = circ_mean_ci(alpha=alpha, w=w)

    lb = float(lb)
    ub = float(ub)

    reject = not is_within_circular_range(angle, lb, ub)

    if verbose:
        print("One-Sample Test for the Mean Angle")
        print("----------------------------------")
        print("H0: μ = μ0")
        print(f"HA: μ ≠ μ0 and μ0 = {angle:.5f} rad")
        print("")
        if reject:
            print(
                f"Reject H0:\nμ0 = {angle:.5f} lies outside the 95% CI of μ ({np.array([lb, ub]).round(5)})"
            )
        else:
            print(
                f"Failed to reject H0:\nμ0 = {angle:.5f} lies within the 95% CI of μ ({np.array([lb, ub]).round(5)})"
            )

    return OneSampleTestResult(reject=reject, angle=angle, ci=(lb, ub))

omnibus_test(alpha, scale=1, verbose=False)

Hodges–Ajne omnibus test for circular uniformity.

  • H0: The population is uniformly distributed around the circle
  • H1: The population is not uniformly distributed.

This test is distribution-free and handles uni-, bi-, and multimodal alternatives. The classical p-value involves factorials and overflows for large n. We therefore compute it in log-space (math.lgamma) and exponentiate at the very end.

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
scale int

Scale factor for the number of lines to be tested.

1
verbose bool

Print formatted results.

False

Returns:

Type Description
OmnibusTestResult

Dataclass containing the test statistic A, the corresponding p-value, and the minimum count m.

Reference

P629-630, Section 27.2, Example 27.4 of Zar, 2010

Source code in pycircstat2/hypothesis.py
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
def omnibus_test(
    alpha: np.ndarray,
    scale: int = 1,
    verbose: bool = False,
) -> OmnibusTestResult:
    """
    Hodges–Ajne omnibus test for circular uniformity.

    - H0: The population is uniformly distributed around the circle
    - H1: The population is not uniformly distributed.

    This test is distribution-free and handles uni-, bi-, and multimodal
    alternatives.  The classical p-value involves factorials and
    overflows for large *n*.  We therefore compute it in log-space
    (``math.lgamma``) and exponentiate at the very end.

    Parameters
    ----------
    alpha: np.array or None
        Angles in radian.

    scale: int
        Scale factor for the number of lines to be tested.

    verbose: bool
        Print formatted results.

    Returns
    -------
    OmnibusTestResult
        Dataclass containing the test statistic `A`, the corresponding p-value,
        and the minimum count `m`.

    Reference
    ---------
    P629-630, Section 27.2, Example 27.4 of Zar, 2010
    """

    if scale <= 0:
        raise ValueError("`scale` must be a positive integer.")

    alpha = np.asarray(alpha, dtype=float)
    if alpha.size == 0:
        raise ValueError("`alpha` must contain at least one angle.")

    lines = np.linspace(0.0, np.pi, scale * 360, endpoint=False)
    n = alpha.size

    lines_rotated = angmod(lines[:, None] - alpha)

    # # count number of points on the right half circle, excluding the boundaries
    right = n - np.logical_and(
        lines_rotated > 0.0, lines_rotated < np.pi
    ).sum(axis=1)
    m = int(np.min(right))

    # ------------------------------------------------------------------
    # 2. p-value   ———  analytical formula and its log form
    # ------------------------------------------------------------------
    #     Classical (Zar 2010, eq. 27-4):
    #
    #         p  =  (n − 2m) · n! / [ m! · (n − m)! · 2^(n−1) ]            …(1)
    #       # pval = (
    #       #    (n - 2 * m)
    #       #    * math.factorial(n)
    #       #    / (math.factorial(m) * math.factorial(n - m))
    #       #    / 2 ** (n - 1)
    #       # ) # eq(27.7)

    #     Taking natural logs and using  Γ(k+1) = k!  with  log Γ = lgamma:
    #
    #         ln p  =  ln(n − 2m)
    #                 + lgamma(n + 1)
    #                 − lgamma(m + 1)
    #                 − lgamma(n − m + 1)
    #                 − (n − 1)·ln 2                                        …(2)
    #
    #     Eq. (2) is numerically safe for very large n; we exponentiate at
    #     the end, knowing the result may under-flow to 0.0 in double precision.
    # ------------------------------------------------------------------

    denom = n - 2 * m
    if denom <= 0:
        logp = -np.inf
        pval = 0.0
        A = np.inf
    else:
        logp = (
            math.log(denom)
            + math.lgamma(n + 1)
            - math.lgamma(m + 1)
            - math.lgamma(n - m + 1)
            - (n - 1) * math.log(2.0)
        )
        pval = float(np.exp(logp))
        A = np.pi * np.sqrt(n) / (2 * denom)

    if verbose:
        print('Hodges-Ajne ("omnibus") Test for Uniformity')
        print("-------------------------------------------")
        print("H0: uniform")
        print("HA: not unifrom")
        print("")
        print(f"Test Statistics: {A:.5f}")
        print(f"P-value: {pval:.5f} {significance_code(pval)}")
    return OmnibusTestResult(A=float(A), pval=float(pval), m=int(m))

batschelet_test(angle, alpha, verbose=False)

Modified Hodges-Ajne Test for Uniformity versus a specified Angle (for ungrouped data).

  • H0: The population is uniformly distributed around the circle.
  • H1: The population is not uniformly distributed around the circle, but is concentrated around a specified angle.

Parameters:

Name Type Description Default
angle Union[int, float]

A specified angle.

required
alpha ndarray

Angles in radian.

required
verbose bool

Print formatted results.

False
Reference

P630-631, Section 27.2, Example 27.5 of Zar, 2010

Source code in pycircstat2/hypothesis.py
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
def batschelet_test(
    angle: Union[int, float],
    alpha: np.ndarray,
    verbose: bool = False,
) -> BatscheletTestResult:
    """Modified Hodges-Ajne Test for Uniformity versus a specified Angle
    (for ungrouped data).

    - H0: The population is uniformly distributed around the circle.
    - H1: The population is not uniformly distributed around the circle, but
        is concentrated around a specified angle.

    Parameters
    ----------
    angle: np.array
        A specified angle.

    alpha: np.array or None
        Angles in radian.

    verbose: bool
        Print formatted results.

    Reference
    ---------
    P630-631, Section 27.2, Example 27.5 of Zar, 2010
    """

    from scipy.stats import binomtest

    alpha = np.asarray(alpha, dtype=float)
    if alpha.size == 0:
        raise ValueError("`alpha` must contain at least one angle.")

    angle = float(angle)

    n = alpha.size
    angle_diff = angmod((angle + 0.5 * np.pi) - alpha)
    m = np.logical_and(angle_diff > 0.0, angle_diff < np.pi).sum()
    C = int(n - m)
    pval = float(binomtest(C, n=n, p=0.5).pvalue)

    if verbose:
        print("Batschelet Test for Uniformity")
        print("------------------------------")
        print("H0: uniform")
        print(f"HA: not unifrom but concentrated around θ = {angle:.5f} rad")
        print("")
        print(f"Test Statistics: {C}")
        print(f"P-value: {pval:.5f} {significance_code(pval)}")

    return BatscheletTestResult(C=C, pval=pval)

symmetry_test(alpha, median=None, verbose=False)

Non-parametric test for symmetry around the median. Works by performing a Wilcoxon sign rank test on the differences to the median. Also known as Wilcoxon paired-sample test.

  • H0: the population is symmetrical around the median
  • HA: the population is not symmetrical around the median

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
median Optional[float]

Median computed by descriptive.median().

None
verbose bool

Print formatted results.

False
Reference

P631-632, Section 27.3, Example 27.6 of Zar, 2010

Source code in pycircstat2/hypothesis.py
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
def symmetry_test(
    alpha: np.ndarray,
    median: Optional[float] = None,
    verbose: bool = False,
) -> SymmetryTestResult:
    """Non-parametric test for symmetry around the median. Works by performing a
    Wilcoxon sign rank test on the differences to the median. Also known as
    Wilcoxon paired-sample test.

    - H0: the population is symmetrical around the median
    - HA: the population is not symmetrical around the median

    Parameters
    ----------
    alpha: np.array
        Angles in radian.

    median: float or None.
        Median computed by `descriptive.median()`.

    verbose: bool
        Print formatted results.

    Reference
    ---------
    P631-632, Section 27.3, Example 27.6 of Zar, 2010
    """

    alpha = np.asarray(alpha, dtype=float)
    if alpha.size == 0:
        raise ValueError("`alpha` must contain at least one angle.")

    if median is None:
        median = float(circ_median(alpha=alpha))
    else:
        median = float(median)

    d = angmod(alpha - median, bounds=[-np.pi, np.pi])

    res = wilcoxon(d, alternative="two-sided")
    test_statistic = float(res.statistic)
    pval = float(res.pvalue)

    if verbose:
        print("Symmetry Test")
        print("------------------------------")
        print("H0: symmetrical around median")
        print("HA: not symmetrical around median")
        print("")
        print(f"Test Statistics: {test_statistic:.5f}")
        print(f"P-value: {pval:.5f} {significance_code(pval)}")

    return SymmetryTestResult(statistic=test_statistic, pval=pval)

watson_williams_test(samples, verbose=False)

The Watson-Williams Test for multiple samples.

  • H0: All samples are from populations with the same mean angle
  • H1: All samples are not from populations with the same mean angle

Parameters:

Name Type Description Default
samples Sequence[Any]

A sequence of Circular objects or one-dimensional array-like radian samples.

required
verbose bool

Print formatted results.

False

Returns:

Type Description
WatsonWilliamsTestResult

Dataclass containing the F statistic, p-value, and associated degrees of freedom.

Reference

P632-636, Section 27.4, Example 27.7/8 of Zar, 2010

Source code in pycircstat2/hypothesis.py
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
def watson_williams_test(
    samples: Sequence[Any],
    verbose: bool = False,
) -> WatsonWilliamsTestResult:
    """The Watson-Williams Test for multiple samples.

    - H0: All samples are from populations with the same mean angle
    - H1: All samples are not from populations with the same mean angle

    Parameters
    ----------
    samples: sequence
        A sequence of `Circular` objects or one-dimensional array-like radian samples.

    verbose: bool
        Print formatted results.

    Returns
    -------
    WatsonWilliamsTestResult
        Dataclass containing the F statistic, p-value, and associated degrees of freedom.

    Reference
    ---------
    P632-636, Section 27.4, Example 27.7/8 of Zar, 2010
    """

    normalized = _coerce_circular_samples(samples)
    if len(normalized) < 2:
        raise ValueError("At least two samples are required for the Watson-Williams test.")

    k = len(normalized)
    N = sum(sample.n for sample in normalized)
    if N <= k:
        raise ValueError("Combined sample size must exceed the number of groups.")

    Rs = np.array([sample.R for sample in normalized], dtype=float)
    rw = float(np.sum(Rs) / N)

    kappa_hat = float(circ_kappa(rw))
    if not np.isfinite(kappa_hat):
        kappa_hat = 0.0
    if kappa_hat <= 0.0:
        K = 1.0
        warnings.warn(
            (
                "Watson-Williams test assumes common, high concentration; "
                "estimated κ≈0. Results may be unreliable."
            ),
            RuntimeWarning,
            stacklevel=2,
        )
    else:
        K = 1.0 + 3.0 / (8.0 * kappa_hat)
        if kappa_hat < 1.0:
            warnings.warn(
                (
                    "Watson-Williams test assumes common, high concentration; "
                    f"estimated κ≈{kappa_hat:.3f}. Results may be unreliable."
                ),
                RuntimeWarning,
                stacklevel=2,
            )

    all_alpha = np.hstack([sample.alpha for sample in normalized])
    all_weights = np.hstack([sample.w for sample in normalized])
    R = N * circ_r(alpha=all_alpha, w=all_weights)
    F = K * (N - k) * (np.sum(Rs) - R) / (N - np.sum(Rs)) / (k - 1)
    df_between = k - 1
    df_within = N - k
    pval = float(f.sf(F, df_between, df_within))

    result = WatsonWilliamsTestResult(
        F=float(F),
        pval=pval,
        df_between=df_between,
        df_within=df_within,
        k=k,
        N=N,
    )

    if verbose:
        print("The Watson-Williams Test for multiple samples")
        print("---------------------------------------------")
        print("H0: all samples are from populations with the same angle.")
        print("HA: all samples are not from populations with the same angle.")
        print("")
        print(f"Test Statistics: {result.F:.5f}")
        print(f"P-value: {result.pval:.5f} {significance_code(result.pval)}")

    return result

watson_u2_test(samples, verbose=False)

Watson's U2 Test for nonparametric two-sample testing (with or without ties).

  • H0: The two samples came from the same population, or from two populations having the same direction.
  • H1: The two samples did not come from the same population, or from two populations having the same directions.

Use this instead of Watson-Williams two-sample test when at least one of the sampled populations is not unimodal or when there are other considerable departures from the assumptions of the latter test. It may be used on grouped data if the grouping interval is no greater than 5 degree.

Parameters:

Name Type Description Default
samples Sequence[Any]

A sequence of Circular objects or one-dimensional array-like radian samples.

required
verbose bool

Print formatted results.

False

Returns:

Type Description
WatsonU2TestResult

Dataclass containing the U² statistic and the associated p-value.

Reference

P637-638, Section 27.5, Example 27.9 of Zar, 2010 P639-640, Section 27.5, Example 27.10 of Zar, 2010

Source code in pycircstat2/hypothesis.py
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
def watson_u2_test(
    samples: Sequence[Any],
    verbose: bool = False,
) -> WatsonU2TestResult:
    """Watson's U2 Test for nonparametric two-sample testing
    (with or without ties).

    - H0: The two samples came from the same population,
        or from two populations having the same direction.
    - H1: The two samples did not come from the same population,
        or from two populations having the same directions.

    Use this instead of Watson-Williams two-sample test when at
    least one of the sampled populations is not unimodal or when
    there are other considerable departures from the assumptions
    of the latter test. It may be used on grouped data if the
    grouping interval is no greater than 5 degree.

    Parameters
    ----------
    samples: sequence
        A sequence of `Circular` objects or one-dimensional array-like radian samples.

    verbose: bool
        Print formatted results.

    Returns
    -------
    WatsonU2TestResult
        Dataclass containing the U² statistic and the associated p-value.

    Reference
    ---------
    P637-638, Section 27.5, Example 27.9 of Zar, 2010
    P639-640, Section 27.5, Example 27.10 of Zar, 2010
    """

    from scipy.stats import rankdata

    normalized = _coerce_circular_samples(samples)
    if len(normalized) != 2:
        raise ValueError("`watson_u2_test` requires exactly two samples.")

    def cumfreq(alpha_unique: np.ndarray, sample: _CircularSample) -> np.ndarray:
        expanded = sample.expand()
        if expanded.size == 0:
            raise ValueError("Each sample must contain at least one observation.")

        idx = [np.where(np.isclose(alpha_unique, val, atol=1e-10))[0] for val in expanded]
        idx = np.concatenate(idx)
        idx = np.hstack([0, idx, alpha_unique.size])

        freq_cumsum = rankdata(expanded, method="max") / sample.n
        freq_cumsum = np.hstack([0, freq_cumsum])

        tiles = np.diff(idx)
        return np.repeat(freq_cumsum, tiles)

    expanded_samples = [sample.expand() for sample in normalized]
    a, t = np.unique(np.hstack(expanded_samples), return_counts=True)
    cfs = [cumfreq(a, sample) for sample in normalized]
    d = np.diff(cfs, axis=0)

    N = sum(sample.n for sample in normalized)
    U2 = (
        np.prod([sample.n for sample in normalized])
        / N**2
        * (np.sum(t * d**2) - np.sum(t * d) ** 2 / N)
    )
    pval = 2 * np.exp(-19.74 * U2)
    # Approximated P-value from Watson (1961)
    # https://github.com/pierremegevand/watsons_u2/blob/master/watsons_U2_approx_p.m

    if verbose:
        print("Watson's U2 Test for two samples")
        print("---------------------------------------------")
        print("H0: The two samples are from populations with the same angle.")
        print("HA: The two samples are not from populations with the same angle.")
        print("")
        print(f"Test Statistics: {U2:.5f}")
        print(f"P-value: {pval:.5f} {significance_code(pval)}")

    return WatsonU2TestResult(U2=float(U2), pval=float(pval))

wheeler_watson_test(samples, verbose=False)

The Wheeler and Watson Two/Multi-Sample Test.

  • H0: The two samples came from the same population, or from two populations having the same direction.
  • H1: The two samples did not come from the same population, or not from two populations having the same directions.

Parameters:

Name Type Description Default
samples Sequence[Any]

A sequence of Circular objects or one-dimensional array-like radian samples.

required
verbose bool

Print formatted results.

False

Returns:

Type Description
WheelerWatsonTestResult

Dataclass containing the W statistic, degrees of freedom, and p-value.

Reference

P640-642, Section 27.5, Example 27.11 of Zar, 2010

Note

The current implementation doesn't consider ties in the data. Can be improved with P144, Pewsey et al. (2013)

Source code in pycircstat2/hypothesis.py
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def wheeler_watson_test(
    samples: Sequence[Any],
    verbose: bool = False,
) -> WheelerWatsonTestResult:
    """The Wheeler and Watson Two/Multi-Sample Test.

    - H0: The two samples came from the same population,
        or from two populations having the same direction.
    - H1: The two samples did not come from the same population,
        or not from two populations having the same directions.

    Parameters
    ----------
    samples: sequence
        A sequence of `Circular` objects or one-dimensional array-like radian samples.

    verbose: bool
        Print formatted results.

    Returns
    -------
    WheelerWatsonTestResult
        Dataclass containing the W statistic, degrees of freedom, and p-value.

    Reference
    ---------
    P640-642, Section 27.5, Example 27.11 of Zar, 2010

    Note
    ----
    The current implementation doesn't consider ties in the data.
    Can be improved with P144, Pewsey et al. (2013)
    """
    from scipy.stats import chi2

    normalized = _coerce_circular_samples(samples)

    def get_circrank(alpha: np.ndarray, sample: _CircularSample, N: int) -> np.ndarray:
        expanded = sample.expand()
        rank_of_direction = (
            np.squeeze([np.where(np.isclose(alpha, value))[0] for value in expanded]) + 1
        )
        return 2 * np.pi / N * rank_of_direction

    N = sum(sample.n for sample in normalized)
    expanded_samples = [sample.expand() for sample in normalized]
    a, _ = np.unique(np.hstack(expanded_samples), return_counts=True)

    circ_ranks = [get_circrank(a, sample, N) for sample in normalized]

    k = len(circ_ranks)

    if k == 2:
        C = np.sum(np.cos(circ_ranks[0]))
        S = np.sum(np.sin(circ_ranks[0]))
        W = 2 * (N - 1) * (C**2 + S**2) / np.prod([sample.n for sample in normalized])
    elif k >= 3:
        W = 0.0
        for i in range(k):
            circ_rank = circ_ranks[i]
            C = np.sum(np.cos(circ_rank))
            S = np.sum(np.sin(circ_rank))
            W += (C**2 + S**2) / normalized[i].n
        W *= 2.0
    else:
        raise ValueError("At least two samples are required for the Wheeler-Watson test.")

    df = 2 * (k - 1)
    pval = float(chi2.sf(W, df=df))

    if verbose:
        print("The Wheeler and Watson Two/Multi-Sample Test")
        print("---------------------------------------------")
        print("H0: All samples are from populations with the same angle.")
        print("HA: All samples are not from populations with the same angle.")
        print("")
        print(f"Test Statistics: {W:.5f}")
        print(f"P-value: {pval:.5f} {significance_code(pval)}")

    return WheelerWatsonTestResult(W=float(W), pval=pval, df=df)

wallraff_test(samples, angle=0.0, verbose=False)

Wallraff test of angular distances / dispersion against a specified angle.

Parameters:

Name Type Description Default
samples Sequence[Any]

A sequence of Circular objects or one-dimensional array-like radian samples.

required
angle float

A specified angle in radian.

0.0
verbose bool

Print formatted results.

False

Returns:

Type Description
WallraffTestResult

Dataclass containing the U statistic and p-value.

Reference

P637-638, Section 27.8, Example 27.13 of Zar, 2010

Source code in pycircstat2/hypothesis.py
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
def wallraff_test(
    samples: Sequence[Any],
    angle: float = 0.0,
    verbose: bool = False,
) -> WallraffTestResult:
    """Wallraff test of angular distances / dispersion against a specified angle.

    Parameters
    ----------
    samples: sequence
        A sequence of `Circular` objects or one-dimensional array-like radian samples.

    angle: float
        A specified angle in radian.

    verbose: bool
        Print formatted results.

    Returns
    -------
    WallraffTestResult
        Dataclass containing the U statistic and p-value.

    Reference
    ---------
    P637-638, Section 27.8, Example 27.13 of Zar, 2010
    """

    normalized = _coerce_circular_samples(samples)

    if len(normalized) != 2:
        raise ValueError("Current implementation only supports two-sample comparison.")

    angle_arr = np.asarray(angle, dtype=float)
    if angle_arr.ndim == 0:
        angles = np.repeat(angle_arr, len(normalized))
    else:
        if angle_arr.size != len(normalized):
            raise ValueError("`angle` must be a scalar or have the same length as `samples`.")
        angles = angle_arr

    ns = [sample.n for sample in normalized]
    distances = [angular_distance(normalized[i].alpha, angles[i]) for i in range(len(normalized))]

    rs = rankdata(np.hstack(distances))

    N = np.sum(ns)

    # mann-whitney
    R1 = np.sum(rs[: ns[0]])
    U1 = np.prod(ns) + ns[0] * (ns[0] + 1) / 2 - R1
    U2 = np.prod(ns) - U1
    U = np.min([U1, U2])

    z = (U - np.prod(ns) / 2 + 0.5) / np.sqrt(np.prod(ns) * (N + 1) / 12)
    pval = float(2 * norm.sf(abs(z)))

    if verbose:
        print("Wallraff test of angular distances / dispersion")
        print("-----------------------------------------------")
        print("H0: The groups have equal dispersion around the specified reference angle.")
        print("HA: At least one group differs in dispersion around the specified angle.")
        print("")
        print(f"Test Statistics: {U:.5f}")
        print(f"P-value: {pval:.5f} {significance_code(pval)}")

    return WallraffTestResult(U=float(U), pval=pval)

circ_anova(samples, method='F-test', kappa=None, f_mod=True, verbose=False)

Circular Analysis of Variance (ANOVA) for multi-sample comparison of mean directions.

  • H₀: All groups have the same mean direction.
  • H₁: At least one group has a different mean direction.

Parameters:

Name Type Description Default
samples list of np.ndarray

List of arrays, where each array contains circular data (angles in radians) for a group.

required
method str

The test statistic to use. Options: - "F-test" (default): High-concentration F-test (Stephens 1972). - "LRT": Likelihood Ratio Test (Cordeiro et al. 1994).

'F-test'
kappa float

The common concentration parameter (κ). If not specified, it is estimated using MLE.

None
f_mod bool

If True, applies a correction factor (1 + 3/8κ) to the F-statistic.

True
verbose bool

If True, prints the test summary.

False

Returns:

Name Type Description
result CircularAnovaResult

Dataclass containing the selected statistic, p-value, and supporting metrics.

References
  • Stephens (1972). Multi-sample tests for the von Mises distribution.
  • Cordeiro, Paula, & Botter (1994). Improved likelihood ratio tests for dispersion models.
  • Jammalamadaka & SenGupta (2001). Topics in Circular Statistics, Section 5.3.
Source code in pycircstat2/hypothesis.py
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
def circ_anova(
    samples: list[np.ndarray],
    method: str = "F-test",
    kappa: Optional[float] = None,
    f_mod: bool = True,
    verbose: bool = False,
) -> CircularAnovaResult:
    """
    Circular Analysis of Variance (ANOVA) for multi-sample comparison of mean directions.

    - **H₀**: All groups have the same mean direction.
    - **H₁**: At least one group has a different mean direction.

    Parameters
    ----------
    samples : list of np.ndarray
        List of arrays, where each array contains circular data (angles in radians) for a group.
    method : str, optional
        The test statistic to use. Options:
        - `"F-test"` (default): High-concentration F-test (Stephens 1972).
        - `"LRT"`: Likelihood Ratio Test (Cordeiro et al. 1994).
    kappa : float, optional
        The common concentration parameter (κ). If not specified, it is estimated using MLE.
    f_mod : bool, optional
        If `True`, applies a correction factor `(1 + 3/8κ)` to the F-statistic.
    verbose : bool, optional
        If `True`, prints the test summary.

    Returns
    -------
    result : CircularAnovaResult
        Dataclass containing the selected statistic, p-value, and supporting metrics.

    References
    ----------
    - Stephens (1972). Multi-sample tests for the von Mises distribution.
    - Cordeiro, Paula, & Botter (1994). Improved likelihood ratio tests for dispersion models.
    - Jammalamadaka & SenGupta (2001). Topics in Circular Statistics, Section 5.3.
    """

    # Number of groups
    k = len(samples)
    if k < 2:
        raise ValueError("At least two groups are required for ANOVA.")

    # Sample sizes, mean directions, and resultants
    ns = np.array([len(group) for group in samples])
    Rs = np.array(
        [circ_r(group) * len(group) for group in samples]
    )  # Sum of resultant vectors
    mus = np.array([circ_mean(group) for group in samples])  # Mean directions

    # Overall resultant and mean direction
    all_samples = np.hstack(samples)
    N = len(all_samples)
    R_all = circ_r(all_samples) * N
    mu_all = circ_mean(all_samples)

    # Estimate κ if not provided
    if kappa is None:
        kappa = circ_kappa(R_all / N)
    kappa_value = float(kappa)

    # **F-test**
    if method == "F-test":
        # Between-group and within-group sum of squares
        SS_between = np.sum(Rs) - R_all
        SS_within = N - np.sum(Rs)
        SS_total = N - R_all

        df_between = k - 1
        df_within = N - k
        df_total = N - 1

        MS_between = SS_between / df_between
        MS_within = SS_within / df_within

        # Apply correction factor (Stephens 1972)
        if f_mod:
            F_stat = (1 + 3 / (8 * kappa)) * (MS_between / MS_within)
        else:
            F_stat = MS_between / MS_within

        p_value = 1 - f.cdf(F_stat, df_between, df_within)

        result = CircularAnovaResult(
            method="F-test",
            mu=mus,
            mu_all=float(mu_all),
            kappa=kappa_value,
            kappa_all=kappa_value,
            R=Rs,
            R_all=float(R_all),
            df=(df_between, df_within, df_total),
            statistic=float(F_stat),
            pval=float(p_value),
            SS=(float(SS_between), float(SS_within), float(SS_total)),
            MS=(float(MS_between), float(MS_within)),
        )

    # **Likelihood Ratio Test (LRT)**
    elif method == "LRT":
        # Compute test statistic
        term1 = 1 - (1 / (4 * kappa_value)) * (sum(1 / ns) - 1 / N)
        term2 = 2 * kappa_value * np.sum(Rs * (1 - np.cos(mus - mu_all)))
        chi_square_stat = term1 * term2

        df = k - 1
        p_value = 1 - chi2.cdf(chi_square_stat, df)

        result = CircularAnovaResult(
            method="LRT",
            mu=mus,
            mu_all=float(mu_all),
            kappa=kappa_value,
            kappa_all=kappa_value,
            R=Rs,
            R_all=float(R_all),
            df=int(df),
            statistic=float(chi_square_stat),
            pval=float(p_value),
        )

    else:
        raise ValueError("Invalid method. Choose 'F-test' or 'LRT'.")

    # Print results if verbose is enabled
    if verbose:
        print("\nCircular Analysis of Variance (ANOVA)")
        print("--------------------------------------")
        print(f"Method: {result.method}")
        print(f"Mean Directions (radians): {result.mu}")
        print(f"Overall Mean Direction (radians): {result.mu_all}")
        print(f"Kappa: {result.kappa}")
        print(f"Kappa (overall): {result.kappa_all}")
        print(f"Degrees of Freedom: {result.df}")
        print(f"Test Statistic: {result.statistic:.5f}")
        print(f"P-value: {result.pval:.5f}")
        if method == "F-test":
            print(f"Sum of Squares (Between, Within, Total): {result.SS}")
            print(f"Mean Squares (Between, Within): {result.MS}")
        print("--------------------------------------\n")

    return result

angular_randomisation_test(samples, n_simulation=1000, seed=2046, verbose=False)

The Angular Randomization Test (ART) for homogeneity.

  • H0: The two samples come from the same population.
  • H1: The two samples do not come from the same population.

Parameters:

Name Type Description Default
samples Sequence[Any]

A sequence of Circular objects or one-dimensional array-like radian samples.

required
n_simulation int

Number of permutations for the test. Defaults to 1000.

1000
seed SeedLike

Seed used to initialize the random number generator for the permutation test. Accepts integers, sequences of integers, numpy.random.Generator, numpy.random.BitGenerator, numpy.random.SeedSequence or None. Defaults to 2046.

2046

Returns:

Type Description
AngularRandomisationTestResult

Dataclass containing the observed statistic and permutation p-value.

Reference

Jebur, A. J., & Abushilah, S. F. (2022). Distribution-free two-sample homogeneity test for circular data based on geodesic distance. International Journal of Nonlinear Analysis and Applications, 13(1), 2703-2711.

Source code in pycircstat2/hypothesis.py
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
def angular_randomisation_test(
    samples: Sequence[Any],
    n_simulation: int = 1000,
    seed: SeedLike = 2046,
    verbose: bool = False,
) -> AngularRandomisationTestResult:
    """The Angular Randomization Test (ART) for homogeneity.

    - H0: The two samples come from the same population.
    - H1: The two samples do not come from the same population.

    Parameters
    ----------
    samples: sequence
        A sequence of `Circular` objects or one-dimensional array-like radian samples.
    n_simulation: int, optional
        Number of permutations for the test. Defaults to 1000.
    seed: SeedLike
        Seed used to initialize the random number generator for the permutation test.
        Accepts integers, sequences of integers, ``numpy.random.Generator``,
        ``numpy.random.BitGenerator``, ``numpy.random.SeedSequence`` or ``None``.
        Defaults to 2046.

    Returns
    -------
    AngularRandomisationTestResult
        Dataclass containing the observed statistic and permutation p-value.

    Reference
    ---------
    Jebur, A. J., & Abushilah, S. F. (2022).
    Distribution-free two-sample homogeneity test for circular data based on geodesic distance.
    International Journal of Nonlinear Analysis and Applications, 13(1), 2703-2711.
    """

    normalized = _coerce_circular_samples(samples)

    if len(normalized) != 2:
        raise ValueError("The Angular Randomization Test requires exactly two samples.")
    if n_simulation <= 0:
        raise ValueError("`n_simulation` must be a positive integer.")

    sample_arrays = [np.asarray(sample.alpha, dtype=float) for sample in normalized]
    if any(arr.size == 0 for arr in sample_arrays):
        raise ValueError("Each sample must contain at least one observation.")

    def art_statistic(S1: np.ndarray, S2: np.ndarray) -> float:
        """
        Compute the Angular Randomisation Test (ART) statistic for two groups of circular data.
        Following equations (3.1) and (4.2) from Jebur & Abushilah (2022) .

        Args:
            S1 (np.ndarray): First group of angles in radians (φ values)
            S2 (np.ndarray): Second group of angles in radians (ψ values)

        Returns:
            float: The ART test statistic
        """
        n = len(S1)
        m = len(S2)

        # Compute the scaling factor ((n+m)/(nm))^(-1/2)
        scaling_factor = np.sqrt(n * m / (n + m))

        # Compute sum of all pairwise geodesic distances
        total_distance = circ_pairdist(S1, S2, metric="geodesic", return_sum=True)

        # Scale the total distance and return
        return scaling_factor * total_distance

    # 1. Compute observed test statistic T*₀
    observed_stat = art_statistic(sample_arrays[0], sample_arrays[1])

    # Initialize counter for permutations more extreme than observed
    n_extreme = 1  # Start at 1 to count the observed statistic

    # Combine samples for permutation
    combined_data = np.concatenate(sample_arrays)
    n1 = sample_arrays[0].size

    # Perform permutation test
    if seed is True and verbose is False:
        warnings.warn(
            "Passing `verbose` as a positional argument is deprecated; use keyword arguments.",
            DeprecationWarning,
            stacklevel=2,
        )
        verbose = bool(seed)
        seed = 2046

    rng = _init_rng(seed)

    for _ in range(n_simulation):
        # Randomly permute the combined data
        permuted_data = rng.permutation(combined_data)

        # Split into two groups of original sizes
        perm_S1 = permuted_data[:n1]
        perm_S2 = permuted_data[n1:]

        # Compute test statistic for this permutation
        perm_stat = art_statistic(perm_S1, perm_S2)

        # Count if permuted statistic is >= observed (one-sided test)
        if perm_stat >= observed_stat:
            n_extreme += 1

    # Compute p-value as in equation (4.3)
    p_value = n_extreme / (n_simulation + 1)

    if verbose:
        print("Angular Randomization Test (ART) for Homogeneity")
        print("-------------------------------------------------")
        print("H0: The two samples come from the same population.")
        print("HA: The two samples do not come from the same population.")
        print("")
        print(f"Observed Test Statistic: {observed_stat:.5f}")
        print(f"P-value: {p_value:.5f} {significance_code(p_value)}")

    return AngularRandomisationTestResult(statistic=float(observed_stat), pval=float(p_value), n_simulation=n_simulation)

kuiper_test(alpha, n_simulation=9999, seed=2046, verbose=False)

Kuiper's test for Circular Uniformity.

  • H0: The data in the population are distributed uniformly around the circle.
  • H1: THe data in the population are not disbutrited uniformly around the circle.

This method is for ungrouped data.

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
n_simulation int

Number of simulation for the p-value. If n_simulation=1, the p-value is asymptotically approximated. If n_simulation>1, the p-value is simulated. Default is 9999.

9999
seed SeedLike

Seed used to initialize the random number generator for the simulation-based p-value. Accepts integers, sequences of integers, numpy.random.Generator, numpy.random.BitGenerator, numpy.random.SeedSequence or None. Defaults to 2046.

2046

Returns:

Type Description
KuiperTestResult

Dataclass containing the Kuiper statistic, p-value, simulation mode, and count.

Note

Implementation from R package Directional https://rdrr.io/cran/Directional/src/R/kuiper.R

Source code in pycircstat2/hypothesis.py
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
def kuiper_test(
    alpha: np.ndarray,
    n_simulation: int = 9999,
    seed: SeedLike = 2046,
    verbose: bool = False,
) -> KuiperTestResult:
    """
    Kuiper's test for Circular Uniformity.

    - H0: The data in the population are distributed uniformly around the circle.
    - H1: THe data in the population are not disbutrited uniformly around the circle.

    This method is for ungrouped data.

    Parameters
    ----------

    alpha: np.array
        Angles in radian.

    n_simulation: int
        Number of simulation for the p-value.
        If n_simulation=1, the p-value is asymptotically approximated.
        If n_simulation>1, the p-value is simulated.
        Default is 9999.

    seed: SeedLike
        Seed used to initialize the random number generator for the simulation-based
        p-value. Accepts integers, sequences of integers, ``numpy.random.Generator``,
        ``numpy.random.BitGenerator``, ``numpy.random.SeedSequence`` or ``None``.
        Defaults to 2046.

    Returns
    -------
    KuiperTestResult
        Dataclass containing the Kuiper statistic, p-value, simulation mode, and count.

    Note
    ----
    Implementation from R package `Directional`
    https://rdrr.io/cran/Directional/src/R/kuiper.R
    """

    if n_simulation <= 0:
        raise ValueError("`n_simulation` must be a positive integer.")

    alpha = np.asarray(alpha, dtype=float)
    if alpha.size == 0:
        raise ValueError("`alpha` must contain at least one angle.")

    def compute_V(sample):
        ordered = np.sort(sample) / (2 * np.pi)
        n = ordered.size
        indices = np.arange(1, n + 1, dtype=float)

        D_plus = np.max(indices / n - ordered)
        D_minus = np.max(ordered - (indices - 1) / n)
        f = np.sqrt(n) + 0.155 + 0.24 / np.sqrt(n)
        V = f * (D_plus + D_minus)
        return float(V), float(f)

    n = alpha.size
    Vo, f = compute_V(alpha)

    if seed is True and verbose is False:
        warnings.warn(
            "Passing `verbose` as a positional argument is deprecated; use keyword arguments.",
            DeprecationWarning,
            stacklevel=2,
        )
        verbose = bool(seed)
        seed = 2046

    if n_simulation == 1:
        # asymptotic p-value
        mode = "asymptotic"
        m = (np.arange(1, 50, dtype=float)) ** 2
        a1 = 4 * m * Vo**2
        a2 = np.exp(-2 * m * Vo**2)
        b1 = 2 * (a1 - 1) * a2
        b2 = 8 * Vo / (3 * f) * m * (a1 - 3) * a2
        pval = float(np.sum(b1 - b2))
    else:
        mode = "simulation"
        rng = _init_rng(seed)
        uniforms = rng.uniform(low=0.0, high=2 * np.pi, size=(n, n_simulation))
        x = np.sort(uniforms, axis=0)
        Vs = np.array([compute_V(x[:, i])[0] for i in range(n_simulation)])
        pval = float((np.count_nonzero(Vs >= Vo) + 1) / (n_simulation + 1))

    if verbose:
        print("Kuiper's Test of Circular Uniformity")
        print("------------------------------------")
        print("H0: The sample is drawn from a circularly uniform distribution.")
        print("HA: The sample is not drawn from a circularly uniform distribution.")
        print("")
        print(f"Test Statistic: {Vo:.4f}")
        print(f"P-value = {pval} {significance_code(pval)}")

    return KuiperTestResult(V=float(Vo), pval=float(pval), mode=mode, n_simulation=n_simulation)

watson_test(alpha, n_simulation=9999, seed=2046, verbose=False)

Watson's Goodness-of-Fit Testing, aka Watson one-sample U2 test.

  • H0: The sample data come from a population distributed uniformly around the circle.
  • H1: The sample data do not come from a population distributed uniformly around the circle.

This method is for ungrouped data.

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
n_simulation int

Number of simulation for the p-value. If n_simulation=1, the p-value is asymptotically approximated. If n_simulation>1, the p-value is simulated.

9999
seed SeedLike

Seed used to initialize the random number generator for the simulation-based p-value. Accepts integers, sequences of integers, numpy.random.Generator, numpy.random.BitGenerator, numpy.random.SeedSequence or None. Defaults to 2046.

2046

Returns:

Type Description
WatsonTestResult

Dataclass containing the Watson U² statistic, p-value, and simulation details.

Note

Implementation from R package Directional https://rdrr.io/cran/Directional/src/R/watson.R

The code for simulated p-value in Directional (v5.7) seems to be just copied from kuiper(), thus yield in wrong results.

See Also

kuiper_test(); rao_spacing_test()

Source code in pycircstat2/hypothesis.py
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
def watson_test(
    alpha: np.ndarray,
    n_simulation: int = 9999,
    seed: SeedLike = 2046,
    verbose: bool = False,
) -> WatsonTestResult:
    """
    Watson's Goodness-of-Fit Testing, aka Watson one-sample U2 test.

    - H0: The sample data come from a population distributed uniformly around the circle.
    - H1: The sample data do not come from a population distributed uniformly around the circle.

    This method is for ungrouped data.

    Parameters
    ----------

    alpha: np.array
        Angles in radian.

    n_simulation: int
        Number of simulation for the p-value.
        If n_simulation=1, the p-value is asymptotically approximated.
        If n_simulation>1, the p-value is simulated.

    seed: SeedLike
        Seed used to initialize the random number generator for the simulation-based
        p-value. Accepts integers, sequences of integers, ``numpy.random.Generator``,
        ``numpy.random.BitGenerator``, ``numpy.random.SeedSequence`` or ``None``.
        Defaults to 2046.

    Returns
    -------
    WatsonTestResult
        Dataclass containing the Watson U² statistic, p-value, and simulation details.

    Note
    ----
    Implementation from R package `Directional`
    https://rdrr.io/cran/Directional/src/R/watson.R

    The code for simulated p-value in Directional (v5.7) seems to be just copied from
    kuiper(), thus yield in wrong results.

    See Also
    --------
    kuiper_test(); rao_spacing_test()
    """

    if n_simulation <= 0:
        raise ValueError("`n_simulation` must be a positive integer.")

    alpha = np.asarray(alpha, dtype=float)
    if alpha.size == 0:
        raise ValueError("`alpha` must contain at least one angle.")

    def compute_U2(sample):
        ordered = np.sort(sample)
        n = ordered.size
        indices = np.arange(1, n + 1, dtype=float)

        u = ordered / (2 * np.pi)
        U2 = np.sum(((u - (indices - 0.5) / n) - (np.sum(u) / n - 0.5)) ** 2) + 1 / (12 * n)
        return float(U2)

    n = alpha.size
    U2o = compute_U2(alpha)

    if seed is True and verbose is False:
        warnings.warn(
            "Passing `verbose` as a positional argument is deprecated; use keyword arguments.",
            DeprecationWarning,
            stacklevel=2,
        )
        verbose = bool(seed)
        seed = 2046

    if n_simulation == 1:
        mode = "asymptotic"
        m = np.arange(1, 51)
        pval = float(2 * sum((-1) ** (m - 1) * np.exp(-2 * m**2 * np.pi**2 * U2o)))
    else:
        mode = "simulation"
        rng = _init_rng(seed)
        uniforms = rng.uniform(low=0.0, high=2 * np.pi, size=(n, n_simulation))
        x = np.sort(uniforms, axis=0)
        U2s = np.array([compute_U2(x[:, i]) for i in range(n_simulation)])
        pval = float((np.count_nonzero(U2s >= U2o) + 1) / (n_simulation + 1))

    if verbose:
        print("Watson's One-Sample U2 Test of Circular Uniformity")
        print("--------------------------------------------------")
        print("H0: The sample is drawn from a circularly uniform distribution.")
        print("HA: The sample is not drawn from a circularly uniform distribution.")
        print("")
        print(f"Test Statistic: {U2o:.4f}")
        print(f"P-value = {pval} {significance_code(pval)}")

    return WatsonTestResult(U2=float(U2o), pval=float(pval), mode=mode, n_simulation=n_simulation)

rao_spacing_test(alpha, w=None, kappa=1000.0, n_simulation=9999, seed=2046, verbose=False)

Simulation based Rao's spacing test.

  • H0: The sample data come from a population distributed uniformly around the circle.
  • H1: The sample data do not come from a population distributed uniformly around the circle.

This method is for both grouped and ungrouped data.

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
w Union[ndarray, None]

Frequencies

None
kappa float

Concentration parameter. Only use for grouped data.

1000.0
n_simulation int

Number of simulations.

9999
seed SeedLike

Seed used to initialize the random number generator for the simulation-based p-value. Accepts integers, sequences of integers, numpy.random.Generator, numpy.random.BitGenerator, numpy.random.SeedSequence or None. Defaults to 2046.

2046

Returns:

Type Description
RaoSpacingTestResult

Dataclass containing the Rao spacing statistic (degrees), p-value, method, and simulation count.

Reference

Landler et al. (2019) https://movementecologyjournal.biomedcentral.com/articles/10.1186/s40462-019-0160-x

Source code in pycircstat2/hypothesis.py
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
def rao_spacing_test(
    alpha: np.ndarray,
    w: Union[np.ndarray, None] = None,
    kappa: float = 1000.0,
    n_simulation: int = 9999,
    seed: SeedLike = 2046,
    verbose: bool = False,
) -> RaoSpacingTestResult:
    """Simulation based Rao's spacing test.

    - H0: The sample data come from a population distributed uniformly around the circle.
    - H1: The sample data do not come from a population distributed uniformly around the circle.

    This method is for both grouped and ungrouped data.

    Parameters
    ----------
    alpha: np.ndarray
        Angles in radian.

    w: np.ndarray or None
        Frequencies

    kappa: float
        Concentration parameter. Only use for grouped data.

    n_simulation: int
        Number of simulations.

    seed: SeedLike
        Seed used to initialize the random number generator for the simulation-based
        p-value. Accepts integers, sequences of integers, ``numpy.random.Generator``,
        ``numpy.random.BitGenerator``, ``numpy.random.SeedSequence`` or ``None``.
        Defaults to 2046.

    Returns
    -------
    RaoSpacingTestResult
        Dataclass containing the Rao spacing statistic (degrees), p-value, method, and simulation count.

    Reference
    ---------
    Landler et al. (2019)
    https://movementecologyjournal.biomedcentral.com/articles/10.1186/s40462-019-0160-x
    """

    if n_simulation <= 0:
        raise ValueError("`n_simulation` must be a positive integer.")

    alpha = np.asarray(alpha, dtype=float)
    if alpha.size == 0:
        raise ValueError("`alpha` must contain at least one angle.")

    def compute_U(sample):
        ordered = np.sort(sample)
        n_local = ordered.size
        spacings = np.hstack([ordered[1:] - ordered[:-1], 2 * np.pi - ordered[-1] + ordered[0]])
        return 0.5 * np.sum(np.abs(spacings - (2 * np.pi / n_local)))

    if w is not None:
        w = np.asarray(w, dtype=float)
        if np.any(w < 0):
            raise ValueError("`w` must contain non-negative frequencies.")
        if not np.all(np.isclose(w, np.round(w))):
            raise ValueError("`w` must contain integer frequencies.")
        w = w.astype(int)
        if w.shape != alpha.shape:
            raise ValueError("`w` must have the same shape as `alpha`.")
        n = int(np.sum(w))
        if n <= 0:
            raise ValueError("Sum of weights must be positive.")
        m = alpha.size
        expanded_alpha = np.repeat(alpha, w)
        mode = "grouped"
    else:
        expanded_alpha = alpha
        n = expanded_alpha.size
        mode = "ungrouped"

    if seed is True and verbose is False:
        warnings.warn(
            "Passing `verbose` as a positional argument is deprecated; use keyword arguments.",
            DeprecationWarning,
            stacklevel=2,
        )
        verbose = bool(seed)
        seed = 2046

    rng = _init_rng(seed)

    Uo = compute_U(expanded_alpha)
    if w is not None:  # noncontinuous / grouped data
        vm_dist = vonmises(kappa=kappa)
        uniforms = rng.uniform(low=0.0, high=2 * np.pi, size=(n_simulation, n))
        snapped = np.floor(uniforms * m / (2 * np.pi)) * (2 * np.pi / m)
        noise = vm_dist.rvs(size=(n_simulation, n), random_state=rng)
        samples = angmod(snapped + noise)
        Us = np.array([compute_U(sample) for sample in samples])
    else:
        samples = rng.uniform(low=0.0, high=2 * np.pi, size=(n_simulation, n))
        Us = np.array([compute_U(sample) for sample in samples])

    counter = np.count_nonzero(Us >= Uo)
    pval = float((counter + 1) / (n_simulation + 1))

    if verbose:
        print("Rao's Spacing Test of Circular Uniformity")
        print("-----------------------------------------")
        print("H0: The sample is drawn from a circularly uniform distribution.")
        print("HA: The sample is not drawn from a circularly uniform distribution.")
        print("")
        print(f"Test Statistic: {Uo:.4f}")
        print(f"P-value = {pval}\n")

    return RaoSpacingTestResult(
        statistic=float(np.rad2deg(Uo)),
        pval=float(pval),
        mode=mode,
        n_simulation=n_simulation,
    )

circ_range_test(alpha, verbose=False)

Perform the Circular Range Test for uniformity.

  • H0: The data is uniformly distributed around the circle.
  • H1: The data is non-uniformly distributed (clustered).

Parameters:

Name Type Description Default
alpha ndarray

Angles in radians. Values must already be wrapped into [-2π, 2π].

required
verbose bool

If True, prints test details and results.

False

Returns:

Type Description
CircularRangeTestResult

Dataclass containing the range statistic and corresponding p-value.

Reference

P162, Section 7.2.3 of Jammalamadaka, S. Rao and SenGupta, A. (2001)

Source code in pycircstat2/hypothesis.py
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
def circ_range_test(alpha: np.ndarray, verbose: bool = False) -> CircularRangeTestResult:
    """
    Perform the Circular Range Test for uniformity.

    - **H0**: The data is uniformly distributed around the circle.
    - **H1**: The data is non-uniformly distributed (clustered).

    Parameters
    ----------
    alpha : np.ndarray
        Angles in radians. Values must already be wrapped into ``[-2π, 2π]``.
    verbose : bool, optional
        If ``True``, prints test details and results.

    Returns
    -------
    CircularRangeTestResult
        Dataclass containing the range statistic and corresponding p-value.

    Reference
    ---------
    P162, Section 7.2.3 of Jammalamadaka, S. Rao and SenGupta, A. (2001)
    """
    alpha = np.asarray(alpha, dtype=float)
    if alpha.size == 0:
        raise ValueError("`alpha` must contain at least one angle.")

    if np.any(np.abs(alpha) > 2 * np.pi + 1e-8):
        raise ValueError("`alpha` must be provided in radians within [-2π, 2π].")

    range_stat = circ_range(alpha)  # Compute test statistic

    # Compute p-value using approximation formula from CircStats (if available)
    n = alpha.size
    stop = int(np.floor(1 / (1 - range_stat / (2 * np.pi))))
    index = np.arange(1, stop + 1)

    # Compute p-value using series expansion
    sequence = (
        ((-1) ** (index - 1))
        * comb(n, index)
        * (1 - index * (1 - range_stat / (2 * np.pi))) ** (n - 1)
    )
    p_value = float(np.sum(sequence))

    result = CircularRangeTestResult(range_stat=float(range_stat), pval=float(p_value))

    if verbose:
        range_deg = float(np.rad2deg(result.range_stat))
        print("Circular Range Test of Uniformity")
        print("---------------------------------")
        print("H0: The sample is uniformly distributed around the circle.")
        print("HA: The sample exhibits clustering (non-uniformity).")
        print("")
        print(f"Sample size: {n}")
        print(f"Range statistic: {result.range_stat:.5f} rad ({range_deg:.2f}°)")
        print(f"P-value: {result.pval:.5g} {significance_code(result.pval)}")

    return result

binomial_test(alpha, md, verbose=False)

Perform the binomial test for the median direction of circular data.

This test evaluates whether the population median angle is equal to a specified value.

  • H0: The population has median angle md.
  • H1: The population does not have median angle md.

Parameters:

Name Type Description Default
alpha ndarray

Sample of angles in radians.

required
md float

Hypothesized median angle.

required
verbose bool

If True, prints test details and results.

False

Returns:

Type Description
BinomialTestResult

Dataclass containing the p-value and counts on each side of the hypothesized median.

References

Zar, J. H. (2010). Biostatistical Analysis. Section 27.4.

Source code in pycircstat2/hypothesis.py
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
def binomial_test(
    alpha: np.ndarray,
    md: float,
    verbose: bool = False,
) -> BinomialTestResult:
    """
    Perform the binomial test for the median direction of circular data.

    This test evaluates whether the population median angle is equal to a specified value.

    - **H0**: The population has median angle `md`.
    - **H1**: The population does not have median angle `md`.

    Parameters
    ----------
    alpha : np.ndarray
        Sample of angles in radians.
    md : float
        Hypothesized median angle.
    verbose : bool, optional
        If ``True``, prints test details and results.

    Returns
    -------
    BinomialTestResult
        Dataclass containing the p-value and counts on each side of the hypothesized median.

    References
    ----------
    Zar, J. H. (2010). Biostatistical Analysis. Section 27.4.
    """
    from scipy.stats import binom

    alpha = np.asarray(alpha, dtype=float)
    if alpha.size == 0:
        raise ValueError("`alpha` must contain at least one angle.")

    if np.ndim(md) != 0:
        raise ValueError("The median (md) must be a single scalar value.")

    # Compute circular differences from hypothesized median
    d = circ_dist(alpha, float(md))

    # Count the number of angles on each side of the hypothesized median
    n1 = int(np.sum(d < 0))
    n2 = int(np.sum(d > 0))
    n_eff = int(n1 + n2)
    if n_eff == 0:
        result = BinomialTestResult(pval=1.0, n_eff=0, n1=n1, n2=n2)
    else:
        # Compute p-value using binomial test
        n_min = int(min(n1, n2))
        pval = float(2 * binom.cdf(n_min, n_eff, 0.5))
        pval = min(pval, 1.0)
        result = BinomialTestResult(pval=pval, n_eff=n_eff, n1=n1, n2=n2)

    if verbose:
        print("Circular Binomial Test for Median Direction")
        print("--------------------------------------------")
        print(f"H0: Median direction equals {float(md):.5f} rad.")
        print("HA: Median direction differs from the hypothesized value.")
        print("")
        print(f"Effective sample size: {result.n_eff}")
        print(f"Counts below/above median: n1 = {result.n1}, n2 = {result.n2}")
        print(f"P-value: {result.pval:.5f} {significance_code(result.pval)}")

    return result

concentration_test(alpha1, alpha2, verbose=False)

Parametric two-sample test for concentration equality in circular data.

This test determines whether two von Mises-type samples have different concentration parameters (i.e., different dispersions).

  • H0: The two samples have the same concentration parameter.
  • H1: The two samples have different concentration parameters.

Parameters:

Name Type Description Default
alpha1 ndarray

First sample of circular data (radians).

required
alpha2 ndarray

Second sample of circular data (radians).

required
verbose bool

If True, prints test details and results.

False

Returns:

Type Description
ConcentrationTestResult

Dataclass with the F statistic, p-value, and associated degrees of freedom.

Notes
  • This test assumes that both samples follow von Mises distributions.
  • The resultant vector length of the combined samples should be greater than 0.7 for validity.
  • Based on Batschelet (1980), Section 6.9, p. 122-124.
References

Batschelet, E. (1980). Circular Statistics in Biology. Academic Press.

Source code in pycircstat2/hypothesis.py
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
def concentration_test(
    alpha1: np.ndarray,
    alpha2: np.ndarray,
    verbose: bool = False,
) -> ConcentrationTestResult:
    """
    Parametric two-sample test for concentration equality in circular data.

    This test determines whether two von Mises-type samples have different
    concentration parameters (i.e., different dispersions).

    - **H0**: The two samples have the same concentration parameter.
    - **H1**: The two samples have different concentration parameters.

    Parameters
    ----------
    alpha1 : np.ndarray
        First sample of circular data (radians).
    alpha2 : np.ndarray
        Second sample of circular data (radians).
    verbose : bool, optional
        If ``True``, prints test details and results.

    Returns
    -------
    ConcentrationTestResult
        Dataclass with the F statistic, p-value, and associated degrees of freedom.

    Notes
    -----
    - This test assumes that both samples follow von Mises distributions.
    - The **resultant vector length** of the combined samples should be greater than 0.7 for validity.
    - Based on Batschelet (1980), Section 6.9, p. 122-124.

    References
    ----------
    Batschelet, E. (1980). Circular Statistics in Biology. Academic Press.
    """
    # Ensure inputs are numpy arrays
    alpha1 = np.asarray(alpha1, dtype=float)
    alpha2 = np.asarray(alpha2, dtype=float)

    # Sample sizes
    n1, n2 = len(alpha1), len(alpha2)
    if min(n1, n2) < 2:
        raise ValueError("Both samples must contain at least two observations.")

    # Compute resultant vector lengths
    R1 = n1 * circ_r(alpha1)
    R2 = n2 * circ_r(alpha2)

    # Compute mean resultant length of combined samples
    rbar = (R1 + R2) / (n1 + n2)

    # Warn if rbar is too low
    if rbar < 0.7:
        warnings.warn(
            "The resultant vector length should exceed 0.7 for the concentration test to be reliable.",
            RuntimeWarning,
            stacklevel=2,
        )

    # Compute F-statistic
    df1 = n1 - 1
    df2 = n2 - 1
    numerator = df2 * (n1 - R1)
    denominator = df1 * (n2 - R2)
    if denominator <= 0 or numerator <= 0:
        raise ValueError("Degenerate data: cannot compute concentration test statistic.")
    f_stat = numerator / denominator

    # Compute p-value (adjusting for F-stat symmetry)
    if f_stat >= 1:
        pval = 2 * f.sf(f_stat, df1, df2)
    else:
        pval = 2 * f.sf(1 / f_stat, df2, df1)

    result = ConcentrationTestResult(
        f_stat=float(f_stat),
        pval=float(min(pval, 1.0)),
        df1=int(df1),
        df2=int(df2),
    )

    if verbose:
        print("Concentration Equality Test")
        print("---------------------------")
        print("H0: Both samples share the same concentration parameter (κ).")
        print("HA: The samples have different concentration parameters.")
        print("")
        print(f"Sample sizes: n1 = {n1}, n2 = {n2}")
        print(
            f"F statistic: {result.f_stat:.5f} "
            f"(df1 = {result.df1}, df2 = {result.df2})"
        )
        print(f"P-value: {result.pval:.5f} {significance_code(result.pval)}")

    return result

rao_homogeneity_test(samples, alpha=0.05, verbose=False)

Perform Rao's test for homogeneity on multiple samples of angular data.

  • Test 1: Equality of Mean Directions (Polar Vectors)
  • Test 2: Equality of Dispersions

Parameters:

Name Type Description Default
samples list of np.ndarray

A list where each entry is a vector of angular values (in radians).

required
alpha float

Significance level for the hypothesis test. Default is 0.05.

0.05
verbose bool

If True, prints test details and decisions.

False

Returns:

Type Description
RaoHomogeneityTestResult

Dataclass containing test statistics, p-values, and rejection flags.

References

Jammalamadaka, S. Rao and SenGupta, A. (2001). Topics in Circular Statistics, Section 7.6.1. Rao, J.S. (1967). Large sample tests for the homogeneity of angular data, Sankhya, Ser, B., 28.

Source code in pycircstat2/hypothesis.py
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
def rao_homogeneity_test(
    samples: list,
    alpha: float = 0.05,
    verbose: bool = False,
) -> RaoHomogeneityTestResult:
    """
    Perform Rao's test for homogeneity on multiple samples of angular data.

    - **Test 1**: Equality of Mean Directions (Polar Vectors)
    - **Test 2**: Equality of Dispersions

    Parameters
    ----------
    samples : list of np.ndarray
        A list where each entry is a vector of angular values (in radians).
    alpha : float, optional
        Significance level for the hypothesis test. Default is 0.05.
    verbose : bool, optional
        If ``True``, prints test details and decisions.

    Returns
    -------
    RaoHomogeneityTestResult
        Dataclass containing test statistics, p-values, and rejection flags.

    References
    ----------
    Jammalamadaka, S. Rao and SenGupta, A. (2001). Topics in Circular Statistics, Section 7.6.1.
    Rao, J.S. (1967). Large sample tests for the homogeneity of angular data, Sankhya, Ser, B., 28.
    """
    if not isinstance(samples, list) or not all(
        isinstance(s, np.ndarray) for s in samples
    ):
        raise ValueError("Input must be a list of numpy arrays.")

    k = len(samples)  # Number of samples
    n = np.array([len(s) for s in samples])  # Sample sizes

    # Compute mean cosine and sine values for each sample
    cos_means = np.array([np.mean(np.cos(s)) for s in samples])
    sin_means = np.array([np.mean(np.sin(s)) for s in samples])

    # Compute variances
    # Compute sample variances (use ddof=1 to match R)
    var_cos = np.array([np.var(np.cos(s), ddof=1) for s in samples])
    var_sin = np.array([np.var(np.sin(s), ddof=1) for s in samples])

    # Compute covariance (use ddof=1 to match R's var(x, y))
    cov_cos_sin = np.array(
        [np.cov(np.cos(s), np.sin(s), ddof=1)[0, 1] for s in samples]
    )

    # Compute test statistics
    s_polar = (
        1
        / n
        * (
            var_sin / cos_means**2
            + (sin_means**2 * var_cos) / cos_means**4
            - (2 * sin_means * cov_cos_sin) / cos_means**3
        )
    )
    tan_means = sin_means / cos_means
    H_polar = np.sum(tan_means**2 / s_polar) - (
        np.sum(tan_means / s_polar) ** 2
    ) / np.sum(1 / s_polar)

    U = cos_means**2 + sin_means**2
    s_disp = (
        4
        / n
        * (
            cos_means**2 * var_cos
            + sin_means**2 * var_sin
            + 2 * cos_means * sin_means * cov_cos_sin
        )
    )
    H_disp = np.sum(U**2 / s_disp) - (np.sum(U / s_disp) ** 2) / np.sum(1 / s_disp)

    # Compute p-values
    df = k - 1  # Degrees of freedom
    pval_polar = 1 - chi2.cdf(H_polar, df)
    pval_disp = 1 - chi2.cdf(H_disp, df)

    # Determine critical values
    crit_polar = chi2.ppf(1 - alpha, df)
    crit_disp = chi2.ppf(1 - alpha, df)

    # Test decisions
    reject_polar = H_polar > crit_polar
    reject_disp = H_disp > crit_disp

    result = RaoHomogeneityTestResult(
        H_polar=float(H_polar),
        pval_polar=float(pval_polar),
        reject_polar=bool(reject_polar),
        H_disp=float(H_disp),
        pval_disp=float(pval_disp),
        reject_disp=bool(reject_disp),
    )

    if verbose:
        print("Rao's Homogeneity Test")
        print("----------------------")
        print("Test 1 H0: All groups share the same mean direction.")
        print("Test 2 H0: All groups share the same dispersion.")
        print("")
        print(
            f"Mean directions: H = {result.H_polar:.5f}, "
            f"p = {result.pval_polar:.5f} {significance_code(result.pval_polar)}; "
            f"reject @ α={alpha}: {result.reject_polar}"
        )
        print(
            f"Dispersions:     H = {result.H_disp:.5f}, "
            f"p = {result.pval_disp:.5f} {significance_code(result.pval_disp)}; "
            f"reject @ α={alpha}: {result.reject_disp}"
        )

    return result

change_point_test(alpha, verbose=False)

Perform a change point test for mean direction, concentration, or both.

Parameters:

Name Type Description Default
alpha ndarray

Vector of angular measurements in radians.

required
verbose bool

If True, prints test details and summary statistics.

False

Returns:

Type Description
ChangePointTestResult

Dataclass containing the change point statistics.

References

Jammalamadaka, S. Rao and SenGupta, A. (2001). Topics in Circular Statistics, Chapter 11.

Notes

Ported from change.pt() function in the CircStats package for R.

Source code in pycircstat2/hypothesis.py
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
def change_point_test(alpha, verbose: bool = False) -> ChangePointTestResult:
    """
    Perform a change point test for mean direction, concentration, or both.

    Parameters
    ----------
    alpha : np.ndarray
        Vector of angular measurements in radians.
    verbose : bool, optional
        If ``True``, prints test details and summary statistics.

    Returns
    -------
    ChangePointTestResult
        Dataclass containing the change point statistics.

    References
    ----------
    Jammalamadaka, S. Rao and SenGupta, A. (2001). Topics in Circular Statistics, Chapter 11.

    Notes
    -----
    Ported from `change.pt()` function in the `CircStats` package for R.
    """

    def phi(x):
        """Helper function for phi computation."""
        inv = A1inv(x)
        bessel = i0(inv)
        if np.isinf(bessel):
            corr = (
                inv
                + np.log(
                    1
                    / np.sqrt(2 * np.pi * inv)
                    * (1 + 1 / (8 * inv) + 9 / (128 * inv**2) + 225 / (1024 * inv**3))
                )
            )
        else:
            corr = np.log(bessel)
        return x * inv - corr

    def est_rho(alpha):
        """Estimate mean resultant length (rho)."""
        return np.linalg.norm(np.sum(np.exp(1j * alpha))) / len(alpha)

    n = len(alpha)
    if n < 4:
        raise ValueError("Sample size must be at least 4 for change point test.")

    rho = est_rho(alpha)

    R1, R2, V = np.zeros(n), np.zeros(n), np.zeros(n)

    for k in range(1, n):
        R1[k - 1] = est_rho(alpha[:k]) * k
        R2[k - 1] = est_rho(alpha[k:]) * (n - k)

        if 2 <= k <= (n - 2):
            V[k - 1] = (k / n) * phi(R1[k - 1] / k) + ((n - k) / n) * phi(
                R2[k - 1] / (n - k)
            )

    R1[-1] = rho * n
    R2[-1] = 0

    R_diff = R1 + R2 - rho * n
    rmax = np.max(R_diff)
    k_r = np.argmax(R_diff)
    rave = np.mean(R_diff)

    if n > 3:
        V = V[1 : n - 2]
        tmax = np.max(V)
        k_t = np.argmax(V) + 1
        tave = np.mean(V)
    else:
        raise ValueError("Sample size must be at least 4.")

    result = ChangePointTestResult(
        n=int(n),
        rho=float(rho),
        rmax=float(rmax),
        k_r=int(k_r),
        rave=float(rave),
        tmax=float(tmax),
        k_t=int(k_t),
        tave=float(tave),
    )

    if verbose:
        print("Circular Change Point Test")
        print("--------------------------")
        print("H0: No change point in mean direction or concentration.")
        print("HA: A change point is present in the sequence.")
        print("")
        print(f"Sample size: {result.n}")
        print(f"Overall resultant length (ρ): {result.rho:.5f}")
        print(f"Max R statistic: {result.rmax:.5f} at k = {result.k_r}")
        print(f"Average R statistic: {result.rave:.5f}")
        print(f"Max T statistic: {result.tmax:.5f} at k = {result.k_t}")
        print(f"Average T statistic: {result.tave:.5f}")

    return result

harrison_kanji_test(alpha, idp, idq, inter=True, fn=None, verbose=False)

Harrison-Kanji Test (Two-Way ANOVA) for Circular Data.

Parameters:

Name Type Description Default
alpha ndarray

Angular measurements (radians).

required
idp ndarray

Factor A identifiers for each observation.

required
idq ndarray

Factor B identifiers for each observation.

required
inter bool

Whether to include the interaction term. Defaults to True.

True
fn list

Names for the two factors. Defaults to ["A", "B"].

None
verbose bool

If True, prints test details and results.

False
Source code in pycircstat2/hypothesis.py
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
def harrison_kanji_test(
    alpha: np.ndarray,
    idp: np.ndarray,
    idq: np.ndarray,
    inter: bool = True,
    fn: Optional[list] = None,
    verbose: bool = False,
) -> HarrisonKanjiTestResult:
    """
    Harrison-Kanji Test (Two-Way ANOVA) for Circular Data.

    Parameters
    ----------
    alpha : np.ndarray
        Angular measurements (radians).
    idp : np.ndarray
        Factor A identifiers for each observation.
    idq : np.ndarray
        Factor B identifiers for each observation.
    inter : bool, optional
        Whether to include the interaction term. Defaults to ``True``.
    fn : list, optional
        Names for the two factors. Defaults to ``["A", "B"]``.
    verbose : bool, optional
        If ``True``, prints test details and results.
    """

    if fn is None:
        fn = ["A", "B"]

    # Ensure data is in column format
    alpha = np.asarray(alpha).flatten()
    idp = np.asarray(idp).flatten()
    idq = np.asarray(idq).flatten()

    # Number of factor levels
    p = len(np.unique(idp))
    q = len(np.unique(idq))

    # Data frame for aggregation
    df = pd.DataFrame({fn[0]: idp, fn[1]: idq, "dependent": alpha})
    n = len(df)

    # Total resultant vector length
    tr = n * circ_r(np.array(df["dependent"].values))
    kk = circ_kappa(tr / n)

    # Compute mean resultants per group
    gr = df.groupby(fn)
    cn = gr.count()
    cr = gr.agg(circ_r) * cn
    cn = cn.unstack(fn[1])
    cr = cr.unstack(fn[1])

    # Factor A
    gr = df.groupby(fn[0])
    pn = gr.count()["dependent"]
    pr = gr.agg(circ_r)["dependent"] * pn

    # Factor B
    gr = df.groupby(fn[1])
    qn = gr.count()["dependent"]
    qr = gr.agg(circ_r)["dependent"] * qn

    if kk > 2:  # Large kappa approximation
        eff_1 = sum(pr**2 / np.sum(cn, axis=1)) - tr**2 / n
        df_1 = p - 1
        ms_1 = eff_1 / df_1

        eff_2 = sum(qr**2 / np.sum(cn, axis=0)) - tr**2 / n
        df_2 = q - 1
        ms_2 = eff_2 / df_2

        eff_t = n - tr**2 / n
        df_t = n - 1
        m = np.asarray(cn.values).mean()

        if inter:
            beta = 1 / (1 - 1 / (5 * kk) - 1 / (10 * (kk**2)))

            eff_r = n - np.asarray((cr**2.0 / cn).values).sum()
            df_r = p * q * (m - 1)
            ms_r = eff_r / df_r

            eff_i = (
                np.asarray((cr**2.0 / cn).values).sum()
                - sum(qr**2.0 / qn)
                - sum(pr**2.0 / pn)
                + tr**2 / n
            )
            df_i = (p - 1) * (q - 1)
            ms_i = eff_i / df_i

            FI = ms_i / ms_r
            pI = 1 - f.cdf(FI, df_i, df_r)  # `f.cdf` is now unambiguous
        else:
            eff_r = n - sum(qr**2.0 / qn) - sum(pr**2.0 / pn) + tr**2 / n
            df_r = (p - 1) * (q - 1)
            ms_r = eff_r / df_r

            eff_i, df_i, ms_i, FI, pI = None, None, None, None, np.nan
            beta = 1

        F1 = beta * ms_1 / ms_r
        p1 = 1 - f.cdf(F1, df_1, df_r)

        F2 = beta * ms_2 / ms_r
        p2 = 1 - f.cdf(F2, df_2, df_r)

    else:  # Small kappa approximation
        rr = iv(1, kk) / iv(0, kk)
        kappa_factor = 2 / (1 - rr**2)  # Renamed `f` to `kappa_factor`

        chi1 = kappa_factor * (sum(pr**2.0 / pn) - tr**2 / n)
        df_1 = 2 * (p - 1)
        p1 = 1 - chi2.cdf(chi1, df=df_1)

        chi2_val = kappa_factor * (sum(qr**2.0 / qn) - tr**2 / n)
        df_2 = 2 * (q - 1)
        p2 = 1 - chi2.cdf(chi2_val, df=df_2)

        chiI = kappa_factor * (
            np.asarray((cr**2.0 / cn).values).sum()
            - sum(pr**2.0 / pn)
            - sum(qr**2.0 / qn)
            + tr**2 / n
        )
        df_i = (p - 1) * (q - 1)
        pI = chi2.sf(chiI, df=df_i)

    pval = float(p1.squeeze()), float(p2.squeeze()), float(np.squeeze(pI))

    # Construct ANOVA Table
    if kk > 2:
        table = pd.DataFrame(
            {
                "Source": fn + ["Interaction", "Residual", "Total"],
                "DoF": [df_1, df_2, df_i, df_r, df_t],
                "SS": [eff_1, eff_2, eff_i, eff_r, eff_t],
                "MS": [ms_1, ms_2, ms_i, ms_r, np.nan],
                "F": [np.squeeze(F1), np.squeeze(F2), FI, np.nan, np.nan],
                "p": list(pval) + [np.nan, np.nan],
            }
        ).set_index("Source")
    else:
        table = pd.DataFrame(
            {
                "Source": fn + ["Interaction"],
                "DoF": [df_1, df_2, df_i],
                "chi2": [chi1.squeeze(), chi2_val.squeeze(), chiI.squeeze()],
                "p": pval,
            }
        ).set_index("Source")

    result = HarrisonKanjiTestResult(p_values=pval, anova_table=table)

    if verbose:
        p_a, p_b, p_inter = result.p_values

        def _fmt(p: Optional[float]) -> str:
            if p is None or (isinstance(p, float) and math.isnan(p)):
                return "n/a"
            return f"{p:.5f} {significance_code(p)}"

        print("Harrison-Kanji Two-Way Circular ANOVA")
        print("-------------------------------------")
        print(f"H0 ({fn[0]}): No difference in mean direction across factor {fn[0]}.")
        print(f"H0 ({fn[1]}): No difference in mean direction across factor {fn[1]}.")
        if inter:
            print("H0 (Interaction): No interaction between the two factors.")
        print("")
        print(f"{fn[0]} effect p-value: {_fmt(p_a)}")
        print(f"{fn[1]} effect p-value: {_fmt(p_b)}")
        if inter:
            print(f"Interaction p-value: {_fmt(p_inter)}")
        print("")
        print("ANOVA table (first rows):")
        print(result.anova_table.head())

    return result

equal_kappa_test(samples, verbose=False)

Test for Homogeneity of Concentration Parameters (κ) in Circular Data.

  • H₀: All groups have the same concentration parameter (κ).
  • H₁: At least one group has a different κ.

Parameters:

Name Type Description Default
samples list of np.ndarray

List of circular data arrays (angles in radians) for different groups.

required
verbose bool

If True, prints the test summary.

False

Returns:

Type Description
EqualKappaTestResult

Dataclass containing the test statistic, p-value, and supporting metrics.

Notes
  • Uses different approximations based on mean resultant length ():
  • Small (< 0.45): Uses arcsin transformation.
  • Moderate (0.45 - 0.7): Uses asinh transformation.
  • Large (> 0.7): Uses Bartlett-type test (log-likelihood method).
References
  • Jammalamadaka & SenGupta (2001), Section 5.4.
  • Fisher (1993), Section 4.3.
  • equal.kappa.test from R's circular package.
Source code in pycircstat2/hypothesis.py
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
def equal_kappa_test(samples: list[np.ndarray], verbose: bool = False) -> EqualKappaTestResult:
    """
    Test for Homogeneity of Concentration Parameters (κ) in Circular Data.

    - **H₀**: All groups have the same concentration parameter (κ).
    - **H₁**: At least one group has a different κ.

    Parameters
    ----------
    samples : list of np.ndarray
        List of circular data arrays (angles in radians) for different groups.
    verbose : bool, optional
        If `True`, prints the test summary.

    Returns
    -------
    EqualKappaTestResult
        Dataclass containing the test statistic, p-value, and supporting metrics.

    Notes
    -----
    - Uses **different approximations based on mean resultant length** (`r̄`):
      - **Small `r̄` (< 0.45)**: Uses `arcsin` transformation.
      - **Moderate `r̄` (0.45 - 0.7)**: Uses `asinh` transformation.
      - **Large `r̄` (> 0.7)**: Uses Bartlett-type test (log-likelihood method).

    References
    ----------
    - Jammalamadaka & SenGupta (2001), Section 5.4.
    - Fisher (1993), Section 4.3.
    - `equal.kappa.test` from R's `circular` package.
    """

    # Number of groups
    k = len(samples)
    if k < 2:
        raise ValueError("At least two groups are required for the test.")

    arrays = [np.asarray(group, dtype=float) for group in samples]
    if any(arr.size == 0 for arr in arrays):
        raise ValueError("Each group must contain at least one observation.")

    # Sample sizes
    ns = np.array([arr.size for arr in arrays])
    if np.any(ns < 2):
        raise ValueError("Each group must contain at least two observations.")

    # Mean resultant lengths
    r_bars = np.array([circ_r(arr) for arr in arrays])
    Rs = r_bars * ns  # Unnormalized resultants

    # Overall resultant and mean resultant length
    all_samples = np.hstack(arrays)
    N = len(all_samples)
    r_bar_all = circ_r(all_samples)

    # Estimate kappa values
    kappas = np.array([circ_kappa(r) for r in r_bars])
    kappa_all = circ_kappa(r_bar_all)

    # Choose test statistic based on `r̄`
    if r_bar_all < 0.45:
        # Small `r̄`: arcsin transformation
        ws = 4 * (ns - 4) / 3
        g1s = np.arcsin(np.sqrt(3 / 8) * 2 * r_bars)
        chi_square_stat = np.sum(ws * g1s**2) - (np.sum(ws * g1s) ** 2 / np.sum(ws))
        regime = "small"

    elif 0.45 <= r_bar_all <= 0.7:
        # Moderate `r̄`: asinh transformation
        ws = (ns - 3) / 0.798
        g2s = np.arcsinh((r_bars - 1.089) / 0.258)
        chi_square_stat = np.sum(ws * g2s**2) - (np.sum(ws * g2s) ** 2 / np.sum(ws))
        regime = "moderate"

    else:
        # Large `r̄`: Bartlett-type test
        vs = ns - 1
        v = N - k
        d = 1 / (3 * (k - 1)) * (np.sum(1 / vs) - 1 / v)
        total_residual = N - np.sum(Rs)
        residuals = ns - Rs
        if np.any(residuals <= 0):
            raise ValueError("Degenerate data: within-group dispersion is zero.")
        if total_residual <= 0:
            raise ValueError("Degenerate data: between-group dispersion is zero.")
        chi_square_stat = (1 / (1 + d)) * (
            v * np.log(total_residual / v) - np.sum(vs * np.log(residuals / vs))
        )
        regime = "large"

    # Compute p-value
    df = k - 1
    p_value = 1 - chi2.cdf(chi_square_stat, df)

    result = EqualKappaTestResult(
        kappa=kappas,
        kappa_all=float(kappa_all),
        rho=r_bars,
        rho_all=float(r_bar_all),
        df=int(df),
        statistic=float(chi_square_stat),
        pval=float(p_value),
        regime=regime,
    )

    # Print results if verbose is enabled
    if verbose:
        print("\nTest for Homogeneity of Concentration Parameters (κ)")
        print("------------------------------------------------------")
        print(f"Mean Resultant Lengths: {result.rho}")
        print(f"Overall Mean Resultant Length: {result.rho_all:.5f}")
        print(f"Estimated Kappa Values: {result.kappa}")
        print(f"Overall Estimated Kappa: {result.kappa_all:.5f}")
        print(f"Degrees of Freedom: {result.df}")
        print(f"Chi-Square Statistic: {result.statistic:.5f}")
        print(f"P-value: {result.pval:.5f}")
        print(f"Regime: {result.regime}")
        print("------------------------------------------------------\n")

    return result

common_median_test(samples, alpha=0.05, verbose=False)

Common Median Test (Equal Median Test) for Multiple Circular Samples.

  • H₀: All groups have the same circular median.
  • H₁: At least one group has a different circular median.

Parameters:

Name Type Description Default
samples list of np.ndarray

List of circular data arrays (angles in radians) for different groups.

required
alpha float

Significance level for deciding whether to reject the null hypothesis (default 0.05).

0.05
verbose bool

If True, prints the test summary.

False

Returns:

Type Description
CommonMedianTestResult

Dataclass containing the common median, test statistic, p-value, and rejection flag.

References
  • Fisher, N. I. (1995). Statistical Analysis of Circular Data.
  • circ_cmtest from MATLAB's Circular Statistics Toolbox.
Source code in pycircstat2/hypothesis.py
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
def common_median_test(
    samples: list[np.ndarray],
    alpha: float = 0.05,
    verbose: bool = False,
) -> CommonMedianTestResult:
    """
    Common Median Test (Equal Median Test) for Multiple Circular Samples.

    - **H₀**: All groups have the same circular median.
    - **H₁**: At least one group has a different circular median.

    Parameters
    ----------
    samples : list of np.ndarray
        List of circular data arrays (angles in radians) for different groups.
    alpha : float, optional
        Significance level for deciding whether to reject the null hypothesis (default 0.05).
    verbose : bool, optional
        If `True`, prints the test summary.

    Returns
    -------
    CommonMedianTestResult
        Dataclass containing the common median, test statistic, p-value, and rejection flag.

    References
    ----------
    - Fisher, N. I. (1995). Statistical Analysis of Circular Data.
    - `circ_cmtest` from MATLAB's Circular Statistics Toolbox.
    """

    # Number of groups
    if not (0 < alpha < 1):
        raise ValueError("`alpha` must be between 0 and 1.")

    k = len(samples)
    if k < 2:
        raise ValueError("At least two groups are required for the test.")

    arrays = [np.asarray(group, dtype=float) for group in samples]
    if any(arr.size == 0 for arr in arrays):
        raise ValueError("Each group must contain at least one observation.")

    # Sample sizes
    ns = np.array([arr.size for arr in arrays])
    N = int(np.sum(ns))  # Total number of observations

    # Compute the common circular median
    common_median = circ_median(np.hstack(arrays))

    # Compute deviations from the common median
    m = np.zeros(k, dtype=float)
    for i, group in enumerate(arrays):
        deviations = circ_dist(group, common_median)
        m[i] = np.sum(deviations < 0)

    # Compute test statistic
    M = np.sum(m)
    if M == 0 or M == N:
        raise ValueError("All observations fall on the same side of the median; test is undefined.")

    P = (N**2 / (M * (N - M))) * np.sum(m**2 / ns) - (N * M) / (N - M)

    # Compute p-value
    df = k - 1
    p_value = 1 - chi2.cdf(P, df)
    reject = p_value < alpha

    # If the null hypothesis is rejected, return NaN for the median
    if reject:
        common_median = np.nan

    result = CommonMedianTestResult(
        common_median=float(common_median),
        statistic=float(P),
        pval=float(p_value),
        reject=bool(reject),
    )

    # Print results if verbose is enabled
    if verbose:
        print("\nCommon Median Test (Equal Median Test)")
        print("--------------------------------------")
        median_display = result.common_median if not result.reject else "NaN"
        print(f"Estimated Common Median: {median_display}")
        print(f"Test Statistic: {result.statistic:.5f}")
        print(f"P-value: {result.pval:.5f}")
        decision = "Yes" if result.reject else "No"
        print(f"Reject H₀ (α={alpha:.2f}): {decision}")
        print("--------------------------------------\n")

    return result