Example #1
0
def test_scalars():
    """test some scalar fields"""
    grid = CartesianGrid([[0.1, 0.3], [-2, 3]], [3, 4])
    s1 = ScalarField(grid, np.full(grid.shape, 1))
    s2 = ScalarField(grid, np.full(grid.shape, 2))
    assert s1.average == pytest.approx(1)
    assert s1.magnitude == pytest.approx(1)

    s3 = s1 + s2
    assert s3.grid == grid
    np.testing.assert_allclose(s3.data, 3)
    s1 += s2
    np.testing.assert_allclose(s1.data, 3)

    s2 = FieldBase.from_state(s1.attributes, data=s1.data)
    assert s1 == s2
    assert s1.grid is s2.grid

    attrs = ScalarField.unserialize_attributes(s1.attributes_serialized)
    s2 = FieldBase.from_state(attrs, data=s1.data)
    assert s1 == s2
    assert s1.grid is not s2.grid

    # test options for plotting images
    if module_available("matplotlib"):
        s1.plot(transpose=True, colorbar=True)

    s3 = ScalarField(grid, s1)
    assert s1 is not s3
    assert s1 == s3
    assert s1.grid is s3.grid

    # multiplication with numpy arrays
    arr = np.random.randn(*grid.shape)
    np.testing.assert_allclose((arr * s1).data, (s1 * arr).data)
Example #2
0
    def evolution_rate(self, state: FieldBase, t: float = 0) -> FieldBase:
        """ evaluate the right hand side of the PDE
        
        Args:
            state (:class:`~pde.fields.FieldBase`):
                The field describing the state of the PDE
            t (float):
                The current time point
            
        Returns:
            :class:`~pde.fields.FieldBase`:
            Field describing the evolution rate of the PDE 
        """
        self._prepare(state)

        if isinstance(state, DataFieldBase):
            rhs = self._cache['rhs_funcs'][0]
            return state.copy(data=rhs(state.data, t))

        elif isinstance(state, FieldCollection):
            result = state.copy()
            for i in range(len(state)):
                data_tpl = self._cache['get_data_tuple'](state.data)
                result[i].data = self._cache['rhs_funcs'][i](*data_tpl, t)
            return result

        else:
            raise TypeError(f'Unsupported field {state.__class__.__name__}')
Example #3
0
def test_tensors_basic():
    """test some tensor calculations"""
    grid = CartesianGrid([[0.1, 0.3], [-2, 3]], [3, 4])

    t1 = Tensor2Field(grid, np.full((2, 2) + grid.shape, 1))
    t2 = Tensor2Field(grid, np.full((2, 2) + grid.shape, 2))
    np.testing.assert_allclose(t2.average, [[2, 2], [2, 2]])
    assert t1.magnitude == pytest.approx(2)

    assert t1["x", "x"] == t1[0, 0]
    assert t1["x", 1] == t1[0, "y"] == t1[0, 1]
    t1[0, 0] = t1[0, 0]

    t3 = t1 + t2
    assert t3.grid == grid
    np.testing.assert_allclose(t3.data, 3)
    t1 += t2
    np.testing.assert_allclose(t1.data, 3)

    field = Tensor2Field.random_uniform(grid)
    trace = field.trace()

    assert isinstance(trace, ScalarField)
    np.testing.assert_allclose(trace.data, field.data.trace())

    t1 = Tensor2Field(grid)
    t1[0, 0] = 1
    t1[0, 1] = 2
    t1[1, 0] = 3
    t1[1, 1] = 4
    for method, value in [
        ("min", 1),
        ("max", 4),
        ("norm", np.linalg.norm([[1, 2], [3, 4]])),
        ("squared_sum", 30),
        ("norm_squared", 30),
        ("trace", 5),
        ("invariant1", 5),
        ("invariant2", -1),
    ]:
        p1 = t1.to_scalar(method)
        assert p1.data.shape == grid.shape
        np.testing.assert_allclose(p1.data, value)

    for idx in ((1, ), (1, 2, 3), (1.5, 2), ("a", "b"), 1.0):
        with pytest.raises(IndexError):
            t1[idx]

    t2 = FieldBase.from_state(t1.attributes, data=t1.data)
    assert t1 == t2
    assert t1.grid is t2.grid

    attrs = Tensor2Field.unserialize_attributes(t1.attributes_serialized)
    t2 = FieldBase.from_state(attrs, data=t1.data)
    assert t1 == t2
    assert t1.grid is not t2.grid
Example #4
0
def test_vectors():
    """ test some vector fields """
    grid = CartesianGrid([[0.1, 0.3], [-2, 3]], [3, 4])
    v1 = VectorField(grid, np.full((2, ) + grid.shape, 1))
    v2 = VectorField(grid, np.full((2, ) + grid.shape, 2))
    np.testing.assert_allclose(v1.average, (1, 1))
    assert np.allclose(v1.magnitude, np.sqrt(2))

    v3 = v1 + v2
    assert v3.grid == grid
    np.testing.assert_allclose(v3.data, 3)
    v1 += v2
    np.testing.assert_allclose(v1.data, 3)

    # test projections
    v1 = VectorField(grid)
    v1.data[0, :] = 3
    v1.data[1, :] = 4
    for method, value in [
        ("min", 3),
        ("max", 4),
        ("norm", 5),
        ("squared_sum", 25),
        ("norm_squared", 25),
        ("auto", 5),
    ]:
        p1 = v1.to_scalar(method)
        assert p1.data.shape == grid.shape
        np.testing.assert_allclose(p1.data, value)

    v2 = FieldBase.from_state(v1.attributes, data=v1.data)
    assert v1 == v2
    assert v1.grid is v2.grid

    attrs = VectorField.unserialize_attributes(v1.attributes_serialized)
    v2 = FieldBase.from_state(attrs, data=v1.data)
    assert v1 == v2
    assert v1.grid is not v2.grid

    # test dot product
    v2._grid = v1.grid  # make sure grids are identical
    v1.data = 1
    v2.data = 2
    dot_op = v1.make_dot_operator()
    res = ScalarField(grid, dot_op(v1.data, v2.data))
    for s in (v1 @ v2, v2 @ v1, v1.dot(v2), res):
        assert isinstance(s, ScalarField)
        assert s.grid is grid
        np.testing.assert_allclose(s.data, np.full(grid.shape, 4))

    # test options for plotting images
    if module_available("matplotlib"):
        v1.plot(method="streamplot", transpose=True)
def test_collections():
    """test field collections"""
    grid = UnitGrid([3, 4])
    sf = ScalarField.random_uniform(grid, label="sf")
    vf = VectorField.random_uniform(grid, label="vf")
    tf = Tensor2Field.random_uniform(grid, label="tf")
    fields = FieldCollection([sf, vf, tf])
    assert fields.data.shape == (7, 3, 4)
    assert isinstance(str(fields), str)

    fields.data[:] = 0
    np.testing.assert_allclose(sf.data, 0)
    np.testing.assert_allclose(vf.data, 0)
    np.testing.assert_allclose(tf.data, 0)

    assert fields[0] is fields["sf"]
    assert fields[1] is fields["vf"]
    assert fields[2] is fields["tf"]
    with pytest.raises(KeyError):
        fields["42"]

    sf.data = 1
    vf.data = 1
    tf.data = 1
    np.testing.assert_allclose(fields.data, 1)
    assert all(np.allclose(i, 12) for i in fields.integrals)
    assert all(np.allclose(i, 1) for i in fields.averages)
    assert np.allclose(fields.magnitudes, np.sqrt([1, 2, 4]))

    assert sf.data.shape == (3, 4)
    assert vf.data.shape == (2, 3, 4)
    assert tf.data.shape == (2, 2, 3, 4)

    c2 = FieldBase.from_state(fields.attributes, data=fields.data)
    assert c2 == fields
    assert c2.grid is grid

    attrs = FieldCollection.unserialize_attributes(
        fields.attributes_serialized)
    c2 = FieldCollection.from_state(attrs, data=fields.data)
    assert c2 == fields
    assert c2.grid is not grid

    fields["sf"] = 2.0
    np.testing.assert_allclose(sf.data, 2)
    with pytest.raises(KeyError):
        fields["42"] = 0

    fields.plot(subplot_args=[{}, {"scale": 1}, {"colorbar": False}])
Example #6
0
def test_hdf_input_output(tmp_path):
    """test writing and reading files"""
    grid = UnitGrid([4, 4])
    s = ScalarField.random_uniform(grid, label="scalar")
    v = VectorField.random_uniform(grid, label="vector")
    t = Tensor2Field.random_uniform(grid, label="tensor")
    col = FieldCollection([s, v, t], label="collection")

    path = tmp_path / "test_hdf_input_output.hdf5"
    for f in [s, v, t, col]:
        f.to_file(path)
        f2 = FieldBase.from_file(path)
        assert f == f2
        assert f.label == f2.label
        assert isinstance(str(f), str)
        assert isinstance(repr(f), str)