Skip to content

Array Math Module Documentation

This module provides a set of functions to perform operations in arrays as vectors or matrices and as lists.

Functions:

Name Description
norm

Returns the norm of a vector or matrix.

normalize

Returns the normalized vector or matrix.

mean

Returns the mean of a vector or matrix.

median

Returns the median of a vector or matrix.

std

Returns the standard deviation of a vector or matrix.

min

Returns the minimum value of a vector or matrix.

max

Returns the maximum value of a vector or matrix.

print_stats

Prints the statistics of a vector or matrix.

remove_offset

Removes a constant offset from a vector or matrix.

remove_mean

Removes the mean from a vector or matrix.

remove_median

Removes the median from a vector or matrix.

difference

Returns the difference of a vector or matrix.

derivative

Returns the derivative of a vector or matrix.

resample

Resamples a signal to a new time vector.

distance_traveled

Returns the distance traveled by a vector or matrix.

saturate

Saturates a vector or matrix.

wrap360

Wraps an input of angles between 0 and 360 degrees.

wrap180

Wraps an input of angles between -180 and 180 degrees.

wrap2pi

Wraps an input of angles between 0 and 2pi radians.

wrap1pi

Wraps an input of angles between -pi and pi radians.

unwrap2pi

Unwraps an input of angles wrapped between 0 and 2pi radians.

unwrap1pi

Unwraps an input of angles wrapped between -pi and pi radians.

unwrap360

Unwraps an input of angles wrapped between 0 and 360 degrees.

unwrap180

Unwraps an input of angles wrapped between -180 and 180 degrees.

wrapunwrap

Wraps and unwraps an input of angles between 0 and 2pi radians.

wrapunwrap360

Wraps and unwraps an input of angles between 0 and 360 degrees.

Returns the derivative of a vector or matrix.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required
time Union[ndarray, List[float]]

Time vector.

required

Returns:

Type Description
ndarray

Union[np.ndarray, List[float]]: Derivative of the vector or matrix.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> time = np.array([1, 2, 3])
>>> print(derivative(vec, time))
[1. 1.]
Source code in navlib/math/vmath.py
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
514
515
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
def derivative(
    mat: Union[np.ndarray, List[float]], time: Union[np.ndarray, List[float]]
) -> np.ndarray:
    """
    Returns the derivative of a vector or matrix.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.
        time (Union[np.ndarray, List[float]]): Time vector.

    Returns:
        Union[np.ndarray, List[float]]: Derivative of the vector or matrix.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> time = np.array([1, 2, 3])
        >>> print(derivative(vec, time))
        [1. 1.]
    """
    # Convert to lists
    if isinstance(mat, list):
        mat = np.array(mat)
    if isinstance(time, list):
        time = np.array(time)

    # Check for data type
    if not isinstance(mat, np.ndarray):
        raise TypeError("Input must be a numpy array or a list.")

    if not isinstance(time, np.ndarray):
        raise TypeError("Input must be a numpy array or a list.")

    # Shape check
    mat = np.squeeze(mat)
    if mat.ndim > 2:
        raise ValueError("The dimension of the mat array must be up to 2D")
    time = time.squeeze()
    if time.ndim != 1:
        raise ValueError("The time array must be exactly 1D")
    if time.shape[0] != mat.shape[0]:
        raise ValueError(
            "The time vector must have the same number of rows as the input matrix."
        )

    time_diff = difference(time)
    mat_diff = difference(mat)

    if mat.ndim == 1:
        return mat_diff / time_diff
    else:
        # If the input is a matrix, compute the derivative for each column
        return np.array([mat_diff[:, i] / time_diff for i in range(mat.shape[1])]).T

Returns the difference of a vector or matrix. If the input is a matrix, the difference is calculated within each column.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required

Returns:

Type Description
ndarray

Union[np.ndarray, List[float]]: Difference of the vector or matrix.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> print(difference(vec))
[1 1]
Source code in navlib/math/vmath.py
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
def difference(mat: Union[np.ndarray, List[float]]) -> np.ndarray:
    """
    Returns the difference of a vector or matrix. If the input is a matrix, the
    difference is calculated within each column.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.

    Returns:
        Union[np.ndarray, List[float]]: Difference of the vector or matrix.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> print(difference(vec))
        [1 1]
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat

    return np.diff(mat, axis=0, n=1)

Returns the distance traveled by a vector or matrix. If the input is a matrix, the distance traveled is calculated for column the first two or three columns, depending on the dimensions parameter.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required
dimensions (str, default)

Number of dimensions to compute the distance. Options are '2d' or '3d'. Default is '2d'. If the input is a matrix, with more than two columns, the distance will be computed by default with the first two columns if '2d' is selected, or with the first three columns if '3d' is selected.

'2d'
linear bool

If True, the euclidean distance is computed for each measurement between the point and the origin; otherwise, computes the euclidean norm between points as a cumulative distance.

False
full bool

If True, the distance traveled computed for each point is returned; otherwise, the total distance traveled is returned.

False

Returns:

Type Description
Union[float, ndarray]

Union[float, np.ndarray]: The distance traveled given the matrix of points.

Raises:

Type Description
ValueError

If the dimensions options is different than '2d' and '3d'.

ValueError

If the dimensions is set to '2d' and the matrix has less than 2 columns.

ValueError

If the dimensions is set to '3d' and the matrix has less than 3 columns.

Examples:

>>> mat = np.array([[0, 0], [1, 1], [2, 2]])
>>> print(distance_traveled(mat, '2d', True, False))
Source code in navlib/math/vmath.py
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
666
667
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
def distance_traveled(
    mat: Union[np.ndarray, List[float]],
    dimensions: str = "2d",
    linear: bool = False,
    full: bool = False,
) -> Union[float, np.ndarray]:
    """
    Returns the distance traveled by a vector or matrix. If the input is a matrix,
    the distance traveled is calculated for column the first two or three columns,
    depending on the dimensions parameter.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.
        dimensions (str, default): Number of dimensions to compute the distance.
            Options are '2d' or '3d'. Default is '2d'. If the input is a matrix,
            with more than two columns, the distance will be computed by default
            with the first two columns if '2d' is selected, or with the first
            three columns if '3d' is selected.
        linear (bool): If True, the euclidean distance is computed for each
            measurement between the point and the origin; otherwise, computes
            the euclidean norm between points as a cumulative distance.
        full (bool): If True, the distance traveled computed for each point is
            returned; otherwise, the total distance traveled is returned.

    Returns:
        Union[float, np.ndarray]: The distance traveled given the matrix of points.

    Raises:
        ValueError: If the dimensions options is different than '2d' and '3d'.
        ValueError: If the dimensions is set to '2d' and the matrix has less than
            2 columns.
        ValueError: If the dimensions is set to '3d' and the matrix has less than
            3 columns.

    Examples:
        >>> mat = np.array([[0, 0], [1, 1], [2, 2]])
        >>> print(distance_traveled(mat, '2d', True, False))
    """
    # Check dimensions
    if dimensions not in ["2d", "3d"]:
        raise ValueError("Dimensions must be either 2d or 3d.")

    if dimensions == "2d":
        if mat.shape[1] < 2:
            raise ValueError("The input matrix must have at least two columns.")
        mat = mat[:, :2]
    else:
        if mat.shape[1] < 3:
            raise ValueError("The input matrix must have at least three columns.")
        mat = mat[:, :3]

    # Compute distance traveled
    # If linear, for each measurement compute the distance between the point and the origin. If full, return the
    # distance for each point; otherwise, just between the last point and the origin.
    if linear:
        if full:
            return norm(remove_offset(mat, mat[0]))
        else:
            return norm(remove_offset(mat, mat[0]))[-1]

    # Otherwise, for each measurement compute the distance between the current and the previous point and then compute
    # the cumulative distance. If full, return the cumulative sum for each measurement, otherwise, return the total
    # cumulative sum.
    else:
        if full:
            return np.r_[0.0, np.cumsum(norm(difference(mat)))]
        else:
            return np.sum(norm(difference(mat)))

Returns the maximum value of a vector or matrix. If the input is a matrix, the maximum value is calculated for each column.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required
keepdims bool

If True, the output is the same shape as the input. If False, the output is a row vector.

False

Returns:

Type Description
ndarray

np.ndarray: Maximum value of the vector or matrix. If the input is a

ndarray

vector, a float is returned. If the input is a matrix, the maximum value

ndarray

of each column is returned as a row vector.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> print(max(vec))
3
Source code in navlib/math/vmath.py
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
def max(mat: Union[np.ndarray, List[float]], keepdims: bool = False) -> np.ndarray:
    """
    Returns the maximum value of a vector or matrix. If the input is a matrix,
    the maximum value is calculated for each column.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.
        keepdims (bool): If True, the output is the same shape as the input. If
            False, the output is a row vector.

    Returns:
        np.ndarray: Maximum value of the vector or matrix. If the input is a
        vector, a float is returned. If the input is a matrix, the maximum value
        of each column is returned as a row vector.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> print(max(vec))
        3
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat

    # Squeeze the matrix if it has only one row or column
    mat = np.squeeze(mat)

    return np.max(mat, axis=0, keepdims=keepdims)

Returns the mean of a vector or matrix. If the input is a matrix, the mean is calculated for each column.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required
keepdims bool

If True, the output is the same shape as the input. If False, the output is a row vector.

False

Returns:

Type Description
ndarray

np.ndarray: Mean of the vector or matrix. If the input is a vector, a float is returned. If the input is a matrix, the mean of each column is returned as a row vector.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> print(mean(vec))
2.0
Source code in navlib/math/vmath.py
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
def mean(mat: Union[np.ndarray, List[float]], keepdims: bool = False) -> np.ndarray:
    """
    Returns the mean of a vector or matrix. If the input is a matrix, the mean
    is calculated for each column.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.
        keepdims (bool): If True, the output is the same shape as the input. If
            False, the output is a row vector.

    Returns:
        np.ndarray: Mean of the vector or matrix. If the input is a vector, a
            float is returned. If the input is a matrix, the mean of each column
            is returned as a row vector.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> print(mean(vec))
        2.0
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat

    # Squeeze the matrix if it has only one row or column
    mat = np.squeeze(mat)

    return np.mean(mat, axis=0, keepdims=keepdims)

Returns the median of a vector or matrix. If the input is a matrix, the median is calculated for each column.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required
keepdims bool

If True, the output is the same shape as the input. If False, the output is a row vector.

False

Returns:

Type Description
ndarray

np.ndarray: Median of the vector or matrix. If the input is a vector, a float is returned. If the input is a matrix, the median of each column is returned as a row vector.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> print(median(vec))
2.0
Source code in navlib/math/vmath.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def median(mat: Union[np.ndarray, List[float]], keepdims: bool = False) -> np.ndarray:
    """
    Returns the median of a vector or matrix. If the input is a matrix, the
    median is calculated for each column.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.
        keepdims (bool): If True, the output is the same shape as the input. If
            False, the output is a row vector.

    Returns:
        np.ndarray: Median of the vector or matrix. If the input is a vector, a
            float is returned. If the input is a matrix, the median of each column
            is returned as a row vector.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> print(median(vec))
        2.0
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat

    # Squeeze the matrix if it has only one row or column
    mat = np.squeeze(mat)

    return np.median(mat, axis=0, keepdims=keepdims)

Returns the minimum value of a vector or matrix. If the input is a matrix, the minimum value is calculated for each column.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required
keepdims bool

If True, the output is the same shape as the input. If False, the output is a row vector.

False

Returns:

Type Description
ndarray

np.ndarray: Minimum value of the vector or matrix. If the input is a vector, a float is returned. If the input is a matrix, the minimum value of each column is returned as a row vector.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> print(min(vec))
1
Source code in navlib/math/vmath.py
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
282
def min(mat: Union[np.ndarray, List[float]], keepdims: bool = False) -> np.ndarray:
    """
    Returns the minimum value of a vector or matrix. If the input is a matrix,
    the minimum value is calculated for each column.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.
        keepdims (bool): If True, the output is the same shape as the input. If
            False, the output is a row vector.

    Returns:
        np.ndarray: Minimum value of the vector or matrix. If the input is a
            vector, a float is returned. If the input is a matrix, the minimum
            value of each column is returned as a row vector.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> print(min(vec))
        1
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat

    # Squeeze the matrix if it has only one row or column
    mat = np.squeeze(mat)

    return np.min(mat, axis=0, keepdims=keepdims)

Returns the norm of a vector or matrix. If the input is a matrix, the norm is calculated for each row.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required
keepdims bool

If True, the output is the same shape as the input. If False, the output is a row vector.

False

Returns:

Type Description
Union[float, ndarray]

Union[float, np.ndarray]: Norm of the vector or matrix. If the input is a vector, a float is returned. If the input is a matrix, the norm of each column is returned as a row vector

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> norm = np.array([1, 2, 3])
>>> print(norm)
3.7416573867739413
Source code in navlib/math/vmath.py
43
44
45
46
47
48
49
50
51
52
53
54
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
def norm(
    mat: Union[np.ndarray, List[float]], keepdims: bool = False
) -> Union[float, np.ndarray]:
    """
    Returns the norm of a vector or matrix. If the input is a matrix, the norm
    is calculated for each row.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.
        keepdims (bool): If True, the output is the same shape as the input. If
            False, the output is a row vector.

    Returns:
        Union[float, np.ndarray]: Norm of the vector or matrix. If the input is
            a vector, a float is returned. If the input is a matrix, the norm of
            each column is returned as a row vector

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> norm = np.array([1, 2, 3])
        >>> print(norm)
        3.7416573867739413
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat

    # Squeeze the matrix if it has only one row or column
    mat = np.squeeze(mat)

    if mat.ndim == 1:
        return np.linalg.norm(mat)
    else:
        return np.linalg.norm(mat, axis=1, keepdims=keepdims)

Returns the normalized vector or matrix.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required

Returns:

Type Description
ndarray

np.ndarray: Normalized vector or matrix.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> print(normalize(vec))
[0.26726124 0.53452248 0.80178373]
Source code in navlib/math/vmath.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def normalize(mat: Union[np.ndarray, List[float]]) -> np.ndarray:
    """
    Returns the normalized vector or matrix.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.

    Returns:
        np.ndarray: Normalized vector or matrix.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> print(normalize(vec))
        [0.26726124 0.53452248 0.80178373]
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat

    if mat.ndim == 1:
        return mat / norm(mat)
    else:
        return mat / norm(mat, keepdims=True)

Prints the statistics of a vector or matrix.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> print_stats(vec)
Mean: 2.00
Median: 2.00
Standard deviation: 0.82
Min: 1.00
Max: 3.00
Norm: 3.74
MinMax: 2.00
Source code in navlib/math/vmath.py
319
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
354
355
356
357
358
359
360
361
def print_stats(mat: Union[np.ndarray, List[float]]) -> None:
    """
    Prints the statistics of a vector or matrix.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> print_stats(vec)
        Mean: 2.00
        Median: 2.00
        Standard deviation: 0.82
        Min: 1.00
        Max: 3.00
        Norm: 3.74
        MinMax: 2.00
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    if isinstance(mat, list):
        mat = np.array(mat)

    if mat.ndim > 1:
        print("Mean:   " + ", ".join("%.2f" % f for f in mean(mat)))
        print("Median: " + ", ".join("%.2f" % f for f in median(mat)))
        print("Standard deviation: " + ", ".join("%.2f" % f for f in std(mat)))
        print("Min: " + ", ".join("%.2f" % f for f in min(mat)))
        print("Max: " + ", ".join("%.2f" % f for f in max(mat)))
        print("Norm: " + ", ".join("%.2f" % f for f in norm(mat)))
        print("MinMax: " + ", ".join("%.2f" % f for f in (max(mat) - min(mat))))
    else:
        print("Mean:   %.2f" % mean(mat))
        print("Median: %.2f" % median(mat))
        print("Standard deviation: %.2f" % std(mat))
        print("Min: %.2f" % min(mat))
        print("Max: %.2f" % max(mat))
        print("Norm: %.2f" % norm(mat))
        print("MinMax: %.2f" % (max(mat) - min(mat)))

Removes the mean from a vector or matrix. If the array is 2D, the mean is calculated for each column.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required

Returns:

Type Description
ndarray

np.ndarray: Vector or matrix with the mean removed.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> print(remove_mean(vec))
[-1.  0.  1.]
Source code in navlib/math/vmath.py
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
def remove_mean(mat: Union[np.ndarray, List[float]]) -> np.ndarray:
    """
    Removes the mean from a vector or matrix. If the array is 2D, the mean
    is calculated for each column.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.

    Returns:
        np.ndarray: Vector or matrix with the mean removed.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> print(remove_mean(vec))
        [-1.  0.  1.]
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat

    return mat - mean(mat, keepdims=True)

Removes the median from a vector or matrix. If the array is 2D, the median is calculated for each column.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required

Returns:

Type Description
ndarray

np.ndarray: Vector or matrix with the median removed.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> print(remove_median(vec))
[-1.  0.  1.]
Source code in navlib/math/vmath.py
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
def remove_median(mat: Union[np.ndarray, List[float]]) -> np.ndarray:
    """
    Removes the median from a vector or matrix. If the array is 2D, the median
    is calculated for each column.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.

    Returns:
        np.ndarray: Vector or matrix with the median removed.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> print(remove_median(vec))
        [-1.  0.  1.]
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat

    return mat - median(mat, keepdims=True)

Removes a constant offset from a vector or matrix.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required
offset Union[float, int, ndarray, List[float]]

Offset to remove.

required

Returns:

Type Description
ndarray

np.ndarray: Vector or matrix with the offset removed.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

TypeError

If the offset is not a number or an array.

Examples:

>>> vec = np.array([1, 2, 3])
>>> offset = 2
>>> print(remove_offset(vec, offset))
[-1  0  1]
Source code in navlib/math/vmath.py
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
def remove_offset(
    mat: Union[np.ndarray, List[float]],
    offset: Union[float, int, np.ndarray, List[float]],
) -> np.ndarray:
    """
    Removes a constant offset from a vector or matrix.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.
        offset (Union[float, int, np.ndarray, List[float]]): Offset to remove.

    Returns:
        np.ndarray: Vector or matrix with the offset removed.

    Raises:
        TypeError: If the input is not a numpy array or a list.
        TypeError: If the offset is not a number or an array.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> offset = 2
        >>> print(remove_offset(vec, offset))
        [-1  0  1]
    """
    if isinstance(mat, list):
        mat = np.array(mat)
    if not isinstance(mat, np.ndarray):
        raise TypeError("Input must be a numpy array or a list.")
    if isinstance(offset, list):
        offset = np.array(offset)
    if not isinstance(offset, (int, float, np.ndarray)):
        raise TypeError("Offset must be a number or an array.")
    if mat.ndim == 1 and isinstance(offset, np.ndarray) and offset.ndim > 1:
        raise TypeError("Offset must be a number or a 1D array for 1D input.")
    if mat.ndim == 2 and isinstance(offset, np.ndarray):
        offset = offset.squeeze()
        if offset.ndim > 1:
            raise TypeError("Offset must be a number or a 1D array for 2D arrays.")
    return mat - offset

Resamples a signal to a new time vector. If the new time vector extends beyond the range of the old time vector, extrapolation will be performed using linear interpolation with the nearest boundary values.

Parameters:

Name Type Description Default
x Union[ndarray, List[float]]

New time vector, as a 1-D sequence of k floats.

required
xp Union[ndarray, List[float]]

Old time vector, as a 1-D sequence of n floats.

required
fp Union[ndarray, List[float]]

Signal to resample, as a 1-D sequence of n floats or as a nxm array, where n is the number of time steps and m is the number of signals.

required

Returns:

Type Description
ndarray

np.ndarray: Resampled signal, as a 1-D sequence of k floats or as a kxm

ndarray

array, where k is the number of time steps and m is the number of signals.

Raises:

Type Description
TypeError

If the input x, xp or fp is not a numpy array or a list.

ValueError

If the input xp or x is not a 1-D sequence of n floats.

ValueError

If the number of samples in the old time vector and the signal do not match.

ValueError

Time series must be monotonically increasing.

Examples:

>>> x = np.arange(0, 10, 0.1)
>>> xp = np.arange(0, 10, 1)
>>> fp = np.sin(xp)
>>> print(resample(x, xp, fp))
Source code in navlib/math/vmath.py
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
def resample(
    x: Union[np.ndarray, List[float]],
    xp: Union[np.ndarray, List[float]],
    fp: Union[np.ndarray, List[float]],
) -> np.ndarray:
    """
    Resamples a signal to a new time vector. If the new time vector extends beyond
    the range of the old time vector, extrapolation will be performed using linear
    interpolation with the nearest boundary values.

    Args:
        x (Union[np.ndarray, List[float]]): New time vector, as a 1-D sequence of
            k floats.
        xp (Union[np.ndarray, List[float]]): Old time vector, as a 1-D sequence
            of n floats.
        fp (Union[np.ndarray, List[float]]): Signal to resample, as a 1-D sequence
            of n floats or as a nxm array, where n is the number of time steps and m
            is the number of signals.

    Returns:
        np.ndarray: Resampled signal, as a 1-D sequence of k floats or as a kxm
        array, where k is the number of time steps and m is the number of signals.

    Raises:
        TypeError: If the input x, xp or fp is not a numpy array or a list.
        ValueError: If the input xp or x is not a 1-D sequence of n floats.
        ValueError: If the number of samples in the old time vector and the signal do not match.
        ValueError: Time series must be monotonically increasing.

    Examples:
        >>> x = np.arange(0, 10, 0.1)
        >>> xp = np.arange(0, 10, 1)
        >>> fp = np.sin(xp)
        >>> print(resample(x, xp, fp))
    """
    # Check for data type
    if not isinstance(x, (np.ndarray, list)):
        raise TypeError("Input x must be a numpy array or a list.")
    if not isinstance(xp, (np.ndarray, list)):
        raise TypeError("Input xp must be a numpy array or a list.")
    if not isinstance(fp, (np.ndarray, list)):
        raise TypeError("Input fp must be a numpy array or a list.")

    # Convert to numpy arrays
    if isinstance(x, list):
        x = np.array(x)
    if isinstance(xp, list):
        xp = np.array(xp)
    if isinstance(fp, list):
        fp = np.array(fp)

    # Squeeze the arrays
    x = np.squeeze(x)
    xp = np.squeeze(xp)
    fp = np.squeeze(fp)

    # Check for data shape
    if xp.ndim != 1:
        raise ValueError("Input xp must be a 1-D sequence of n floats.")
    if x.ndim != 1:
        raise ValueError("Input x must be a 1-D sequence of k floats.")

    # Check that the number of samples in the old time vector and the signal match
    if xp.shape[0] != fp.shape[0]:
        raise ValueError(
            "The number of samples in the old time vector and the signal must match."
        )

    # Check for data integrity - time series must be monotonic
    if not np.all(difference(xp) > 0):
        raise ValueError("Time series must be monotonically increasing.")

    # Check if new time vector is within bounds and warn if extrapolation is needed
    if x[0] < xp[0] or x[-1] > xp[-1]:
        warn(
            "The new time vector extends beyond the range of the old time vector. "
            f"Old range: [{xp[0]:.3f}, {xp[-1]:.3f}], "
            f"New range: [{x[0]:.3f}, {x[-1]:.3f}]. "
            "Extrapolation will be performed using linear interpolation."
        )

    # Resample the signal
    if fp.ndim == 1:
        return np.interp(x, xp, fp)
    else:
        f = np.empty((x.shape[0], fp.shape[1]))
        for i in range(fp.shape[1]):
            f[:, i] = np.interp(x, xp, fp[:, i])
        return f

Saturates a vector or matrix.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required
min_val float

Minimum value.

required
max_val float

Maximum value.

required

Returns:

Type Description
ndarray

np.ndarray: Saturated vector or matrix.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> min_val = 0
>>> max_val = 2
>>> print(saturate(vec, min_val, max_val))
[1 2 2]
Source code in navlib/math/vmath.py
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
def saturate(
    mat: Union[np.ndarray, List[float]], min_val: float, max_val: float
) -> np.ndarray:
    """
    Saturates a vector or matrix.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.
        min_val (float): Minimum value.
        max_val (float): Maximum value.

    Returns:
        np.ndarray: Saturated vector or matrix.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> min_val = 0
        >>> max_val = 2
        >>> print(saturate(vec, min_val, max_val))
        [1 2 2]
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat
    return np.clip(mat, min_val, max_val)

Returns the standard deviation of a vector or matrix. If the input is a matrix, the standard deviation is calculated for each column.

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required
keepdims bool

If True, the output is the same shape as the input. If False, the output is a row vector.

False

Returns:

Type Description
ndarray

np.ndarray: Standard deviation of the vector or matrix. If the input is a vector, a float is returned. If the input is a matrix, the standard deviation of each column is returned as a row vector.

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([1, 2, 3])
>>> print(std(vec))
0.816496580927726
Source code in navlib/math/vmath.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def std(mat: Union[np.ndarray, List[float]], keepdims: bool = False) -> np.ndarray:
    """
    Returns the standard deviation of a vector or matrix. If the input is a
    matrix, the standard deviation is calculated for each column.

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.
        keepdims (bool): If True, the output is the same shape as the input. If
            False, the output is a row vector.

    Returns:
        np.ndarray: Standard deviation of the vector or matrix. If the input is
            a vector, a float is returned. If the input is a matrix, the standard
            deviation of each column is returned as a row vector.

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([1, 2, 3])
        >>> print(std(vec))
        0.816496580927726
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")

    mat = np.array(mat) if isinstance(mat, list) else mat

    # Squeeze the matrix if it has only one row or column
    mat = np.squeeze(mat)

    return np.std(mat, axis=0, keepdims=keepdims)

Returns the transpose of a vector or matrix. The input can be either 2D or 3D. For 3D arrays einsum is used for better performance

Parameters:

Name Type Description Default
mat Union[ndarray, List[float]]

Vector or matrix.

required

Returns:

Type Description
ndarray

np.ndarray: Transpose of the vector or matrix

Raises:

Type Description
TypeError

If the input is not a numpy array or a list.

Examples:

>>> vec = np.array([[1, 2], [3, 4]])
>>> print(transpose(vec))
[[1  3] [2  4]]
>>> mat = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
>>> print(transpose(mat))
[[[1  3] [5  7]] [[2  4] [6  8]]]
Source code in navlib/math/vmath.py
146
147
148
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
def transpose(mat: Union[np.ndarray, List[float]]) -> np.ndarray:
    """
    Returns the transpose of a vector or matrix. The input can be either 2D or
    3D.
    For 3D arrays einsum is used for better performance

    Args:
        mat (Union[np.ndarray, List[float]]): Vector or matrix.

    Returns:
        np.ndarray: Transpose of the vector or matrix

    Raises:
        TypeError: If the input is not a numpy array or a list.

    Examples:
        >>> vec = np.array([[1, 2], [3, 4]])
        >>> print(transpose(vec))
        [[1  3] [2  4]]

        >>> mat = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
        >>> print(transpose(mat))
        [[[1  3] [5  7]] [[2  4] [6  8]]]
    """
    if not isinstance(mat, np.ndarray) and not isinstance(mat, list):
        raise TypeError("Input must be a numpy array or a list.")
    mat = np.array(mat) if isinstance(mat, list) else mat
    if mat.ndim > 3:
        raise ValueError("The dimension of the array must be up to 3D")

    # Squeeze the matrix if it has only one row or column
    if mat.ndim in [1, 2]:
        return mat.T
    else:
        return np.einsum("ijk->ikj", mat)

Unwraps an input of angles wrapped between -180 and 180 degrees. If the input is a matrix, the wrap is applied to each element.

Parameters:

Name Type Description Default
angles Union[Iterable[float], ndarray]

The angles in degrees as a numpy array or a list.

required

Returns:

Type Description
ndarray

np.ndarray: The unwrapped angles in degrees as a numpy array.

Raises:

Type Description
ValueError

If the input angles are not a numpy array or a list.

Examples:

>>> angles = np.array([45, 90, 135, 180, 45, 90, 135, 180])
>>> unwrapped_angles = unwrap180(angles)
>>> print(unwrapped_angles)
[ 45.  90. 135. 180. 225. 270. 315. 360.]
>>> angles = np.array([[45, 90, 135, 180, 45, 90, 135, 180],
                       [45, 90, 135, 180, 45, 90, 135, 180]])
>>> unwrapped_angles = unwrap180(angles.T)
>>> print(unwrapped_angles.T)
[[ 45.  90. 135. 180. 225. 270. 315. 360.],
 [ 45.  90. 135. 180. 225. 270. 315. 360.]]
Notes

The unwrapping is done using the numpy unwrap function. By default, if the discontinuity between angles is greater than 90 degrees, no unwrapping is done.

Source code in navlib/math/vmath.py
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
def unwrap180(angles: Union[Iterable[float], np.ndarray]) -> np.ndarray:
    """
    Unwraps an input of angles wrapped between -180 and 180 degrees. If the input is a matrix,
    the wrap is applied to each element.

    Args:
        angles (Union[Iterable[float], np.ndarray]): The angles in degrees as a numpy array or a list.

    Returns:
        np.ndarray: The unwrapped angles in degrees as a numpy array.

    Raises:
        ValueError: If the input angles are not a numpy array or a list.

    Examples:
        >>> angles = np.array([45, 90, 135, 180, 45, 90, 135, 180])
        >>> unwrapped_angles = unwrap180(angles)
        >>> print(unwrapped_angles)
        [ 45.  90. 135. 180. 225. 270. 315. 360.]

        >>> angles = np.array([[45, 90, 135, 180, 45, 90, 135, 180],
                               [45, 90, 135, 180, 45, 90, 135, 180]])
        >>> unwrapped_angles = unwrap180(angles.T)
        >>> print(unwrapped_angles.T)
        [[ 45.  90. 135. 180. 225. 270. 315. 360.],
         [ 45.  90. 135. 180. 225. 270. 315. 360.]]

    Notes:
        The unwrapping is done using the numpy unwrap function.
        By default, if the discontinuity between angles is greater than 90 degrees, no unwrapping is done.
    """
    if not isinstance(angles, np.ndarray) and not isinstance(angles, list):
        raise ValueError("Type Error: The angles must be a numpy array or a list.")

    angles = np.array(angles) if isinstance(angles, list) else angles

    # Unwrap each column in the array
    unwrapped = (
        np.unwrap(angles, axis=0, period=180.0)
        if angles.ndim > 1
        else np.unwrap(angles, period=180.0)
    )

    return unwrapped

Unwraps an input of angles wrapped between -pi and pi radians. If the input is a matrix, the wrap is applied to each element.

Parameters:

Name Type Description Default
angles Union[Iterable[float], ndarray]

The angles in radians as a numpy array or a list.

required

Returns:

Type Description
ndarray

np.ndarray: The unwrapped angles in radians as a numpy array.

Raises:

Type Description
ValueError

If the input angles are not a numpy array or a list.

Examples:

>>> angles = np.array([-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
>>> unwrapped_angles = unwrap1pi(angles)
>>> print(unwrapped_angles)
[-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531]
>>> angles = np.array([[-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
                       [-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]])
>>> unwrapped_angles = unwrap1pi(angles.T)
>>> print(unwrapped_angles.T)
[[-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531],
 [-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531]]
Notes

The unwrapping is done using the numpy unwrap function. By default, if the discontinuity between angles is greater than pi/2 radians, no unwrapping is done.

Source code in navlib/math/vmath.py
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
def unwrap1pi(angles: Union[Iterable[float], np.ndarray]) -> np.ndarray:
    """
    Unwraps an input of angles wrapped between -pi and pi radians. If the input is a matrix,
    the wrap is applied to each element.

    Args:
        angles (Union[Iterable[float], np.ndarray]): The angles in radians as a numpy array or a list.

    Returns:
        np.ndarray: The unwrapped angles in radians as a numpy array.

    Raises:
        ValueError: If the input angles are not a numpy array or a list.

    Examples:
        >>> angles = np.array([-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
        >>> unwrapped_angles = unwrap1pi(angles)
        >>> print(unwrapped_angles)
        [-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531]

        >>> angles = np.array([[-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
                               [-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]])
        >>> unwrapped_angles = unwrap1pi(angles.T)
        >>> print(unwrapped_angles.T)
        [[-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531],
         [-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531]]

    Notes:
        The unwrapping is done using the numpy unwrap function.
        By default, if the discontinuity between angles is greater than pi/2 radians, no unwrapping is done.
    """
    if not isinstance(angles, np.ndarray) and not isinstance(angles, list):
        raise ValueError("Type Error: The angles must be a numpy array or a list.")

    angles = np.array(angles) if isinstance(angles, list) else angles

    # Unwrap each column in the array
    unwrapped = (
        np.unwrap(angles, axis=0, period=np.pi)
        if angles.ndim > 1
        else np.unwrap(angles, period=np.pi)
    )

    return unwrapped

Unwraps an input of angles wrapped between 0 and 2pi radians. If the input is a matrix, the wrap is applied to each element.

Parameters:

Name Type Description Default
angles Union[Iterable[float], ndarray]

The angles in radians as a numpy array or a list.

required

Returns:

Type Description
ndarray

np.ndarray: The unwrapped angles in radians as a numpy array.

Raises:

Type Description
ValueError

If the input angles are not a numpy array or a list.

Examples:

>>> angles = np.array([np.pi/2, np.pi, 3*np.pi/2, 2*np.pi, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
>>> unwrapped_angles = unwrap2pi(angles)
>>> print(unwrapped_angles)
[1.57079633 3.14159265 4.71238898 6.28318531 7.85398163 9.42477796 10.99557429 12.56637061]
>>> angles = np.array([[np.pi/2, np.pi, 3*np.pi/2, 2*np.pi, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
                       [np.pi/2, np.pi, 3*np.pi/2, 2*np.pi, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]])
>>> unwrapped_angles = unwrap2pi(angles.T)
>>> print(unwrapped_angles.T)
[[1.57079633 3.14159265 4.71238898 6.28318531 7.85398163 9.42477796 10.99557429 12.56637061],
 [1.57079633 3.14159265 4.71238898 6.28318531 7.85398163 9.42477796 10.99557429 12.56637061]]
Notes

The unwrapping is done using the numpy unwrap function. By default, if the discontinuity between angles is greater than pi radians, no unwrapping is done.

Source code in navlib/math/vmath.py
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
def unwrap2pi(angles: Union[Iterable[float], np.ndarray]) -> np.ndarray:
    """
    Unwraps an input of angles wrapped between 0 and 2pi radians. If the input is a matrix,
    the wrap is applied to each element.

    Args:
        angles (Union[Iterable[float], np.ndarray]): The angles in radians as a numpy array or a list.

    Returns:
        np.ndarray: The unwrapped angles in radians as a numpy array.

    Raises:
        ValueError: If the input angles are not a numpy array or a list.

    Examples:
        >>> angles = np.array([np.pi/2, np.pi, 3*np.pi/2, 2*np.pi, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
        >>> unwrapped_angles = unwrap2pi(angles)
        >>> print(unwrapped_angles)
        [1.57079633 3.14159265 4.71238898 6.28318531 7.85398163 9.42477796 10.99557429 12.56637061]

        >>> angles = np.array([[np.pi/2, np.pi, 3*np.pi/2, 2*np.pi, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
                               [np.pi/2, np.pi, 3*np.pi/2, 2*np.pi, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]])
        >>> unwrapped_angles = unwrap2pi(angles.T)
        >>> print(unwrapped_angles.T)
        [[1.57079633 3.14159265 4.71238898 6.28318531 7.85398163 9.42477796 10.99557429 12.56637061],
         [1.57079633 3.14159265 4.71238898 6.28318531 7.85398163 9.42477796 10.99557429 12.56637061]]

    Notes:
        The unwrapping is done using the numpy unwrap function.
        By default, if the discontinuity between angles is greater than pi radians, no unwrapping is done.
    """
    if not isinstance(angles, np.ndarray) and not isinstance(angles, list):
        raise ValueError("Type Error: The angles must be a numpy array or a list.")

    angles = np.array(angles) if isinstance(angles, list) else angles

    # Unwrap each column in the array
    unwrapped = np.unwrap(angles, axis=0) if angles.ndim > 1 else np.unwrap(angles)

    return unwrapped

Unwraps an input of angles wrapped between 0 and 360 degrees. If the input is a matrix, the wrap is applied to each element.

Parameters:

Name Type Description Default
angles Union[Iterable[float], ndarray]

The angles in degrees as a numpy array or a list.

required

Returns:

Type Description
ndarray

np.ndarray: The unwrapped angles in degrees as a numpy array.

Raises:

Type Description
ValueError

If the input angles are not a numpy array or a list.

Examples:

>>> angles = np.array([30, 90, 180, 270, 360, 30, 90, 180, 270, 360])
>>> unwrapped_angles = unwrap360(angles)
>>> print(unwrapped_angles)
[ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.]
>>> angles = np.array([[30, 90, 180, 270, 360, 30, 90, 180, 270, 360],
                       [30, 90, 180, 270, 360, 30, 90, 180, 270, 360]])
>>> unwrapped_angles = unwrap360(angles.T)
>>> print(unwrapped_angles.T)
[[ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.],
 [ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.]]
Notes

The unwrapping is done using the numpy unwrap function. By default, if the discontinuity between angles is greater than 180 degrees, no unwrapping is done.

Source code in navlib/math/vmath.py
 962
 963
 964
 965
 966
 967
 968
 969
 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
def unwrap360(angles: Union[Iterable[float], np.ndarray]) -> np.ndarray:
    """
    Unwraps an input of angles wrapped between 0 and 360 degrees. If the input is a matrix,
    the wrap is applied to each element.

    Args:
        angles (Union[Iterable[float], np.ndarray]): The angles in degrees as a numpy array or a list.

    Returns:
        np.ndarray: The unwrapped angles in degrees as a numpy array.

    Raises:
        ValueError: If the input angles are not a numpy array or a list.

    Examples:
        >>> angles = np.array([30, 90, 180, 270, 360, 30, 90, 180, 270, 360])
        >>> unwrapped_angles = unwrap360(angles)
        >>> print(unwrapped_angles)
        [ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.]

        >>> angles = np.array([[30, 90, 180, 270, 360, 30, 90, 180, 270, 360],
                               [30, 90, 180, 270, 360, 30, 90, 180, 270, 360]])
        >>> unwrapped_angles = unwrap360(angles.T)
        >>> print(unwrapped_angles.T)
        [[ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.],
         [ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.]]

    Notes:
        The unwrapping is done using the numpy unwrap function.
        By default, if the discontinuity between angles is greater than 180 degrees, no unwrapping is done.
    """
    if not isinstance(angles, np.ndarray) and not isinstance(angles, list):
        raise ValueError("Type Error: The angles must be a numpy array or a list.")

    angles = np.array(angles) if isinstance(angles, list) else angles

    # Unwrap each column in the array
    unwrapped = (
        np.unwrap(angles, axis=0, period=360.0)
        if angles.ndim > 1
        else np.unwrap(angles, period=360.0)
    )

    return unwrapped

Wraps an input of angles between -180 and 180 degrees. If the input is a matrix, the wrap is applied to each column.

Parameters:

Name Type Description Default
angles Union[Iterable[float], ndarray]

The angles in degrees as a numpy array or a list.

required

Returns:

Type Description
ndarray

np.ndarray: The wrapped angles in degrees between -180 and 180 as a numpy array.

Raises:

Type Description
ValueError

If the input angles are not a numpy array or a list.

Examples:

>>> angles = np.array([[-360, -270, -180, -90, 0, 90, 180, 270, 360])
>>> wrapped_angles = wrap180(angles)
>>> print(wrapped_angles)
[  0. 90. -180. -90.   0.  90. -180. -90.   0.]
>>> angles_matrix = np.array([[-360, -270, -180, -90, 0, 90, 180, 270, 360],
                              [720, -450, 180, 270, -540, 630, -720, 810, -900]])
>>> wrapped_angles_matrix = wrap180(angles_matrix)
>>> print(wrapped_angles_matrix)
[[   0.   90. -180.  -90.    0.   90. -180.  -90.    0.]
 [   0.  -90. -180.  -90.    0.  270.    0.  450.    0.]]
Source code in navlib/math/vmath.py
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
def wrap180(angles: Union[Iterable[float], np.ndarray]) -> np.ndarray:
    """
    Wraps an input of angles between -180 and 180 degrees.  If the input is a matrix,
    the wrap is applied to each column.

    Args:
        angles (Union[Iterable[float], np.ndarray]): The angles in degrees as a numpy array or a list.

    Returns:
        np.ndarray: The wrapped angles in degrees between -180 and 180 as a numpy array.

    Raises:
        ValueError: If the input angles are not a numpy array or a list.

    Examples:
        >>> angles = np.array([[-360, -270, -180, -90, 0, 90, 180, 270, 360])
        >>> wrapped_angles = wrap180(angles)
        >>> print(wrapped_angles)
        [  0. 90. -180. -90.   0.  90. -180. -90.   0.]

        >>> angles_matrix = np.array([[-360, -270, -180, -90, 0, 90, 180, 270, 360],
                                      [720, -450, 180, 270, -540, 630, -720, 810, -900]])
        >>> wrapped_angles_matrix = wrap180(angles_matrix)
        >>> print(wrapped_angles_matrix)
        [[   0.   90. -180.  -90.    0.   90. -180.  -90.    0.]
         [   0.  -90. -180.  -90.    0.  270.    0.  450.    0.]]
    """
    if not isinstance(angles, np.ndarray) and not isinstance(angles, list):
        raise ValueError("Type Error: The angles must be a numpy array or a list.")

    angles = np.array(angles) if isinstance(angles, list) else angles

    return np.mod(angles + 180.0, 360.0) - 180.0

Wraps an input of angles between -pi and pi radians. If the input is a matrix, the wrap is applied to each element.

Parameters:

Name Type Description Default
angles Union[Iterable[float], ndarray]

The angles in radians as a numpy array or a list.

required

Returns:

Type Description
ndarray

np.ndarray: The wrapped angles in radians between -pi and pi as a numpy array.

Raises:

Type Description
ValueError

If the input angles are not a numpy array or a list.

Examples:

>>> angles = np.array([-2*np.pi, -3*np.pi/2, -np.pi, 0, np.pi, 3*np.pi/2, 2*np.pi])
>>> wrapped_angles = wrap1pi(angles)
>>> print(wrapped_angles)
[  0.          1.57079633 3.14159265  0.         -3.14159265 -1.57079633  0.          ]
>>> angles_matrix = np.array([[-2*np.pi, -3*np.pi/2, -np.pi, 0, np.pi, 3*np.pi/2, 2*np.pi],
                              [4*np.pi, -5*np.pi/2, 6*np.pi, -7*np.pi/2, 8*np.pi, -9*np.pi/2, 10*np.pi]])
>>> wrapped_angles_matrix = wrap1pi(angles_matrix)
>>> print(wrapped_angles_matrix)
[[ 0.          1.57079633 -3.14159265  0.         -3.14159265 -1.57079633  0.        ]
 [ 0.         -1.57079633  0.          1.57079633  0.         -1.57079633  0.        ]]
Source code in navlib/math/vmath.py
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
def wrap1pi(angles: Union[Iterable[float], np.ndarray]) -> np.ndarray:
    """
    Wraps an input of angles between -pi and pi radians. If the input is a matrix,
    the wrap is applied to each element.

    Args:
        angles (Union[Iterable[float], np.ndarray]): The angles in radians as a numpy array or a list.

    Returns:
        np.ndarray: The wrapped angles in radians between -pi and pi as a numpy array.

    Raises:
        ValueError: If the input angles are not a numpy array or a list.

    Examples:
        >>> angles = np.array([-2*np.pi, -3*np.pi/2, -np.pi, 0, np.pi, 3*np.pi/2, 2*np.pi])
        >>> wrapped_angles = wrap1pi(angles)
        >>> print(wrapped_angles)
        [  0.          1.57079633 3.14159265  0.         -3.14159265 -1.57079633  0.          ]

        >>> angles_matrix = np.array([[-2*np.pi, -3*np.pi/2, -np.pi, 0, np.pi, 3*np.pi/2, 2*np.pi],
                                      [4*np.pi, -5*np.pi/2, 6*np.pi, -7*np.pi/2, 8*np.pi, -9*np.pi/2, 10*np.pi]])
        >>> wrapped_angles_matrix = wrap1pi(angles_matrix)
        >>> print(wrapped_angles_matrix)
        [[ 0.          1.57079633 -3.14159265  0.         -3.14159265 -1.57079633  0.        ]
         [ 0.         -1.57079633  0.          1.57079633  0.         -1.57079633  0.        ]]
    """
    if not isinstance(angles, np.ndarray) and not isinstance(angles, list):
        raise ValueError("Type Error: The angles must be a numpy array or a list.")

    angles = np.array(angles) if isinstance(angles, list) else angles

    return np.mod(angles + np.pi, 2 * np.pi) - np.pi

Wraps an input of angles between 0 and 2pi radians. If the input is a matrix, the wrap is applied to each column.

Parameters:

Name Type Description Default
angles Union[Iterable[float], ndarray]

The angles in radians as a numpy array or a list.

required

Returns:

Type Description
ndarray

np.ndarray: The wrapped angles in radians between 0 and 2pi as a numpy array.

Raises:

Type Description
ValueError

If the input angles are not a numpy array or a list

Examples:

>>> angles = np.array([-np.pi/6, 0, np.pi/2, 5*np.pi])
>>> wrapped_angles = wrap2pi(angles)
>>> print(wrapped_angles)
[5.7595865 0.         1.57079633 3.1415927]
>>> angles_matrix = np.array([[-np.pi/6, 0, np.pi/2, 5*np.pi],
                              [7*np.pi, -4*np.pi, 3*np.pi, 8*np.pi]])
>>> wrapped_angles_matrix = wrap2pi(angles_matrix)
>>> print(wrapped_angles_matrix)
[[5.75958653 0.         1.57079633 3.14159265]
 [3.14159265 0.         3.14159265 0.        ]]
Source code in navlib/math/vmath.py
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
def wrap2pi(angles: Union[Iterable[float], np.ndarray]) -> np.ndarray:
    """
    Wraps an input of angles between 0 and 2pi radians. If the input is a matrix,
    the wrap is applied to each column.

    Args:
        angles (Union[Iterable[float], np.ndarray]): The angles in radians as a numpy array or a list.

    Returns:
        np.ndarray: The wrapped angles in radians between 0 and 2pi as a numpy array.

    Raises:
        ValueError: If the input angles are not a numpy array or a list

    Examples:
        >>> angles = np.array([-np.pi/6, 0, np.pi/2, 5*np.pi])
        >>> wrapped_angles = wrap2pi(angles)
        >>> print(wrapped_angles)
        [5.7595865 0.         1.57079633 3.1415927]

        >>> angles_matrix = np.array([[-np.pi/6, 0, np.pi/2, 5*np.pi],
                                      [7*np.pi, -4*np.pi, 3*np.pi, 8*np.pi]])
        >>> wrapped_angles_matrix = wrap2pi(angles_matrix)
        >>> print(wrapped_angles_matrix)
        [[5.75958653 0.         1.57079633 3.14159265]
         [3.14159265 0.         3.14159265 0.        ]]
    """
    if not isinstance(angles, np.ndarray) and not isinstance(angles, list):
        raise ValueError("Type Error: The angles must be a numpy array or a list.")

    angles = np.array(angles) if isinstance(angles, list) else angles

    return np.mod(angles, 2 * np.pi)

Wraps an input of angles between 0 and 360 degrees. If the input is a matrix, the wrap is applied to each column.

Parameters:

Name Type Description Default
angles Union[Iterable[float], ndarray]

The angles in degrees as a numpy array or a list.

required

Returns:

Type Description
ndarray

np.ndarray: The wrapped angles in degrees between 0 and 360 as a numpy array.

Raises:

Type Description
ValueError

If the input angles are not a numpy array or a list.

Examples:

>>> angles = np.array([-30, 0, 90, 400])
>>> wrapped_angles = wrap360(angles)
>>> print(wrapped_angles)
[330.   0.  90.  40.]
>>> angles_matrix = np.array([[-30, 0, 90, 400], [720, -450, 180, 270]])
>>> wrapped_angles_matrix = wrap360(angles_matrix)
>>> print(wrapped_angles_matrix)
[[330.   0.  90.  40.]
 [  0. 270. 180. 270.]]
Source code in navlib/math/vmath.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
def wrap360(angles: Union[Iterable[float], np.ndarray]) -> np.ndarray:
    """
    Wraps an input of angles between 0 and 360 degrees. If the input is a matrix,
    the wrap is applied to each column.

    Args:
        angles (Union[Iterable[float], np.ndarray]): The angles in degrees as a numpy array or a list.

    Returns:
        np.ndarray: The wrapped angles in degrees between 0 and 360 as a numpy array.

    Raises:
        ValueError: If the input angles are not a numpy array or a list.

    Examples:
        >>> angles = np.array([-30, 0, 90, 400])
        >>> wrapped_angles = wrap360(angles)
        >>> print(wrapped_angles)
        [330.   0.  90.  40.]

        >>> angles_matrix = np.array([[-30, 0, 90, 400], [720, -450, 180, 270]])
        >>> wrapped_angles_matrix = wrap360(angles_matrix)
        >>> print(wrapped_angles_matrix)
        [[330.   0.  90.  40.]
         [  0. 270. 180. 270.]]
    """
    if not isinstance(angles, np.ndarray) and not isinstance(angles, list):
        raise ValueError("Type Error: The angles must be a numpy array or a list.")

    angles = np.array(angles) if isinstance(angles, list) else angles

    return np.mod(angles, 360.0)

Wraps an input of angle between -pi and pi radians and then unwraps it. If the input is a matrix, the wrap is applied to each element.

Parameters:

Name Type Description Default
angles Union[Iterable[float], ndarray]

The angles in radians as a numpy array or a list.

required

Returns:

Type Description
ndarray

np.ndarray: The wrapped and unwrapped angles in radians as a numpy array.

Raises:

Type Description
ValueError

If the input angles are not a numpy array or a list.

Examples:

>>> angles = np.array([-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
>>> wrapped_unwrapped_angles = wrapunwrap(angles)
>>> print(wrapped_unwrapped_angles)
[-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531]
>>> angles = np.array([[-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
                       [-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]])
>>> wrapped_unwrapped_angles = wrapunwrap(angles.T)
>>> print(wrapped_unwrapped_angles.T)
[[-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531],
 [-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531]]
Source code in navlib/math/vmath.py
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
def wrapunwrap(angles: Union[Iterable[float], np.ndarray]) -> np.ndarray:
    """
    Wraps an input of angle between -pi and pi radians and then unwraps it. If the input is a matrix,
    the wrap is applied to each element.

    Args:
        angles (Union[Iterable[float], np.ndarray]): The angles in radians as a numpy array or a list.

    Returns:
        np.ndarray: The wrapped and unwrapped angles in radians as a numpy array.

    Raises:
        ValueError: If the input angles are not a numpy array or a list.

    Examples:
        >>> angles = np.array([-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi])
        >>> wrapped_unwrapped_angles = wrapunwrap(angles)
        >>> print(wrapped_unwrapped_angles)
        [-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531]

        >>> angles = np.array([[-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi],
                               [-3*np.pi/2, -np.pi, -np.pi/2, 0, np.pi/2, np.pi, 3*np.pi/2, 2*np.pi]])
        >>> wrapped_unwrapped_angles = wrapunwrap(angles.T)
        >>> print(wrapped_unwrapped_angles.T)
        [[-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531],
         [-4.71238898 -3.14159265 -1.57079633  0.          1.57079633  3.14159265  4.71238898  6.28318531]]
    """
    if not isinstance(angles, np.ndarray) and not isinstance(angles, list):
        raise ValueError("Type Error: The angles must be a numpy array or a list.")

    angles = np.array(angles) if isinstance(angles, list) else angles

    return unwrap1pi(wrap1pi(angles))

Wraps an input of angle between 0 and 360 degrees and then unwraps it. If the input is a matrix, the wrap is applied to each element.

Parameters:

Name Type Description Default
angles Union[Iterable[float], ndarray]

The angles in degrees as a numpy array or a list.

required

Returns:

Type Description
ndarray

np.ndarray: The wrapped and unwrapped angles in degrees as a numpy array.

Raises:

Type Description
ValueError

If the input angles are not a numpy array or a list.

Examples:

>>> angles = np.array([30, 90, 180, 270, 360, 390, 450, 540, 630, 720])
>>> wrapped_unwrapped_angles = wrapunwrap360(angles)
>>> print(wrapped_unwrapped_angles)
[ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.]
>>> angles = np.array([[30, 90, 180, 270, 360, 390, 450, 540, 630, 720],
                       [30, 90, 180, 270, 360, 390, 450, 540, 630, 720]])
>>> wrapped_unwrapped_angles = wrapunwrap360(angles.T)
>>> print(wrapped_unwrapped_angles.T)
[[ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.],
 [ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.]]
Source code in navlib/math/vmath.py
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
def wrapunwrap360(angles: Union[Iterable[float], np.ndarray]) -> np.ndarray:
    """
    Wraps an input of angle between 0 and 360 degrees and then unwraps it. If the input is a matrix,
    the wrap is applied to each element.

    Args:
        angles (Union[Iterable[float], np.ndarray]): The angles in degrees as a numpy array or a list.

    Returns:
        np.ndarray: The wrapped and unwrapped angles in degrees as a numpy array.

    Raises:
        ValueError: If the input angles are not a numpy array or a list.

    Examples:
        >>> angles = np.array([30, 90, 180, 270, 360, 390, 450, 540, 630, 720])
        >>> wrapped_unwrapped_angles = wrapunwrap360(angles)
        >>> print(wrapped_unwrapped_angles)
        [ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.]

        >>> angles = np.array([[30, 90, 180, 270, 360, 390, 450, 540, 630, 720],
                               [30, 90, 180, 270, 360, 390, 450, 540, 630, 720]])
        >>> wrapped_unwrapped_angles = wrapunwrap360(angles.T)
        >>> print(wrapped_unwrapped_angles.T)
        [[ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.],
         [ 30.  90. 180. 270. 360. 390. 450. 540. 630. 720.]]
    """
    if not isinstance(angles, np.ndarray) and not isinstance(angles, list):
        raise ValueError("Type Error: The angles must be a numpy array or a list.")

    angles = np.array(angles) if isinstance(angles, list) else angles

    return unwrap360(wrap360(angles))