Python numpy.testing.assert_array_almost_equal() Examples

The following are code examples for showing how to use numpy.testing.assert_array_almost_equal(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: geonum   Author: jgliss   File: test_elevationprofile.py    GNU General Public License v3.0 6 votes vote down vote up
def test_ElevationProfile():
    
    lat_taranaki = -39.296571
    lon_observer = 173.9224
    
    obs = GeoPoint(lat_taranaki, lon_observer)
    
    npt.assert_almost_equal(obs.altitude, 324)
    
    prof = obs.get_elevation_profile(azimuth=90, dist_hor=50)
    
    prof_nans = obs.get_elevation_profile(azimuth=45, dist_hor=50)
    prof2 = obs.get_elevation_profile(azimuth=45, dist_hor=50,
                                      order=1)
    
    npt.assert_array_equal([len(prof.dists), len(prof.profile),
                            np.sum(np.isnan(prof_nans.profile))],
                            [10092,10092,10263])
    npt.assert_array_almost_equal([prof.profile.max(), prof.profile.min(), 
                                   prof.profile.mean(), prof.profile.std(),
                                   prof.dists.max(),
                                   prof2.profile.max(), prof2.profile.min()],
                                  [2482.598405, 176.008484, 583.012202,  
                                   486.57815, 50.033677, 1005.208932, 0.]) 
Example 2
Project: SSTMap   Author: KurtzmanLab   File: test_gist_output.py    MIT License 6 votes vote down vote up
def test_quantity(self, quantity_index):
        """

        Args:
            quantity_index:

        Returns:

        """

        passed = True
        try:
            npt.assert_array_almost_equal(self.test_data[:, quantity_index], self.ref_data[:, quantity_index], decimal=2)
        except Exception as e:
            print(e)
            passed = False

        return passed 
Example 3
Project: astroNN   Author: henrysky   File: test_loss_func.py    MIT License 6 votes vote down vote up
def test_binary_crossentropy(self):
        with tf.device("/cpu:0"), context.eager_mode():
            y_pred = tf.constant([[0.5, 0., 1.], [2., 0., -1.]])
            y_pred_2 = tf.constant([[0.5, 2., 1.], [2., 2., -1.]])
            y_true = tf.constant([[1., MAGIC_NUMBER, 1.], [1., MAGIC_NUMBER, 0.]])
            y_pred_sigmoid = tf.nn.sigmoid(y_pred)
            y_pred_2_sigmoid = tf.nn.sigmoid(y_pred_2)

            # Truth with Magic number is wrong
            npt.assert_array_almost_equal(binary_crossentropy(y_true, y_pred_sigmoid).numpy(),
                                          binary_crossentropy(y_true, y_pred, from_logits=True).numpy(), decimal=3)
            # make sure neural network prediction won't matter for magic number term
            npt.assert_array_almost_equal(
                binary_crossentropy(y_true, y_pred_2, from_logits=True).numpy(),
                binary_crossentropy(y_true, y_pred, from_logits=True).numpy()
                , decimal=3)
            npt.assert_array_almost_equal(binary_crossentropy(y_true, y_pred_sigmoid).numpy(),
                                          binary_crossentropy(y_true, y_pred_2_sigmoid).numpy(), decimal=3) 
Example 4
Project: astroNN   Author: henrysky   File: test_gaia_tools.py    MIT License 6 votes vote down vote up
def test_logsol(self):
        # Test conversion tools related to log solar luminosity
        from astroNN.gaia import fakemag_to_logsol, absmag_to_logsol, logsol_to_absmag, logsol_to_fakemag
        self.assertEqual(logsol_to_fakemag(fakemag_to_logsol(100.)), 100.)
        npt.assert_array_equal(logsol_to_fakemag(fakemag_to_logsol([100., 100.])), [100., 100.])
        npt.assert_array_equal(logsol_to_fakemag(fakemag_to_logsol(np.array([100, 100, 100]))), [100., 100., 100.])
        self.assertEqual(fakemag_to_logsol(MAGIC_NUMBER), MAGIC_NUMBER)
        self.assertEqual(logsol_to_fakemag(fakemag_to_logsol(MAGIC_NUMBER)), MAGIC_NUMBER)
        self.assertEqual(np.any(fakemag_to_logsol([MAGIC_NUMBER, 1000]) == MAGIC_NUMBER), True)

        self.assertEqual(logsol_to_absmag(absmag_to_logsol(99.)), 99.)
        self.assertAlmostEqual(logsol_to_absmag(absmag_to_logsol(-99.)), -99.)
        npt.assert_array_equal(logsol_to_absmag(absmag_to_logsol([99., 99.])), [99., 99.])
        npt.assert_array_almost_equal(logsol_to_absmag(absmag_to_logsol([-99., -99.])), [-99., -99.])
        npt.assert_array_almost_equal(logsol_to_absmag(absmag_to_logsol(np.array([99., 99., 99.]))), [99., 99., 99.])
        self.assertEqual(absmag_to_logsol(MAGIC_NUMBER), MAGIC_NUMBER)
        self.assertEqual(logsol_to_absmag(absmag_to_logsol(MAGIC_NUMBER)), MAGIC_NUMBER)
        self.assertEqual(np.any(absmag_to_logsol([MAGIC_NUMBER, 1000]) == MAGIC_NUMBER), True) 
Example 5
Project: astroNN   Author: henrysky   File: test_numpy_tools.py    MIT License 6 votes vote down vote up
def test_regularizator(self):
        # make sure its the same as tensorflow
        x = np.array([-1., 2., 3., 4.])
        reg = 0.2

        astroNN_x = l1(x, l1=reg)
        astroNN_x_2 = l2(x, l2=reg)

        with tf.device("/cpu:0"), context.eager_mode():
            l1_reg = tf.keras.regularizers.l1(l=reg)
            l2_reg = tf.keras.regularizers.l2(l=reg)
            tf_x = l1_reg(tf.convert_to_tensor(x))
            tf_x_2 = l2_reg(tf.convert_to_tensor(x))

            npt.assert_array_almost_equal(tf_x.numpy(), astroNN_x)
            npt.assert_array_almost_equal(tf_x_2.numpy(), astroNN_x_2) 
Example 6
Project: Dragonfly   Author: duaneloh   File: unit.py    GNU General Public License v3.0 6 votes vote down vote up
def test_rotate_model(self):
        print('=== Testing rotate_model() ===')
        model = np.random.random((101,101,101))
        rotmodel = np.zeros_like(model)
        interp.rotate_model(np.identity(3), model, rotmodel)
        self.assertAlmostEqual(np.linalg.norm((model-rotmodel)[1:-1,1:-1,1:-1].flatten()), 0.)
        rotmodel.fill(0.)
        interp.rotate_model(np.array([[1,0,0],[0,0,-1],[0,1,0]], dtype='f8'), model, rotmodel)
        self.assertAlmostEqual(np.linalg.norm((np.rot90(model,1,axes=(2,1))-rotmodel)[1:-1,1:-1,1:-1].flatten()), 0.)
        rotmodel.fill(0.)
        interp.rotate_model(np.array([[0,-1,0],[1,0,0],[0,0,1]], dtype='f8'), model, rotmodel)
        self.assertAlmostEqual(np.linalg.norm((np.rot90(model,1,axes=(1,0))-rotmodel)[1:-1,1:-1,1:-1].flatten()), 0.)
        
        intens = 1.e-9*np.fromfile(recon_folder+b'/data/intensities.bin').reshape(3*(145,))
        quat = np.array([np.sqrt(0.86),0.1,0.2,0.3])
        rot = interp.make_rot_quat(quat)
        rotmodel = np.zeros_like(intens)
        interp.rotate_model(rot, intens, rotmodel)
        npt.assert_array_almost_equal(rotmodel[100:103,100:103,100:103], [[[0.09167898, 0.03647299, 0.00707748], [0.12777323, 0.06260195, 0.02031047], [0.16907458, 0.09657051, 0.04333556]], [[0.06231541, 0.02152542, 0.00546131], [0.09500319, 0.04364314, 0.0141322], [0.13197364, 0.07370418, 0.03259982]], [[0.04283407, 0.01201542, 0.00398634], [0.06886472, 0.02839342, 0.00625303], [0.10017888, 0.05289991, 0.02144472]]]) 
Example 7
Project: Dragonfly   Author: duaneloh   File: unit.py    GNU General Public License v3.0 6 votes vote down vote up
def test_slice_merge3d(self):
        print('=== Testing slice_merge3d() ===')
        det = detector.detector()
        det.parse_detector(recon_folder+b'/data/det_sim.dat')
        view = np.ascontiguousarray(det.pixels[:,3])
        quat = np.array([np.sqrt(0.86),0.1,0.2,0.3])
        model = np.zeros(3*(145,))
        weight = np.zeros_like(model)
        interp.slice_merge3d(quat, view, model, weight, det)
        npt.assert_array_almost_equal(model, weight)
        npt.assert_array_almost_equal(model[103:106,68:71,82:85], [[[0.05970267, 0.86777407, 0.08261854], [0.29557584, 0.6624112, 0.00868513], [0.69197243, 0.40168333, 0.]], [[0., 0.69936496, 0.34398347], [0.07919628, 1.25519294, 0.0490487], [0.38575382, 0.65815609, 0.]], [[0., 0.45319003, 0.65207203], [0.01374454, 0.68324196, 0.25491581], [0.12366799, 0.84800088, 0.05462553]]])
        
        view = np.ascontiguousarray(det.pixels[:,3])*np.arange(det.num_pix)
        model = np.zeros(3*(145,))
        weight2 = np.zeros_like(model)
        interp.slice_merge3d(quat, view, model, weight2, det)
        npt.assert_array_almost_equal(weight, weight2)
        npt.assert_array_almost_equal(model[103:106,68:71,82:85], [[[480.23952805, 7053.79230354, 672.87605846], [2377.76518912, 5341.74335349, 70.74035788], [5519.30333337, 3220.70729727, 0.]], [[0., 5738.38868753, 2835.8821622], [640.53422865, 10226.00092727, 403.93064498], [3106.35276845, 5325.18474032, 0.]], [[0., 3752.37021246, 5424.77431879], [111.97675292, 5624.55664759, 2102.41717762], [1007.59124681, 6925.69283809, 450.55910447]]]) 
Example 8
Project: Dragonfly   Author: duaneloh   File: unit.py    GNU General Public License v3.0 6 votes vote down vote up
def test_slice_gen2d(self):
        print('=== Testing slice_gen2d() ===')
        det = detector.detector()
        det.parse_detector(recon_folder+b'/data/det_sim.dat', norm_flag=-3)
        intens = np.arange(145*145*3).astype('f8').reshape(3,145,145)
        view = np.zeros(det.num_pix)
        
        angle = np.array([1.37*np.pi])
        interp.slice_gen2d(angle, view, intens, det)
        self.assertAlmostEqual(view.mean(), 10512.)
        npt.assert_array_almost_equal(view[:5], [6674.995665, 6808.058374, 6941.174136, 7074.339593, 7207.551378])
        interp.slice_gen2d(angle, view, intens, det, rescale=1.)
        self.assertAlmostEqual(view.mean(), 9.1579227696454524)
        npt.assert_array_almost_equal(view[:5], [8.806124, 8.825862, 8.845226, 8.864229, 8.882885])
        
        angle = np.array([3.14*np.pi])
        interp.slice_gen2d(angle, view, intens[1:], det)
        self.assertAlmostEqual(view.mean(), 31537.)
        npt.assert_array_almost_equal(view[:5], [34414.902109, 34489.21956, 34563.301629, 34637.146226, 34710.751266])
        interp.slice_gen2d(angle, view, intens[1:], det, rescale=1.)
        self.assertAlmostEqual(view.mean(), 10.349731872416205)
        npt.assert_array_almost_equal(view[:5], [10.446245, 10.448402, 10.450548, 10.452682, 10.454805]) 
Example 9
Project: Dragonfly   Author: duaneloh   File: unit.py    GNU General Public License v3.0 6 votes vote down vote up
def test_slice_merge2d(self):
        print('=== Testing slice_merge2d() ===')
        det = detector.detector()
        qmax = det.parse_detector(recon_folder+b'/data/det_sim.dat', norm_flag=-3)
        view = np.ascontiguousarray(det.pixels[:,2])
        angle = np.array([1.37*np.pi])
        model = np.zeros((3, 145, 145))
        weight = np.zeros_like(model)
        interp.slice_merge2d(angle, view, model, weight, det)
        npt.assert_array_almost_equal(model, weight)
        npt.assert_array_almost_equal(model[0,88:91,82:85], [[1.013543, 1.013526, 0.95921],[0.948738, 0.988016, 0.986792], [1.013526, 0.985034, 0.98392]])
        
        view = np.ascontiguousarray(det.pixels[:,2])*np.arange(det.num_pix)
        model = np.zeros((3, 145, 145))
        weight2 = np.zeros_like(model)
        interp.slice_merge2d(angle, view, model, weight2, det)
        npt.assert_array_almost_equal(weight, weight2)
        npt.assert_array_almost_equal(model[0,88:91,82:85], [[3590.950843, 3495.003523, 3221.593928], [3314.725198, 3367.85047, 3269.304046], [3513.177067, 3323.48564, 3226.194119]]) 
Example 10
Project: vnpy_crypto   Author: birforce   File: test_ros.py    MIT License 6 votes vote down vote up
def test__impute():
    expected = numpy.array([
         3.11279729,   3.60634338,   4.04602788,   4.04602788,
         4.71008116,   6.14010906,   6.97841457,   2.        ,
         4.2       ,   4.62      ,   5.57      ,   5.66      ,
         5.86      ,   6.65      ,   6.78      ,   6.79      ,
         7.5       ,   7.5       ,   7.5       ,   8.63      ,
         8.71      ,   8.99      ,   9.85      ,  10.82      ,
        11.25      ,  11.25      ,  12.2       ,  14.92      ,
        16.77      ,  17.81      ,  19.16      ,  19.19      ,
        19.64      ,  20.18      ,  22.97
    ])
    df = load_advanced_data()
    df = ros._impute(df, 'conc', 'censored', numpy.log, numpy.exp)
    result = df['final'].values
    npt.assert_array_almost_equal(result, expected) 
Example 11
Project: vnpy_crypto   Author: birforce   File: test_ros.py    MIT License 6 votes vote down vote up
def test__do_ros():
    expected = numpy.array([
         3.11279729,   3.60634338,   4.04602788,   4.04602788,
         4.71008116,   6.14010906,   6.97841457,   2.        ,
         4.2       ,   4.62      ,   5.57      ,   5.66      ,
         5.86      ,   6.65      ,   6.78      ,   6.79      ,
         7.5       ,   7.5       ,   7.5       ,   8.63      ,
         8.71      ,   8.99      ,   9.85      ,  10.82      ,
        11.25      ,  11.25      ,  12.2       ,  14.92      ,
        16.77      ,  17.81      ,  19.16      ,  19.19      ,
        19.64      ,  20.18      ,  22.97
    ])

    df = load_basic_data()
    df = ros._do_ros(df, 'conc', 'censored', numpy.log, numpy.exp)
    result = df['final'].values
    npt.assert_array_almost_equal(result, expected) 
Example 12
Project: PyQuEST-cffi   Author: HQSquantumsimulations   File: test_errors.py    Apache License 2.0 6 votes vote down vote up
def test_one_qubit_errors(prob, gate_def) -> None:

    op = gate_def[0]
    prob = prob*gate_def[1]
    env = utils.createQuestEnv()()
    dm = utils.createDensityQureg()(1, env)
    state = 1/2*np.array([1, 1, 1, 1])
    cheat.initPlusState()(dm)
    # cheat.initStateFromAmps()(dm, np.real(state), np.imag(state))
    # cheat.setDensityAmps()(qureg=dm, startind=0, reals=np.real(state), imags=np.imag(state), numamps=4)

    op()(qureg=dm, qubit=0, probability=prob)
    superop = op().superoperator_matrix(probability=prob)
    end_matrix = (superop @ state).reshape((2, 2))
    matrix = cheat.getDensityMatrix()(dm)
    npt.assert_array_almost_equal(matrix, end_matrix) 
Example 13
Project: osqp-python   Author: oxfordcontrol   File: feasibility_test.py    Apache License 2.0 6 votes vote down vote up
def test_feasibility_problem(self):

        # Solve problem
        res = self.model.solve()

        # Assert close
        nptest.assert_array_almost_equal(
            res.x,
            np.array([-0.0656074, 1.04194398, 0.4756959, -1.64036689,
                      -0.34180168, -0.81696303, -1.06389178, 0.44944554,
                      -0.44829675, -1.01289944, -0.12513655, 0.02267293,
                      -1.15206474, 1.06817424, 1.18143313, 0.01690332,
                      -0.11373645, -0.48115767,  0.25373436, 0.81369707,
                      0.18883475, 0.47000419, -0.24932451, 0.09298623,
                      1.88381076, 0.77536814, -1.35971433, 0.51511176,
                      0.03317466, 0.90226419]), decimal=3)
        nptest.assert_array_almost_equal(res.y, np.zeros(self.m), decimal=3)
        nptest.assert_array_almost_equal(res.info.obj_val, 0., decimal=3) 
Example 14
Project: osqp-python   Author: oxfordcontrol   File: codegen_matrices_test.py    Apache License 2.0 6 votes vote down vote up
def test_update_P_allind(self):
        import mat_emosqp

        # Update matrix P
        Px = self.P_new.data
        mat_emosqp.update_P(Px, None, 0)
        x, y, _, _, _ = mat_emosqp.solve()

        # Assert close
        nptest.assert_array_almost_equal(x, np.array([0., 5.]), decimal=5)
        nptest.assert_array_almost_equal(
            y, np.array([0., 0., 3., 0., 0.]), decimal=5)

        # Update matrix P to the original value
        Px_idx = np.arange(self.P.nnz)
        mat_emosqp.update_P(Px, Px_idx, len(Px)) 
Example 15
Project: osqp-python   Author: oxfordcontrol   File: codegen_matrices_test.py    Apache License 2.0 6 votes vote down vote up
def test_update_A(self):
        import mat_emosqp

        # Update matrix A
        Ax = self.A_new.data
        Ax_idx = np.arange(self.A_new.nnz)
        mat_emosqp.update_A(Ax, Ax_idx, len(Ax))

        # Solve problem
        x, y, _, _, _ = mat_emosqp.solve()

        # Assert close
        nptest.assert_array_almost_equal(x,
            np.array([0.15765766, 7.34234234]), decimal=5)
        nptest.assert_array_almost_equal(
            y, np.array([0., 0., 2.36711712, 0., 0.]), decimal=5)

        # Update matrix A to the original value
        Ax = self.A.data
        Ax_idx = np.arange(self.A.nnz)
        mat_emosqp.update_A(Ax, Ax_idx, len(Ax)) 
Example 16
Project: osqp-python   Author: oxfordcontrol   File: codegen_matrices_test.py    Apache License 2.0 6 votes vote down vote up
def test_update_A_allind(self):
        import mat_emosqp

        # Update matrix A
        Ax = self.A_new.data
        mat_emosqp.update_A(Ax, None, 0)
        x, y, _, _, _ = mat_emosqp.solve()

        # Assert close
        nptest.assert_array_almost_equal(x,
            np.array([0.15765766, 7.34234234]), decimal=5)
        nptest.assert_array_almost_equal(
            y, np.array([0., 0., 2.36711712, 0., 0.]), decimal=5)

        # Update matrix A to the original value
        Ax = self.A.data
        Ax_idx = np.arange(self.A.nnz)
        mat_emosqp.update_A(Ax, Ax_idx, len(Ax)) 
Example 17
Project: osqp-python   Author: oxfordcontrol   File: codegen_matrices_test.py    Apache License 2.0 6 votes vote down vote up
def test_update_P_A_indP_indA(self):
        import mat_emosqp

        # Update matrices P and A
        Px = self.P_new.data
        Px_idx = np.arange(self.P_new.nnz)
        Ax = self.A_new.data
        Ax_idx = np.arange(self.A_new.nnz)
        mat_emosqp.update_P_A(Px, Px_idx, len(Px), Ax, Ax_idx, len(Ax))

        # Solve problem
        x, y, _, _, _ = mat_emosqp.solve()

        # Assert close
        nptest.assert_array_almost_equal(x, np.array([4.25, 3.25]), decimal=5)
        nptest.assert_array_almost_equal(
            y, np.array([0., 0., 3.625, 0., 0.]), decimal=5)

        # Update matrices P and A to the original values
        Px = self.P.data
        Ax = self.A.data
        mat_emosqp.update_P_A(Px, None, 0, Ax, None, 0) 
Example 18
Project: osqp-python   Author: oxfordcontrol   File: codegen_matrices_test.py    Apache License 2.0 6 votes vote down vote up
def test_update_P_A_indP(self):
        import mat_emosqp

        # Update matrices P and A
        Px = self.P_new.data
        Px_idx = np.arange(self.P_new.nnz)
        Ax = self.A_new.data
        mat_emosqp.update_P_A(Px, Px_idx, len(Px), Ax, None, 0)
        x, y, _, _, _ = mat_emosqp.solve()

        # Assert close
        nptest.assert_array_almost_equal(x, np.array([4.25, 3.25]), decimal=5)
        nptest.assert_array_almost_equal(
            y, np.array([0., 0., 3.625, 0., 0.]), decimal=5)

        # Update matrices P and A to the original values
        Px = self.P.data
        Ax = self.A.data
        mat_emosqp.update_P_A(Px, None, 0, Ax, None, 0) 
Example 19
Project: osqp-python   Author: oxfordcontrol   File: codegen_matrices_test.py    Apache License 2.0 6 votes vote down vote up
def test_update_P_A_allind(self):
        import mat_emosqp

        # Update matrices P and A
        Px = self.P_new.data
        Ax = self.A_new.data
        mat_emosqp.update_P_A(Px, None, 0, Ax, None, 0)
        x, y, _, _, _ = mat_emosqp.solve()

        # Assert close
        nptest.assert_array_almost_equal(x, np.array([4.25, 3.25]), decimal=5)
        nptest.assert_array_almost_equal(y, np.array([0., 0., 3.625, 0., 0.]), decimal=5)

        # Update matrices P and A to the original values
        Px = self.P.data
        Ax = self.A.data
        mat_emosqp.update_P_A(Px, None, 0, Ax, None, 0) 
Example 20
Project: osqp-python   Author: oxfordcontrol   File: unconstrained_test.py    Apache License 2.0 6 votes vote down vote up
def test_unconstrained_problem(self):

        # Solve problem
        res = self.model.solve()

        # Assert close
        nptest.assert_array_almost_equal(
            res.x, np.array([
                -0.61981415, -0.06174194, 0.83824061, -0.0595013, -0.17810828,
                2.90550031, -1.8901713, -1.91191741, -3.73603446, 1.7530356,
                -1.67018181, 3.42221944, 0.61263403, -0.45838347, -0.13194248,
                2.95744794, 5.2902277, -1.42836238, -8.55123842, -0.79093815,
                0.43418189, -0.69323554, 1.15967924, -0.47821898, 3.6108927,
                0.03404309, 0.16322926, -2.17974795, 0.32458796, -1.97553574]))
        nptest.assert_array_almost_equal(res.y, np.array([]))
        nptest.assert_array_almost_equal(res.info.obj_val, -35.020288603855825) 
Example 21
Project: osqp-python   Author: oxfordcontrol   File: polishing_test.py    Apache License 2.0 6 votes vote down vote up
def test_polish_simple(self):

        # Simple QP problem
        self.P = sparse.diags([11., 0.], format='csc')
        self.q = np.array([3, 4])
        self.A = sparse.csc_matrix([[-1, 0], [0, -1], [-1, -3], [2, 5], [3, 4]])
        self.u = np.array([0, 0, -15, 100, 80])
        self.l = -np.inf * np.ones(len(self.u))
        self.n = self.P.shape[0]
        self.m = self.A.shape[0]
        self.model = osqp.OSQP()
        self.model.setup(P=self.P, q=self.q, A=self.A, l=self.l, u=self.u,
                         **self.opts)

        # Solve problem
        res = self.model.solve()

        # Assert close
        nptest.assert_array_almost_equal(res.x, np.array([0., 5.]))
        nptest.assert_array_almost_equal(res.y, np.array([1.66666667, 0.,
                                                          1.33333333, 0., 0.]))
        nptest.assert_array_almost_equal(res.info.obj_val, 20.) 
Example 22
Project: osqp-python   Author: oxfordcontrol   File: basic_test.py    Apache License 2.0 6 votes vote down vote up
def test_upper_triangular_P(self):
        res_default = self.model.solve()

        # Get upper triangular P
        P_triu = sparse.triu(self.P, format='csc')

        # Setup and solve with upper triangular part only
        m = osqp.OSQP()
        m.setup(P=P_triu, q=self.q, A=self.A, l=self.l, u=self.u,
                **self.opts)
        res_triu = m.solve()

        # Assert equal
        nptest.assert_array_almost_equal(res_default.x, res_triu.x)
        nptest.assert_array_almost_equal(res_default.y, res_triu.y)
        nptest.assert_array_almost_equal(res_default.info.obj_val, 
                                         res_triu.info.obj_val) 
Example 23
Project: osqp-python   Author: oxfordcontrol   File: codegen_vectors_test.py    Apache License 2.0 6 votes vote down vote up
def test_update_u(self):
        import vec_emosqp

        # Update upper bound
        u_new = 1000. * np.ones(self.m)
        vec_emosqp.update_upper_bound(u_new)
        x, y, _, _, _ = vec_emosqp.solve()

        # Assert close
        nptest.assert_array_almost_equal(
            x, np.array([-1.51515152e-01, -3.33282828e+02]), decimal=4)
        nptest.assert_array_almost_equal(
            y, np.array([0., 0., 1.33333333, 0., 0.]), decimal=4)

        # Update upper bound to the original value
        vec_emosqp.update_upper_bound(self.u) 
Example 24
Project: geonum   Author: jgliss   File: test_topodata.py    GNU General Public License v3.0 5 votes vote down vote up
def test_srtm():
    acc = tp.SRTMAccess()
    d = acc.get_data(acc._TESTLAT, acc._TESTLON)
    npt.assert_equal(d.data.shape, (2, 2))
    vals = [d.data.std(), d.data.mean(), d.data.min(), d.data.max()]
    
    npt.assert_array_almost_equal(vals, [4.0, 857.0, 853.0, 861.0]) 
Example 25
Project: geonum   Author: jgliss   File: test_base_classes.py    GNU General Public License v3.0 5 votes vote down vote up
def test_GeoVector3D():
    """Test basic arithmetic operations on GeoVectors."""
    v = GeoVector3D(dx=1, dy=1, dz=100)
    
    npt.assert_array_equal([v.dx, v.dy, v.dz], [1,1,100])
    npt.assert_array_almost_equal([v.elevation, 
                                   v.magnitude, 
                                   v.azimuth, 
                                   v.dist_hor], 
                                  [4.044691, 1.417745, 45., 1.414214]) 
Example 26
Project: geonum   Author: jgliss   File: test_srtm_database.py    GNU General Public License v3.0 5 votes vote down vote up
def test_guallatiri_topo(guallatiri_data):
    data = guallatiri_data
    npt.assert_array_equal(data.shape, (242, 122))
    npt.assert_array_almost_equal([data.min, data.max, data.mean(), data.std()],
                                  [4084., 6057., 4690.692827, 393.816227])
    
    return data 
Example 27
Project: me-ica   Author: ME-ICA   File: test_quaternions.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_quat2mat():
    # also tested in roundtrip case below
    M = nq.quat2mat([1, 0, 0, 0])
    yield assert_array_almost_equal, M, np.eye(3)
    M = nq.quat2mat([3, 0, 0, 0])
    yield assert_array_almost_equal, M, np.eye(3)
    M = nq.quat2mat([0, 1, 0, 0])
    yield assert_array_almost_equal, M, np.diag([1, -1, -1])
    M = nq.quat2mat([0, 2, 0, 0])
    yield assert_array_almost_equal, M, np.diag([1, -1, -1])
    M = nq.quat2mat([0, 0, 0, 0])
    yield assert_array_almost_equal, M, np.eye(3) 
Example 28
Project: me-ica   Author: ME-ICA   File: test_quaternions.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_mult():
    # Test that quaternion * same as matrix * 
    for M1, q1 in eg_pairs[0::4]:
        for M2, q2 in eg_pairs[1::4]:
            q21 = nq.mult(q2, q1)
            yield assert_array_almost_equal, np.dot(M2,M1), nq.quat2mat(q21) 
Example 29
Project: me-ica   Author: ME-ICA   File: test_quaternions.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_qrotate():
    vecs = np.eye(3)
    for vec in np.eye(3):
        for M, q in eg_pairs:
            vdash = nq.rotate_vector(vec, q)
            vM = np.dot(M, vec)
            yield assert_array_almost_equal, vdash, vM 
Example 30
Project: me-ica   Author: ME-ICA   File: test_quaternions.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_angle_axis2quat():
    q = nq.angle_axis2quat(0, [1, 0, 0])
    yield assert_array_equal, q, [1, 0, 0, 0]
    q = nq.angle_axis2quat(np.pi, [1, 0, 0])
    yield assert_array_almost_equal, q, [0, 1, 0, 0]
    q = nq.angle_axis2quat(np.pi, [1, 0, 0], True)
    yield assert_array_almost_equal, q, [0, 1, 0, 0]
    q = nq.angle_axis2quat(np.pi, [2, 0, 0], False)
    yield assert_array_almost_equal, q, [0, 1, 0, 0] 
Example 31
Project: me-ica   Author: ME-ICA   File: test_quaternions.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_angle_axis():
    for M, q in eg_pairs:
        theta, vec = nq.quat2angle_axis(q)
        q2 = nq.angle_axis2quat(theta, vec)
        yield nq.nearly_equivalent, q, q2
        aa_mat = nq.angle_axis2mat(theta, vec)
        yield assert_array_almost_equal, aa_mat, M 
Example 32
Project: me-ica   Author: ME-ICA   File: test_euler.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def test_quats():
    for x, y, z in eg_rots:
        M1 = nea.euler2mat(z, y, x)
        quatM = nq.mat2quat(M1)
        quat = nea.euler2quat(z, y, x)
        yield nq.nearly_equivalent, quatM, quat
        quatS = sympy_euler2quat(z, y, x)
        yield nq.nearly_equivalent, quat, quatS
        zp, yp, xp = nea.quat2euler(quat)
        # The parameters may not be the same as input, but they give the
        # same rotation matrix
        M2 = nea.euler2mat(zp, yp, xp)
        yield assert_array_almost_equal, M1, M2 
Example 33
Project: CirqProjectQ   Author: HQSquantumsimulations   File: test_xmon_gates.py    Apache License 2.0 5 votes vote down vote up
def test_expz_matrix(half_turns):
    if (version[0] == 0 and version[1] <= 3):
        nptest.assert_array_almost_equal(xmon_gates.ExpZGate(half_turns=half_turns).matrix,
                                google.ExpZGate(half_turns=half_turns).matrix())
    else:
        nptest.assert_array_almost_equal(xmon_gates.ExpZGate(half_turns=half_turns).matrix,
                                unitary(ops.ZPowGate(exponent=half_turns,
                                                     global_shift=half_turns))) 
Example 34
Project: CirqProjectQ   Author: HQSquantumsimulations   File: test_xmon_gates.py    Apache License 2.0 5 votes vote down vote up
def test_expw_matrix(half_turns, axis_half_turns):
    m1 = xmon_gates.ExpWGate(half_turns=half_turns,
                                axis_half_turns=axis_half_turns).matrix
    if (version[0] == 0 and version[1] <= 3):
        m2 = google.ExpWGate(half_turns=half_turns,
                            axis_half_turns=axis_half_turns).matrix()
    else:
         m2 = unitary(ops.PhasedXPowGate(exponent=half_turns,
                            phase_exponent=axis_half_turns))
    nptest.assert_array_almost_equal(m1, m2) 
Example 35
Project: CirqProjectQ   Author: HQSquantumsimulations   File: test_xmon_gates.py    Apache License 2.0 5 votes vote down vote up
def test_expw_matrix(half_turns):
    if (version[0] == 0 and version[1] <= 3):
        nptest.assert_array_almost_equal(xmon_gates.Exp11Gate(half_turns=half_turns).matrix,
                                google.Exp11Gate(half_turns=half_turns).matrix())
    else:
        nptest.assert_array_almost_equal(xmon_gates.Exp11Gate(half_turns=half_turns).matrix,
                                unitary(ops.CZPowGate(exponent=half_turns))) 
Example 36
Project: paramnormal   Author: phobson   File: test_dist.py    MIT License 5 votes vote down vote up
def do_check(self, size):
        result = generate_test_dist(self.dist, size, *self.cargs, **self.ckwds)
        known = generate_knowns(self.np_rand_fxn, size, *self.npargs, **self.npkwds)

        nptest.assert_array_almost_equal(result, known) 
Example 37
Project: tenpy   Author: tenpy   File: test_mps.py    GNU General Public License v3.0 5 votes vote down vote up
def test_charge_fluctuations():
    L = 6
    pairs = [(0, 3), (2, 4)]
    lonely = [1, 5]
    psi = mps.MPS.from_singlets(spin_half,
                                L,
                                pairs,
                                lonely=lonely,
                                lonely_state='up',
                                bc='segment')
    # mps not yet gauged to zero qtotal!
    average_charge = np.array([psi.average_charge(b) for b in range(psi.L + 1)]).T
    charge_variance = np.array([psi.charge_variance(b) for b in range(psi.L + 1)]).T
    print(average_charge)
    print(charge_variance)
    npt.assert_array_almost_equal(average_charge, [[0., 0., 0., 0., 0., 0., 0.]], decimal=14)
    npt.assert_array_almost_equal(charge_variance, [[0., 1., 1., 2., 1., 0., 0.]], decimal=14)

    # now gauge to zero qtotal
    psi.gauge_total_charge()
    average_charge = np.array([psi.average_charge(b) for b in range(psi.L + 1)]).T
    charge_variance = np.array([psi.charge_variance(b) for b in range(psi.L + 1)]).T
    print(average_charge)
    print(charge_variance)
    npt.assert_array_almost_equal(average_charge, [[0., 0., 1., 1., 1., 1., 2.]], decimal=14)
    npt.assert_array_almost_equal(charge_variance, [[0., 1., 1., 2., 1., 0., 0.]], decimal=14) 
Example 38
Project: tenpy   Author: tenpy   File: test_tools.py    GNU General Public License v3.0 5 votes vote down vote up
def test_matvec_to_array():
    A_orig = np.random.random([5, 5]) + 1.j * np.random.random([5, 5])

    class A_matvec:
        def __init__(self, A):
            self.A = A
            self.shape = A.shape
            self.dtype = A.dtype

        def matvec(self, v):
            return np.dot(self.A, v)

    A_reg = tools.math.matvec_to_array(A_matvec(A_orig))
    npt.assert_array_almost_equal(A_orig, A_reg, 14) 
Example 39
Project: astroNN   Author: henrysky   File: test_utilities.py    MIT License 5 votes vote down vote up
def test_normalizer(self):
        from astroNN.nn.utilities.normalizer import Normalizer
        from astroNN.config import MAGIC_NUMBER
        import numpy as np

        data = np.random.normal(0, 1, (100, 10))
        magic_idx = (10, 5)
        data[magic_idx] = MAGIC_NUMBER

        # create a normalizer instance
        normer = Normalizer(mode=1)
        norm_data = normer.normalize(data)

        # make sure normalizer preserve magic_number
        self.assertEqual(norm_data[magic_idx], MAGIC_NUMBER)

        # test demoralize
        data_denorm = normer.denormalize(norm_data)
        # make sure demoralizer preserve magic_number
        self.assertEqual(data_denorm[magic_idx], MAGIC_NUMBER)
        npt.assert_array_almost_equal(data_denorm, data)

        errorous_norm = Normalizer(mode=-1234)

        self.assertRaises(ValueError, errorous_norm.normalize, data)

        # test mode='3s' can do identity transformation
        s3_norm = Normalizer(mode='3s')
        data = np.random.normal(0, 1, (100, 10))
        npt.assert_array_almost_equal(s3_norm.denormalize(s3_norm.normalize(data)), data) 
Example 40
Project: astroNN   Author: henrysky   File: test_loss_func.py    MIT License 5 votes vote down vote up
def test_loss_abs_error(self):
        # =============Abs Percentage Accuracy============= #
        with tf.device("/cpu:0"), context.eager_mode():
            y_pred = tf.constant([[1., 0., 0.], [1., 0., 0.]])
            y_pred_2 = tf.constant([[1., 9., 0.], [1., -1., 0.]])
            y_true = tf.constant([[1., MAGIC_NUMBER, 1.], [1., MAGIC_NUMBER, 1.]])

            npt.assert_array_almost_equal(mean_absolute_percentage_error(y_true, y_pred).numpy(),
                                          [50., 50.], decimal=3)
            # make sure neural network prediction won't matter for magic number term
            npt.assert_array_almost_equal(mean_absolute_percentage_error(y_true, y_pred).numpy(),
                                          mean_absolute_percentage_error(y_true, y_pred_2).numpy(),
                                          decimal=3) 
Example 41
Project: astroNN   Author: henrysky   File: test_loss_func.py    MIT License 5 votes vote down vote up
def test_loss_percentage_error(self):
        # =============Percentage Accuracy============= #
        with tf.device("/cpu:0"), context.eager_mode():
            y_pred = tf.constant([[1., 0., 0.], [1., 0., 0.]])
            y_pred_2 = tf.constant([[1., 9., 0.], [1., -1., 0.]])
            y_true = tf.constant([[1., MAGIC_NUMBER, 1.], [1., MAGIC_NUMBER, 1.]])

            npt.assert_array_almost_equal(mean_percentage_error(y_true, y_pred).numpy(),
                                          [50., 50.], decimal=3)
            # make sure neural network prediction won't matter for magic number term
            npt.assert_array_almost_equal(mean_percentage_error(y_true, y_pred).numpy(),
                                          mean_percentage_error(y_true, y_pred_2).numpy(),
                                          decimal=3) 
Example 42
Project: astroNN   Author: henrysky   File: test_loss_func.py    MIT License 5 votes vote down vote up
def test_loss_log_error(self):
        # =============Mean Squared Log Error============= #
        with tf.device("/cpu:0"), context.eager_mode():
            y_pred = tf.constant([[1., 0., 0.], [1., 0., 0.]])
            y_pred_2 = tf.constant([[1., 9., 0.], [1., -1., 0.]])
            y_true = tf.constant([[1., MAGIC_NUMBER, 1.], [1., MAGIC_NUMBER, 1.]])

            npt.assert_array_almost_equal(mean_squared_logarithmic_error(y_true, y_pred).numpy(),
                                          [0.24, 0.24], decimal=3)
            # make sure neural network prediction won't matter for magic number term
            npt.assert_array_almost_equal(mean_squared_logarithmic_error(y_true, y_pred).numpy(),
                                          mean_squared_logarithmic_error(y_true, y_pred_2).numpy(),
                                          decimal=3) 
Example 43
Project: astroNN   Author: henrysky   File: test_loss_func.py    MIT License 5 votes vote down vote up
def test_loss_zeros(self):
        # =============Zeros Loss============= #
        with tf.device("/cpu:0"), context.eager_mode():
            y_pred = tf.constant([[1., 0., 0.], [5., -9., 2.]])
            y_true = tf.constant([[1., MAGIC_NUMBER, 1.], [1., MAGIC_NUMBER, 1.]])

            npt.assert_array_almost_equal(zeros_loss(y_true, y_pred).numpy(), [0., 0.]) 
Example 44
Project: astroNN   Author: henrysky   File: test_loss_func.py    MIT License 5 votes vote down vote up
def test_negative_log_likelihood(self):
        with tf.device("/cpu:0"), context.eager_mode():
            y_pred = tf.constant([[0.5, 0., 1.], [2., 0., -1.]])
            y_true = tf.constant([[1., MAGIC_NUMBER, 1.], [1., MAGIC_NUMBER, 0.]])

            npt.assert_array_almost_equal(nll(y_true, y_pred).numpy(), 0.34657377, decimal=3) 
Example 45
Project: astroNN   Author: henrysky   File: test_numpy_tools.py    MIT License 5 votes vote down vote up
def test_sigmoid(self):
        # make sure its the same as tensorflow
        x = np.array([-1., 2., 3., 4.])
        astroNN_x = sigmoid(x)
        with tf.device("/cpu:0"), context.eager_mode():
            tf_x = tf.nn.sigmoid(tf.convert_to_tensor(x))
            npt.assert_array_equal(tf_x.numpy(), astroNN_x)

        # make sure identity transform
        npt.assert_array_almost_equal(sigmoid_inv(sigmoid(x)), x)

        # for list
        # make sure its the same as tensorflow
        x = [-1., 2., 3., 4.]
        astroNN_x_list = sigmoid(x)
        npt.assert_array_equal(astroNN_x_list, astroNN_x)

        # make sure identity transform
        npt.assert_array_almost_equal(sigmoid_inv(sigmoid(x)), x)

        # for float
        # make sure its the same as tensorflow
        x = 0.
        astroNN_x = sigmoid(x)
        npt.assert_array_equal(0.5, astroNN_x)

        # make sure identity transform
        npt.assert_array_almost_equal(sigmoid_inv(sigmoid(x)), x) 
Example 46
Project: Dragonfly   Author: duaneloh   File: unit.py    GNU General Public License v3.0 5 votes vote down vote up
def quat_tests(self, rot):
        self.assertEqual(rot.num_rot, 3240)
        self.assertFalse(rot.icosahedral_flag)
        self.assertEqual(rot.quat.shape, (3240, 5))
        npt.assert_array_almost_equal(rot.quat[0], [0.5,-0.5,-0.5,-0.5, 2.07312814e-04])
        npt.assert_array_almost_equal(rot.quat[-1], [2.18508012e-01, 0.00000000e+00, 5.72061403e-01, 7.90569415e-01, 3.38911452e-04]) 
Example 47
Project: Dragonfly   Author: duaneloh   File: unit.py    GNU General Public License v3.0 5 votes vote down vote up
def test_generate_quaternion(self):
        print('=== Testing generate_quaternion() ===')
        rot = quat.rotation()
        rot.generate_quaternion(config_fname)
        self.quat_tests(rot)
        rot.generate_quaternion(config_fname)
        quat_fname = recon_folder+b'/data/quat.dat'
        with open(quat_fname, 'w') as f:
            w = csv.writer(f, delimiter=' ')
            w.writerow([rot.num_rot])
            w.writerows(rot.quat)
        
        config = DragonflyConfig(config_fname)
        config.modify_entry('emc', 'sym_icosahedral', '1')
        rot.generate_quaternion(config_fname)
        self.assertTrue(rot.icosahedral_flag)
        self.assertEqual(rot.num_rot, 75)
        npt.assert_array_almost_equal(rot.quat[0], [1., 0., 0., 0., 0.00881278])
        npt.assert_array_almost_equal(rot.quat[1], [0.98830208, -0.12973191, -0.08017873,  0., 0.01192908])
        config.remove_entry('emc', 'sym_icosahedral')
        
        rot.free_quat()
        rot = quat.rotation()
        config.modify_entry('emc', 'in_quat_file', 'data/quat.dat')
        self.assertRaises(AssertionError, rot.generate_quaternion, config_fname)
        config.remove_entry('emc', 'num_div')
        rot.generate_quaternion(config_fname)
        self.quat_tests(rot)
        
        os.remove(quat_fname)
        config.modify_entry('emc', 'num_div', '4')
        config.remove_entry('emc', 'in_quat_file') 
Example 48
Project: Dragonfly   Author: duaneloh   File: unit.py    GNU General Public License v3.0 5 votes vote down vote up
def test_make_rot_quat(self):
        print('=== Testing make_rot_quat() ===')
        npt.assert_array_almost_equal(interp.make_rot_quat(np.array([1,0,0,0], dtype='f8')), np.identity(3))
        npt.assert_array_almost_equal(interp.make_rot_quat(0.5*np.array([1,-1,-1,-1], dtype='f8')), [[0,0,1],[1,0,0],[0,1,0]])
        npt.assert_array_almost_equal(interp.make_rot_quat(0.5*np.array([1,-1,-1,+1], dtype='f8')), [[0,1,0],[0,0,-1],[-1,0,0]])
        npt.assert_array_almost_equal(interp.make_rot_quat(0.5*np.array([1,+1,+1,-1], dtype='f8')), [[0,0,-1],[1,0,0],[0,-1,0]])
        npt.assert_array_almost_equal(interp.make_rot_quat(np.array([0,0,1/np.sqrt(2.),-1/np.sqrt(2.)], dtype='f8')), [[-1,0,0],[0,0,-1],[0,-1,0]])
        npt.assert_array_almost_equal(interp.make_rot_quat(np.array([1/np.sqrt(2.),0,1/np.sqrt(2.),0], dtype='f8')), [[0,0,-1],[0,1,0],[1,0,0]])
        npt.assert_array_almost_equal(interp.make_rot_quat(np.array([-1/np.sqrt(2.),1/np.sqrt(2.),0,0], dtype='f8')), [[1,0,0],[0,0,-1],[0,1,0]]) 
Example 49
Project: Dragonfly   Author: duaneloh   File: unit.py    GNU General Public License v3.0 5 votes vote down vote up
def test_symmetrize_friedel(self):
        print('=== Testing symmetrize_friedel() ===')
        arr = np.arange(27.).reshape(3,3,3)
        interp.symmetrize_friedel(arr)
        npt.assert_array_almost_equal(arr, 13.*np.ones((3,3,3), dtype='f8'))
        arr = np.zeros((3,3,3), dtype='f8'); arr[0] = 2.2
        interp.symmetrize_friedel(arr)
        npt.assert_array_almost_equal(arr, np.concatenate((1.1*np.ones(9), np.zeros(9), 1.1*np.ones(9))).reshape(3,3,3))
        arr = np.zeros((3,3,3), dtype='f8'); arr[:,0] = 2.2
        interp.symmetrize_friedel(arr)
        npt.assert_array_almost_equal(arr, np.concatenate((1.1*np.ones(9), np.zeros(9), 1.1*np.ones(9))).reshape(3,3,3).transpose(1,0,2))
        arr = np.zeros((3,3,3), dtype='f8'); arr[:,:,0] = 2.2
        interp.symmetrize_friedel(arr)
        npt.assert_array_almost_equal(arr, np.concatenate((1.1*np.ones(9), np.zeros(9), 1.1*np.ones(9))).reshape(3,3,3).transpose(2,1,0)) 
Example 50
Project: Dragonfly   Author: duaneloh   File: unit.py    GNU General Public License v3.0 5 votes vote down vote up
def test_parse_scale(self):
        print('=== Testing parse_scale() ===')
        itr, det, dset, param, qmax = self.allocate_iterate()
        itr.calc_scale(dset, det)
        self.assertEqual(itr.parse_scale(b''), 0)
        
        scale_fname = recon_folder+b'/data/scales.dat'
        rand_scales = np.random.random(dset.tot_num_data)
        np.savetxt(scale_fname.decode('utf-8'), rand_scales)
        self.assertEqual(itr.parse_scale(scale_fname), 1)
        npt.assert_array_almost_equal(itr.scale, rand_scales)