def test_degenerated_grid(): """ test operators on grids with singular dimensions """ g1 = CartesianGrid([[0, 1]], 4) g2 = CartesianGrid([[0, 1], [0, 0.1]], [4, 1], periodic=[False, True]) d = np.random.random(4) v1 = g1.get_operator("laplace", bc="natural")(d) v2 = g2.get_operator("laplace", bc="natural")(d.reshape(g2.shape)) assert v2.shape == g2.shape np.testing.assert_allclose(v1.flat, v2.flat)
def test_rect_div_grad(): """ compare div grad to laplacian """ grid = CartesianGrid([[0, 2 * np.pi], [0, 2 * np.pi]], [16, 16], periodic=True) x, y = grid.cell_coords[..., 0], grid.cell_coords[..., 1] arr = np.cos(x) + np.sin(y) bcs = grid.get_boundary_conditions("natural") laplace = grid.get_operator("laplace", bcs) grad = grid.get_operator("gradient", bcs) div = grid.get_operator("divergence", bcs.differentiated) a = laplace(arr) b = div(grad(arr)) np.testing.assert_allclose(a, -arr, rtol=0.05, atol=0.01) np.testing.assert_allclose(b, -arr, rtol=0.05, atol=0.01)
def test_noise_scaling(): """compare the noise strength (in terms of the spectral density of two different noise sources that should be equivalent)""" # create a grid x, w = 2 + 10 * np.random.random(2) size = np.random.randint(128, 256) grid = CartesianGrid([[x, x + w]], size, periodic=True) # colored noise noise_colored = make_colored_noise(grid.shape, grid.discretization, exponent=2) # divergence of white noise shape = (grid.dim,) + grid.shape div = grid.get_operator("divergence", bc="natural") def noise_div(): return div(np.random.randn(*shape)) # calculate spectral densities of the two noises result = [] for noise_func in [noise_colored, noise_div]: def get_noise(): k, density = spectral_density(data=noise_func(), dx=grid.discretization) assert k[0] == 0 assert density[0] == pytest.approx(0) return np.log(density[1]) # log of spectral density # average spectral density of longest length scale mean = np.mean([get_noise() for _ in range(64)]) result.append(mean) np.testing.assert_allclose(*result, rtol=0.5)