File: utils.py

package info (click to toggle)
meep-mpi-default 1.29.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 79,148 kB
  • sloc: cpp: 32,541; python: 31,061; lisp: 1,225; makefile: 516; sh: 249; ansic: 131; javascript: 5
file content (29 lines) | stat: -rw-r--r-- 984 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from typing import Union
import unittest

import numpy as np


class ApproxComparisonTestCase(unittest.TestCase):
    """A mixin for adding correct scalar/vector comparison."""

    def assertClose(
        self,
        x: Union[float, np.ndarray],
        y: Union[float, np.ndarray],
        epsilon: float = 1e-2,
        msg: str = "",
    ):
        """Checks if two scalars or vectors satisfy ‖x-y‖ ≤ ε * max(‖x‖, ‖y‖).

        Args:
            x, y: two quantities to be compared (scalars or 1d arrays).
            epsilon: threshold value (maximum) of the relative error.
            msg: a string to display if the inequality is violated.
        """
        x = np.atleast_1d(x).ravel()
        y = np.atleast_1d(y).ravel()
        x_norm = np.linalg.norm(x, ord=np.inf)
        y_norm = np.linalg.norm(y, ord=np.inf)
        diff_norm = np.linalg.norm(x - y, ord=np.inf)
        self.assertLessEqual(diff_norm, epsilon * np.maximum(x_norm, y_norm), msg)