def test_complex_vectors(): """test some complex vector fields""" grid = CartesianGrid([[0.1, 0.3], [-2, 3]], [3, 4]) shape = (2, 2) + grid.shape numbers = np.random.random(shape) + np.random.random(shape) * 1j v1 = VectorField(grid, numbers[0]) v2 = VectorField(grid, numbers[1]) assert v1.is_complex and v2.is_complex for backend in ["numpy", "numba"]: dot_op = v1.make_dot_operator(backend) # test complex conjugate expected = v1.to_scalar("norm_squared").data np.testing.assert_allclose((v1 @ v1).data, expected) np.testing.assert_allclose(dot_op(v1.data, v1.data), expected) # test dot product res = dot_op(v1.data, v2.data) for s in (v1 @ v2, (v2 @ v1).conjugate(), v1.dot(v2)): assert isinstance(s, ScalarField) assert s.grid is grid np.testing.assert_allclose(s.data, res) # test without conjugate dot_op = v1.make_dot_operator(backend, conjugate=False) res = v1.dot(v2, conjugate=False) np.testing.assert_allclose(dot_op(v1.data, v2.data), res.data)
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)