def test_contains_all(): # 1d intvp = IntervalProd(1, 2) arr_in1 = np.array([1.0, 1.6, 1.3, 2.0]) arr_in2 = np.array([[1.0, 1.6, 1.3, 2.0]]) mesh_in = sparse_meshgrid([1.0, 1.7, 1.9]) arr_not_in1 = np.array([1.0, 1.6, 1.3, 2.0, 0.8]) arr_not_in2 = np.array([[1.0, 1.6, 2.0], [1.0, 1.5, 1.6]]) mesh_not_in = sparse_meshgrid([-1.0, 1.7, 1.9]) assert intvp.contains_all(arr_in1) assert intvp.contains_all(arr_in2) assert intvp.contains_all(mesh_in) assert not intvp.contains_all(arr_not_in1) assert not intvp.contains_all(arr_not_in2) assert not intvp.contains_all(mesh_not_in) # 2d intvp = IntervalProd([0, 0], [1, 2]) arr_in = np.array([[0.5, 1.9], [0.0, 1.0], [1.0, 0.1]]).T mesh_in = sparse_meshgrid([0, 0.1, 0.6, 0.7, 1.0], [0]) arr_not_in = np.array([[0.5, 1.9], [1.1, 1.0], [1.0, 0.1]]).T mesh_not_in = sparse_meshgrid([0, 0.1, 0.6, 0.7, 1.0], [0, -1]) assert intvp.contains_all(arr_in) assert intvp.contains_all(mesh_in) assert not intvp.contains_all(arr_not_in) assert not intvp.contains_all(mesh_not_in)
def test_out_shape_from_meshgrid(): # 1d x = np.zeros(2) mg = sparse_meshgrid(x, order='C') assert out_shape_from_meshgrid(mg) == (2,) mg = sparse_meshgrid(x, order='F') assert out_shape_from_meshgrid(mg) == (2,) # 3d x, y, z = np.zeros(2), np.zeros(3), np.zeros(4) mg = sparse_meshgrid(x, y, z, order='C') assert out_shape_from_meshgrid(mg) == (2, 3, 4) mg = sparse_meshgrid(x, y, z, order='F') assert out_shape_from_meshgrid(mg) == (2, 3, 4) # 3d, fleshed out meshgrids x, y, z = np.zeros(2), np.zeros(3), np.zeros(4) mg = np.meshgrid(x, y, z, sparse=False, indexing='ij', copy=True) assert out_shape_from_meshgrid(mg) == (2, 3, 4) mg = np.meshgrid(x, y, z, sparse=False, indexing='ij', copy=True) mg = tuple(reversed([np.asfortranarray(arr) for arr in mg])) assert out_shape_from_meshgrid(mg) == (2, 3, 4)
def test_sparse_meshgrid(): # One array only x = np.zeros(2) true_mg = (x,) assert all_equal(sparse_meshgrid(x), true_mg) x = np.zeros((2, 2)) true_mg = (x,) assert all_equal(sparse_meshgrid(x), true_mg) # Two arrays, 'C' ordering x, y = np.zeros(2), np.zeros(3) true_mg = (x[:, None], y[None, :]) mg = sparse_meshgrid(x, y, order='C') assert all_equal(mg, true_mg) assert all(vec.flags.c_contiguous for vec in mg) # Two arrays, 'F' ordering x, y = np.zeros(2), np.zeros(3) true_mg = (y[None, :], x[:, None]) mg = sparse_meshgrid(x, y, order='F') assert all_equal(mg, true_mg) assert all(vec.flags.f_contiguous for vec in mg) # Array-like input x, y = [1, 2, 3], [4, 5, 6] true_mg = (np.array(x)[:, None], np.array(y)[None, :]) mg = sparse_meshgrid(x, y, order='C') assert all_equal(mg, true_mg) assert all(vec.flags.c_contiguous for vec in mg)
def test_vecs_from_meshgrid(): # 1d x = np.zeros(2) mg = sparse_meshgrid(x, order='C') vx = vecs_from_meshgrid(mg, order='C')[0] assert x.shape == vx.shape assert all_equal(x, vx) mg = sparse_meshgrid(x, order='F') vx = vecs_from_meshgrid(mg, order='F')[0] assert x.shape == vx.shape assert all_equal(x, vx) # 3d x, y, z = np.zeros(2), np.zeros(3), np.zeros(4) mg = sparse_meshgrid(x, y, z, order='C') vx, vy, vz = vecs_from_meshgrid(mg, order='C') assert x.shape == vx.shape assert all_equal(x, vx) assert y.shape == vy.shape assert all_equal(y, vy) assert z.shape == vz.shape assert all_equal(z, vz) mg = sparse_meshgrid(x, y, z, order='F') vx, vy, vz = vecs_from_meshgrid(mg, order='F') assert x.shape == vx.shape assert all_equal(x, vx) assert y.shape == vy.shape assert all_equal(y, vy) assert z.shape == vz.shape assert all_equal(z, vz) # 3d, fleshed out meshgrids x, y, z = np.zeros(2), np.zeros(3), np.zeros(4) mg = np.meshgrid(x, y, z, sparse=False, indexing='ij', copy=True) vx, vy, vz = vecs_from_meshgrid(mg, order='C') assert x.shape == vx.shape assert all_equal(x, vx) assert y.shape == vy.shape assert all_equal(y, vy) assert z.shape == vz.shape assert all_equal(z, vz) mg = np.meshgrid(x, y, z, sparse=False, indexing='ij', copy=True) mg = tuple(reversed([np.asfortranarray(arr) for arr in mg])) vx, vy, vz = vecs_from_meshgrid(mg, order='F') assert x.shape == vx.shape assert all_equal(x, vx) assert y.shape == vy.shape assert all_equal(y, vy) assert z.shape == vz.shape assert all_equal(z, vz)
def test_nearest_interpolation_2d_float(): """Test nearest neighbor interpolation in 2d.""" rect = odl.IntervalProd([0, 0], [1, 1]) part = odl.uniform_partition_fromintv(rect, [4, 2], nodes_on_bdry=False) # Coordinate vectors are: # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75] fspace = odl.FunctionSpace(rect) tspace = odl.rn(part.shape) interp_op = NearestInterpolation(fspace, part, tspace) function = interp_op(np.reshape([0, 1, 2, 3, 4, 5, 6, 7], part.shape)) # Evaluate at single point val = function([0.3, 0.6]) # closest to index (1, 1) -> 3 assert val == 3.0 # Input array, with and without output array pts = np.array([[0.3, 0.6], [1.0, 1.0]]) true_arr = [3, 7] assert all_equal(function(pts.T), true_arr) out = np.empty(2, dtype='float64') function(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0]) # Indices: (1, 3) x (0, 1) true_mg = [[2, 3], [6, 7]] assert all_equal(function(mg), true_mg) out = np.empty((2, 2), dtype='float64') function(mg, out=out) assert all_equal(out, true_mg) assert repr(interp_op) != ''
def test_vectorize_1d_lazy(): # Test vectorization in 1d without data type --> lazy vectorization arr = (np.arange(5) - 2)[None, :] mg = sparse_meshgrid(np.arange(5) - 3) val_1 = -1 val_2 = 2 @vectorize def simple_func(x): return 0 if x < 0 else 1 true_result_arr = [0, 0, 1, 1, 1] true_result_mg = [0, 0, 0, 1, 1] # Out-of-place out = simple_func(arr) assert isinstance(out, np.ndarray) assert is_int_dtype(out.dtype) assert out.shape == (5, ) assert all_equal(out, true_result_arr) out = simple_func(mg) assert isinstance(out, np.ndarray) assert out.shape == (5, ) assert is_int_dtype(out.dtype) assert all_equal(out, true_result_mg) assert simple_func(val_1) == 0 assert simple_func(val_2) == 1
def test_nearest_interpolation_1d_complex(): """Test nearest neighbor interpolation in 1d with complex values.""" coord_vecs = [[0.1, 0.3, 0.5, 0.7, 0.9]] f = np.array([0 + 1j, 1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j], dtype="complex128") interpolator = nearest_interpolator(f, coord_vecs) # Evaluate at single point val = interpolator(0.35) # closest to index 1 -> 1 + 2j assert val == 1.0 + 2.0j # Input array, with and without output array pts = np.array([0.39, 0.0, 0.65, 0.95]) true_arr = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j] assert all_equal(interpolator(pts), true_arr) # Should also work with a (1, N) array pts = pts[None, :] assert all_equal(interpolator(pts), true_arr) out = np.empty(4, dtype='complex128') interpolator(pts, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array # Same as array for 1d mg = sparse_meshgrid([0.39, 0.0, 0.65, 0.95]) true_mg = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j] assert all_equal(interpolator(mg), true_mg) interpolator(mg, out=out) assert all_equal(out, true_mg)
def test_vectorize_1d_lazy(): # Test vectorization in 1d without data type --> lazy vectorization arr = (np.arange(5) - 2)[None, :] mg = sparse_meshgrid(np.arange(5) - 3) val_1 = -1 val_2 = 2 @vectorize def simple_func(x): return 0 if x < 0 else 1 true_result_arr = [0, 0, 1, 1, 1] true_result_mg = [0, 0, 0, 1, 1] # Out-of-place out = simple_func(arr) assert isinstance(out, np.ndarray) assert is_int_dtype(out.dtype) assert out.shape == (5,) assert all_equal(out, true_result_arr) out = simple_func(mg) assert isinstance(out, np.ndarray) assert out.shape == (5,) assert is_int_dtype(out.dtype) assert all_equal(out, true_result_mg) assert simple_func(val_1) == 0 assert simple_func(val_2) == 1
def test_nearest_interpolation_1d_complex(fn_impl): intv = odl.IntervalProd(0, 1) part = odl.uniform_partition_fromintv(intv, 5, nodes_on_bdry=False) # Coordinate vectors are: # [0.1, 0.3, 0.5, 0.7, 0.9] space = odl.FunctionSpace(intv, field=odl.ComplexNumbers()) dspace = odl.cn(part.size) interp_op = NearestInterpolation(space, part, dspace) function = interp_op([0 + 1j, 1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j]) # Evaluate at single point val = function(0.35) # closest to index 1 -> 1 + 2j assert val == 1.0 + 2.0j # Input array, with and without output array pts = np.array([0.4, 0.0, 0.65, 0.95]) true_arr = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j] assert all_equal(function(pts), true_arr) # Should also work with a (1, N) array pts = pts[None, :] assert all_equal(function(pts), true_arr) out = np.empty(4, dtype='complex128') function(pts, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array # Same as array for 1d mg = sparse_meshgrid([0.4, 0.0, 0.65, 0.95]) true_mg = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j] assert all_equal(function(mg), true_mg) function(mg, out=out) assert all_equal(out, true_mg)
def test_nearest_interpolation_2d_float(): rect = odl.Rectangle([0, 0], [1, 1]) grid = odl.uniform_sampling(rect, [4, 2], as_midp=True) # Coordinate vectors are: # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75] space = odl.FunctionSpace(rect) dspace = odl.Rn(grid.ntotal) interp_op = NearestInterpolation(space, grid, dspace) function = interp_op([0, 1, 2, 3, 4, 5, 6, 7]) # Evaluate at single point val = function([0.3, 0.6]) # closest to index (1, 1) -> 3 assert val == 3.0 # Input array, with and without output array pts = np.array([[0.3, 0.6], [1.0, 1.0]]) true_arr = [3, 7] assert all_equal(function(pts.T), true_arr) out = np.empty(2, dtype='float64') function(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0]) # Indices: (1, 3) x (0, 1) true_mg = [[2, 3], [6, 7]] assert all_equal(function(mg), true_mg) out = np.empty((2, 2), dtype='float64') function(mg, out=out) assert all_equal(out, true_mg)
def test_nearest_interpolation_2d_string(): """Test nearest neighbor interpolation in 2d with string values.""" rect = odl.IntervalProd([0, 0], [1, 1]) part = odl.uniform_partition_fromintv(rect, [4, 2], nodes_on_bdry=False) # Coordinate vectors are: # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75] fspace = odl.FunctionSpace(rect, out_dtype='U1') tspace = odl.tensor_space(part.shape, dtype='U1') interp_op = NearestInterpolation(fspace, part, tspace) values = np.array([c for c in 'mystring']).reshape(tspace.shape) function = interp_op(values) # Evaluate at single point val = function([0.3, 0.6]) # closest to index (1, 1) -> 3 assert val == 't' # Input array, with and without output array pts = np.array([[0.3, 0.6], [1.0, 1.0]]) true_arr = ['t', 'g'] assert all_equal(function(pts.T), true_arr) out = np.empty(2, dtype='U1') function(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0]) # Indices: (1, 3) x (0, 1) true_mg = [['s', 't'], ['n', 'g']] assert all_equal(function(mg), true_mg) out = np.empty((2, 2), dtype='U1') function(mg, out=out) assert all_equal(out, true_mg) assert repr(interp_op) != ''
def test_nearest_interpolation_2d_string(): rect = odl.Rectangle([0, 0], [1, 1]) grid = odl.uniform_sampling(rect, [4, 2], as_midp=True) # Coordinate vectors are: # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75] space = odl.FunctionSet(rect, odl.Strings(1)) dspace = odl.Ntuples(grid.ntotal, dtype='U1') interp_op = NearestInterpolation(space, grid, dspace) values = np.array([c for c in 'mystring']) function = interp_op(values) # Evaluate at single point val = function([0.3, 0.6]) # closest to index (1, 1) -> 3 assert val == 't' # Input array, with and without output array pts = np.array([[0.3, 0.6], [1.0, 1.0]]) true_arr = ['t', 'g'] assert all_equal(function(pts.T), true_arr) out = np.empty(2, dtype='U1') function(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0]) # Indices: (1, 3) x (0, 1) true_mg = [['s', 't'], ['n', 'g']] assert all_equal(function(mg), true_mg) out = np.empty((2, 2), dtype='U1') function(mg, out=out) assert all_equal(out, true_mg)
def test_nearest_interpolation_1d_complex(): intv = odl.Interval(0, 1) grid = odl.uniform_sampling(intv, 5, as_midp=True) # Coordinate vectors are: # [0.1, 0.3, 0.5, 0.7, 0.9] space = odl.FunctionSpace(intv, field=odl.ComplexNumbers()) dspace = odl.Cn(grid.ntotal) interp_op = NearestInterpolation(space, grid, dspace) function = interp_op([0 + 1j, 1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j]) # Evaluate at single point val = function(0.35) # closest to index 1 -> 1 + 2j assert val == 1.0 + 2.0j # Input array, with and without output array pts = np.array([0.4, 0.0, 0.65, 0.95]) true_arr = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j] assert all_equal(function(pts), true_arr) # Should also work with a (1, N) array pts = pts[None, :] assert all_equal(function(pts), true_arr) out = np.empty(4, dtype='complex128') function(pts, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array # Same as array for 1d mg = sparse_meshgrid([0.4, 0.0, 0.65, 0.95]) true_mg = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j] assert all_equal(function(mg), true_mg) function(mg, out=out) assert all_equal(out, true_mg)
def test_nearest_interpolation_1d_complex(odl_tspace_impl): """Test nearest neighbor interpolation in 1d with complex values.""" impl = odl_tspace_impl # TODO: not used! intv = odl.IntervalProd(0, 1) part = odl.uniform_partition_fromintv(intv, 5, nodes_on_bdry=False) # Coordinate vectors are: # [0.1, 0.3, 0.5, 0.7, 0.9] fspace = odl.FunctionSpace(intv, out_dtype=complex) tspace = odl.cn(part.shape) interp_op = NearestInterpolation(fspace, part, tspace) function = interp_op([0 + 1j, 1 + 2j, 2 + 3j, 3 + 4j, 4 + 5j]) # Evaluate at single point val = function(0.35) # closest to index 1 -> 1 + 2j assert val == 1.0 + 2.0j # Input array, with and without output array pts = np.array([0.4, 0.0, 0.65, 0.95]) true_arr = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j] assert all_equal(function(pts), true_arr) # Should also work with a (1, N) array pts = pts[None, :] assert all_equal(function(pts), true_arr) out = np.empty(4, dtype='complex128') function(pts, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array # Same as array for 1d mg = sparse_meshgrid([0.4, 0.0, 0.65, 0.95]) true_mg = [1 + 2j, 0 + 1j, 3 + 4j, 4 + 5j] assert all_equal(function(mg), true_mg) function(mg, out=out) assert all_equal(out, true_mg) assert repr(interp_op) != ''
def test_nearest_interpolation_2d_string(): rect = odl.Rectangle([0, 0], [1, 1]) part = odl.uniform_partition_fromintv(rect, [4, 2], nodes_on_bdry=False) # Coordinate vectors are: # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75] space = odl.FunctionSet(rect, odl.Strings(1)) dspace = odl.Ntuples(part.size, dtype='U1') interp_op = NearestInterpolation(space, part, dspace) values = np.array([c for c in 'mystring']) function = interp_op(values) # Evaluate at single point val = function([0.3, 0.6]) # closest to index (1, 1) -> 3 assert val == 't' # Input array, with and without output array pts = np.array([[0.3, 0.6], [1.0, 1.0]]) true_arr = ['t', 'g'] assert all_equal(function(pts.T), true_arr) out = np.empty(2, dtype='U1') function(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0]) # Indices: (1, 3) x (0, 1) true_mg = [['s', 't'], ['n', 'g']] assert all_equal(function(mg), true_mg) out = np.empty((2, 2), dtype='U1') function(mg, out=out) assert all_equal(out, true_mg)
def test_vectorize_2d_lazy(): # Test vectorization in 1d without data type --> lazy vectorization arr = np.empty((2, 5), dtype='int') arr[0] = ([-3, -2, -1, 0, 1]) arr[1] = ([-1, 0, 1, 2, 3]) mg = sparse_meshgrid([-3, -2, -1, 0, 1], [-1, 0, 1, 2, 3]) val_1 = (-1, 1) val_2 = (2, 1) @vectorize def simple_func(x): return 0 if x[0] < 0 and x[1] > 0 else 1 true_result_arr = [1, 1, 0, 1, 1] true_result_mg = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] # Out-of-place out = simple_func(arr) assert isinstance(out, np.ndarray) assert is_int_dtype(out.dtype) assert out.shape == (5, ) assert all_equal(out, true_result_arr) out = simple_func(mg) assert isinstance(out, np.ndarray) assert is_int_dtype(out.dtype) assert out.shape == (5, 5) assert all_equal(out, true_result_mg) assert simple_func(val_1) == 0 assert simple_func(val_2) == 1
def test_per_axis_interpolation(): """Test different interpolation schemes per axis.""" rect = odl.IntervalProd([0, 0], [1, 1]) part = odl.uniform_partition_fromintv(rect, [4, 2], nodes_on_bdry=False) # Coordinate vectors are: # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75] fspace = odl.FunctionSpace(rect) tspace = odl.rn(part.shape) schemes = ['linear', 'nearest'] variants = [None, 'right'] interp_op = PerAxisInterpolation(fspace, part, tspace, schemes=schemes, nn_variants=variants) values = np.arange(1, 9, dtype='float64').reshape(part.shape) function = interp_op(values) rvals = values.reshape([4, 2]) # Evaluate at single point val = function([0.3, 0.5]) l1 = (0.3 - 0.125) / (0.375 - 0.125) # 0.5 equally far from both neighbors -> 'right' chooses 0.75 true_val = (1 - l1) * rvals[0, 1] + l1 * rvals[1, 1] assert val == pytest.approx(true_val) # Input array, with and without output array pts = np.array([[0.3, 0.6], [0.1, 0.25], [1.0, 1.0]]) l1 = (0.3 - 0.125) / (0.375 - 0.125) true_val_1 = (1 - l1) * rvals[0, 1] + l1 * rvals[1, 1] l1 = (0.125 - 0.1) / (0.375 - 0.125) true_val_2 = (1 - l1) * rvals[0, 0] # only lower left contributes l1 = (1.0 - 0.875) / (0.875 - 0.625) true_val_3 = (1 - l1) * rvals[3, 1] # lower left only true_arr = [true_val_1, true_val_2, true_val_3] assert all_equal(function(pts.T), true_arr) out = np.empty(3, dtype='float64') function(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 0.85]) # Indices: (1, 3) x (0, 1) lx1 = (0.3 - 0.125) / (0.375 - 0.125) lx2 = (1.0 - 0.875) / (0.875 - 0.625) true_val_11 = (1 - lx1) * rvals[0, 0] + lx1 * rvals[1, 0] true_val_12 = ((1 - lx1) * rvals[0, 1] + lx1 * rvals[1, 1]) true_val_21 = (1 - lx2) * rvals[3, 0] true_val_22 = (1 - lx2) * rvals[3, 1] true_mg = [[true_val_11, true_val_12], [true_val_21, true_val_22]] assert all_equal(function(mg), true_mg) out = np.empty((2, 2), dtype='float64') function(mg, out=out) assert all_equal(out, true_mg) assert repr(interp_op) != ''
def _meshgrid(domain, shape): min_pt = domain.min_pt max_pt = domain.max_pt ndim = domain.ndim coord_vecs = [] for i in range(ndim): vec = np.random.uniform(low=min_pt[i], high=max_pt[i], size=shape[i]) vec.sort() coord_vecs.append(vec) return sparse_meshgrid(*coord_vecs)
def _meshgrid(domain, shape): beg = domain.begin end = domain.end ndim = domain.ndim coord_vecs = [] for i in range(ndim): vec = np.random.uniform(low=beg[i], high=end[i], size=shape[i]) vec.sort() coord_vecs.append(vec) return sparse_meshgrid(*coord_vecs)
def test_per_axis_interpolation(): rect = odl.Rectangle([0, 0], [1, 1]) grid = odl.uniform_sampling(rect, [4, 2], as_midp=True) # Coordinate vectors are: # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75] space = odl.FunctionSpace(rect) dspace = odl.Rn(grid.ntotal) schemes = ['linear', 'nearest'] variants = [None, 'right'] interp_op = PerAxisInterpolation(space, grid, dspace, schemes=schemes, nn_variants=variants) values = np.arange(1, 9, dtype='float64') function = interp_op(values) rvals = values.reshape([4, 2]) # Evaluate at single point val = function([0.3, 0.5]) l1 = (0.3 - 0.125) / (0.375 - 0.125) # 0.5 equally far from both neighbors -> 'right' chooses 0.75 true_val = (1 - l1) * rvals[0, 1] + l1 * rvals[1, 1] assert almost_equal(val, true_val) # Input array, with and without output array pts = np.array([[0.3, 0.6], [0.1, 0.25], [1.0, 1.0]]) l1 = (0.3 - 0.125) / (0.375 - 0.125) true_val_1 = (1 - l1) * rvals[0, 1] + l1 * rvals[1, 1] l1 = (0.125 - 0.1) / (0.375 - 0.125) true_val_2 = (1 - l1) * rvals[0, 0] # only lower left contributes l1 = (1.0 - 0.875) / (0.875 - 0.625) true_val_3 = (1 - l1) * rvals[3, 1] # lower left only true_arr = [true_val_1, true_val_2, true_val_3] assert all_equal(function(pts.T), true_arr) out = np.empty(3, dtype='float64') function(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 0.85]) # Indices: (1, 3) x (0, 1) lx1 = (0.3 - 0.125) / (0.375 - 0.125) lx2 = (1.0 - 0.875) / (0.875 - 0.625) true_val_11 = (1 - lx1) * rvals[0, 0] + lx1 * rvals[1, 0] true_val_12 = ((1 - lx1) * rvals[0, 1] + lx1 * rvals[1, 1]) true_val_21 = (1 - lx2) * rvals[3, 0] true_val_22 = (1 - lx2) * rvals[3, 1] true_mg = [[true_val_11, true_val_12], [true_val_21, true_val_22]] assert all_equal(function(mg), true_mg) out = np.empty((2, 2), dtype='float64') function(mg, out=out) assert all_equal(out, true_mg)
def test_linear_interpolation_2d(): """Test linear interpolation in 2d.""" coord_vecs = [[0.125, 0.375, 0.625, 0.875], [0.25, 0.75]] f = np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype='float64') interpolator = linear_interpolator(f, coord_vecs) # Evaluate at single point val = interpolator([0.3, 0.6]) l1 = (0.3 - 0.125) / (0.375 - 0.125) l2 = (0.6 - 0.25) / (0.75 - 0.25) true_val = ((1 - l1) * (1 - l2) * f[0, 0] + (1 - l1) * l2 * f[0, 1] + l1 * (1 - l2) * f[1, 0] + l1 * l2 * f[1, 1]) assert val == pytest.approx(true_val) # Input array, with and without output array pts = np.array([[0.3, 0.6], [0.1, 0.25], [1.0, 1.0]]) l1 = (0.3 - 0.125) / (0.375 - 0.125) l2 = (0.6 - 0.25) / (0.75 - 0.25) true_val_1 = ((1 - l1) * (1 - l2) * f[0, 0] + (1 - l1) * l2 * f[0, 1] + l1 * (1 - l2) * f[1, 0] + l1 * l2 * f[1, 1]) l1 = (0.125 - 0.1) / (0.375 - 0.125) # l2 = 0 true_val_2 = (1 - l1) * f[0, 0] # only lower left contributes l1 = (1.0 - 0.875) / (0.875 - 0.625) l2 = (1.0 - 0.75) / (0.75 - 0.25) true_val_3 = (1 - l1) * (1 - l2) * f[3, 1] # lower left only true_arr = [true_val_1, true_val_2, true_val_3] assert all_equal(interpolator(pts.T), true_arr) out = np.empty(3, dtype='float64') interpolator(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 0.75]) # Indices: (1, 3) x (0, 1) lx1 = (0.3 - 0.125) / (0.375 - 0.125) lx2 = (1.0 - 0.875) / (0.875 - 0.625) ly1 = (0.4 - 0.25) / (0.75 - 0.25) # ly2 = 0 true_val_11 = ((1 - lx1) * (1 - ly1) * f[0, 0] + (1 - lx1) * ly1 * f[0, 1] + lx1 * (1 - ly1) * f[1, 0] + lx1 * ly1 * f[1, 1]) true_val_12 = ((1 - lx1) * f[0, 1] + lx1 * f[1, 1] # ly2 = 0 ) true_val_21 = ((1 - lx2) * (1 - ly1) * f[3, 0] + (1 - lx2) * ly1 * f[3, 1] # high node 1.0, no upper ) true_val_22 = (1 - lx2) * f[3, 1] # ly2 = 0, no upper for 1.0 true_mg = [[true_val_11, true_val_12], [true_val_21, true_val_22]] assert all_equal(interpolator(mg), true_mg) out = np.empty((2, 2), dtype='float64') interpolator(mg, out=out) assert all_equal(out, true_mg)
def test_out_shape_from_meshgrid(): # 1d x = np.zeros(2) mg = sparse_meshgrid(x) assert out_shape_from_meshgrid(mg) == (2, ) # 3d x, y, z = np.zeros(2), np.zeros(3), np.zeros(4) mg = sparse_meshgrid(x, y, z) assert out_shape_from_meshgrid(mg) == (2, 3, 4) # 3d, fleshed out meshgrids x, y, z = np.zeros(2), np.zeros(3), np.zeros(4) mg = np.meshgrid(x, y, z, sparse=False, indexing='ij', copy=True) assert out_shape_from_meshgrid(mg) == (2, 3, 4) mg = np.meshgrid(x, y, z, sparse=False, indexing='ij', copy=True) mg = tuple(reversed([np.asfortranarray(arr) for arr in mg])) assert out_shape_from_meshgrid(mg) == (2, 3, 4)
def _meshgrid(domain, shape): """Helper to generate a ``shape`` meshgrid of points in ``domain``.""" min_pt = domain.min_pt max_pt = domain.max_pt ndim = domain.ndim coord_vecs = [] for i in range(ndim): vec = np.random.uniform(low=min_pt[i], high=max_pt[i], size=shape[i]) vec.sort() coord_vecs.append(vec) return sparse_meshgrid(*coord_vecs)
def test_is_valid_input_meshgrid(): # 1d x = np.zeros(2) valid_mg = sparse_meshgrid(x) assert is_valid_input_meshgrid(valid_mg, ndim=1) invalid_mg = sparse_meshgrid(x, x) assert not is_valid_input_meshgrid(invalid_mg, ndim=1) x = np.zeros((2, 2)) invalid_mg = sparse_meshgrid(x) assert not is_valid_input_meshgrid(invalid_mg, ndim=1) # 3d x, y, z = np.zeros(2), np.zeros(3), np.zeros(4) valid_mg = sparse_meshgrid(x, y, z) assert is_valid_input_meshgrid(valid_mg, ndim=3) invalid_mg = sparse_meshgrid(x, x, y, z) assert not is_valid_input_meshgrid(invalid_mg, ndim=3) x = np.zeros((3, 3)) invalid_mg = sparse_meshgrid(x) assert not is_valid_input_meshgrid(invalid_mg, ndim=3) # Other input invalid_input = [1, [1, 2], ([1, 2], [3, 4]), (5, ), np.zeros((2, 2))] for inp in invalid_input: assert not is_valid_input_meshgrid(inp, ndim=1) assert not is_valid_input_meshgrid(inp, ndim=2)
def test_meshgrid_input_order(): # 1d x = np.zeros(2) mg = sparse_meshgrid(x, order='C') assert meshgrid_input_order(mg) == 'C' # Both 'C' and 'F' contiguous, defaults to 'C' mg = sparse_meshgrid(x, order='F') assert meshgrid_input_order(mg) == 'C' # 3d x, y, z = np.zeros(2), np.zeros(3), np.zeros(4) mg = sparse_meshgrid(x, y, z, order='C') assert meshgrid_input_order(mg) == 'C' mg = sparse_meshgrid(x, y, z, order='F') assert meshgrid_input_order(mg) == 'F' # 3d, fleshed out meshgrids x, y, z = np.zeros(2), np.zeros(3), np.zeros(4) mg = np.meshgrid(x, y, z, sparse=False, indexing='ij', copy=True) assert meshgrid_input_order(mg) == 'C' mg = np.meshgrid(x, y, z, sparse=False, indexing='ij', copy=True) mg = [np.asfortranarray(arr) for arr in mg] assert meshgrid_input_order(mg) == 'F' # non-contiguous --> error mg = np.meshgrid(x, y, z, sparse=False, indexing='ij', copy=False) with pytest.raises(ValueError): meshgrid_input_order(mg) # messed up tuple mg = list(sparse_meshgrid(x, y, z, order='C')) mg[1] = mg[0] with pytest.raises(ValueError): meshgrid_input_order(mg)
def test_is_valid_input_meshgrid(): # 1d x = np.zeros(2) valid_mg = sparse_meshgrid(x) assert is_valid_input_meshgrid(valid_mg, ndim=1) invalid_mg = sparse_meshgrid(x, x) assert not is_valid_input_meshgrid(invalid_mg, ndim=1) x = np.zeros((2, 2)) invalid_mg = sparse_meshgrid(x) assert not is_valid_input_meshgrid(invalid_mg, ndim=1) # 3d x, y, z = np.zeros(2), np.zeros(3), np.zeros(4) valid_mg = sparse_meshgrid(x, y, z) assert is_valid_input_meshgrid(valid_mg, ndim=3) invalid_mg = sparse_meshgrid(x, x, y, z) assert not is_valid_input_meshgrid(invalid_mg, ndim=3) x = np.zeros((3, 3)) invalid_mg = sparse_meshgrid(x) assert not is_valid_input_meshgrid(invalid_mg, ndim=3) # Other input invalid_input = [1, [1, 2], ([1, 2], [3, 4]), (5,), np.zeros((2, 2))] for inp in invalid_input: assert not is_valid_input_meshgrid(inp, ndim=1) assert not is_valid_input_meshgrid(inp, ndim=2)
def test_sparse_meshgrid(): # One array only x = np.zeros(2) true_mg = (x, ) assert all_equal(sparse_meshgrid(x), true_mg) x = np.zeros((2, 2)) true_mg = (x, ) assert all_equal(sparse_meshgrid(x), true_mg) # Two arrays x, y = np.zeros(2), np.zeros(3) true_mg = (x[:, None], y[None, :]) mg = sparse_meshgrid(x, y) assert all_equal(mg, true_mg) assert all(vec.flags.c_contiguous for vec in mg) # Array-like input x, y = [1, 2, 3], [4, 5, 6] true_mg = (np.array(x)[:, None], np.array(y)[None, :]) mg = sparse_meshgrid(x, y) assert all_equal(mg, true_mg) assert all(vec.flags.c_contiguous for vec in mg)
def test_vectorize_1d_otype(): import sys # Test vectorization in 1d with given data type for output arr = (np.arange(5) - 2)[None, :] mg = sparse_meshgrid(np.arange(5) - 3) val_1 = -1 val_2 = 2 @vectorize(otypes=['int']) def simple_func(x): return 0 if x < 0 else 1 true_result_arr = [0, 0, 1, 1, 1] true_result_mg = [0, 0, 0, 1, 1] # Out-of-place out = simple_func(arr) assert isinstance(out, np.ndarray) assert out.dtype == np.dtype('int') assert out.shape == (5, ) assert all_equal(out, true_result_arr) out = simple_func(mg) assert isinstance(out, np.ndarray) assert out.shape == (5, ) assert out.dtype == np.dtype('int') assert all_equal(out, true_result_mg) assert simple_func(val_1) == 0 assert simple_func(val_2) == 1 # Python 2 really swallows this stuff in comparisons... bogus_input = [lambda x: x, object, Exception] if sys.version_info.major > 2: for b in bogus_input: with pytest.raises(TypeError): simple_func(b) # In-place out = np.empty(5, dtype='int') simple_func(arr, out=out) assert all_equal(out, true_result_arr) out = np.empty(5, dtype='int') simple_func(mg, out=out) assert all_equal(out, true_result_mg)
def test_vectorize_1d_otype(): import sys # Test vectorization in 1d with given data type for output arr = (np.arange(5) - 2)[None, :] mg = sparse_meshgrid(np.arange(5) - 3) val_1 = -1 val_2 = 2 @vectorize(otypes=['int']) def simple_func(x): return 0 if x < 0 else 1 true_result_arr = [0, 0, 1, 1, 1] true_result_mg = [0, 0, 0, 1, 1] # Out-of-place out = simple_func(arr) assert isinstance(out, np.ndarray) assert out.dtype == np.dtype('int') assert out.shape == (5,) assert all_equal(out, true_result_arr) out = simple_func(mg) assert isinstance(out, np.ndarray) assert out.shape == (5,) assert out.dtype == np.dtype('int') assert all_equal(out, true_result_mg) assert simple_func(val_1) == 0 assert simple_func(val_2) == 1 # Python 2 really swallows this stuff in comparisons... bogus_input = [lambda x: x, object, Exception] if sys.version_info.major > 2: for b in bogus_input: with pytest.raises(TypeError): simple_func(b) # In-place out = np.empty(5, dtype='int') simple_func(arr, out=out) assert all_equal(out, true_result_arr) out = np.empty(5, dtype='int') simple_func(mg, out=out) assert all_equal(out, true_result_mg)
def test_collocation_interpolation_identity(): """Check if collocation is left-inverse to interpolation.""" # Interpolation followed by collocation on the same grid should be # the identity coord_vecs = [[0.125, 0.375, 0.625, 0.875], [0.25, 0.75]] f = np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype='float64') interpolators = [ nearest_interpolator(f, coord_vecs), linear_interpolator(f, coord_vecs), per_axis_interpolator(f, coord_vecs, interp=['linear', 'nearest']), ] for interpolator in interpolators: mg = sparse_meshgrid(*coord_vecs) ident_f = point_collocation(interpolator, mg) assert all_almost_equal(ident_f, f)
def test_vectorize_2d_dtype(): # Test vectorization in 2d with given data type for output arr = np.empty((2, 5), dtype='int') arr[0] = ([-3, -2, -1, 0, 1]) arr[1] = ([-1, 0, 1, 2, 3]) mg = sparse_meshgrid([-3, -2, -1, 0, 1], [-1, 0, 1, 2, 3]) val_1 = (-1, 1) val_2 = (2, 1) @vectorize(dtype='int') def simple_func(x): return 0 if x[0] < 0 and x[1] > 0 else 1 true_result_arr = [1, 1, 0, 1, 1] true_result_mg = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] # Out of place out = simple_func(arr) assert isinstance(out, np.ndarray) assert out.dtype == np.dtype('int') assert out.shape == (5,) assert all_equal(out, true_result_arr) out = simple_func(mg) assert isinstance(out, np.ndarray) assert out.dtype == np.dtype('int') assert out.shape == (5, 5) print(out) assert all_equal(out, true_result_mg) assert simple_func(val_1) == 0 assert simple_func(val_2) == 1 # In-place out = np.empty(5, dtype='int') simple_func(arr, out=out) assert all_equal(out, true_result_arr) out = np.empty((5, 5), dtype='int') simple_func(mg, out=out) assert all_equal(out, true_result_mg)
def test_per_axis_interpolation(): """Test different interpolation schemes per axis.""" coord_vecs = [[0.125, 0.375, 0.625, 0.875], [0.25, 0.75]] interp = ['linear', 'nearest'] f = np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype='float64') interpolator = per_axis_interpolator(f, coord_vecs, interp) # Evaluate at single point val = interpolator([0.3, 0.5]) l1 = (0.3 - 0.125) / (0.375 - 0.125) # 0.5 equally far from both neighbors -> NN chooses 0.75 true_val = (1 - l1) * f[0, 1] + l1 * f[1, 1] assert val == pytest.approx(true_val) # Input array, with and without output array pts = np.array([[0.3, 0.6], [0.1, 0.25], [1.0, 1.0]]) l1 = (0.3 - 0.125) / (0.375 - 0.125) true_val_1 = (1 - l1) * f[0, 1] + l1 * f[1, 1] l1 = (0.125 - 0.1) / (0.375 - 0.125) true_val_2 = (1 - l1) * f[0, 0] # only lower left contributes l1 = (1.0 - 0.875) / (0.875 - 0.625) true_val_3 = (1 - l1) * f[3, 1] # lower left only true_arr = [true_val_1, true_val_2, true_val_3] assert all_equal(interpolator(pts.T), true_arr) out = np.empty(3, dtype='float64') interpolator(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 0.85]) # Indices: (1, 3) x (0, 1) lx1 = (0.3 - 0.125) / (0.375 - 0.125) lx2 = (1.0 - 0.875) / (0.875 - 0.625) true_val_11 = (1 - lx1) * f[0, 0] + lx1 * f[1, 0] true_val_12 = ((1 - lx1) * f[0, 1] + lx1 * f[1, 1]) true_val_21 = (1 - lx2) * f[3, 0] true_val_22 = (1 - lx2) * f[3, 1] true_mg = [[true_val_11, true_val_12], [true_val_21, true_val_22]] assert all_equal(interpolator(mg), true_mg) out = np.empty((2, 2), dtype='float64') interpolator(mg, out=out) assert all_equal(out, true_mg)
def test_vectorize_2d_dtype(): # Test vectorization in 2d with given data type for output arr = np.empty((2, 5), dtype='int') arr[0] = ([-3, -2, -1, 0, 1]) arr[1] = ([-1, 0, 1, 2, 3]) mg = sparse_meshgrid([-3, -2, -1, 0, 1], [-1, 0, 1, 2, 3]) val_1 = (-1, 1) val_2 = (2, 1) @vectorize(otypes=['int']) def simple_func(x): return 0 if x[0] < 0 and x[1] > 0 else 1 true_result_arr = [1, 1, 0, 1, 1] true_result_mg = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] # Out-of-place out = simple_func(arr) assert isinstance(out, np.ndarray) assert out.dtype == np.dtype('int') assert out.shape == (5, ) assert all_equal(out, true_result_arr) out = simple_func(mg) assert isinstance(out, np.ndarray) assert out.dtype == np.dtype('int') assert out.shape == (5, 5) assert all_equal(out, true_result_mg) assert simple_func(val_1) == 0 assert simple_func(val_2) == 1 # In-place out = np.empty(5, dtype='int') simple_func(arr, out=out) assert all_equal(out, true_result_arr) out = np.empty((5, 5), dtype='int') simple_func(mg, out=out) assert all_equal(out, true_result_mg)
def test_vectorize_2d_lazy(): # Test vectorization in 1d without data type --> lazy vectorization arr = np.empty((2, 5), dtype='int') arr[0] = ([-3, -2, -1, 0, 1]) arr[1] = ([-1, 0, 1, 2, 3]) mg = sparse_meshgrid([-3, -2, -1, 0, 1], [-1, 0, 1, 2, 3]) val_1 = (-1, 1) val_2 = (2, 1) @vectorize def simple_func(x): return 0 if x[0] < 0 and x[1] > 0 else 1 true_result_arr = [1, 1, 0, 1, 1] true_result_mg = [[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]] # Out-of-place out = simple_func(arr) assert isinstance(out, np.ndarray) assert is_int_dtype(out.dtype) assert out.shape == (5,) assert all_equal(out, true_result_arr) out = simple_func(mg) assert isinstance(out, np.ndarray) assert is_int_dtype(out.dtype) assert out.shape == (5, 5) assert all_equal(out, true_result_mg) assert simple_func(val_1) == 0 assert simple_func(val_2) == 1
def test_nearest_interpolation_2d(): """Test nearest neighbor interpolation in 2d.""" coord_vecs = [[0.125, 0.375, 0.625, 0.875], [0.25, 0.75]] f = np.array([[0, 1], [2, 3], [4, 5], [6, 7]], dtype="float64") interpolator = nearest_interpolator(f, coord_vecs) # Evaluate at single point val = interpolator([0.3, 0.6]) # closest to index (1, 1) -> 3 assert val == 3.0 # Input array, with and without output array pts = np.array([[0.3, 0.6], [1.0, 1.0]]) true_arr = [3, 7] assert all_equal(interpolator(pts.T), true_arr) out = np.empty(2, dtype='float64') interpolator(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0]) # Indices: (1, 3) x (0, 1) true_mg = [[2, 3], [6, 7]] assert all_equal(interpolator(mg), true_mg) out = np.empty((2, 2), dtype='float64') interpolator(mg, out=out) assert all_equal(out, true_mg)
def test_nearest_interpolation_2d_string(): """Test nearest neighbor interpolation in 2d with string values.""" coord_vecs = [[0.125, 0.375, 0.625, 0.875], [0.25, 0.75]] f = np.array([['m', 'y'], ['s', 't'], ['r', 'i'], ['n', 'g']], dtype='U1') interpolator = nearest_interpolator(f, coord_vecs) # Evaluate at single point val = interpolator([0.3, 0.6]) # closest to index (1, 1) -> 3 assert val == u't' # Input array, with and without output array pts = np.array([[0.3, 0.6], [1.0, 1.0]]) true_arr = np.array(['t', 'g'], dtype='U1') assert all_equal(interpolator(pts.T), true_arr) out = np.empty(2, dtype='U1') interpolator(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 1.0]) # Indices: (1, 3) x (0, 1) true_mg = np.array([['s', 't'], ['n', 'g']], dtype='U1') assert all_equal(interpolator(mg), true_mg) out = np.empty((2, 2), dtype='U1') interpolator(mg, out=out) assert all_equal(out, true_mg)
def ssim(data, ground_truth, size=11, sigma=1.5, K1=0.01, K2=0.03, dynamic_range=None, normalized=False, force_lower_is_better=False): r"""Structural SIMilarity between ``data`` and ``ground_truth``. The SSIM takes value -1 for maximum dissimilarity and +1 for maximum similarity. See also `this Wikipedia article <https://en.wikipedia.org/wiki/Structural_similarity>`_. Parameters ---------- data : `array-like` Input data to compare to the ground truth. ground_truth : `array-like` Reference to which ``data`` should be compared. size : odd int, optional Size in elements per axis of the Gaussian window that is used for all smoothing operations. sigma : positive float, optional Width of the Gaussian function used for smoothing. K1, K2 : positive float, optional Small constants to stabilize the result. See [Wan+2004] for details. dynamic_range : nonnegative float, optional Difference between the maximum and minimum value that the pixels can attain. Use 255 if pixel range is :math:`[0, 255]` and 1 if it is :math:`[0, 1]`. Default: `None`, obtain maximum and minimum from the ground truth. normalized : bool, optional If ``True``, the output values are mapped to the interval :math:`[0, 1]` (see `Notes` for details), otherwise return the original SSIM. force_lower_is_better : bool, optional If ``True``, it is ensured that lower values correspond to better matches by returning the negative of the SSIM, otherwise the (possibly normalized) SSIM is returned. If both `normalized` and `force_lower_is_better` are ``True``, then the order is reversed before mapping the outputs, so that the latter are still in the interval :math:`[0, 1]`. Returns ------- ssim : float FOM value, where a higher value means a better match if `force_lower_is_better` is ``False``. Notes ----- The SSIM is computed on small windows and then averaged over the whole image. The SSIM between two windows :math:`x` and :math:`y` of size :math:`N \times N` .. math:: SSIM(x,y) = \frac{(2\mu_x\mu_y + c_1)(2\sigma_{xy} + c_2)} {(\mu_x^2 + \mu_y^2 + c_1)(\sigma_x^2 + \sigma_y^2 + c_2)} where: * :math:`\mu_x`, :math:`\mu_y` is the mean of :math:`x` and :math:`y`, respectively. * :math:`\sigma_x`, :math:`\sigma_y` is the standard deviation of :math:`x` and :math:`y`, respectively. * :math:`\sigma_{xy}` the covariance of :math:`x` and :math:`y` * :math:`c_1 = (k_1L)^2`, :math:`c_2 = (k_2L)^2` where :math:`L` is the dynamic range of the image. The unnormalized values are contained in the interval :math:`[-1, 1]`, where 1 corresponds to a perfect match. The normalized values are given by .. math:: SSIM_{normalized}(x, y) = \frac{SSIM(x, y) + 1}{2} References ---------- [Wan+2004] Wang, Z, Bovik, AC, Sheikh, HR, and Simoncelli, EP. *Image Quality Assessment: From Error Visibility to Structural Similarity*. IEEE Transactions on Image Processing, 13.4 (2004), pp 600--612. """ from scipy.signal import fftconvolve data = np.asarray(data) ground_truth = np.asarray(ground_truth) # Compute gaussian on a `size`-sized grid in each axis coords = np.linspace(-(size - 1) / 2, (size - 1) / 2, size) grid = sparse_meshgrid(*([coords] * data.ndim)) window = np.exp(-(sum(xi**2 for xi in grid) / (2.0 * sigma**2))) window /= np.sum(window) def smoothen(img): """Smoothes an image by convolving with a window function.""" return fftconvolve(window, img, mode='valid') if dynamic_range is None: dynamic_range = np.max(ground_truth) - np.min(ground_truth) C1 = (K1 * dynamic_range)**2 C2 = (K2 * dynamic_range)**2 mu1 = smoothen(data) mu2 = smoothen(ground_truth) mu1_sq = mu1 * mu1 mu2_sq = mu2 * mu2 mu1_mu2 = mu1 * mu2 sigma1_sq = smoothen(data * data) - mu1_sq sigma2_sq = smoothen(ground_truth * ground_truth) - mu2_sq sigma12 = smoothen(data * ground_truth) - mu1_mu2 num = (2 * mu1_mu2 + C1) * (2 * sigma12 + C2) denom = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2) pointwise_ssim = num / denom result = np.mean(pointwise_ssim) if force_lower_is_better: result = -result if normalized: result = (result + 1.0) / 2.0 return result
def test_linear_interpolation_2d(): rect = odl.Rectangle([0, 0], [1, 1]) grid = odl.uniform_sampling(rect, [4, 2], as_midp=True) # Coordinate vectors are: # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75] space = odl.FunctionSpace(rect) dspace = odl.Rn(grid.ntotal) interp_op = LinearInterpolation(space, grid, dspace) values = np.arange(1, 9, dtype='float64') function = interp_op(values) rvals = values.reshape([4, 2]) # Evaluate at single point val = function([0.3, 0.6]) l1 = (0.3 - 0.125) / (0.375 - 0.125) l2 = (0.6 - 0.25) / (0.75 - 0.25) true_val = ((1 - l1) * (1 - l2) * rvals[0, 0] + (1 - l1) * l2 * rvals[0, 1] + l1 * (1 - l2) * rvals[1, 0] + l1 * l2 * rvals[1, 1]) assert almost_equal(val, true_val) # Input array, with and without output array pts = np.array([[0.3, 0.6], [0.1, 0.25], [1.0, 1.0]]) l1 = (0.3 - 0.125) / (0.375 - 0.125) l2 = (0.6 - 0.25) / (0.75 - 0.25) true_val_1 = ((1 - l1) * (1 - l2) * rvals[0, 0] + (1 - l1) * l2 * rvals[0, 1] + l1 * (1 - l2) * rvals[1, 0] + l1 * l2 * rvals[1, 1]) l1 = (0.125 - 0.1) / (0.375 - 0.125) # l2 = 0 true_val_2 = (1 - l1) * rvals[0, 0] # only lower left contributes l1 = (1.0 - 0.875) / (0.875 - 0.625) l2 = (1.0 - 0.75) / (0.75 - 0.25) true_val_3 = (1 - l1) * (1 - l2) * rvals[3, 1] # lower left only true_arr = [true_val_1, true_val_2, true_val_3] assert all_equal(function(pts.T), true_arr) out = np.empty(3, dtype='float64') function(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 0.75]) # Indices: (1, 3) x (0, 1) lx1 = (0.3 - 0.125) / (0.375 - 0.125) lx2 = (1.0 - 0.875) / (0.875 - 0.625) ly1 = (0.4 - 0.25) / (0.75 - 0.25) # ly2 = 0 true_val_11 = ((1 - lx1) * (1 - ly1) * rvals[0, 0] + (1 - lx1) * ly1 * rvals[0, 1] + lx1 * (1 - ly1) * rvals[1, 0] + lx1 * ly1 * rvals[1, 1]) true_val_12 = ((1 - lx1) * rvals[0, 1] + lx1 * rvals[1, 1]) # ly2 = 0 true_val_21 = ((1 - lx2) * (1 - ly1) * rvals[3, 0] + (1 - lx2) * ly1 * rvals[3, 1]) # high node 1.0, no upper true_val_22 = (1 - lx2) * rvals[3, 1] # ly2 = 0, no upper for 1.0 true_mg = [[true_val_11, true_val_12], [true_val_21, true_val_22]] assert all_equal(function(mg), true_mg) out = np.empty((2, 2), dtype='float64') function(mg, out=out) assert all_equal(out, true_mg)
def test_linear_interpolation_2d(): """Test linear interpolation in 2d.""" rect = odl.IntervalProd([0, 0], [1, 1]) part = odl.uniform_partition_fromintv(rect, [4, 2], nodes_on_bdry=False) # Coordinate vectors are: # [0.125, 0.375, 0.625, 0.875], [0.25, 0.75] fspace = odl.FunctionSpace(rect) tspace = odl.rn(part.shape) interp_op = LinearInterpolation(fspace, part, tspace) values = np.arange(1, 9, dtype='float64').reshape(part.shape) function = interp_op(values) rvals = values.reshape([4, 2]) # Evaluate at single point val = function([0.3, 0.6]) l1 = (0.3 - 0.125) / (0.375 - 0.125) l2 = (0.6 - 0.25) / (0.75 - 0.25) true_val = ((1 - l1) * (1 - l2) * rvals[0, 0] + (1 - l1) * l2 * rvals[0, 1] + l1 * (1 - l2) * rvals[1, 0] + l1 * l2 * rvals[1, 1]) assert val == pytest.approx(true_val) # Input array, with and without output array pts = np.array([[0.3, 0.6], [0.1, 0.25], [1.0, 1.0]]) l1 = (0.3 - 0.125) / (0.375 - 0.125) l2 = (0.6 - 0.25) / (0.75 - 0.25) true_val_1 = ((1 - l1) * (1 - l2) * rvals[0, 0] + (1 - l1) * l2 * rvals[0, 1] + l1 * (1 - l2) * rvals[1, 0] + l1 * l2 * rvals[1, 1]) l1 = (0.125 - 0.1) / (0.375 - 0.125) # l2 = 0 true_val_2 = (1 - l1) * rvals[0, 0] # only lower left contributes l1 = (1.0 - 0.875) / (0.875 - 0.625) l2 = (1.0 - 0.75) / (0.75 - 0.25) true_val_3 = (1 - l1) * (1 - l2) * rvals[3, 1] # lower left only true_arr = [true_val_1, true_val_2, true_val_3] assert all_equal(function(pts.T), true_arr) out = np.empty(3, dtype='float64') function(pts.T, out=out) assert all_equal(out, true_arr) # Input meshgrid, with and without output array mg = sparse_meshgrid([0.3, 1.0], [0.4, 0.75]) # Indices: (1, 3) x (0, 1) lx1 = (0.3 - 0.125) / (0.375 - 0.125) lx2 = (1.0 - 0.875) / (0.875 - 0.625) ly1 = (0.4 - 0.25) / (0.75 - 0.25) # ly2 = 0 true_val_11 = ((1 - lx1) * (1 - ly1) * rvals[0, 0] + (1 - lx1) * ly1 * rvals[0, 1] + lx1 * (1 - ly1) * rvals[1, 0] + lx1 * ly1 * rvals[1, 1]) true_val_12 = ((1 - lx1) * rvals[0, 1] + lx1 * rvals[1, 1]) # ly2 = 0 true_val_21 = ( (1 - lx2) * (1 - ly1) * rvals[3, 0] + (1 - lx2) * ly1 * rvals[3, 1] ) # high node 1.0, no upper true_val_22 = (1 - lx2) * rvals[3, 1] # ly2 = 0, no upper for 1.0 true_mg = [[true_val_11, true_val_12], [true_val_21, true_val_22]] assert all_equal(function(mg), true_mg) out = np.empty((2, 2), dtype='float64') function(mg, out=out) assert all_equal(out, true_mg) assert repr(interp_op) != ''