我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.testing.assert_allclose()。
def test_water_use_efficiency(): """ Unit test does not quarantee the wue function is correct, but if this fails, something has changed, and better understand why. """ hf_stats = SimpleNamespace( rho_vapor=9.607e-3, rho_co2=658.8e-6, T=28.56 + 273.15, P=100.1e3, cov_w_q=0.1443e-3, cov_w_c=-1.059e-6, cov_w_T=0.1359, ustar=0.4179, rho_totair=1.150) wue = water_use_efficiency(hf_stats, meas_ht=7.11, canopy_ht=4.42, ppath='C3', ci_mod='const_ppm', diff_ratio=(1 / 0.7)) npt.assert_allclose(wue.wue, -6.45e-3, atol=0.005e-3) npt.assert_allclose(wue.ambient_h2o, 12.4e-3, atol=0.05e-3) npt.assert_allclose(wue.ambient_co2, 638.e-6, atol=0.5e-6) npt.assert_allclose(wue.inter_h2o, 28.3e-3, atol=0.05e-3) npt.assert_allclose(wue.inter_co2, 492.e-6, atol=0.5e-6)
def _compare_xlsx(self, file1, file2, rtol=1e-02, atol=1e-03): # print("requested compare: {} and {}".format(file1, file2)) xl1 = pd.ExcelFile(file1) xl2 = pd.ExcelFile(file2) self.assertEqual(xl1.sheet_names, xl2.sheet_names) for sheet in xl1.sheet_names: # print("Prrocessing sheet {}".format(sheet)) df1 = xl1.parse(sheet) df2 = xl2.parse(sheet) columns1 = list(df1) columns2 = list(df2) self.assertEqual(len(columns1), len(columns2)) arr1 = df1.values arr2 = df2.values self.assertEqual(arr1.shape, arr2.shape) for x, y in np.ndindex(arr1.shape): v1 = arr1[x, y] v2 = arr2[x, y] # print("{}: ({}, {}): {} vs {}".format(sheet, x, y, v1, v2)) if isinstance(v1, six.string_types) or isinstance(v2, six.string_types): self.assertEqual(v1, v2) else: npt.assert_allclose(v1, v2, rtol=rtol, atol=atol)
def test_cov_trob_2d(): x = np.array(df[['x', 'y']]) res = cov_trob(x, cor=True) # Values from MASS::cov.trob n_obs = 5 center = [3.110130, 4.359847] cov = [[1.979174, 2.812684], [2.812684, 4.584488]] cor = [[1.0000000, 0.9337562], [0.9337562, 1.0000000]] assert res['n_obs'] == n_obs npt.assert_allclose(res['center'], center) npt.assert_allclose(res['cov'], cov) npt.assert_allclose(res['cor'], cor)
def check_allclose(actual, desired, rtol=1e-07, atol=0, err_msg='', verbose=True): """ Wrapper around np.testing.assert_allclose that also verifies that inputs are ndarrays. See Also -------- np.assert_allclose """ if type(actual) != type(desired): raise AssertionError("%s != %s" % (type(actual), type(desired))) return assert_allclose( actual, desired, atol=atol, rtol=rtol, err_msg=err_msg, verbose=verbose, )
def test_null_space(self, rave_re_torque_data): """pc.D[i] must equals N.T, where N is orthogonal to the loop closure Jacobian. """ data, pc = rave_re_torque_data pi, ss, robot, J_lc = data # Assert nullspace matrix at s index = 0 q = pi.eval(ss) for i in range(pc.N + 1): Nmat = pc.D[i].T qi = q[i] nr, nc = Nmat.shape for i in range(nc): _ = np.dot(J_lc(qi), Nmat[:, i]) npt.assert_allclose(np.linalg.norm(_), 0, atol=TINY)
def test_cov_trob_3d(): x = np.array(df[['x', 'y', 'z']]) res = cov_trob(x, cor=True) # Values from MASS::cov.trob n_obs = 5 center = [2.844500, 3.930879, 3.543190] cov = [[1.9412275, 2.713547, 0.7242778], [2.7135469, 4.479363, 1.2210262], [0.7242778, 1.221026, 1.6008466]] cor = [[1.0000000, 0.9202185, 0.4108583], [0.9202185, 1.0000000, 0.4559760], [0.4108583, 0.4559760, 1.0000000]] assert res['n_obs'] == n_obs npt.assert_allclose(res['center'], center, rtol=1e-6) npt.assert_allclose(res['cov'], cov, rtol=1e-6) npt.assert_allclose(res['cor'], cor, rtol=1e-6)
def test_calculate_baz(): elat = 0.0 elon = 0.0 slat = 10.0 # put a very small value here slon = 0.000000001 npt.assert_allclose(rotate.calculate_baz(elat, elon, slat, slon), 180.0) assert np.isclose(rotate.calculate_baz(slat, slon, elat, elon), 0.0) elat = 0.0 elon = 0.0 slat = 0.0 slon = 10.0 npt.assert_allclose(rotate.calculate_baz(elat, elon, slat, slon), 270.0) npt.assert_allclose(rotate.calculate_baz(slat, slon, elat, elon), 90.0)
def test_prepare_adjoint_station_information(): adjoint_stations = gas.prepare_adjoint_station_information( ["II.ABKT..BHR"], _stations) _true = [0.0, 120.0, 2437.8, 0.0] assert len(adjoint_stations) == 1 npt.assert_allclose(adjoint_stations["II.ABKT"], _true) adjoint_stations = gas.prepare_adjoint_station_information( ["II.ABKT..BHR", "II.ABKT..BHZ"], _stations) assert len(adjoint_stations) == 1 npt.assert_allclose(adjoint_stations["II.ABKT"], _true) adjoint_stations = gas.prepare_adjoint_station_information( ["II.ABKT..BHR", "II.ABKT..BHZ", "IU.BCD..BHZ"], _stations) assert len(adjoint_stations) == 2 npt.assert_allclose(adjoint_stations["II.ABKT"], _true) npt.assert_allclose(adjoint_stations["IU.BCD"], [0.0, -120.0, 2437.8, 0.0])
def test_generate_adjoint_stations(tmpdir): ms_one = deepcopy(_measurements) ms_one["IU.BCD"].pop("IU.BCD..BHR") ms_one["IU.BCD"].pop("IU.BCD..BHT") ms = {"17_40": deepcopy(ms_one), "40_100": deepcopy(ms_one), "90_250": deepcopy(ms_one)} outputfn = os.path.join(str(tmpdir), "STATIONS.tmp") gas.generate_adjoint_stations( ms, _stations, outputfn, benchmark_flag=False) output_station = read_station_txt(outputfn) assert len(output_station) == 3 npt.assert_allclose(output_station["II.AAK"], [0.0, 0.0, 2437.8, 0.0]) npt.assert_allclose(output_station["II.ABKT"], [0.0, 120.0, 2437.8, 0.0]) npt.assert_allclose(output_station["IU.BCD"], [0.0, -120.0, 2437.8, 0.0]) with pytest.raises(ValueError): gas.generate_adjoint_stations( ms, _stations, outputfn, benchmark_flag=True)
def test_convert_adjs_to_trace(): array = np.array([1., 2., 3., 4., 5.]) starttime = UTCDateTime(1990, 1, 1) adj = AdjointSource( "cc_traveltime_misfit", 0, 1.0, 17, 40, "BHZ", adjoint_source=array, network="II", station="AAK", location="", starttime=starttime) tr, meta = pa.convert_adj_to_trace(adj) npt.assert_allclose(tr.data, array) assert tr.stats.starttime == starttime npt.assert_almost_equal(tr.stats.delta, 1.0) assert tr.id == "II.AAK..BHZ" assert meta["adj_src_type"] == "cc_traveltime_misfit" npt.assert_almost_equal(meta["misfit"], 0.0) npt.assert_almost_equal(meta["min_period"], 17.0) npt.assert_almost_equal(meta["max_period"], 40.0)
def test_zero_padding_stream(): tr = obspy.Trace() array = np.array([1., 2., 3.]) tr.data = np.array(array) st = obspy.Stream([tr]) starttime = tr.stats.starttime - 10 * tr.stats.delta endtime = tr.stats.endtime + 5 * tr.stats.delta st_new = deepcopy(st) pa.zero_padding_stream(st_new, starttime, endtime) assert len(st_new) == 1 tr_new = st_new[0] assert tr_new.stats.starttime == (starttime - 1.0) assert tr_new.stats.endtime == (endtime + 1.0) assert len(tr_new) == 20 npt.assert_allclose(tr_new.data[0:11], np.zeros(11)) npt.assert_allclose(tr_new.data[11:14], array) npt.assert_allclose(tr_new.data[14:20], np.zeros(6))
def test_add_missing_components(): array = np.array([1., 2., 3., 4., 5.]) starttime = UTCDateTime(1990, 1, 1) adjsrcs = get_sample_adjsrcs(array, starttime) st, _ = pa.convert_adjs_to_stream(adjsrcs) nadds = pa.add_missing_components(st) assert nadds == 0 st.remove(st.select(component="Z")[0]) nadds = pa.add_missing_components(st) assert nadds == 1 trz = st.select(component="Z")[0] assert trz.id == "II.AAK..BHZ" npt.assert_allclose(trz.data, np.zeros(5)) assert trz.stats.starttime == starttime st.remove(st.select(component="R")[0]) nadds = pa.add_missing_components(st) assert nadds == 1 trr = st.select(component="R")[0] assert trr.id == "II.AAK..BHR" npt.assert_allclose(trr.data, np.zeros(5)) assert trr.stats.starttime == starttime
def test_division(self): qr_1 = Quaternion(1, 2, 3, 4) qt_1 = Quaternion(1, 3, 3, 6) dq_1 = DualQuaternion(qr_1, qt_1) identity_dq = np.array([0., 0., 0., 1., 0., 0., 0., 0.]).T npt.assert_allclose((dq_1 / dq_1).dq, identity_dq, atol=1e-6) # TODO(ff): Fix this test. qr_2 = Quaternion(1, 4, 5, 1) qt_2 = Quaternion(-4, 2, 3, 4) dq_2 = DualQuaternion(qr_2, qt_2) # dq_2_copy = dq_2.copy() # dq_2_copy.normalize() # dq_expected = dq_1 / dq_2.norm()[0] * dq_2.conjugate() # dq_expected = 1.0 / dq_2.norm()[0] * DualQuaternion( # qr_1 * qr_2.conjugate(), # -1.0 / dq_2.norm()[0] * (qr_1 * qt_2.conjugate() + # qt_1 * qr_2.conjugate())) # dq_expected = dq_1 * DualQuaternion(qr_2.inverse(), # -qt_2 * qr_2.inverse() * qr_2.inverse()) # npt.assert_allclose((dq_1 / dq_2).dq, dq_expected.dq, atol=1e-6)
def test_output_equation_function_kwarg(): with pytest.raises(ValueError, match=zero_dim_output_msg): DynamicalSystem(input_=x) args = np.random.rand(len(x)+1) sys = DynamicalSystem(state=x, state_equation=state_equation, constants_values=constants) npt.assert_allclose( sys.output_equation_function(args[0], args[1:]).squeeze(), args[1:] ) sys = DynamicalSystem(state=x, state_equation=state_equation, output_equation=output_equation, constants_values=constants) npt.assert_allclose( sys.output_equation_function(args[0], args[1:]).squeeze(), np.r_[args[1]**2 + args[2]**2, np.arctan2(args[2], args[1])] )
def test_event_equation_function(switch_fixture): sys = SwitchedSystem( dim_output=1, event_variable_equation_function=event_variable_equation_function, event_bounds=switch_fixture[0], state_equations_functions=switch_fixture[1], output_equations_functions=switch_fixture[2], ) assert sys.state_update_equation_function == full_state_output for x in np.linspace(bounds_min, bounds_max): if not np.any(np.isclose(x, switch_fixture[0])): assert ~np.any(np.isclose( sys.event_equation_function(x, x), 0 )) for zero in switch_fixture[0]: npt.assert_allclose( sys.event_equation_function(len(switch_fixture[0]), zero), 0 )
def test_output_equation_function_kwarg(): with pytest.raises(ValueError, match=need_output_equation_function_msg): DynamicalSystem(dim_output=N) args = np.random.rand(N+1) sys = DynamicalSystem(dim_state=N, state_equation_function=ones_equation_function) npt.assert_allclose( sys.output_equation_function(args[0], args[1:]), args[1:] ) sys = DynamicalSystem(dim_state=1, state_equation_function=ones_equation_function, output_equation_function=ones_equation_function) npt.assert_allclose( sys.output_equation_function(args[0], args[1:]), np.ones(N) )
def test_RegularImagePatches(): img1 = np.reshape(np.arange(12), (3, 4)) samples = [(img1, 0)] get_patches = RegularImagePatches(0, (2, 2), 2) expected = [(np.array([[0, 1], [4, 5]]), 0), (np.array([[2, 3], [6, 7]]), 0)] patches = samples >> get_patches >> Collect() for (p, ps), (e, es) in zip(patches, expected): nt.assert_allclose(p, e) assert ps == es samples = [(img1, img1 + 1)] get_patches = RegularImagePatches((0, 1), (1, 1), 3) expected = [(np.array([[0]]), np.array([[1]])), (np.array([[3]]), np.array([[4]]))] patches = samples >> get_patches >> Collect() for p, e in zip(patches, expected): nt.assert_allclose(p, e)
def test_ImagePatchesByMask_3channel(): img = np.reshape(np.arange(25 * 3), (5, 5, 3)) mask = np.eye(5, dtype='uint8') * 255 samples = [(img, mask)] np.random.seed(0) get_patches = ImagePatchesByMask(0, 1, (3, 3), 1, 1, retlabel=False) patches = samples >> get_patches >> Collect() assert len(patches) == 2 p, m = patches[0] img_patch0 = np.array([[[36, 37, 38], [39, 40, 41], [42, 43, 44]], [[51, 52, 53], [54, 55, 56], [57, 58, 59]], [[66, 67, 68], [69, 70, 71], [72, 73, 74]]]) mask_patch0 = np.array([[255, 0, 0], [0, 255, 0], [0, 0, 255]]) nt.assert_allclose(p, img_patch0) nt.assert_allclose(m, mask_patch0)
def test_load_image(datadirs): h, w = 213, 320 _, formatsdir, arraydir, _ = datadirs pathpattern = formatsdir + '*' for filepath in glob(pathpattern): img = ni.load_image(filepath) is_color = 'color' in filepath assert img.shape == (h, w, 3) if is_color else (h, w) assert isinstance(img, np.ndarray) assert img.dtype == np.uint8 assert np.max(img) <= 255 assert np.min(img) >= 0 for filepath in glob(pathpattern): img = ni.load_image(filepath, as_grey=True) assert img.shape == (h, w) assert np.max(img) <= 255 assert np.min(img) >= 0 for filepath in glob(pathpattern): img = ni.load_image(filepath) fdir, fname = op.split(filepath) arr = np.load(arraydir + fname + '.npy') nt.assert_allclose(img, arr)
def test_pil_to_arr(): rgb_arr = np.ones((5, 4, 3), dtype='uint8') pil_img = ni.arr_to_pil(rgb_arr) arr = ni.pil_to_arr(pil_img) nt.assert_allclose(rgb_arr, arr) assert arr.dtype == np.uint8 gray_arr = np.ones((5, 4), dtype='uint8') pil_img = ni.arr_to_pil(gray_arr) arr = ni.pil_to_arr(pil_img) nt.assert_allclose(gray_arr, arr) assert arr.dtype == np.uint8 with pytest.raises(ValueError) as ex: rgb_arr = np.ones((5, 4, 3), dtype='uint8') hsv_img = pil.Image.fromarray(rgb_arr, 'HSV') ni.pil_to_arr(hsv_img) assert str(ex.value).startswith('Expect RBG or grayscale but got')
def test_patch_iter(): img = np.reshape(np.arange(12), (3, 4)) patches = list(ni.patch_iter(img, (2, 2), 2)) expected = [np.array([[0, 1], [4, 5]]), np.array([[2, 3], [6, 7]])] for p, e in zip(patches, expected): nt.assert_allclose(p, e) patches = list(ni.patch_iter(img, (2, 2), 3)) expected = [np.array([[0, 1], [4, 5]])] for p, e in zip(patches, expected): nt.assert_allclose(p, e) patches = list(ni.patch_iter(img, (1, 3), 1)) expected = [np.array([[0, 1, 2]]), np.array([[1, 2, 3]]), np.array([[4, 5, 6]]), np.array([[5, 6, 7]]), np.array([[8, 9, 10]]), np.array([[9, 10, 11]])] for p, e in zip(patches, expected): nt.assert_allclose(p, e)
def test_sample_pn_patches(): np.random.seed(0) mask = np.zeros((3, 4), dtype='uint8') img = np.reshape(np.arange(12, dtype='uint8'), (3, 4)) mask[1, 2] = 255 results = list(ni.sample_pn_patches(img, mask, (2, 2), 1, 1)) assert len(results) == 2 img_patch, mask_patch, label = results[0] assert label == 0 nt.assert_allclose(img_patch, [[0, 1], [4, 5]]) nt.assert_allclose(mask_patch, [[0, 0], [0, 0]]) img_patch, mask_patch, label = results[1] assert label == 1 nt.assert_allclose(img_patch, [[1, 2], [5, 6]]) nt.assert_allclose(mask_patch, [[0, 0], [0, 255]])
def test_whiten(self): """ make sure that predicting using the whitened representation is the sameas the non-whitened one. """ with self.test_context() as sess: Xs, X, F, k, num_data, feed_dict = self.prepare() k.compile(session=sess) K = k.K(X) + tf.eye(num_data, dtype=settings.float_type) * 1e-6 L = tf.cholesky(K) V = tf.matrix_triangular_solve(L, F, lower=True) Fstar_mean, Fstar_var = gpflow.conditionals.conditional(Xs, X, k, F) Fstar_w_mean, Fstar_w_var = gpflow.conditionals.conditional(Xs, X, k, V, white=True) mean1, var1 = sess.run([Fstar_w_mean, Fstar_w_var], feed_dict=feed_dict) mean2, var2 = sess.run([Fstar_mean, Fstar_var], feed_dict=feed_dict) # TODO: should tolerance be type dependent? assert_allclose(mean1, mean2) assert_allclose(var1, var2)
def test_ERAInterim_image(): fname = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_data", "ei_2000", "39.128_EI_OPER_0001_AN_N128_20000101_0000_0.grb") dset = ERAInterimImg(fname) data = dset.read() assert data.data.shape == (256, 512) assert data.lon.shape == (256, 512) assert data.lat.shape == (256, 512) metadata_should = {'long_name': u'Volumetric soil water layer 1', 'units': u'm**3 m**-3', 'depth': u'0-7 cm'} assert data.metadata == metadata_should nptest.assert_allclose(data.data[34, 23], 0.30950284004211426) nptest.assert_allclose(data.lat[0, 0], 89.46282157) nptest.assert_allclose(data.lon[0, 0], 0) nptest.assert_allclose(data.lon[0, 256], 179.99956164383)
def test_ERAInterim_dataset_two_var(): root_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_data") ds = ERAInterimDs(['39', '40'], root_path) data = ds.read(datetime(2000, 1, 1, 0)) assert data.data['39'].shape == (256, 512) assert data.data['40'].shape == (256, 512) assert data.lon.shape == (256, 512) assert data.lat.shape == (256, 512) assert data.timestamp == datetime(2000, 1, 1, 0, 0) metadata_should = {'39': {'long_name': u'Volumetric soil water layer 1', 'units': u'm**3 m**-3', 'depth': u'0-7 cm'}, '40': {'long_name': u'Volumetric soil water layer 2', 'units': u'm**3 m**-3', 'depth': u'7-28 cm'}, } assert data.metadata == metadata_should nptest.assert_allclose(data.data['39'][34, 23], 0.30950284004211426) nptest.assert_allclose(data.data['40'][34, 23], 0.3094451427459717) nptest.assert_allclose(data.lat[0, 0], 89.46282157)
def test_reshuffle(): inpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "test_data") ts_path = tempfile.mkdtemp() startdate = "2000-01-01" enddate = "2000-01-02" parameters = ["39", "40"] args = [inpath, ts_path, startdate, enddate] + parameters main(args) assert len(glob.glob(os.path.join(ts_path, "*.nc"))) == 2589 ds = ERAinterimTs(ts_path) ts = ds.read_ts(45, 15) ts_39_values_should = np.array([0.17183685, 0.17189026, 0.17173004, 0.17175293, 0.17183685, 0.17189026, 0.17171478, 0.1717453], dtype=np.float32) nptest.assert_allclose(ts['39'].values, ts_39_values_should) ts_40_values_should = np.array([0.17861938, 0.17861176, 0.17866516, 0.17865753, 0.1786499, 0.17864227, 0.17868042, 0.17867279], dtype=np.float32) nptest.assert_allclose(ts['40'].values, ts_40_values_should)
def test_compat_NUFFT(backend, X, Y, Z, RO, PS, K, oversamp, n, width): pymr = pytest.importorskip('pymr') b = backend() c_dims = (X, Y, Z, K) nc_dims = (1, RO, PS, K) t_dims = (3, RO, PS) x = indigo.util.rand64c(*c_dims) traj = indigo.util.rand64c( *t_dims ).real - 0.5 kwargs = dict(oversamp=oversamp, width=width, n=n, dtype=x.dtype) print(nc_dims, c_dims, traj.shape) G0 = pymr.linop.NUFFT(nc_dims, c_dims, traj, **kwargs) G1 = b.NUFFT(nc_dims[:3], c_dims[:3], traj, **kwargs) x_indigo = np.asfortranarray(x.reshape((-1,K), order='F')) x_pmr = pymr.util.vec(x) y_exp = G0 * x_pmr y_act = G1 * x_indigo y_act = y_act.reshape(-1, order='F') npt.assert_allclose(abs(y_act), abs(y_exp), rtol=1e-2)
def test_compat_conjgrad(backend, N): pymr = pytest.importorskip('pymr') b = backend() A = indigo.util.randM( N, N, 0.5 ) A = A.H @ A # make positive definite y = indigo.util.rand64c( N ) x0 = np.zeros( N, dtype=np.complex64 ) A_pmr = pymr.linop.Matrix( A.toarray(), dtype=A.dtype ) x_exp = pymr.alg.cg(A_pmr, A.H * y, x0, maxiter=40) A_indigo = b.SpMatrix(A) b.cg(A_indigo, y, x0, maxiter=40) x_act = x0.copy() npt.assert_allclose(x_act, x_exp, rtol=1e-6)
def test_DenseMatrix(backend, M, N, K, forward, alpha, beta): b = backend() A_h = indigo.util.rand64c(M,N) A = b.DenseMatrix(A_h) if forward: x = b.rand_array((N,K)) y = b.rand_array((M,K)) y_exp = beta * y.to_host() + alpha * A_h.dot(x.to_host()) A.eval(y, x, alpha=alpha, beta=beta) else: x = b.rand_array((M,K)) y = b.rand_array((N,K)) y_exp = beta * y.to_host() + alpha * np.conj(A_h.T).dot(x.to_host()) A.H.eval(y, x, alpha=alpha, beta=beta) npt.assert_allclose(y.to_host(), y_exp, rtol=1e-5)
def test_batch(backend, M, N, K, density, alpha, beta, batch): b = backend() A_h = indigo.util.randM(M, N, density) A = b.SpMatrix(A_h, batch=batch) # forward x = b.rand_array((N,K)) y = b.rand_array((M,K)) y_exp = beta * y.to_host() + alpha * A_h * x.to_host() A.eval(y, x, alpha=alpha, beta=beta) npt.assert_allclose(y.to_host(), y_exp, rtol=1e-5) # adjoint x = b.rand_array((M,K)) y = b.rand_array((N,K)) y_exp = beta * y.to_host() + alpha * A_h.H * x.to_host() A.H.eval(y, x, alpha=alpha, beta=beta) npt.assert_allclose(y.to_host(), y_exp, rtol=1e-5)
def test_One(backend, M, N, K, alpha, beta, forward): x = indigo.util.rand64c(K,N) y = indigo.util.rand64c(M,N) B = backend() if getattr(B.onemm, '__isabstractmethod__', False): pytest.skip("backed <%s> doesn't implement onemm" % backend.__name__) if not hasattr(B, 'onemm'): pytest.skip("backend doesn't implement onemm") O = B.One((M,K), dtype=np.complex64) if forward: u, v = x, y else: v, u = x, y u_d = B.copy_array(u) v_d = B.copy_array(v) exp = beta * v + \ np.broadcast_to(alpha*u.sum(axis=0,keepdims=True), v.shape) O.eval(v_d, u_d, alpha=alpha, beta=beta, forward=forward) act = v_d.to_host() np.testing.assert_allclose(act, exp, rtol=1e-5)
def test_dl_dG(): nz, neq, nineq = 10, 0, 3 [p, Q, G, h, A, b, truez], [dQ, dp, dG, dh, dA, db] = get_grads( nz=nz, neq=neq, nineq=nineq) def f(G): G = G.reshape(nineq, nz) _, zhat, nu, lam, slacks = qp_cvxpy.forward_single_np(Q, p, G, h, A, b) return 0.5 * np.sum(np.square(zhat - truez)) df = nd.Gradient(f) dG_fd = df(G.ravel()).reshape(nineq, nz) if verbose: # print('dG_fd[1,:]: ', dG_fd[1,:]) # print('dG[1,:]: ', dG[1,:]) print('dG_fd: ', dG_fd) print('dG: ', dG) npt.assert_allclose(dG_fd, dG, rtol=RTOL, atol=ATOL)
def test_dl_dA(): nz, neq, nineq = 10, 3, 1 [p, Q, G, h, A, b, truez], [dQ, dp, dG, dh, dA, db] = get_grads( nz=nz, neq=neq, nineq=nineq, Qscale=100., Gscale=100., Ascale=100.) def f(A): A = A.reshape(neq, nz) _, zhat, nu, lam, slacks = qp_cvxpy.forward_single_np(Q, p, G, h, A, b) return 0.5 * np.sum(np.square(zhat - truez)) df = nd.Gradient(f) dA_fd = df(A.ravel()).reshape(neq, nz) if verbose: # print('dA_fd[0,:]: ', dA_fd[0,:]) # print('dA[0,:]: ', dA[0,:]) print('dA_fd: ', dA_fd) print('dA: ', dA) npt.assert_allclose(dA_fd, dA, rtol=RTOL, atol=ATOL)
def make_func(varname, wrfnc, timeidx, method, squeeze, meta): def func(self): try: args = get_args(varname, wrfnc, timeidx, method, squeeze) except ProjectionError: # Don't fail for this return routine = ROUTINE_MAP[varname] kwargs = {"meta" : meta} result = routine(*args, **kwargs) ref = getvar(wrfnc, varname, timeidx, method, squeeze, cache=None, meta=meta) nt.assert_allclose(to_np(result), to_np(ref)) if meta: self.assertEqual(result.dims, ref.dims) return func
def test_RectangularFinExchanger(): PFE = RectangularFinExchanger(0.03, 0.001, 0.012) assert_allclose(PFE.fin_height, 0.03) assert_allclose(PFE.fin_thickness, 0.001) assert_allclose(PFE.fin_spacing, 0.012) # calculated values assert_allclose(PFE.channel_height, 0.029) assert_allclose(PFE.blockage_ratio, 0.8861111111111111) assert_allclose(PFE.fin_count, 83.33333333333333) assert_allclose(PFE.Dh, 0.01595) assert_allclose(PFE.channel_width, 0.011) # with layers, plate thickness, width, and length (fully defined) PFE = RectangularFinExchanger(0.03, 0.001, 0.012, length=1.2, width=2.401, plate_thickness=.005, layers=40) assert_allclose(PFE.A_HX_layer, 19.2) assert_allclose(PFE.layer_fin_count, 200) assert_allclose(PFE.A_HX, 768.0) assert_allclose(PFE.height, 1.4+.005) assert_allclose(PFE.volume, 4.048085999999999) assert_allclose(PFE.A_specific_HX, 189.71928956054794)
def test_RectangularOffsetStripFinExchanger(): ROSFE = RectangularOffsetStripFinExchanger(fin_length=.05, fin_height=.01, fin_thickness=.003, fin_spacing=.05) assert_allclose(ROSFE.fin_length, 0.05) assert_allclose(ROSFE.fin_height, 0.01) assert_allclose(ROSFE.fin_thickness, 0.003) assert_allclose(ROSFE.fin_spacing, 0.05) assert_allclose(ROSFE.blockage_ratio, 0.348) assert_allclose(ROSFE.blockage_ratio_Kim, 0.34199999999999997) assert_allclose(ROSFE.alpha, 5) assert_allclose(ROSFE.delta, 0.06) assert_allclose(ROSFE.gamma, 0.06) assert_allclose(ROSFE.A_channel, 0.000329) # assert_allclose(ROSFE.SA_fin, 0.005574) assert_allclose(ROSFE.Dh, 0.011804808037316112) assert_allclose(ROSFE.Dh_Kays_London, 0.012185185185185186) assert_allclose(ROSFE.Dh_Joshi_Webb, 0.011319367879456085) # With layers, plate thickness, width (fully defined) # ROSFE = RectangularOffsetStripFinExchanger(fin_length=.05, fin_height=.01, fin_thickness=.003, fin_spacing=.05, length=1.2, width=2.401, plate_thickness=.005, layers=40) # assert_allclose(ROSFE.A_HX_layer, 0.267552)
def test_create_Toeplitz(): from stfinv.utils.inversion import _create_Toeplitz # even length d1 = np.array([1., 0., 0., 0., 1., 2., 1., 0., 0., 1]) d2 = np.array([0., 0., 1., 3., 2., 1., 0., 0., 0., 0]) G = _create_Toeplitz(d2) npt.assert_allclose(np.matmul(G, d1), np.convolve(d1, d2, 'same'), atol=1e-7, rtol=1e-7) # odd length d1 = np.array([1., 0., 0., 0., 1., 2., 1., 0., 0.]) d2 = np.array([0., 0., 1., 3., 2., 1., 0., 0., 0.]) G = _create_Toeplitz(d2) npt.assert_allclose(np.matmul(G, d1), np.convolve(d1, d2, 'same'), atol=1e-7, rtol=1e-7)
def test_invert_STF(): from stfinv.utils.inversion import invert_STF tr = obspy.Trace(data=np.array([0., 0., 0., 0., 1., 2., 1., 0., 0.])) st_synth = obspy.Stream(tr) tr = obspy.Trace(data=np.array([0., 0., 1., 3., 2., 1., 0., 0., 0.])) st_synth.append(tr) stf_ref = np.array([0., 0., 1., 1., 0., 1., 1., 0., 0.]) tr = obspy.Trace(data=np.convolve(st_synth[0].data, stf_ref, 'same')) st_data = obspy.Stream(tr) tr = obspy.Trace(data=np.convolve(st_synth[1].data, stf_ref, 'same')) st_data.append(tr) stf = invert_STF(st_data, st_synth) halflen = (len(stf) + 1) / 2 stf = np.r_[stf[halflen:], stf[0:halflen]] npt.assert_allclose(stf, stf_ref, rtol=1e-7, atol=1e-10)
def test_invert_STF_dampened(): from stfinv.utils.inversion import invert_STF tr = obspy.Trace(data=np.array([0., 0., 0., 0., 1., 2., 1., 0., 0.])) st_synth = obspy.Stream(tr) tr = obspy.Trace(data=np.array([0., 0., 1., 3., 2., 1., 0., 0., 0.])) st_synth.append(tr) stf_ref = np.array([0., 0., 1., 1., 0., 1., 1., 0., 0.]) tr = obspy.Trace(data=np.convolve(st_synth[0].data, stf_ref, 'same')) st_data = obspy.Stream(tr) tr = obspy.Trace(data=np.convolve(st_synth[1].data, stf_ref, 'same')) st_data.append(tr) stf = invert_STF(st_data, st_synth, method='dampened', eps=1e-4) npt.assert_allclose(stf, stf_ref, rtol=1e-2, atol=1e-10)
def test_stats2(): """Test stats2 func from fluxpart.util""" data = "7 8 4\n6 1 3\n10 6 6\n6 7 3\n8 2 4" dtype = [('v0', int), ('v1', int), ('v2', int)] arr = np.genfromtxt(io.BytesIO(data.encode()), dtype=dtype) ans = stats2(arr) npt.assert_allclose(ans.ave_v0, 37 / 5) npt.assert_allclose(ans.ave_v1, 24 / 5) npt.assert_allclose(ans.ave_v2, 4) npt.assert_allclose(ans.var_v0, 14 / 5) npt.assert_allclose(ans.var_v1, 97 / 10) npt.assert_allclose(ans.var_v2, 3 / 2) npt.assert_allclose(ans.cov_v0_v1, 3 / 5) npt.assert_allclose(ans.cov_v0_v2, 2) npt.assert_allclose(ans.cov_v1_v0, ans.cov_v0_v1) npt.assert_allclose(ans.cov_v1_v2, 1) npt.assert_allclose(ans.cov_v2_v0, ans.cov_v0_v2) npt.assert_allclose(ans.cov_v2_v1, ans.cov_v1_v2) data = "7 8 4\n6 1 3\n10 6 6\n6 7 3\n8 2 4" dtype = [('v0', int), ('v1', int), ('v2', int)] arr = np.genfromtxt(io.BytesIO(data.encode()), dtype=dtype) ans = stats2(arr, names=('v0', 'v2')) npt.assert_allclose(ans.ave_v0, 37 / 5) npt.assert_allclose(ans.ave_v2, 4) npt.assert_allclose(ans.var_v0, 14 / 5) npt.assert_allclose(ans.var_v2, 3 / 2) npt.assert_allclose(ans.cov_v0_v2, 2) npt.assert_allclose(ans.cov_v2_v0, ans.cov_v0_v2) assert not hasattr(ans, 'ave_v1') assert not hasattr(ans, 'var_v1') assert not hasattr(ans, 'cov_v0_v1') assert not hasattr(ans, 'cov_v1_v0') assert not hasattr(ans, 'cov_v1_v2') assert not hasattr(ans, 'cov_v2_v1')
def assert_flux_components(calc, desired): npt.assert_allclose(calc.Fcp, desired.Fcp, atol=0.5e-6) npt.assert_allclose(calc.Fcr, desired.Fcr, atol=0.1e-6) npt.assert_allclose(calc.Fqe, desired.Fqe, atol=0.01e-3) npt.assert_allclose(calc.Fqt, desired.Fqt, atol=0.05e-3) npt.assert_allclose(calc.Fcp_mol, desired.Fcp_mol, atol=10e-6) npt.assert_allclose(calc.Fcr_mol, desired.Fcr_mol, atol=10e-6) npt.assert_allclose(calc.LEe, desired.LEe, atol=10) npt.assert_allclose(calc.LEt, desired.LEt, atol=50)
def assert_partition(rsoln, fluxes, desired): if rsoln.validroot: npt.assert_allclose(rsoln.var_cp, desired.var_cp, atol=1e-14) npt.assert_allclose(rsoln.corr_cp_cr, desired.corr_cp_cr, atol=1e-2) npt.assert_allclose(fluxes.wqt, desired.wqt, atol=1e-7) npt.assert_allclose(fluxes.wqe, desired.wqe, atol=1e-7) npt.assert_allclose(fluxes.wcp, desired.wcp, atol=1e-9) npt.assert_allclose(fluxes.wcr, desired.wcr, atol=1e-10) else: assert False
def test_scalar(self): pi = PolynomialInterpolator([1, 2, 3]) # 1 + 2s + 3s^2 assert pi.dof == 1 npt.assert_allclose(pi.eval([0, 0.5, 1]), [1, 2.75, 6]) npt.assert_allclose(pi.evald([0, 0.5, 1]), [2, 5, 8]) npt.assert_allclose(pi.evaldd([0, 0.5, 1]), [6, 6, 6])
def test_2_dof(self): pi = PolynomialInterpolator([[1, 2, 3], [-2, 3, 4, 5]]) # [1 + 2s + 3s^2] # [-2 + 3s + 4s^2 + 5s^3] assert pi.dof == 2 npt.assert_allclose( pi.eval([0, 0.5, 1]), [[1, -2], [2.75, 1.125], [6, 10]]) npt.assert_allclose( pi.evald([0, 0.5, 1]), [[2, 3], [5, 10.75], [8, 26]]) npt.assert_allclose(pi.evaldd([0, 0.5, 1]), [[6, 8], [6, 23], [6, 38]])
def test_slack_bounds(self, rave_re_torque_data): """ Test pc.l, pc.h vectors """ data, pc = rave_re_torque_data path, ss, robot, J_lc = data tau_bnd = robot.GetDOFTorqueLimits() for i in range(pc.N + 1): npt.assert_allclose(pc.l[i], -tau_bnd) npt.assert_allclose(pc.h[i], tau_bnd)
def AR1(constrained=False): g = .95 sn = .3 y, c, s = [a[0] for a in gen_data([g], sn, N=1)] result = constrained_oasisAR1(y, g, sn) if constrained else oasisAR1(y, g, lam=2.4) result_foopsi = constrained_foopsi(y, [g], sn) if constrained else foopsi(y, [g], lam=2.4) npt.assert_allclose(np.corrcoef(result[0], result_foopsi[0])[0, 1], 1) npt.assert_allclose(np.corrcoef(result[1], result_foopsi[1])[0, 1], 1) npt.assert_allclose(np.corrcoef(result[0], c)[0, 1], 1, .03) npt.assert_allclose(np.corrcoef(result[1], s)[0, 1], 1, .2)
def AR2(constrained=False): g = [1.7, -.712] sn = .3 y, c, s = [a[0] for a in gen_data(g, sn, N=1, seed=3)] result = constrained_onnlsAR2(y, g, sn) if constrained else onnls(y, g, lam=25) result_foopsi = constrained_foopsi(y, g, sn) if constrained else foopsi(y, g, lam=25) npt.assert_allclose(np.corrcoef(result[0], result_foopsi[0])[0, 1], 1, 1e-3) npt.assert_allclose(np.corrcoef(result[1], result_foopsi[1])[0, 1], 1, 1e-2) npt.assert_allclose(np.corrcoef(result[0], c)[0, 1], 1, .03) npt.assert_allclose(np.corrcoef(result[1], s)[0, 1], 1, .2) result2 = constrained_oasisAR2(y, g[0], g[1], sn) if constrained \ else oasisAR2(y, g[0], g[1], lam=25) npt.assert_allclose(np.corrcoef(result2[0], c)[0, 1], 1, .03) npt.assert_allclose(np.corrcoef(result2[1], s)[0, 1], 1, .2)
def test_rotate_certain_angle(): d1 = np.array([1.0, 0.0]) d2 = np.array([0.0, 1.0]) dnew1, dnew2 = rotate.rotate_certain_angle(d1, d2, 30.0) dnew1_true = np.array([np.sqrt(3)/2.0, 0.5]) dnew2_true = np.array([-0.5, np.sqrt(3)/2.0]) npt.assert_allclose(dnew1, dnew1_true) npt.assert_allclose(dnew2, dnew2_true)
def test_rotate_12_ne(): d1 = np.array([1.0, 0.0]) d2 = np.array([0.0, 1.0]) n, e = rotate.rotate_12_ne(d1, d2, 30, 120) n_true = np.array([np.sqrt(3)/2.0, -0.5]) e_true = np.array([0.5, np.sqrt(3)/2.0]) npt.assert_allclose(n, n_true) npt.assert_allclose(e, e_true)