Beispiel #1
0
 def indicator(X):
     T = np.logical_and(float_cmp(X[:, 1], dd.domain[1, 1]),
                        dd.top == bt)
     B = np.logical_and(float_cmp(X[:, 1], dd.domain[0, 1]),
                        dd.bottom == bt)
     TB = np.logical_or(T, B)
     return TB
Beispiel #2
0
 def indicator(X):
     L = np.logical_and(float_cmp(X[:, 0], dd.domain[0, 0]), dd.left == bt)
     R = np.logical_and(float_cmp(X[:, 0], dd.domain[1, 0]), dd.right == bt)
     T = np.logical_and(float_cmp(X[:, 1], dd.domain[1, 1]), dd.top == bt)
     B = np.logical_and(float_cmp(X[:, 1], dd.domain[0, 1]), dd.bottom == bt)
     LR = np.logical_or(L, R)
     TB = np.logical_or(T, B)
     return np.logical_or(LR, TB)
Beispiel #3
0
 def indicator(X):
     L = np.logical_and(float_cmp(X[:, 0], dd.domain[0, 0]), dd.left == bt)
     R = np.logical_and(float_cmp(X[:, 0], dd.domain[1, 0]), dd.right == bt)
     T = np.logical_and(float_cmp(X[:, 1], dd.domain[1, 1]), dd.top == bt)
     B = np.logical_and(float_cmp(X[:, 1], dd.domain[0, 1]), dd.bottom == bt)
     LR = np.logical_or(L, R)
     TB = np.logical_or(T, B)
     return np.logical_or(LR, TB)
Beispiel #4
0
 def test_other_functions(self):
     order = GaussQuadratures.orders[-1]
     for name, function, integral in FUNCTIONS:
         Q = GaussQuadratures.iter_quadrature(order)
         ret = sum([function(p) * w for (p, w) in Q])
         assert float_cmp(ret, integral), '{} integral wrong: {} vs {} (quadrature order {})'.format(
             name, integral, ret, order)
Beispiel #5
0
def test_newton(order, error_measure):
    mop = MonomOperator(order)
    U, _ = _newton(mop,
                   atol=1e-15 if error_measure == 'residual' else 1e-7,
                   rtol=0.,
                   error_measure=error_measure)
    assert float_cmp(mop.apply(U).to_numpy(), 0.0)
Beispiel #6
0
def test_quadrature_other_functions():
    order = GaussQuadratures.orders[-1]
    for name, function, integral in FUNCTIONS:
        Q = GaussQuadratures.iter_quadrature(order)
        ret = sum([function(p) * w for (p, w) in Q])
        assert float_cmp(ret, integral), \
            f'{name} integral wrong: {integral} vs {ret} (quadrature order {order})'
Beispiel #7
0
 def test_other_functions(self):
     order = GaussQuadratures.orders[-1]
     for name, function, integral in FUNCTIONS:
         Q = GaussQuadratures.iter_quadrature(order)
         ret = sum([function(p) * w for (p, w) in Q])
         assert float_cmp(ret, integral), '{} integral wrong: {} vs {} (quadrature order {})'.format(
             name, integral, ret, order)
Beispiel #8
0
 def test_other_functions(self):
     order = GaussQuadratures.orders[-1]
     for name, function, integral in FUNCTIONS:
         Q = GaussQuadratures.iter_quadrature(order)
         ret = sum([function(p) * w for (p, w) in Q])
         assert float_cmp(ret, integral), \
             f'{name} integral wrong: {integral} vs {ret} (quadrature order {order})'
Beispiel #9
0
 def __init__(self, thetas_prime, thetas, mu_bar, gamma_mu_bar=1., name=None):
     assert isinstance(thetas_prime, (list, tuple))
     assert isinstance(thetas, (list, tuple))
     assert len(thetas) > 0
     assert len(thetas) == len(thetas_prime)
     assert all([isinstance(theta, (Number, ParameterFunctional)) for theta in thetas])
     assert all([isinstance(theta, (Number, ParameterFunctional)) for theta in thetas_prime])
     thetas = tuple(ConstantParameterFunctional(f) if not isinstance(f, ParameterFunctional) else f
                    for f in thetas)
     thetas_prime = tuple(ConstantParameterFunctional(f) if not isinstance(f, ParameterFunctional) else f
                    for f in thetas_prime)
     if not isinstance(mu_bar, Mu):
         mu_bar = Parameters.of(thetas).parse(mu_bar)
     assert Parameters.of(thetas).assert_compatible(mu_bar)
     thetas_mu_bar = np.array([theta(mu_bar) for theta in thetas])
     assert not np.any(float_cmp(thetas_mu_bar, 0))
     assert isinstance(gamma_mu_bar, Number)
     assert gamma_mu_bar > 0
     self.__auto_init(locals())
     self.thetas_mu_bar = thetas_mu_bar
     self.theta_mu_bar_has_negative = True if np.any(thetas_mu_bar < 0) else False
     if self.theta_mu_bar_has_negative:
         # If 0 is in theta_prime(mu), we need to use the absolute value to ensure
         # that the bound is still valid (and not zero)
         self.abs_thetas_mu_bar = np.array([np.abs(theta(mu_bar)) for theta in thetas])
Beispiel #10
0
 def test_polynomials(self):
     for n, function, _, integral in polynomials(GaussQuadratures.orders[-1]):
         name = 'x^{}'.format(n)
         for order in GaussQuadratures.orders:
             if n > order / 2:
                 continue
             Q = GaussQuadratures.iter_quadrature(order)
             ret = sum([function(p) * w for (p, w) in Q])
             assert float_cmp(ret, integral), '{} integral wrong: {} vs {} (quadrature order {})'.format(
                 name, integral, ret, order)
Beispiel #11
0
def test_quadrature_polynomials():
    for n, function, _, integral in polynomials(GaussQuadratures.orders[-1]):
        name = f'x^{n}'
        for order in GaussQuadratures.orders:
            if n > order / 2:
                continue
            Q = GaussQuadratures.iter_quadrature(order)
            ret = sum([function(p) * w for (p, w) in Q])
            assert float_cmp(ret, integral), \
                f'{name} integral wrong: {integral} vs {ret} (quadrature order {order})'
Beispiel #12
0
 def test_polynomials(self):
     for n, function, _, integral in polynomials(GaussQuadratures.orders[-1]):
         name = 'x^{}'.format(n)
         for order in GaussQuadratures.orders:
             if n > order / 2:
                 continue
             Q = GaussQuadratures.iter_quadrature(order)
             ret = sum([function(p) * w for (p, w) in Q])
             assert float_cmp(ret, integral), '{} integral wrong: {} vs {} (quadrature order {})'.format(
                 name, integral, ret, order)
Beispiel #13
0
 def test_polynomials(self):
     for n, function, _, integral in polynomials(GaussQuadratures.orders[-1]):
         name = f'x^{n}'
         for order in GaussQuadratures.orders:
             if n > order / 2:
                 continue
             Q = GaussQuadratures.iter_quadrature(order)
             ret = sum([function(p) * w for (p, w) in Q])
             assert float_cmp(ret, integral), \
                 f'{name} integral wrong: {integral} vs {ret} (quadrature order {order})'
 def __init__(self, thetas, mu_bar, gamma_mu_bar=1., name=None):
     assert isinstance(thetas, (list, tuple))
     assert len(thetas) > 0
     assert all([isinstance(theta, (Number, ParameterFunctional)) for theta in thetas])
     thetas = tuple(ConstantParameterFunctional(f) if not isinstance(f, ParameterFunctional) else f
                    for f in thetas)
     self.build_parameter_type(*thetas)
     mu_bar = self.parse_parameter(mu_bar)
     thetas_mu_bar = np.array([theta(mu_bar) for theta in thetas])
     assert not np.any(float_cmp(thetas_mu_bar, 0))
     assert isinstance(gamma_mu_bar, Number)
     assert gamma_mu_bar > 0
     self.__auto_init(locals())
     self.thetas_mu_bar = thetas_mu_bar
Beispiel #15
0
    def test_props(self):
        tol_range = [0.0, 1e-8, 1]
        nan = float('nan')
        inf = float('inf')
        for (rtol, atol) in itertools.product(tol_range, tol_range):
            msg = 'rtol: {} | atol {}'.format(rtol, atol)
            assert float_cmp(0., 0., rtol, atol), msg
            assert float_cmp(-0., -0., rtol, atol), msg
            assert float_cmp(-1., -1., rtol, atol), msg
            assert float_cmp(0., -0., rtol, atol), msg
            assert not float_cmp(2., -2., rtol, atol), msg

            assert not float_cmp(nan, nan, rtol, atol), msg
            assert nan != nan
            assert not (nan == nan)
            assert not float_cmp(-nan, nan, rtol, atol), msg

            assert not float_cmp(inf, inf, rtol, atol), msg
            assert not (inf != inf)
            assert inf == inf
            if rtol > 0:
                assert float_cmp(-inf, inf, rtol, atol), msg
            else:
                assert not float_cmp(-inf, inf, rtol, atol), msg
Beispiel #16
0
    def test_props(self):
        tol_range = [0.0, 1e-8, 1]
        nan = float('nan')
        inf = float('inf')
        for (rtol, atol) in itertools.product(tol_range, tol_range):
            msg = 'rtol: {} | atol {}'.format(rtol, atol)
            assert float_cmp(0., 0., rtol, atol), msg
            assert float_cmp(-0., -0., rtol, atol), msg
            assert float_cmp(-1., -1., rtol, atol), msg
            assert float_cmp(0., -0., rtol, atol), msg
            assert not float_cmp(2., -2., rtol, atol), msg

            assert not float_cmp(nan, nan, rtol, atol), msg
            assert nan != nan
            assert not (nan == nan)
            assert not float_cmp(-nan, nan, rtol, atol), msg

            assert not float_cmp(inf, inf, rtol, atol), msg
            assert not (inf != inf)
            assert inf == inf
            if rtol > 0:
                assert float_cmp(-inf, inf, rtol, atol), msg
            else:
                assert not float_cmp(-inf, inf, rtol, atol), msg
Beispiel #17
0
    def test_props(self):
        tol_range = [None, 0.0, 1]
        nan = float('nan')
        inf = float('inf')
        for (rtol, atol) in itertools.product(tol_range, tol_range):
            msg = 'rtol: {} | atol {}'.format(rtol, atol)
            self.assertTrue(float_cmp(0, 0, rtol, atol), msg)
            self.assertTrue(float_cmp(-0, -0, rtol, atol), msg)
            self.assertTrue(float_cmp(-1, -1, rtol, atol), msg)
            self.assertTrue(float_cmp(0, -0, rtol, atol), msg)
            self.assertFalse(float_cmp(2, -2, rtol, atol), msg)

            self.assertFalse(float_cmp(nan, nan, rtol, atol), msg)
            self.assertTrue(nan != nan)
            self.assertFalse(nan == nan)
            self.assertFalse(float_cmp(-nan, nan, rtol, atol), msg)

            self.assertFalse(float_cmp(inf, inf, rtol, atol), msg)
            self.assertFalse(inf != inf)
            self.assertTrue(inf == inf)
            self.assertTrue(float_cmp(-inf, inf, rtol, atol), msg)
Beispiel #18
0
def contains_zero_vector(vector_array, rtol=None, atol=None):
    """returns `True` iff any vector in the array float_compares to 0s of the same dim

    Parameters
    ----------
    vector_array
        a |VectorArray| implementation
    rtol
        relative tolerance for float_cmp
    atol
        absolute tolerance for float_cmp
    """
    for i in range(len(vector_array)):
        sup = vector_array[i].sup_norm()
        if float_cmp(sup, 0.0, rtol, atol):
            return True
    return False
Beispiel #19
0
    def almost_equal(self, other, ind=None, o_ind=None, rtol=None, atol=None):
        assert self.check_ind(ind)
        assert other.check_ind(o_ind)
        assert self.dim == other.dim

        if NUMPY_INDEX_QUIRK:
            if self._len == 0 and hasattr(ind, '__len__'):
                ind = None
            if other._len == 0 and hasattr(o_ind, '__len__'):
                o_ind = None

        A = self._array[:self._len] if ind is None else \
            self._array[ind] if hasattr(ind, '__len__') else self._array[ind:ind + 1]
        B = other._array[:other._len] if o_ind is None else \
            other._array[o_ind] if hasattr(o_ind, '__len__') else other._array[o_ind:o_ind + 1]

        R = np.all(float_cmp(A, B, rtol=rtol, atol=atol), axis=1).squeeze()
        if R.ndim == 0:
            R = R[np.newaxis, ...]
        return R
Beispiel #20
0
def test_copy_repeated_index(vector_array):
    v = vector_array
    if len(v) == 0:
        return
    ind = [int(len(v) * 3 / 4)] * 2
    for deep in (True, False):
        c = v[ind].copy(deep)
        assert almost_equal(c[0], v[ind[0]])
        assert almost_equal(c[1], v[ind[0]])
        try:
            assert indexed(v.to_numpy(), ind).shape == c.to_numpy().shape
        except NotImplementedError:
            pass
        c[0].scal(2.)
        assume(c[0].norm() != np.inf)
        assert almost_equal(c[1], v[ind[0]])
        assert float_cmp(c[0].norm(), 2 * v[ind[0]].norm())
        try:
            assert indexed(v.to_numpy(), ind).shape == c.to_numpy().shape
        except NotImplementedError:
            pass
Beispiel #21
0
 def test_weights(self):
     for order in GaussQuadratures.orders:
         _, W = GaussQuadratures.quadrature(order)
         assert float_cmp(sum(W), 1)
Beispiel #22
0
def test_newton(order):
    U, _ = _newton(order, atol=1e-15)
    assert float_cmp(U.data, 0.0)
Beispiel #23
0
def flatten_grid(grid):
    """This method is used by our visualizers to render n-dimensional grids which cannot
    be embedded into R^n by duplicating vertices which would have to be mapped to multiple
    points at once. (Think of grids on rectangular domains with identified edges.)

    Parameters
    ----------
    grid
        The |Grid| to flatten.

    Returns
    -------
    subentities
        The `subentities(0, grid.dim)` relation for the flattened grid.
    coordinates
        The coordinates of the codim-`grid.dim` entities.
    entity_map
        Maps the indices of the codim-`grid.dim` entities of the flattened
        grid to the indices of the corresponding entities in the original grid.
    """
    # special handling of known flat grids
    if isinstance(grid, (RectGrid, TriaGrid)) and not grid.identify_left_right and not grid.identify_bottom_top:
        subentities = grid.subentities(0, grid.dim)
        coordinates = grid.centers(grid.dim)
        entity_map = np.arange(grid.size(grid.dim), dtype=np.int32)
        return subentities, coordinates, entity_map

    # first we determine which vertices are mapped to different coordinates when using the
    # embeddings of their codim-0 superentities
    dim = grid.dim
    global_coordinates = grid.embeddings(dim)[1]
    subentities = grid.subentities(0, dim)
    super_entities = grid.superentities(dim, 0)
    superentity_indices = grid.superentity_indices(dim, 0)
    A, B = grid.embeddings(0)
    ref_el_coordinates = grid.reference_element.subentity_embedding(dim)[1]
    local_coordinates = np.einsum('eij,vj->evi', A, ref_el_coordinates) + B[:, np.newaxis, :]
    critical_vertices = np.unique(subentities[np.logical_not(np.all(float_cmp(global_coordinates[subentities],
                                                                              local_coordinates), axis=2))])
    del A
    del B

    # when there are critical vertices, we have to create additional vertices
    if len(critical_vertices) > 0:
        subentities = subentities.copy()
        supe = super_entities[critical_vertices]
        supi = superentity_indices[critical_vertices]
        coord = local_coordinates[supe, supi]

        new_points = np.ones_like(supe, dtype=np.int32) * -1
        new_points[:, 0] = critical_vertices
        num_points = grid.size(dim)
        entity_map = np.empty((0,), dtype=np.int32)
        for i in xrange(new_points.shape[1]):
            for j in xrange(i):
                new_points[:, i] = np.where(supe[:, i] == -1, new_points[:, i],
                                            np.where(np.all(float_cmp(coord[:, i], coord[:, j]), axis=1),
                                                     new_points[:, j], new_points[:, i]))
            new_point_inds = np.where(np.logical_and(new_points[:, i] == -1, supe[:, i] != -1))[0]
            new_points[new_point_inds, i] = np.arange(num_points, num_points + len(new_point_inds))
            num_points += len(new_point_inds)
            entity_map = np.hstack((entity_map, critical_vertices[new_point_inds]))

        entity_map = np.hstack((np.arange(grid.size(dim), dtype=np.int32), entity_map))

        # handle -1 entries in supe/supi correctly ...
        ci = np.where(critical_vertices == subentities[-1, -1])[0]
        if len(ci) > 0:
            assert len(ci) == 1
            ci = ci[0]
            i = np.where(supe[ci] == (grid.size(0) - 1))[0]
            if len(i) > 0:
                assert len(i) == 1
                i = i[0]
                new_points[supe == -1] = new_points[ci, i]
            else:
                new_points[supe == -1] = subentities[-1, -1]
        else:
            new_points[supe == -1] = subentities[-1, -1]
        subentities[supe, supi] = new_points
        super_entities, superentity_indices = inverse_relation(subentities, size_rhs=num_points, with_indices=True)
        coordinates = local_coordinates[super_entities[:, 0], superentity_indices[:, 0]]
    else:
        coordinates = global_coordinates
        entity_map = np.arange(grid.size(dim), dtype=np.int32)

    return subentities, coordinates, entity_map
Beispiel #24
0
def flatten_grid(grid):
    """This method is used by our visualizers to render n-dimensional grids which cannot
    be embedded into R^n by duplicating vertices which would have to be mapped to multiple
    points at once. (Think of grids on rectangular domains with identified edges.)

    Parameters
    ----------
    grid
        The |Grid| to flatten.

    Returns
    -------
    subentities
        The `subentities(0, grid.dim)` relation for the flattened grid.
    coordinates
        The coordinates of the codim-`grid.dim` entities.
    entity_map
        Maps the indices of the codim-`grid.dim` entities of the flattened
        grid to the indices of the corresponding entities in the original grid.
    """
    # special handling of known flat grids
    if isinstance(
            grid,
        (RectGrid, TriaGrid
         )) and not grid.identify_left_right and not grid.identify_bottom_top:
        subentities = grid.subentities(0, grid.dim)
        coordinates = grid.centers(grid.dim)
        entity_map = np.arange(grid.size(grid.dim), dtype=np.int32)
        return subentities, coordinates, entity_map

    # first we determine which vertices are mapped to different coordinates when using the
    # embeddings of their codim-0 superentities
    dim = grid.dim
    global_coordinates = grid.embeddings(dim)[1]
    subentities = grid.subentities(0, dim)
    super_entities = grid.superentities(dim, 0)
    superentity_indices = grid.superentity_indices(dim, 0)
    A, B = grid.embeddings(0)
    ref_el_coordinates = grid.reference_element.subentity_embedding(dim)[1]
    local_coordinates = np.einsum('eij,vj->evi', A,
                                  ref_el_coordinates) + B[:, np.newaxis, :]
    critical_vertices = np.unique(subentities[np.logical_not(
        np.all(float_cmp(global_coordinates[subentities], local_coordinates),
               axis=2))])
    del A
    del B

    # when there are critical vertices, we have to create additional vertices
    if len(critical_vertices) > 0:
        subentities = subentities.copy()
        supe = super_entities[critical_vertices]
        supi = superentity_indices[critical_vertices]
        coord = local_coordinates[supe, supi]

        new_points = np.ones_like(supe, dtype=np.int32) * -1
        new_points[:, 0] = critical_vertices
        num_points = grid.size(dim)
        entity_map = np.empty((0, ), dtype=np.int32)
        for i in range(new_points.shape[1]):
            for j in range(i):
                new_points[:, i] = np.where(
                    supe[:, i] == -1, new_points[:, i],
                    np.where(
                        np.all(float_cmp(coord[:, i], coord[:, j]), axis=1),
                        new_points[:, j], new_points[:, i]))
            new_point_inds = np.where(
                np.logical_and(new_points[:, i] == -1, supe[:, i] != -1))[0]
            new_points[new_point_inds,
                       i] = np.arange(num_points,
                                      num_points + len(new_point_inds))
            num_points += len(new_point_inds)
            entity_map = np.hstack(
                (entity_map, critical_vertices[new_point_inds]))

        entity_map = np.hstack((np.arange(grid.size(dim),
                                          dtype=np.int32), entity_map))

        # handle -1 entries in supe/supi correctly ...
        ci = np.where(critical_vertices == subentities[-1, -1])[0]
        if len(ci) > 0:
            assert len(ci) == 1
            ci = ci[0]
            i = np.where(supe[ci] == (grid.size(0) - 1))[0]
            if len(i) > 0:
                assert len(i) == 1
                i = i[0]
                new_points[supe == -1] = new_points[ci, i]
            else:
                new_points[supe == -1] = subentities[-1, -1]
        else:
            new_points[supe == -1] = subentities[-1, -1]
        subentities[supe, supi] = new_points
        super_entities, superentity_indices = inverse_relation(
            subentities, size_rhs=num_points, with_indices=True)
        coordinates = local_coordinates[super_entities[:, 0],
                                        superentity_indices[:, 0]]
    else:
        coordinates = global_coordinates
        entity_map = np.arange(grid.size(dim), dtype=np.int32)

    return subentities, coordinates, entity_map
Beispiel #25
0
def test_newton_residual_is_zero(order=5):
    mop = MonomOperator(order)
    U, _ = _newton(mop, initial_value=0.0)
    assert float_cmp(mop.apply(U).to_numpy(), 0.0)
Beispiel #26
0
def test_newton_with_line_search():
    mop = MonomOperator(3) - 2 * MonomOperator(1) + 2 * MonomOperator(0)
    U, _ = _newton(mop, initial_value=0.0, atol=1e-15, relax='armijo')
    assert float_cmp(mop.apply(U).to_numpy(), 0.0)
Beispiel #27
0
def test_newton(order):
    U, _ = _newton(order)
    assert float_cmp(U.data, 0.0)
Beispiel #28
0
def test_newton(order):
    U, _ = _newton(order, atol=1e-15)
    assert float_cmp(U.to_numpy(), 0.0)
Beispiel #29
0
 def test_weights(self):
     for order in GaussQuadratures.orders:
         _, W = GaussQuadratures.quadrature(order)
         assert float_cmp(sum(W), 1)
Beispiel #30
0
 def indicator(X):
     T = np.logical_and(float_cmp(X[:, 1], dd.domain[1, 1]), dd.top == bt)
     B = np.logical_and(float_cmp(X[:, 1], dd.domain[0, 1]), dd.bottom == bt)
     TB = np.logical_or(T, B)
     return TB
Beispiel #31
0
 def indicator(X):
     L = np.logical_and(float_cmp(X[:, 0], dd.domain[0]), dd.left == bt)
     R = np.logical_and(float_cmp(X[:, 0], dd.domain[1]), dd.right == bt)
     return np.logical_or(L, R)
Beispiel #32
0
 def indicator(X):
     L = np.logical_and(float_cmp(X[:, 0], dd.domain[0]),
                        dd.left == bt)
     R = np.logical_and(float_cmp(X[:, 0], dd.domain[1]),
                        dd.right == bt)
     return np.logical_or(L, R)
Beispiel #33
0
def test_newton(order):
    U, _ = _newton(order)
    assert float_cmp(U.data, 0.0)
Beispiel #34
0
def test_newton(order):
    U, _ = _newton(order, atol=1e-15)
    assert float_cmp(U.to_numpy(), 0.0)