Skip to content

Descriptive Statistics

circ_r(alpha=None, w=None, Cbar=None, Sbar=None)

Circular mean resultant vector length (r).

\[ r = \sqrt{\bar{C}^2 + \bar{S}^2} \]

Parameters:

Name Type Description Default
alpha Optional[ndarray]

Angles in radian.

None
w Optional[ndarray]

Frequencies or weights

None
Cbar Optional[float]

Precomputed intermediate values

None
Sbar Optional[float]

Precomputed intermediate values

None

Returns:

Name Type Description
r float

Resultant vector length

References

Implementation of Example 26.5 (Zar, 2010)

Source code in pycircstat2/descriptive.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def circ_r(
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    Cbar: Optional[float] = None,
    Sbar: Optional[float] = None,
) -> float:
    r"""
    Circular mean resultant vector length (r).

    $$
    r = \sqrt{\bar{C}^2 + \bar{S}^2}
    $$

    Parameters
    ----------
    alpha: np.array (n, )
        Angles in radian.
    w: np.array (n,)
        Frequencies or weights
    Cbar, Sbar: float
        Precomputed intermediate values

    Returns
    -------
    r: float
        Resultant vector length

    References
    ----------
    Implementation of Example 26.5 (Zar, 2010)
    """
    if alpha is None and (Cbar is None or Sbar is None):
        raise ValueError("`alpha` is needed for computing the resultant vector length.")

    if w is None:
        w = np.ones_like(alpha)

    if Cbar is None or Sbar is None:
        Cbar, Sbar = compute_C_and_S(alpha, w)

    # mean resultant vecotr length
    r = np.sqrt(Cbar**2 + Sbar**2)

    return r

circ_mean(alpha, w=None)

Circular mean (m).

\[\cos\bar\theta = C/R,\space \sin\bar\theta = S/R\]

or

\[ \bar\theta = \begin{cases} \tan^{-1}\left(S/C\right), & \text{if } S > 0, C > 0 \\ \tan^{-1}\left(S/C\right) + \pi, & \text{if } C < 0 \\ \tan^{-1}\left(S/C\right) + 2\pi, & \text{S < 0, C > 0} \end{cases} \]

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
w Optional[ndarray]

Frequencies or weights

None

Returns:

Name Type Description
m float or NaN

Circular mean

Note

Implementation of Example 26.5 (Zar, 2010)

Source code in pycircstat2/descriptive.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def circ_mean(
    alpha: np.ndarray,
    w: Optional[np.ndarray] = None,
) -> Union[np.ndarray, float]:
    r"""
    Circular mean (m).

    $$\cos\bar\theta = C/R,\space \sin\bar\theta = S/R$$

    or 

    $$
    \bar\theta =
    \begin{cases} 
    \tan^{-1}\left(S/C\right), & \text{if } S > 0, C > 0 \\ 
    \tan^{-1}\left(S/C\right) + \pi, & \text{if } C < 0 \\ 
    \tan^{-1}\left(S/C\right) + 2\pi, & \text{S < 0, C > 0}
    \end{cases}
    $$

    Parameters
    ----------
    alpha: np.array (n, )
        Angles in radian.
    w: np.array (n,)
        Frequencies or weights

    Returns
    -------
    m: float or NaN
        Circular mean

    Note
    ----
    Implementation of Example 26.5 (Zar, 2010)
    """
    if w is None:
        w = np.ones_like(alpha)

    # mean resultant vecotr length
    Cbar, Sbar = compute_C_and_S(alpha, w)
    r = circ_r(alpha, w, Cbar, Sbar)

    # angular mean
    if np.isclose(r, 0):
        m = np.nan
    else:
        m = np.arctan2(Sbar, Cbar)

    return angmod(m)

circ_mean_and_r(alpha, w=None)

Circular mean (m) and resultant vector length (r).

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
w Optional[ndarray]

Frequencies or weights

None

Returns:

Name Type Description
m float or NaN

Circular mean

r float

Resultant vector length

Note

Implementation of Example 26.5 (Zar, 2010)

Source code in pycircstat2/descriptive.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def circ_mean_and_r(
    alpha: np.ndarray,
    w: Optional[np.ndarray] = None,
) -> Tuple[Union[float, np.ndarray], float]:
    """
    Circular mean (m) and resultant vector length (r).

    Parameters
    ----------
    alpha: np.array (n, )
        Angles in radian.
    w: np.array (n,)
        Frequencies or weights

    Returns
    -------
    m: float or NaN
        Circular mean
    r: float
        Resultant vector length

    Note
    ----
    Implementation of Example 26.5 (Zar, 2010)
    """
    if w is None:
        w = np.ones_like(alpha)

    # mean resultant vecotr length
    Cbar, Sbar = compute_C_and_S(alpha, w)
    r = circ_r(alpha, w, Cbar, Sbar)

    # angular mean
    if np.isclose(r, 0):
        m = np.nan
        return m, r
    else:
        m = np.arctan2(Sbar, Cbar)

        return angmod(m), r

circ_mean_and_r_of_means(circs=None, ms=None, rs=None)

The Mean of a set of Mean Angles

Parameters:

Name Type Description Default
circs Union[list, None]

a list of Circular Objects

None
ms Optional[ndarray]

a set of mean angles in radian

None
rs Optional[ndarray]

a set of mean resultant vecotr lengths

None

Returns:

Name Type Description
m float

mean of means in radian

r float

mean of mean resultant vector lengths

Source code in pycircstat2/descriptive.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
def circ_mean_and_r_of_means(
    circs: Union[list, None] = None,
    ms: Optional[np.ndarray] = None,
    rs: Optional[np.ndarray] = None,
) -> Tuple[float, float]:
    """The Mean of a set of Mean Angles

    Parameters
    ----------
    circs: list
        a list of Circular Objects

    ms: np.array (n, )
        a set of mean angles in radian

    rs: np.array (n, )
        a set of mean resultant vecotr lengths

    Returns
    -------
    m: float
        mean of means in radian

    r: float
        mean of mean resultant vector lengths

    """

    if circs is None:
        assert isinstance(ms, np.ndarray) and isinstance(
            rs, np.ndarray
        ), "If `circs` is None, then `ms` and `rs` are needed."
    else:
        ms, rs = map(np.array, zip(*[(circ.mean, circ.r) for circ in circs]))

    X = np.mean(np.cos(ms) * rs)
    Y = np.mean(np.sin(ms) * rs)
    r = np.sqrt(X**2 + Y**2)
    C = X / r
    S = Y / r

    m = angmod(np.arctan2(S, C))

    return m, r

circ_moment(alpha, w=None, p=1, mean=None, centered=False)

Compute the p-th circular moment.

\[ m^{\prime}_{p} = \bar{C}_{p} + i\bar{S}_{p} \]

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
w Optional[ndarray]

Frequencies or weights. If None, equal weights are used.

None
p int

Order of the moment to compute.

1
mean Union[float, ndarray, None]

Precomputed circular mean. If None, mean is computed internally.

None
centered bool

If True, center alpha by subtracting the mean.

False

Returns:

Name Type Description
mp complex

The p-th circular moment as a complex number.

Note

Implementation of Equation 2.24 (Fisher, 1993).

Source code in pycircstat2/descriptive.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def circ_moment(
    alpha: np.ndarray,
    w: Optional[np.ndarray] = None,
    p: int = 1,
    mean: Union[float, np.ndarray, None] = None,
    centered: bool = False,
) -> complex:
    r"""
    Compute the p-th circular moment.

    $$
    m^{\prime}_{p} = \bar{C}_{p} + i\bar{S}_{p}
    $$

    Parameters
    ----------
    alpha: np.ndarray
        Angles in radian.
    w: np.ndarray, optional
        Frequencies or weights. If None, equal weights are used.
    p: int, optional
        Order of the moment to compute.
    mean: float, optional
        Precomputed circular mean. If None, mean is computed internally.
    centered: bool, optional
        If True, center alpha by subtracting the mean.

    Returns
    -------
    mp: complex
        The p-th circular moment as a complex number.

    Note
    ----
    Implementation of Equation 2.24 (Fisher, 1993).
    """
    if w is None:
        w = np.ones_like(alpha)

    if mean is None:
        mean = circ_mean(alpha, w) if centered else 0.0

    Cbar, Sbar = compute_C_and_S(alpha, w, p, mean)

    return Cbar + 1j * Sbar

circ_dispersion(alpha, w=None, mean=None)

Sample Circular Dispersion, defined by Equation 2.28 (Fisher, 1993):

\[ \hat\delta = (1 - \hat\rho_{2})/(2 \hat\rho_{1}^{2}) \]

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
w Optional[ndarray]

Frequencies or weights

None
mean

Precomputed circular mean.

None

Returns:

Name Type Description
dispersion float

Sample Circular Dispersion

Source code in pycircstat2/descriptive.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def circ_dispersion(
    alpha: np.ndarray,
    w: Optional[np.ndarray] = None,
    mean=None,
) -> float:
    r"""
    Sample Circular Dispersion, defined by Equation 2.28 (Fisher, 1993):

    $$
    \hat\delta = (1 - \hat\rho_{2})/(2 \hat\rho_{1}^{2})
    $$

    Parameters
    ----------

    alpha: np.array, (n, )
        Angles in radian.
    w: None or np.array, (n)
        Frequencies or weights
    mean: None or float
        Precomputed circular mean.

    Returns
    -------
    dispersion: float
        Sample Circular Dispersion
    """

    if w is None:
        w = np.ones_like(alpha)

    mp1 = circ_moment(alpha=alpha, w=w, p=1, mean=mean, centered=False)  # eq(2.26)
    mp2 = circ_moment(alpha=alpha, w=w, p=2, mean=mean, centered=False)  # eq(2.27)

    r1 = np.abs(mp1)
    r2 = np.abs(mp2)

    dispersion = (1 - r2) / (2 * r1**2)  # eq(2.28)

    return dispersion

circ_skewness(alpha, w=None)

Circular skewness, as defined by Equation 2.29 (Fisher, 1993):

\[\hat s = [\hat\rho_2 \sin(\hat\mu_2 - 2 \hat\mu_1)] / (1 - \hat\rho_1)^{\frac{3}{2}}\]

But unlike the implementation of Fisher (1993), here we followed Pewsey et al. (2014) by NOT centering the second moment.

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
w Optional[ndarray]

Frequencies or weights

None

Returns:

Name Type Description
skewness float

Circular Skewness

Source code in pycircstat2/descriptive.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def circ_skewness(alpha: np.ndarray, w: Optional[np.ndarray] = None) -> float:
    r"""
    Circular skewness, as defined by Equation 2.29 (Fisher, 1993):

    $$\hat s = [\hat\rho_2 \sin(\hat\mu_2 - 2 \hat\mu_1)] / (1 - \hat\rho_1)^{\frac{3}{2}}$$

    But unlike the implementation of Fisher (1993), here we followed Pewsey et al. (2014) by NOT centering the second moment.

    Parameters
    ----------

    alpha: np.array, (n, )
        Angles in radian.
    w: None or np.array, (n)
        Frequencies or weights

    Returns
    -------
    skewness: float
        Circular Skewness
    """

    if w is None:
        w = np.ones_like(alpha)

    mp1 = circ_moment(alpha=alpha, w=w, p=1, mean=None, centered=False)
    mp2 = circ_moment(alpha=alpha, w=w, p=2, mean=None, centered=False)  # eq(2.27)

    u1, r1 = convert_moment(mp1)
    u2, r2 = convert_moment(mp2)

    skewness = (r2 * np.sin(u2 - 2 * u1)) / (1 - r1) ** 1.5

    return skewness

circ_kurtosis(alpha, w=None)

Circular kurtosis, as defined by Equation 2.30 (Fisher, 1993):

\[\hat k = [\hat\rho_2 \cos(\hat\mu_2 - 2 \hat\mu_1) - \hat\rho_1^4] / (1 - \hat\rho_1)^{2}\]

But unlike the implementation of Fisher (1993), here we followed Pewsey et al. (2014) by NOT centering the second moment.

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
w Optional[ndarray]

Frequencies or weights

None

Returns:

Name Type Description
kurtosis float

Circular Kurtosis

Source code in pycircstat2/descriptive.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
def circ_kurtosis(alpha: np.ndarray, w: Optional[np.ndarray] = None) -> float:
    r"""
    Circular kurtosis, as defined by Equation 2.30 (Fisher, 1993):

    $$\hat k = [\hat\rho_2 \cos(\hat\mu_2 - 2 \hat\mu_1) - \hat\rho_1^4] / (1 - \hat\rho_1)^{2}$$

    But unlike the implementation of Fisher (1993), here we followed Pewsey et al. (2014) by **NOT** centering the second moment.

    Parameters
    ----------

    alpha: np.array, (n, )
        Angles in radian.
    w: None or np.array, (n)
        Frequencies or weights

    Returns
    -------
    kurtosis: float
        Circular Kurtosis
    """

    if w is None:
        w = np.ones_like(alpha)

    mp1 = circ_moment(alpha=alpha, w=w, p=1, mean=None, centered=False)
    mp2 = circ_moment(alpha=alpha, w=w, p=2, mean=None, centered=False)  # eq(2.27)

    u1, r1 = convert_moment(mp1)
    u2, r2 = convert_moment(mp2)

    kurtosis = (r2 * np.cos(u2 - 2 * u1) - r1**4) / (1 - r1) ** 2

    return kurtosis

angular_var(alpha=None, w=None, r=None, bin_size=None)

Angular variance

Parameters:

Name Type Description Default
alpha Optional[ndarray]

Angles in radian.

None
w Optional[ndarray]

Frequencies or weights

None
r Optional[float]

Resultant vector length

None
bin_size Optional[float]

Interval size of grouped data. Needed for correcting biased r.

None

Returns:

Name Type Description
angular_variance float

Angular variance, range from 0 to 2.

References
  • Batschlet (1965, 1981), from Section 26.5 of Zar (2010)
Source code in pycircstat2/descriptive.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
def angular_var(
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    r: Optional[float] = None,
    bin_size: Optional[float] = None,
) -> float:
    r"""
    Angular variance

    Parameters
    ----------
    alpha: np.array (n, ) or None
        Angles in radian.
    w: np.array (n,) or None
        Frequencies or weights
    r: float or None
        Resultant vector length
    bin_size: float
        Interval size of grouped data. Needed for correcting biased r.

    Returns
    -------
    angular_variance: float
        Angular variance, range from 0 to 2.

    References
    ----------
    - Batschlet (1965, 1981), from Section 26.5 of Zar (2010)
    """

    variance = circ_var(alpha=alpha, w=w, r=r, bin_size=bin_size)
    angular_variance = 2 * variance
    return angular_variance

angular_std(alpha=None, w=None, r=None, bin_size=None)

Angular (standard) deviation

\[ s = \sqrt{2V} = \sqrt{2(1 - r)} \]

Parameters:

Name Type Description Default
alpha Optional[ndarray]

Angles in radian.

None
w Optional[ndarray]

Frequencies or weights

None
r Optional[float]

Resultant vector length

None
bin_size Optional[float]

Interval size of grouped data. Needed for correcting biased r.

None

Returns:

Name Type Description
angular_std float

Angular (standard) deviation, range from 0 to sqrt(2).

References
  • Equation 26.20 of Zar (2010)
Source code in pycircstat2/descriptive.py
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
def angular_std(
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    r: Optional[float] = None,
    bin_size: Optional[float] = None,
) -> float:
    r"""
    Angular (standard) deviation

    $$
    s = \sqrt{2V} = \sqrt{2(1 - r)}
    $$

    Parameters
    ----------
    alpha: np.array (n, ) or None
        Angles in radian.
    w: np.array (n,) or None
        Frequencies or weights
    r: float or None
        Resultant vector length
    bin_size: float
        Interval size of grouped data. Needed for correcting biased r.

    Returns
    -------
    angular_std: float
        Angular (standard) deviation, range from 0 to sqrt(2).

    References
    ----------
    - Equation 26.20 of Zar (2010)
    """

    angular_variance = angular_var(alpha=alpha, w=w, r=r, bin_size=bin_size)
    angular_std = np.sqrt(angular_variance)
    return angular_std

circ_var(alpha=None, w=None, r=None, bin_size=None)

Circular variance

\[ V = 1 - r \]

Parameters:

Name Type Description Default
alpha Optional[ndarray]

Angles in radian.

None
w Optional[ndarray]

Frequencies or weights

None
r Optional[float]

Resultant vector length

None
bin_size Optional[float]

Interval size of grouped data. Needed for correcting biased r.

None

Returns:

Name Type Description
variance float

Circular variance, range from 0 to 1.

References
  • Equation 2.11 of Fisher (1993)
  • Equation 26.17 of Zar (2010)
Source code in pycircstat2/descriptive.py
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
def circ_var(
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    r: Optional[float] = None,
    bin_size: Optional[float] = None,
) -> float:
    r"""
    Circular variance

    $$ V = 1 - r $$

    Parameters
    ----------
    alpha: np.array (n, ) or None
        Angles in radian.
    w: np.array (n,) or None
        Frequencies or weights
    r: float or None
        Resultant vector length
    bin_size: float
        Interval size of grouped data. Needed for correcting biased r.

    Returns
    -------
    variance: float
        Circular variance, range from 0 to 1.

    References
    ----------
    - Equation 2.11 of Fisher (1993)
    - Equation 26.17 of Zar (2010)
    """

    if w is None:
        w = np.ones_like(alpha)

    if r is None:
        assert isinstance(alpha, np.ndarray) and isinstance(
            w, np.ndarray
        ), "If `r` is None, then `alpha` and `w` are needed."
        r = circ_r(alpha, w)

    if bin_size is None:
        assert isinstance(alpha, np.ndarray) and isinstance(
            w, np.ndarray
        ), "If `bin_size` is None, then `alpha` and `w` are needed."
        if (w == w[0]).all():  #
            bin_size = 0
        else:
            bin_size = np.diff(alpha).min()

    ## corrected r if data are grouped.
    if bin_size == 0:
        rc = r

    else:
        c = bin_size / 2 / np.sin(bin_size / 2)  # eq(26.16)
        rc = r * c  # eq(26.15)

    variance = 1 - rc

    return variance

circ_std(alpha=None, w=None, r=None, bin_size=None)

Circular standard deviation (s).

\[ s = \sqrt{-2 \ln(1 - V)} \]

Parameters:

Name Type Description Default
alpha Optional[ndarray]

Angles in radian.

None
w Optional[ndarray]

Frequencies or weights

None
r Optional[float]

Resultant vector length

None
bin_size Optional[float]

Interval size of grouped data. Needed for correcting biased r.

None

Returns:

Name Type Description
s float

Circular standard deviation.

References

Implementation of Equation 26.15-16/20-21 (Zar, 2010)

Source code in pycircstat2/descriptive.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
def circ_std(
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    r: Optional[float] = None,
    bin_size: Optional[float] = None,
) -> tuple:
    r"""
    Circular standard deviation (s).

    $$ s = \sqrt{-2 \ln(1 - V)} $$

    Parameters
    ----------
    alpha: np.array (n, ) or None
        Angles in radian.
    w: np.array (n,) or None
        Frequencies or weights
    r: float or None
        Resultant vector length
    bin_size: float
        Interval size of grouped data.
        Needed for correcting biased r.

    Returns
    -------
    s: float
        Circular standard deviation.

    References
    ----------
    Implementation of Equation 26.15-16/20-21 (Zar, 2010)
    """
    var = circ_var(alpha=alpha, w=w, r=r, bin_size=bin_size)

    # circular standard deviation
    s = np.sqrt(-2 * np.log(1 - var))  # eq(26.21)

    return s

circ_median(alpha, w=None, method='deviation', return_average=True, average_method='all')

Circular median.

Two ways to compute the circular median for ungrouped data (Fisher, 1993):

  • deviation: find the angle that has the minimal mean deviation.
  • count: find the angle that has the equally devide the number of points on the right and left of it.

For grouped data, we use the method described in Mardia (1972).

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
w Optional[ndarray]

Frequencies or weights

None
method str
  • For ungrouped data, there are two ways
  • To compute the medians:
    • deviation
    • count
  • Set to none to return np.nan.
'deviation'
return_average bool

Return the average of the median

True
average_method str
  • all: circular mean of all medians
  • unique: circular mean of unique medians
'all'

Returns:

Name Type Description
median float or NaN
References
  • For ungrouped data: Section 2.3.2 of Fisher (1993)
  • For grouped data: Mardia (1972)
Source code in pycircstat2/descriptive.py
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
572
573
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
def circ_median(
    alpha: np.ndarray,
    w: Optional[np.ndarray] = None,
    method: str = "deviation",
    return_average: bool = True,
    average_method: str = "all",
) -> Union[float, np.ndarray]:
    r"""
    Circular median.

    Two ways to compute the circular median for ungrouped data (Fisher, 1993):

    - `deviation`: find the angle that has the minimal mean deviation.
    - `count`: find the angle that has the equally devide the number of points on the right and left of it.

    For grouped data, we use the method described in Mardia (1972).

    Parameters
    ----------
    alpha: np.array (n, )
        Angles in radian.
    w: np.array (n,) or None
        Frequencies or weights
    method: str
        - For ungrouped data, there are two ways
        - To compute the medians:
            - deviation
            - count
        - Set to `none` to return np.nan.
    return_average: bool
        Return the average of the median
    average_method: str
        - all: circular mean of all medians
        - unique: circular mean of unique medians

    Returns
    -------
    median: float or NaN

    References
    ----------
    - For ungrouped data: Section 2.3.2 of Fisher (1993)
    - For grouped data: Mardia (1972)
    """

    if w is None:
        w = np.ones_like(alpha)

    # grouped data
    if not np.all(w == 1):
        median = _circ_median_grouped(alpha, w)
    # ungrouped data
    else:
        # find which data point that can divide the dataset into two half
        if method == "count":
            median = _circ_median_count(alpha)
        # find the angle that has the minimal mean deviation
        elif method == "deviation":
            median = _circ_median_mean_deviation(alpha)
        elif method == "none" or method is None:
            median = np.nan
        else:
            raise ValueError(
                f"Method `{method}` for `circ_median` is not supported.\nTry `deviation` or `count`"
            )

    if return_average:
        if average_method == "all":
            # Circular mean of all medians
            median = circ_mean(alpha=median)
        elif average_method == "unique":
            # Circular mean of unique medians
            median = circ_mean(alpha=np.unique(median))
        else:
            raise ValueError(
                f"Average method `{average_method}` is not supported.\nTry `all` or `unique`."
            )

    return angmod(median)

_circ_median_mean_deviation(alpha)

Note

Implementation of Section 2.3.2 of Fisher (1993)

Source code in pycircstat2/descriptive.py
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
def _circ_median_mean_deviation(alpha: np.array) -> float:
    """
    Note
    ----
    Implementation of Section 2.3.2 of Fisher (1993)
    """

    # get pairwise circular mean deviation
    if len(alpha) > 10000:
        angdist = circ_mean_deviation_chuncked(alpha, alpha)
    else:
        # get pairwise circular mean deviation
        angdist = circ_mean_deviation(alpha, alpha)
    # data point(s) with minimal circular mean deviation is/are potential median(s);
    idx_candidates = np.where(angdist == angdist.min())[0]
    # if number of potential median is the same as the number of data point
    # meaning that the data is more or less uniformly distributed. Retrun Nan.
    if len(idx_candidates) == len(alpha):
        median = np.nan
    # if number of potential median is 1, return it as median
    elif len(idx_candidates) == 1:
        median = alpha[idx_candidates][0]
    # if there are more than one potential median, return them all
    else:
        median = alpha[idx_candidates]

    return median

circ_mean_deviation_chuncked(alpha, beta, chunk_size=1000)

Optimized circular mean deviation with chunking.

\[ \delta = \pi - \frac{1}{n} \sum^{n}_{1}\left| \pi - \left| \alpha - \beta \right| \right| \]

Parameters:

Name Type Description Default
alpha ndarray

Data in radians.

required
beta ndarray

Reference angles in radians.

required
chunk_size int

Number of rows to process in chunks.

1000

Returns:

Type Description
ndarray

Circular mean deviation.

Source code in pycircstat2/descriptive.py
735
736
737
738
739
740
741
742
743
744
745
746
747
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
def circ_mean_deviation_chuncked(
    alpha: Union[np.ndarray, float, int, list],
    beta: Union[np.ndarray, float, int, list],
    chunk_size=1000,
):
    r"""
    Optimized circular mean deviation with chunking.

    $$
    \delta = \pi - \frac{1}{n} \sum^{n}_{1}\left| \pi - \left| \alpha - \beta \right| \right|
    $$

    Parameters
    ----------
    alpha : np.ndarray
        Data in radians.
    beta : np.ndarray
        Reference angles in radians.
    chunk_size : int
        Number of rows to process in chunks.

    Returns
    -------
    np.ndarray
        Circular mean deviation.
    """
    if not isinstance(alpha, np.ndarray):
        alpha = np.array([alpha])

    if not isinstance(beta, np.ndarray):
        beta = np.array([beta])

    n = len(beta)
    result = np.zeros(n)

    for i in range(0, n, chunk_size):
        beta_chunk = beta[i : i + chunk_size]
        angdist = np.pi - np.abs(np.pi - np.abs(alpha - beta_chunk[:, None]))
        result[i : i + chunk_size] = np.mean(angdist, axis=1).round(5)

    return result

circ_mean_deviation(alpha, beta)

Circular mean deviation.

\[ \delta = \pi - \left| \pi - \left| \alpha - \beta \right| \right| / n \]

It is the mean angular distance from one data point to all others. The circular median of a set of data should be the point with minimal circular mean deviation.

Parameters:

Name Type Description Default
alpha Union[ndarray, float, int, list]

Data in radian.

required
beta Union[ndarray, float, int, list]

reference angle in radian.

required

Returns:

Type Description
circular mean deviation: np.array
Note

eq 2.32, Section 2.3.2, Fisher (1993)

Source code in pycircstat2/descriptive.py
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
def circ_mean_deviation(
    alpha: Union[np.ndarray, float, int, list],
    beta: Union[np.ndarray, float, int, list],
) -> np.ndarray:
    r"""
    Circular mean deviation.

    $$
    \delta = \pi - \left| \pi - \left| \alpha - \beta \right| \right| / n
    $$

    It is the mean angular distance from one data point to all others.
    The circular median of a set of data should be the point with minimal
    circular mean deviation.

    Parameters
    ---------
    alpha: np.array, int or float
        Data in radian.
    beta: np.array, int or float
        reference angle in radian.

    Returns
    -------
    circular mean deviation: np.array

    Note
    ----
    eq 2.32, Section 2.3.2, Fisher (1993)
    """
    if not isinstance(alpha, np.ndarray):
        alpha = np.array([alpha])

    if not isinstance(beta, np.ndarray):
        beta = np.array([beta])

    return (np.pi - np.mean(np.abs(np.pi - np.abs(alpha - beta[:, None])), 1)).round(5)

circ_mean_ci(alpha=None, w=None, mean=None, r=None, n=None, ci=0.95, method='approximate', B=2000)

Confidence interval of circular mean.

There are three methods to compute the confidence interval of circular mean:

  • approximate: for n > 8
  • bootstrap: for 8 < n < 25
  • dispersion: for n >= 25
Approximate Method

For n as small as 8, and r \(\le\) 0.9, r \(>\) \(\sqrt{\chi^{2}_{\alpha, 1}/2n}\), the confidence interval can be approximated by:

\[ \delta = \arccos\left(\sqrt{\frac{2n(2R^{2} - n\chi^{2}_{\alpha, 1})}{4n - \chi^{2}_{\alpha, 1}}} /R \right) \]

For r \(ge\) 0.9,

\[ \delta = \arccos \left(\sqrt{n^2 - (n^2 - R^2)e^{\chi^2_{\alpha, 1}/n} } /R \right) \]
Bootstrap Method

For 8 \(<\) n \(<\) 25, the confidence interval can be computed by bootstrapping the data.

Dispersion Method

For n \(\ge\) 25, the confidence interval can be computed by the circular dispersion:

\[ \hat\sigma = \hat\delta / n\]

where \(\hat\delta\) is the sample circular dispersion (see circ_dispersion). The confidence interval is then:

\[(\hat\mu - \sin^-1(z_{\frac{1}{2}\alpha}\hat\sigma),\space \hat\mu + \sin^-1(z_{\frac{1}{2}\alpha} \hat\sigma))\]

Parameters:

Name Type Description Default
alpha Optional[ndarray]

Angles in radian.

None
w Optional[ndarray]

Frequencies or weights

None
mean Optional[float]

Precomputed circular mean.

None
r Optional[float]

Precomputed resultant vector length.

None
n Union[int, None]

Sample size.

None
ci float

Confidence interval (default is 0.95).

0.95
method str
  • approximate: for n > 8
  • bootstrap: for n < 25
  • dispersion: for n >= 25
'approximate'
B int

Number of samples for bootstrap.

2000

Returns:

Name Type Description
lower_bound float

Lower bound of the confidence interval.

upper_bound float

Upper bound of the confidence

References
  • Section 26.7, Zar (2010)
  • Section 4.4.4a/b, Fisher (1993)
Source code in pycircstat2/descriptive.py
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
854
855
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
908
909
910
911
912
913
914
915
916
917
def circ_mean_ci(
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    mean: Optional[float] = None,
    r: Optional[float] = None,
    n: Union[int, None] = None,
    ci: float = 0.95,
    method: str = "approximate",
    B: int = 2000,  # number of samples for bootstrap
) -> tuple[float, float]:
    r"""
    Confidence interval of circular mean.

    There are three methods to compute the confidence interval of circular mean:

    - `approximate`: for n > 8
    - `bootstrap`: for 8 < n < 25
    - `dispersion`: for n >= 25

    ### Approximate Method

    For n as small as 8, and r $\le$ 0.9, r $>$ $\sqrt{\chi^{2}_{\alpha, 1}/2n}$, the confidence interval can be approximated by:

    $$
    \delta = \arccos\left(\sqrt{\frac{2n(2R^{2} - n\chi^{2}_{\alpha, 1})}{4n - \chi^{2}_{\alpha, 1}}} /R \right)
    $$

    For r $ge$ 0.9,

    $$
    \delta = \arccos \left(\sqrt{n^2 - (n^2 - R^2)e^{\chi^2_{\alpha, 1}/n} } /R \right)
    $$

    ### Bootstrap Method

    For 8 $<$ n $<$ 25, the confidence interval can be computed by bootstrapping the data.

    ### Dispersion Method

    For n $\ge$ 25, the confidence interval can be computed by the circular dispersion:

    $$ \hat\sigma = \hat\delta / n$$

    where $\hat\delta$ is the sample circular dispersion (see `circ_dispersion`). The confidence interval is then:

    $$(\hat\mu - \sin^-1(z_{\frac{1}{2}\alpha}\hat\sigma),\space \hat\mu + \sin^-1(z_{\frac{1}{2}\alpha} \hat\sigma))$$

    Parameters
    ----------
    alpha: np.array (n, )
        Angles in radian.
    w: np.array (n,) or None
        Frequencies or weights
    mean: float or None
        Precomputed circular mean.
    r: float or None
        Precomputed resultant vector length.
    n: int or None
        Sample size.
    ci: float
        Confidence interval (default is 0.95).
    method: str
        - approximate: for n > 8
        - bootstrap: for n < 25
        - dispersion: for n >= 25
    B: int
        Number of samples for bootstrap.

    Returns
    -------
    lower_bound: float
        Lower bound of the confidence interval.
    upper_bound: float
        Upper bound of the confidence

    References
    ----------
    - Section 26.7, Zar (2010)
    - Section 4.4.4a/b, Fisher (1993)
    """

    #  n > 8, according to Ch 26.7 (Zar, 2010)
    if method == "approximate":
        (lb, ub) = _circ_mean_ci_approximate(
            alpha=alpha, w=w, mean=mean, r=r, n=n, ci=ci
        )

    # n < 25, according to 4.4.4a (Fisher, 1993, P75)
    elif method == "bootstrap":
        (lb, ub) = _circ_mean_ci_bootstrap(alpha=alpha, B=B, ci=ci)

    # n >= 25, according to 4.4.4b (Fisher, 1993, P75)
    elif method == "dispersion":
        (lb, ub) = _circ_mean_ci_dispersion(alpha=alpha, w=w, mean=mean, ci=ci)

    else:
        raise ValueError(
            f"Method `{method}` for `circ_mean_ci` is not supported.\nTry `dispersion`, `approximate` or `bootstrap`"
        )

    return angmod(lb), angmod(ub)

_circ_mean_ci_dispersion(alpha, w=None, mean=None, ci=0.95)

Confidence intervals based on circular dispersion.

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
w Optional[ndarray]

Frequencies or weights

None
mean Optional[float]

Precomputed circular mean.

None
ci float

Confidence interval (default is 0.95).

0.95

Returns:

Name Type Description
lower_bound float

Lower bound of the confidence interval.

upper_bound float

Upper bound of the confidence interval.

Note

Implementation of Section 4.4.4b (Fisher, 1993)

Source code in pycircstat2/descriptive.py
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
963
964
965
966
967
968
969
970
971
972
973
974
975
def _circ_mean_ci_dispersion(
    alpha: np.ndarray,
    w: Optional[np.ndarray] = None,
    mean: Optional[float] = None,
    ci: float = 0.95,
) -> tuple[float, float]:
    r"""Confidence intervals based on circular dispersion.

    Parameters
    ----------
    alpha: np.array (n, )
        Angles in radian.
    w: np.array (n,) or None
        Frequencies or weights
    mean: float or None
        Precomputed circular mean.
    ci: float
        Confidence interval (default is 0.95).


    Returns
    -------
    lower_bound: float
        Lower bound of the confidence interval.
    upper_bound: float
        Upper bound of the confidence interval.


    Note
    ----
    Implementation of Section 4.4.4b (Fisher, 1993)
    """

    if w is None:
        w = np.ones_like(alpha)
    if mean is None:
        mean, r = circ_mean_and_r(alpha, w)

    n = np.sum(w)
    if n < 25:
        raise ValueError(
            f"n={n} is too small (< 25) for computing CI with circular dispersion."
        )

    # TODO: sometime return nan because x in arcsin(x) is larger than 1.
    # Should we centered the data here? <- No.
    d = np.arcsin(
        np.sqrt(circ_dispersion(alpha=alpha, w=w) / n) * norm.ppf(1 - 0.5 * (1 - ci))
    )
    lb = mean - d
    ub = mean + d

    if not is_within_circular_range(mean, lb, ub):
        lb, ub = ub, lb

    return (lb, ub)

_circ_mean_ci_approximate(alpha=None, w=None, mean=None, r=None, n=None, ci=0.95)

Confidence Interval of circular mean.

\[ \displaylines{ \delta = \arccos\left(\sqrt{\frac{2n(2R^{2} - n\chi^{2}_{alpha, 1})}{4n - \chi^{2}_{\alpha, 1}}}\right)/R \cr } \]

Parameters:

Name Type Description Default
alpha Optional[ndarray]

Angles in radian.

None
w Optional[ndarray]

Frequencies or weights

None
mean Optional[float]

Precomputed circular mean.

None
r Optional[float]

Precomputed resultant vector length.

None
n Union[int, None]

Sample size.

None
ci float

Confidence interval (default is 0.95).

0.95

Returns:

Name Type Description
lower_bound float

Lower bound of the confidence interval.

upper_bound float

Upper bound of the confidence interval.

Note

Implementation of Example 26.6 (Zar, 2010)

Source code in pycircstat2/descriptive.py
 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
1061
1062
1063
def _circ_mean_ci_approximate(
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    mean: Optional[float] = None,
    r: Optional[float] = None,
    n: Union[int, None] = None,
    ci: float = 0.95,
) -> tuple:
    r"""
    Confidence Interval of circular mean.

    $$
    \displaylines{
    \delta = \arccos\left(\sqrt{\frac{2n(2R^{2} - n\chi^{2}_{alpha, 1})}{4n - \chi^{2}_{\alpha, 1}}}\right)/R \cr
    }
    $$

    Parameters
    ----------
    alpha: np.array (n, )
        Angles in radian.
    w: np.array (n,) or None
        Frequencies or weights
    mean: float or None
        Precomputed circular mean.
    r: float or None
        Precomputed resultant vector length.
    n: int or None
        Sample size.
    ci: float
        Confidence interval (default is 0.95).

    Returns
    -------
    lower_bound: float
        Lower bound of the confidence interval.
    upper_bound: float
        Upper bound of the confidence interval.

    Note
    ----
    Implementation of Example 26.6 (Zar, 2010)
    """

    if r is None:
        assert isinstance(
            alpha, np.ndarray
        ), "If `r` is None, then `alpha` (and `w`) is needed."
        if w is None:
            w = np.ones_like(alpha)
        n = np.sum(w)
        mean, r = circ_mean_and_r(alpha, w)

    if n is None:
        raise ValueError("Sample size `n` is missing.")

    R = n * r

    # Zar cited (Upton, 1986) that n can be as small as 8
    # but I encountered a few cases where n<11 will result in negative
    # value within `inner`.
    if n >= 8:  #
        if r <= 0.9:  # eq(26.24)
            inner = (
                np.sqrt(
                    (2 * n * (2 * R**2 - n * chi2.isf(0.05, 1)))
                    / (4 * n - chi2.isf(1 - ci, 1))
                )
                / R
            )
        else:  # eq(26.25)
            inner = np.sqrt(n**2 - (n**2 - R**2) * np.exp(chi2.isf(1 - ci, 1) / n)) / R

        d = np.arccos(inner)
        lb = mean - d
        ub = mean + d

        if not is_within_circular_range(mean, lb, ub):
            lb, ub = ub, lb

        return (lb, ub)

    else:
        raise ValueError(
            f"n={n} is too small (<= 8) for computing CI with approximation method."
        )

_circ_mean_ci_bootstrap(alpha, B=2000, ci=0.95)

Implementation of Section 8.3 (Fisher, 1993, P207)

Source code in pycircstat2/descriptive.py
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
def _circ_mean_ci_bootstrap(alpha, B=2000, ci=0.95):
    """
    Implementation of Section 8.3 (Fisher, 1993, P207)
    """

    # Precompute z0 and v0 from original data
    # algo 1
    X = np.cos(alpha)
    Y = np.sin(alpha)
    z1 = np.mean(X)  # eq(8.24)
    z2 = np.mean(Y)
    z0 = np.array([z1, z2])

    # algo 2
    u11 = np.mean((X - z1) ** 2)  # eq(8.25)
    u22 = np.mean((Y - z2) ** 2)
    u12 = u21 = np.mean((X - z1) * (Y - z2))  # eq(8.26)

    β = (u11 - u22) / (2 * u12) - np.sqrt(
        (u11 - u22) ** 2 / (4 * u12**2 + 1)
    )  # eq(8.27)
    t1 = np.sqrt(β**2 * u11 + 2 * β * u12 + u22) / np.sqrt(1 + β**2)  # eq(8.28)
    t2 = np.sqrt(u11 - 2 * β * u12 + β**2 * u22) / np.sqrt(1 + β**2)  # eq(8.29)
    v11 = (β**2 * t1 + t2) / (1 + β**2)  # eq(8.30)
    v22 = (t1 + β**2 * t2) / (1 + β**2)
    v12 = v21 = β * (t1 - t2) / (1 + β**2)  # eq(8.31)
    v0 = np.array([[v11, v12], [v21, v22]])

    beta = np.array([_circ_mean_resample(alpha, z0, v0) for i in range(B)]).flatten()

    # here we use HDI instead of the percentile method
    lb, ub = compute_hdi(beta, ci=ci)

    mean = circ_mean(beta)
    if not is_within_circular_range(mean, lb, ub):
        lb, ub = ub, lb

    return lb, ub

_circ_mean_resample(alpha, z0, v0)

Implementation of Section 8.3.5 (Fisher, 1993, P210)

Source code in pycircstat2/descriptive.py
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
def _circ_mean_resample(alpha, z0, v0):
    """
    Implementation of Section 8.3.5 (Fisher, 1993, P210)
    """

    θ = np.random.choice(alpha, len(alpha), replace=True)
    X = np.cos(θ)
    Y = np.sin(θ)

    # algo 1
    z1 = np.mean(X)  # eq(8.24)
    z2 = np.mean(Y)
    zB = np.array([z1, z2])

    u11 = np.mean((X - z1) ** 2)  # eq(8.25)
    u22 = np.mean((X - z2) ** 2)
    u12 = u21 = np.mean((X - z1) * (Y - z2))  # eq(8.26)

    # algo 3
    β = (u11 - u22) / (2 * u12) - np.sqrt(
        (u11 - u22) ** 2 / (4 * u12**2 + 1)
    )  # eq(8.27)
    t1 = np.sqrt(1 + β**2) / np.sqrt(β**2 * u11 + 2 * β * u12 + u22)  # eq(8.33)
    t2 = np.sqrt(1 + β**2) / np.sqrt(u11 - 2 * β * u12 + β**2 * u22)  # eq(8.34)
    w11 = (β**2 * t1 + t2) / (1 + β**2)  # eq(8.35)
    w22 = (t1 + β**2 * t2) / (1 + β**2)
    w12 = w21 = β * (t1 - t2) / (1 + β**2)  # eq(8.36)

    wB = np.array([[w11, w12], [w21, w22]])

    Cbar, Sbar = z0 + v0 @ wB @ (zB - z0)
    Cbar = np.power(Cbar**2 + Sbar**2, -0.5) * Cbar
    Sbar = np.power(Cbar**2 + Sbar**2, -0.5) * Sbar

    m = np.arctan2(Sbar, Cbar)

    return angmod(m)

circ_median_ci(median=None, alpha=None, w=None, method='deviation', ci=0.95)

Confidence interval for circular median

For n > 15, the confidence interval can be computed by:

\[ m = 1 + \text{integer part of} \frac{1}{2} n^{1/2} z_{\frac{1}{2}\alpha} \]

For n \(\le\) 15, the confidence interval can be selected from the table in Fisher (1993).

Parameters:

Name Type Description Default
median float

Circular median.

None
alpha Optional[ndarray]

Data in radian.

None
w Optional[ndarray]

Frequencies or weights

None

Returns:

Type Description
lower, upper, ci: tuple

confidence intervals and alpha-level

Note

Implementation of section 4.4.2 (Fisher,1993)

Source code in pycircstat2/descriptive.py
1145
1146
1147
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
1228
1229
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
def circ_median_ci(
    median: float = None,
    alpha: Optional[np.ndarray] = None,
    w: Optional[np.ndarray] = None,
    method: str = "deviation",
    ci: float = 0.95,
) -> tuple:
    r"""Confidence interval for circular median

    For n > 15, the confidence interval can be computed by:

    $$
    m = 1 + \text{integer part of} \frac{1}{2} n^{1/2} z_{\frac{1}{2}\alpha}
    $$

    For n $\le$ 15, the confidence interval can be selected from the table in Fisher (1993).

    Parameters
    ----------
    median: float or None
        Circular median.
    alpha: np.array or None
        Data in radian.
    w: np.array or None
        Frequencies or weights

    Returns
    -------
    lower, upper, ci: tuple
        confidence intervals and alpha-level

    Note
    ----
    Implementation of section 4.4.2 (Fisher,1993)
    """

    if median is None:
        assert isinstance(
            alpha, np.ndarray
        ), "If `median` is None, then `alpha` (and `w`) is needed."
        if w is None:
            w = np.ones_like(alpha)
        median = circ_median(alpha=alpha, w=w, method=method)

    if alpha is None:
        raise ValueError(
            "`alpha` is needed for computing the confidence interval for circular median."
        )

    n = len(alpha)
    alpha = np.sort(alpha)

    if n > 15:
        z = norm.ppf(1 - 0.5 * (1 - ci))

        offset = int(1 + np.floor(0.5 * np.sqrt(n) * z))  # fisher:eq(4.19)

        # idx_median = np.where(alpha.round(5) < np.round(median, 5))[0][-1]
        arr = np.where(alpha.round(5) < np.round(median, 5))[0]
        if len(arr) == 0:
            # That means median is smaller than alpha[0] (to 5 decimals).
            # In a circular sense, the “closest index below” is alpha[-1].
            idx_median = len(alpha) - 1
        else:
            idx_median = arr[-1]

        idx_lb = idx_median - offset + 1
        idx_ub = idx_median + offset
        if np.round(median, 5) in alpha.round(5):  # don't count the median per se
            idx_ub += 1

        if idx_ub > n:
            idx_ub = idx_ub - n

        if idx_lb < 0:
            idx_lb = n + idx_lb

        lower, upper = alpha[int(idx_lb)], alpha[int(idx_ub)]

        if not is_within_circular_range(median, lower, upper):
            lower, upper = upper, lower

    # selected confidence intervals for the median direction for n < 15
    # from A6, Fisher, 1993.
    # We only return the widest CI if there are more than one in the table.

    elif n == 3:
        lower, upper = alpha[0], alpha[2]
        ci = 0.75
    elif n == 4:
        lower, upper = alpha[0], alpha[3]
        ci = 0.875
    elif n == 5:
        lower, upper = alpha[0], alpha[4]
        ci = 0.937
    elif n == 6:
        lower, upper = alpha[0], alpha[5]
        ci = 0.97
    elif n == 7:
        lower, upper = alpha[0], alpha[6]
        ci = 0.984
    elif n == 8:
        lower, upper = alpha[0], alpha[7]
        ci = 0.992
    elif n == 9:
        lower, upper = alpha[0], alpha[8]
        ci = 0.996
    elif n == 10:
        lower, upper = alpha[1], alpha[8]
        ci = 0.978
    elif n == 11:
        lower, upper = alpha[1], alpha[9]
        ci = 0.99
    elif n == 12:
        lower, upper = alpha[2], alpha[9]
        ci = 0.962
    elif n == 13:
        lower, upper = alpha[2], alpha[10]
        ci = 0.978
    elif n == 14:
        lower, upper = alpha[3], alpha[10]
        ci = 0.937
    elif n == 15:
        lower, upper = alpha[2], alpha[12]
        ci = 0.965
    else:
        lower, upper = np.nan, np.nan

    return (angmod(lower), angmod(upper), ci)

circ_kappa(r, n=None)

Estimate kappa by approximation.

\[ \hat\kappa_{ML} = \begin{cases} 2r + r^3 + 5r^5/6, , & \text{if } r < 0.53 \\ -0.4 + 1.39 r + 0.43 / (1 - r) , & \text{if } 0.53 \le r < 0.85\\ 1 / (r^3 - 4r^2 + 3r), & \text{if } r \ge 0.85 \end{cases} \]

For \(n \le 15\):

\[ \hat\kappa = \begin{cases} \max\left(\hat\kappa - \frac{2}{n\hat\kappa}, 0\right), & \text{if } \hat\kappa < 2 \\ \frac{(n - 1)^3 \hat\kappa}{n^3 + n}, & \text{if } \hat\kappa \ge 2 \end{cases} \]

Parameters:

Name Type Description Default
r float

Resultant vector length

required
n Union[int, None]

Sample size. If n is not None, the adjustment for small sample size will be applied.

None

Returns:

Name Type Description
kappa float

Concentration parameter

Reference

Section 4.5.5 (P88, Fisher, 1993)

Source code in pycircstat2/descriptive.py
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
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
def circ_kappa(r: float, n: Union[int, None] = None) -> float:
    r"""Estimate kappa by approximation.

    $$
    \hat\kappa_{ML} =
    \begin{cases}
     2r + r^3 + 5r^5/6, , & \text{if } r < 0.53  \\
     -0.4 + 1.39 r + 0.43 / (1 - r) , & \text{if } 0.53 \le r < 0.85\\
        1 / (r^3 - 4r^2 + 3r), & \text{if } r \ge 0.85
    \end{cases}
    $$

    For $n \le 15$:

    $$
    \hat\kappa =
    \begin{cases}
        \max\left(\hat\kappa - \frac{2}{n\hat\kappa}, 0\right), & \text{if } \hat\kappa < 2 \\
        \frac{(n - 1)^3 \hat\kappa}{n^3 + n}, & \text{if } \hat\kappa \ge 2
    \end{cases}
    $$


    Parameters
    ----------
    r: float
        Resultant vector length
    n: int or None
        Sample size. If n is not None, the adjustment for small sample size will be applied.

    Returns
    -------
    kappa: float
        Concentration parameter

    Reference
    ---------
    Section 4.5.5 (P88, Fisher, 1993)
    """

    # eq 4.40
    if r < 0.53:
        kappa = 2 * r + r**3 + 5 * r**5 / 6
    elif r < 0.85:
        kappa = -0.4 + 1.39 * r + 0.43 / (1 - r)
    else:
        nom = r**3 - 4 * r**2 + 3 * r
        if nom != 0:
            kappa = 1 / nom
        else:
            # not sure how to handle this...
            kappa = 1e-16

    # eq 4.41
    if n is not None:
        if n <= 15 and r < 0.7:
            if kappa < 2:
                kappa = np.max([kappa - 2 * 1 / (n * kappa), 0])
            else:
                kappa = (n - 1) ** 3 * kappa / (n**3 + n)

    return kappa

circ_dist(x, y)

Compute the pairwise circular difference \(x_i - y_i\) using complex representation.

Parameters:

Name Type Description Default
x array - like

Sample of circular data (radians).

required
y array - like

Sample of circular data (radians) or a single angle.

required

Returns:

Type Description
array

Circular differences wrapped to [-pi, pi].

References
  • Section 27.7 (Zar, 2010, P642)
Source code in pycircstat2/descriptive.py
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
def circ_dist(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    r"""
    Compute the pairwise circular difference $x_i - y_i$ using complex representation.

    Parameters
    ----------
    x : array-like
        Sample of circular data (radians).
    y : array-like
        Sample of circular data (radians) or a single angle.

    Returns
    -------
    array
        Circular differences wrapped to [-pi, pi].

    References
    ----------
    - Section 27.7 (Zar, 2010, P642)

    """
    return np.angle(np.exp(1j * x) / np.exp(1j * y))

circ_pairdist(x, y=None)

Compute all pairwise circular differences \(x_i - y_j\) around the circle.

Parameters:

Name Type Description Default
x array - like

Sample of circular data (radians).

required
y array - like

Sample of circular data (radians). If None, computes all pairwise differences within x.

None

Returns:

Type Description
ndarray

Matrix of pairwise circular differences wrapped to [-pi, pi].

References
  • Section 27.7 (Zar, 2010, P642)
Source code in pycircstat2/descriptive.py
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
def circ_pairdist(x: np.ndarray, y: Optional[np.ndarray]=None) -> np.ndarray:
    r"""
    Compute all pairwise circular differences $x_i - y_j$ around the circle.

    Parameters
    ----------
    x : array-like
        Sample of circular data (radians).
    y : array-like, optional
        Sample of circular data (radians). If None, computes all pairwise 
        differences within x.

    Returns
    -------
    ndarray
        Matrix of pairwise circular differences wrapped to [-pi, pi].

    References
    ----------
    - Section 27.7 (Zar, 2010, P642)
    """
    x = np.asarray(x)

    if y is None:
        y = x  # Compute pairwise distances within x itself

    y = np.asarray(y)

    # Broadcasting-friendly complex exponentiation method
    return np.angle(np.exp(1j * x[:, None]) / np.exp(1j * y[None, :]))

convert_moment(mp)

Convert complex moment to polar coordinates.

Parameters:

Name Type Description Default
mp complex

Complex moment

required

Returns:

Name Type Description
u float

Angle in radian

r float

Magnitude

Source code in pycircstat2/descriptive.py
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
def convert_moment(
    mp: complex,
) -> Tuple[float, float]:
    """
    Convert complex moment to polar coordinates.

    Parameters
    ----------
    mp: complex
        Complex moment

    Returns
    -------
    u: float
        Angle in radian
    r: float
        Magnitude

    """

    u = angmod(np.angle(mp))
    r = np.abs(mp)

    return u, r

compute_C_and_S(alpha, w, p=1, mean=0.0)

Compute the intermediate values Cbar and Sbar.

\[ \displaylines{ \bar{C}_{p} = \frac{\sum_{i=1}^{n} w_{i} \cos(p(\alpha_{i} - \mu))}{n} \\ \bar{S}_{p} = \frac{\sum_{i=1}^{n} w_{i} \sin(p(\alpha_{i} - \mu))}{n} } \]

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian.

required
w ndarray

Frequencies or weights.

required
p int

Order of the moment (default is 1, for the first moment).

1
mean Union[float, ndarray]

Mean angle (μ) to center the computation (default is 0.0).

0.0

Returns:

Name Type Description
Cbar float

Weighted mean cosine for the given moment.

Sbar float

Weighted mean sine for the given moment.

Source code in pycircstat2/descriptive.py
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
def compute_C_and_S(
    alpha: np.ndarray,
    w: np.ndarray,
    p: int = 1,
    mean: Union[float, np.ndarray] = 0.0,
) -> Tuple[float, float]:
    r"""
    Compute the intermediate values Cbar and Sbar.

    $$
    \displaylines{
    \bar{C}_{p} = \frac{\sum_{i=1}^{n} w_{i} \cos(p(\alpha_{i} - \mu))}{n} \\
    \bar{S}_{p} = \frac{\sum_{i=1}^{n} w_{i} \sin(p(\alpha_{i} - \mu))}{n}
    }
    $$

    Parameters
    ----------
    alpha: np.ndarray
        Angles in radian.
    w: np.ndarray
        Frequencies or weights.
    p: int, optional
        Order of the moment (default is 1, for the first moment).
    mean: float, optional
        Mean angle (μ) to center the computation (default is 0.0).

    Returns
    -------
    Cbar: float
        Weighted mean cosine for the given moment.
    Sbar: float
        Weighted mean sine for the given moment.
    """
    n = np.sum(w)
    Cbar = np.sum(w * np.cos(p * (alpha - mean))) / n
    Sbar = np.sum(w * np.sin(p * (alpha - mean))) / n

    return Cbar, Sbar

compute_hdi(samples, ci=0.95)

Compute the Highest Density Interval (HDI) for circular data.

Parameters:

Name Type Description Default
samples ndarray

Bootstrap samples of the circular mean in radians.

required
ci float

Credible interval (default is 0.95 for 95% HDI).

0.95

Returns:

Name Type Description
hdi tuple

Lower and upper bounds of the HDI in radians.

Source code in pycircstat2/descriptive.py
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
def compute_hdi(samples, ci=0.95):
    """
    Compute the Highest Density Interval (HDI) for circular data.

    Parameters
    ----------
    samples : np.ndarray
        Bootstrap samples of the circular mean in radians.
    ci : float, optional
        Credible interval (default is 0.95 for 95% HDI).

    Returns
    -------
    hdi : tuple
        Lower and upper bounds of the HDI in radians.
    """
    # Wrap samples to [0, 2π) for circular consistency
    wrapped_samples = angmod(samples)

    # Sort the samples
    sorted_samples = np.sort(wrapped_samples)

    # Number of samples in the HDI
    n_samples = len(sorted_samples)
    interval_idx = int(np.floor(ci * n_samples))
    if interval_idx == 0:
        raise ValueError("Insufficient data to compute HDI.")

    # Find the shortest interval
    hdi_width = np.inf
    hdi_bounds = (None, None)
    for i in range(n_samples - interval_idx):
        lower = sorted_samples[i]
        upper = sorted_samples[i + interval_idx]
        width = angmod(upper - lower)  # Handle wrapping for circularity
        if width < hdi_width:
            hdi_width = width
            hdi_bounds = (lower, upper)

    return hdi_bounds

compute_smooth_params(r, n)

Parameters:

Name Type Description Default
r float

resultant vector length

required
n int

sample size

required

Returns:

Name Type Description
h float

smoothing parameter

Reference

Section 2.2 (P26, Fisher, 1993)

Source code in pycircstat2/descriptive.py
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
def compute_smooth_params(r: float, n: int) -> float:
    """
    Parameters
    ----------
    r: float
        resultant vector length
    n: int
        sample size

    Returns
    -------
    h: float
        smoothing parameter

    Reference
    ---------
    Section 2.2 (P26, Fisher, 1993)
    """

    kappa = circ_kappa(r, n)
    l = 1 / np.sqrt(kappa)  # eq 2.3
    h = np.sqrt(7) * l / np.power(n, 0.2)  # eq 2.4

    return h

nonparametric_density_estimation(alpha, h, radius=1)

Nonparametric density estimates with a quartic kernel function.

Parameters:

Name Type Description Default
alpha ndarray

Angles in radian

required
h float

Smoothing parameters

required
radius float

radius of the plotted circle

1

Returns:

Name Type Description
x ndarray(100)

grid

f ndarray(100)

density

Reference

Section 2.2 (P26, Fisher, 1993)

Source code in pycircstat2/descriptive.py
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
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
def nonparametric_density_estimation(
    alpha: np.ndarray,  # angles in radian
    h: float,  # smoothing parameters
    radius: float = 1,  # radius of the plotted circle
) -> tuple:
    """Nonparametric density estimates with
    a quartic kernel function.

    Parameters
    ----------
    alpha: np.ndarray (n, )
        Angles in radian
    h: float
        Smoothing parameters
    radius: float
        radius of the plotted circle

    Returns
    -------
    x: np.ndarray (100, )
        grid
    f: np.ndarray (100, )
        density

    Reference
    ---------
    Section 2.2 (P26, Fisher, 1993)
    """

    # vectorized version of step 3
    a = alpha
    n = len(a)
    x = np.linspace(0, 2 * np.pi, 100)
    d = np.abs(x[:, None] - a)
    e = np.minimum(d, 2 * np.pi - d)
    e = np.minimum(e, h)
    sum = np.sum((1 - e**2 / h**2) ** 2, 1)
    f = 0.9375 * sum / n / h

    f = radius * np.sqrt(1 + np.pi * f) - radius

    return x, f

circ_range(alpha)

Compute the circular range of angular data.

The circular range is the difference between the maximum and minimum angles in the dataset, adjusted for circular continuity.

Parameters:

Name Type Description Default
alpha ndarray

Angles in radians.

required

Returns:

Type Description
float

Circular range, a measure of clustering (higher = more clustered).

Reference

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

Source code in pycircstat2/descriptive.py
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
def circ_range(alpha: np.ndarray) -> float:
    """
    Compute the circular range of angular data.

    The circular range is the difference between the maximum and minimum angles 
    in the dataset, adjusted for circular continuity.

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

    Returns
    -------
    float
        Circular range, a measure of clustering (higher = more clustered).

    Reference
    ---------
    P162, Section 7.2.3 of Jammalamadaka, S. Rao and SenGupta, A. (2001)
    """
    alpha = np.sort(alpha % (2 * np.pi))  # Convert to [0, 2π) and sort
    spacings = np.diff(alpha, prepend=alpha[-1] - 2 * np.pi)  # Compute spacings
    return 2 * np.pi - np.max(spacings)  # Circular range

circ_quantile(alpha, probs=np.array([0, 0.25, 0.5, 0.75, 1.0]), type=7)

Compute quantiles for circular data.

This function computes quantiles for circular data by shifting the data to be centered around the circular median, applying a linear quantile function, and then shifting back.

Parameters:

Name Type Description Default
alpha ndarray

Sample of circular data (radians).

required
probs float or ndarray

Probabilities at which to compute quantiles. Default is [0, 0.25, 0.5, 0.75, 1.0].

array([0, 0.25, 0.5, 0.75, 1.0])
type int

Quantile algorithm type (default 7, matches R’s default quantile type).

7

Returns:

Type Description
ndarray

Circular quantiles.

References
  • R's quantile.circular from the circular package.
  • Fisher (1993), Section 2.3.2.
Source code in pycircstat2/descriptive.py
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
def circ_quantile(
    alpha: np.ndarray,
    probs: Union[float, np.ndarray] = np.array([0, 0.25, 0.5, 0.75, 1.0]),
    type: int = 7,
) -> np.ndarray:
    """
    Compute quantiles for circular data.

    This function computes quantiles for circular data by shifting the 
    data to be centered around the circular median, applying a linear quantile function,
    and then shifting back.

    Parameters
    ----------
    alpha : np.ndarray
        Sample of circular data (radians).
    probs : float or np.ndarray, optional
        Probabilities at which to compute quantiles. Default is `[0, 0.25, 0.5, 0.75, 1.0]`.
    type : int, optional
        Quantile algorithm type (default `7`, matches R’s default quantile type).

    Returns
    -------
    np.ndarray
        Circular quantiles.

    References
    ----------
    - R's `quantile.circular` from the `circular` package.
    - Fisher (1993), Section 2.3.2.
    """

    # Convert to numpy array
    alpha = np.asarray(alpha)
    probs = np.atleast_1d(probs)

    # Compute circular median
    circular_median = circ_median(alpha)

    # If the median is NaN (e.g., uniform data), return NaNs
    if np.isnan(circular_median):
        return np.full_like(probs, np.nan)

    # Transform data relative to circular median
    shifted_alpha = (alpha - circular_median) % (2 * np.pi)
    shifted_alpha = np.where(shifted_alpha > np.pi, shifted_alpha - 2 * np.pi, shifted_alpha)

    # Compute linear quantiles on transformed data
    linear_quantiles = np.quantile(shifted_alpha, probs, method="linear" if type == 7 else "midpoint")

    # Transform back to original circular space
    circular_quantiles = (linear_quantiles + circular_median) % (2 * np.pi)

    return circular_quantiles