Python numpy.testing.assert_almost_equal() Examples

The following are code examples for showing how to use numpy.testing.assert_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: xrft   Author: xgcm   File: test_xrft.py    MIT License 6 votes vote down vote up
def test_dft_4d(self):
        """Test the discrete Fourier transform on 2D data"""
        N = 16
        da = xr.DataArray(np.random.rand(N,N,N,N),
                         dims=['time','z','y','x'],
                         coords={'time':range(N),'z':range(N),
                                'y':range(N),'x':range(N)}
                         )
        with pytest.raises(ValueError):
            xrft.dft(da.chunk({'time':8}), dim=['y','x'], detrend='linear')
        ft = xrft.dft(da, shift=False)
        npt.assert_almost_equal(ft.values, np.fft.fftn(da.values))

        da_prime = xrft.detrendn(da[:,0].values, [0,1,2]) # cubic detrend over time, y, and x
        npt.assert_almost_equal(xrft.dft(da[:,0].drop('z'),
                                        dim=['time','y','x'],
                                        shift=False, detrend='linear'
                                        ).values,
                                np.fft.fftn(da_prime)) 
Example 2
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 6 votes vote down vote up
def test_dft_real_2d(self):
        """
        Test the real discrete Fourier transform function on one-dimensional
        data. Non-trivial because we need to keep only some of the negative
        frequencies.
        """
        Nx, Ny = 16, 32
        da = xr.DataArray(np.random.rand(Nx, Ny), dims=['x', 'y'],
                          coords={'x': range(Nx), 'y': range(Ny)})
        dx = float(da.x[1] - da.x[0])
        dy = float(da.y[1] - da.y[0])

        daft = xrft.dft(da, real='x')
        npt.assert_almost_equal(daft.values,
                               np.fft.rfftn(da.transpose('y','x')).transpose())
        npt.assert_almost_equal(daft.values,
                               xrft.dft(da, dim=['y'], real='x'))

        actual_freq_x = daft.coords['freq_x'].values
        expected_freq_x = np.fft.rfftfreq(Nx, dx)
        npt.assert_almost_equal(actual_freq_x, expected_freq_x)

        actual_freq_y = daft.coords['freq_y'].values
        expected_freq_y = np.fft.fftfreq(Ny, dy)
        npt.assert_almost_equal(actual_freq_y, expected_freq_y) 
Example 3
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 6 votes vote down vote up
def test_cross_phase_2d(self, dask):
        Ny, Nx = (32, 16)
        x = np.linspace(0, 1, num=Nx, endpoint=False)
        y = np.ones(Ny)
        f = 6
        phase_offset = np.pi/2
        signal1 = np.cos(2*np.pi*f*x)  # frequency = 1/(2*pi)
        signal2 = np.cos(2*np.pi*f*x - phase_offset)
        da1 = xr.DataArray(data=signal1*y[:,np.newaxis], name='a',
                          dims=['y','x'], coords={'y':y, 'x':x})
        da2 = xr.DataArray(data=signal2*y[:,np.newaxis], name='b',
                          dims=['y','x'], coords={'y':y, 'x':x})
        with pytest.raises(ValueError):
            xrft.cross_phase(da1, da2, dim=['y','x'])

        if dask:
            da1 = da1.chunk({'x': 16})
            da2 = da2.chunk({'x': 16})
        cp = xrft.cross_phase(da1, da2, dim=['x'])
        actual_phase_offset = cp.sel(freq_x=f).values
        npt.assert_almost_equal(actual_phase_offset, phase_offset) 
Example 4
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: onnx_import_test.py    Apache License 2.0 6 votes vote down vote up
def test_broadcast():
    """Test for broadcasting in onnx operators."""
    input1 = np.random.rand(1, 3, 4, 5).astype("float32")
    input2 = np.random.rand(1, 5).astype("float32")
    inputs = [helper.make_tensor_value_info("input1", TensorProto.FLOAT, shape=(1, 3, 4, 5)),
              helper.make_tensor_value_info("input2", TensorProto.FLOAT, shape=(1, 5))]

    outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=(1, 3, 4, 5))]

    nodes = [helper.make_node("Add", ["input1", "input2"], ["output"])]

    graph = helper.make_graph(nodes,
                              "bcast_test",
                              inputs,
                              outputs)

    bcast_model = helper.make_model(graph)
    
    bkd_rep = mxnet_backend.prepare(bcast_model)
    numpy_op = input1 + input2
    output = bkd_rep.run([input1, input2])
    npt.assert_almost_equal(output[0], numpy_op) 
Example 5
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: onnx_import_test.py    Apache License 2.0 6 votes vote down vote up
def test_greater():
    """Test for logical greater in onnx operators."""
    input1 = np.random.rand(1, 3, 4, 5).astype("float32")
    input2 = np.random.rand(1, 5).astype("float32")
    inputs = [helper.make_tensor_value_info("input1", TensorProto.FLOAT, shape=(1, 3, 4, 5)),
              helper.make_tensor_value_info("input2", TensorProto.FLOAT, shape=(1, 5))]

    outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=(1, 3, 4, 5))]

    nodes = [helper.make_node("Greater", ["input1", "input2"], ["output"])]

    graph = helper.make_graph(nodes,
                              "greater_test",
                              inputs,
                              outputs)

    greater_model = helper.make_model(graph)
    
    bkd_rep = mxnet_backend.prepare(greater_model)
    numpy_op = np.greater(input1, input2).astype(np.float32)
    output = bkd_rep.run([input1, input2])
    npt.assert_almost_equal(output[0], numpy_op) 
Example 6
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: onnx_import_test.py    Apache License 2.0 6 votes vote down vote up
def test_lesser():
    """Test for logical greater in onnx operators."""
    input1 = np.random.rand(1, 3, 4, 5).astype("float32")
    input2 = np.random.rand(1, 5).astype("float32")
    inputs = [helper.make_tensor_value_info("input1", TensorProto.FLOAT, shape=(1, 3, 4, 5)),
              helper.make_tensor_value_info("input2", TensorProto.FLOAT, shape=(1, 5))]

    outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=(1, 3, 4, 5))]

    nodes = [helper.make_node("Less", ["input1", "input2"], ["output"])]

    graph = helper.make_graph(nodes,
                              "lesser_test",
                              inputs,
                              outputs)

    greater_model = helper.make_model(graph)
    
    bkd_rep = mxnet_backend.prepare(greater_model)
    numpy_op = np.less(input1, input2).astype(np.float32)
    output = bkd_rep.run([input1, input2])
    npt.assert_almost_equal(output[0], numpy_op) 
Example 7
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: onnx_import_test.py    Apache License 2.0 6 votes vote down vote up
def test_equal():
    """Test for logical greater in onnx operators."""
    input1 = np.random.rand(1, 3, 4, 5).astype("float32")
    input2 = np.random.rand(1, 5).astype("float32")
    inputs = [helper.make_tensor_value_info("input1", TensorProto.FLOAT, shape=(1, 3, 4, 5)),
              helper.make_tensor_value_info("input2", TensorProto.FLOAT, shape=(1, 5))]

    outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=(1, 3, 4, 5))]

    nodes = [helper.make_node("Equal", ["input1", "input2"], ["output"])]

    graph = helper.make_graph(nodes,
                              "equal_test",
                              inputs,
                              outputs)

    greater_model = helper.make_model(graph)
    
    bkd_rep = mxnet_backend.prepare(greater_model)
    numpy_op = np.equal(input1, input2).astype(np.float32)
    output = bkd_rep.run([input1, input2])
    npt.assert_almost_equal(output[0], numpy_op) 
Example 8
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: mxnet_export_test.py    Apache License 2.0 6 votes vote down vote up
def test_square():
    input1 = np.random.randint(1, 10, (2, 3)).astype("float32")

    ipsym = mx.sym.Variable("input1")
    square = mx.sym.square(data=ipsym)
    model = mx.mod.Module(symbol=square, data_names=['input1'], label_names=None)
    model.bind(for_training=False, data_shapes=[('input1', np.shape(input1))], label_shapes=None)
    model.init_params()

    args, auxs = model.get_params()
    params = {}
    params.update(args)
    params.update(auxs)

    converted_model = onnx_mxnet.export_model(square, params, [np.shape(input1)], np.float32, "square.onnx")

    sym, arg_params, aux_params = onnx_mxnet.import_model(converted_model)
    result = forward_pass(sym, arg_params, aux_params, ['input1'], input1)

    numpy_op = np.square(input1)

    npt.assert_almost_equal(result, numpy_op) 
Example 9
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 6 votes vote down vote up
def test_fix2d():
    x = np.random.randn(5000)
    y = np.random.randn(5000)
    bins = 25
    w = np.random.uniform(0.2, 0.5, 5000)

    pygram_h, __ = pygram11.fix2d(x, y, bins=bins, range=((-3, 3), (-2, 2)))
    numpy_h, __, __ = np.histogram2d(
        x, y, bins=[np.linspace(-3, 3, 26), np.linspace(-2, 2, 26)]
    )
    npt.assert_almost_equal(pygram_h, numpy_h, 5)

    pygram_h, __ = pygram11.fix2d(
        x, y, bins=(25, 27), range=((-3, 3), (-2, 1)), weights=w
    )
    numpy_h, __, __ = np.histogram2d(
        x, y, bins=[np.linspace(-3, 3, 26), np.linspace(-2, 1, 28)], weights=w
    )
    npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 10
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 6 votes vote down vote up
def test_numpyAPI_fix2d():
    x = np.random.randn(5000)
    y = np.random.randn(5000)
    bins = 25
    w = np.random.uniform(0.2, 0.5, 5000)

    pygram_h, __ = pygram11.histogram2d(x, y, bins=bins, range=((-3, 3), (-2, 2)))
    numpy_h, __, __ = np.histogram2d(x, y, bins=bins, range=((-3, 3), (-2, 2)))
    npt.assert_almost_equal(pygram_h, numpy_h, 5)

    pygram_h, __ = pygram11.histogram2d(
        x, y, bins=(25, 27), range=((-3, 3), (-2, 1)), weights=w
    )
    numpy_h, __, __ = np.histogram2d(
        x, y, bins=[np.linspace(-3, 3, 26), np.linspace(-2, 1, 28)], weights=w
    )
    npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 11
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 6 votes vote down vote up
def test_fix2d_omp():
        x = np.random.randn(5000)
        y = np.random.randn(5000)
        bins = 25
        w = np.random.uniform(0.25, 0.5, 5000)

        pygram_h, __ = pygram11.fix2d(
            x, y, bins=bins, range=((-3, 3), (-2, 2)), omp=True
        )
        numpy_h, __, __ = np.histogram2d(
            x, y, bins=[np.linspace(-3, 3, 26), np.linspace(-2, 2, 26)]
        )
        npt.assert_almost_equal(pygram_h, numpy_h, 5)

        pygram_h, __ = pygram11.fix2d(
            x, y, bins=(25, 27), range=((-3, 3), (-2, 1)), weights=w, omp=True
        )
        numpy_h, __, __ = np.histogram2d(
            x, y, bins=[np.linspace(-3, 3, 26), np.linspace(-2, 1, 28)], weights=w
        )
        npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 12
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 13
Project: derplearning   Author: notkarol   File: test_roadgen3d.py    MIT License 6 votes vote down vote up
def test_cart2Spherical(self):
		four_corners3d_mm = np.zeros( (4, 3) )
		four_corners3d_mm[:, 0] = self.four_corners_mm[1, :]
		four_corners3d_mm[:, 1] = -self.four_corners_mm[0, :]
		four_corners3d_mm[:, 2] = self.test0.cam_height

		four_corners_angles = np.zeros( (4, 2) )
		four_corners_angles[:, 1] = [self.test0.cam_arc_x/2, -self.test0.cam_arc_x/2,
										-self.test0.cam_arc_x/2, self.test0.cam_arc_x/2 ]
		four_corners_angles[:, 0] = [np.pi/2 - self.test0.cam_vlim_crop_y,
									 np.pi/2 - self.test0.cam_vlim_crop_y,
									 np.pi/2 - self.test0.cam_to_ground_arc,
									 self.test0.cam_tilt_y - self.test0.cam_arc_y]


		npt.assert_almost_equal(self.test0.cart2Spherical(np.array([[1,0,0]]) ), [[1, 0, 0]])
		npt.assert_almost_equal(self.test0.cart2Spherical(
			np.array([[0,0,2]]) ), [[2, np.pi/2, 0]], decimal=4)
		npt.assert_almost_equal(self.test0.cart2Spherical(
			np.array([[0,2,0]]) ), [[2, 0, np.pi/2]], decimal=4)
		npt.assert_almost_equal(self.test0.cart2Spherical( four_corners3d_mm )[:,1:], four_corners_angles, decimal=4)

	#checks to make sure the named function generates the appropriate rotational matrix 
Example 14
Project: LaserTOF   Author: kyleuckert   File: common_tests.py    MIT License 6 votes vote down vote up
def check_moment(distfn, arg, m, v, msg):
    m1 = distfn.moment(1, *arg)
    m2 = distfn.moment(2, *arg)
    if not np.isinf(m):
        npt.assert_almost_equal(m1, m, decimal=10, err_msg=msg +
                            ' - 1st moment')
    else:                     # or np.isnan(m1),
        npt.assert_(np.isinf(m1),
               msg + ' - 1st moment -infinite, m1=%s' % str(m1))

    if not np.isinf(v):
        npt.assert_almost_equal(m2 - m1 * m1, v, decimal=10, err_msg=msg +
                            ' - 2ndt moment')
    else:                     # or np.isnan(m2),
        npt.assert_(np.isinf(m2),
               msg + ' - 2nd moment -infinite, m2=%s' % str(m2)) 
Example 15
Project: LaserTOF   Author: kyleuckert   File: test_continuous_basic.py    MIT License 6 votes vote down vote up
def check_pdf(distfn, arg, msg):
    # compares pdf at median with numerical derivative of cdf
    median = distfn.ppf(0.5, *arg)
    eps = 1e-6
    pdfv = distfn.pdf(median, *arg)
    if (pdfv < 1e-4) or (pdfv > 1e4):
        # avoid checking a case where pdf is close to zero or
        # huge (singularity)
        median = median + 0.1
        pdfv = distfn.pdf(median, *arg)
    cdfdiff = (distfn.cdf(median + eps, *arg) -
               distfn.cdf(median - eps, *arg))/eps/2.0
    # replace with better diff and better test (more points),
    # actually, this works pretty well
    msg += ' - cdf-pdf relationship'
    npt.assert_almost_equal(pdfv, cdfdiff, decimal=DECIMAL, err_msg=msg) 
Example 16
Project: LaserTOF   Author: kyleuckert   File: test_boxcox.py    MIT License 6 votes vote down vote up
def test_boxcox_basic():
    x = np.array([0.5, 1, 2, 4])

    # lambda = 0  =>  y = log(x)
    y = boxcox(x, 0)
    yield assert_almost_equal, y, np.log(x)

    # lambda = 1  =>  y = x - 1
    y = boxcox(x, 1)
    yield assert_almost_equal, y, x - 1

    # lambda = 2  =>  y = 0.5*(x**2 - 1)
    y = boxcox(x, 2)
    yield assert_almost_equal, y, 0.5*(x**2 - 1)

    # x = 0 and lambda > 0  =>  y = -1 / lambda
    lam = np.array([0.5, 1, 2])
    y = boxcox(0, lam)
    yield assert_almost_equal, y, -1.0 / lam 
Example 17
Project: pulse2percept   Author: pulse2percept   File: test_retina.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_Horsager2009_calc_layer_current():
    tsample = 0.01 / 1000
    tm = retina.Horsager2009(tsample=tsample)

    # Assume 4 electrodes, each getting some stimulation
    pts = [stimuli.PulseTrain(tsample=tsample, dur=0.1)] * 4
    ptrain_data = [pt.data for pt in pts]

    # For each of these 4 electrodes, we have two effective current values:
    # one for the ganglion cell layer, one for the bipolar cell layer
    ecs_item = np.random.rand(2, 4)

    # Calulating layer current:
    # The Horsager model does not support INL, so it's just one layer:
    with pytest.raises(ValueError):
        tm.calc_layer_current(ecs_item, ptrain_data, ['GCL', 'INL'])
    with pytest.raises(ValueError):
        tm.calc_layer_current(ecs_item, ptrain_data, ['unknown'])

    # ...and that should be the same as `calc_layer_current`:
    ecm_by_hand = np.sum(ecs_item[1, :, np.newaxis] * ptrain_data, axis=0)
    ecm = tm.calc_layer_current(ecs_item, ptrain_data, ['GCL'])
    npt.assert_almost_equal(ecm, ecm_by_hand) 
Example 18
Project: pulse2percept   Author: pulse2percept   File: test_retina.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_axon_dist_from_soma():
    # A small grid
    xg, yg = np.meshgrid([-1, 0, 1], [-1, 0, 1], indexing='xy')

    # When axon locations are snapped to the grid, a really short axon should
    # have zero distance to the soma:
    for x_soma in [-1.0, -0.2, 0.51]:
        axon = np.array([[i, i] for i in np.linspace(x_soma, x_soma + 0.01)])
        _, dist = retina.axon_dist_from_soma(axon, xg, yg)
        npt.assert_almost_equal(dist, 0.0)

    # On this simple grid, a diagonal axon should have dist [0, sqrt(2), 2]:
    for sign in [-1.0, 1.0]:
        for num in [10, 20, 50]:
            axon = np.array([[i, i] for i in np.linspace(sign, -sign, num)])
            _, dist = retina.axon_dist_from_soma(axon, xg, yg)
            npt.assert_almost_equal(dist, np.array([0.0, np.sqrt(2), 2.0]))

    # An axon that does not live near the grid should return infinite distance
    axon = np.array([[i, i] for i in np.linspace(1000.0, 1500.0)])
    _, dist = retina.axon_dist_from_soma(axon, xg, yg)
    npt.assert_equal(np.isinf(dist), True) 
Example 19
Project: pulse2percept   Author: pulse2percept   File: test_utils.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_gamma():
    tsample = 0.005 / 1000

    with pytest.raises(ValueError):
        t, g = utils.gamma(0, 0.1, tsample)
    with pytest.raises(ValueError):
        t, g = utils.gamma(2, -0.1, tsample)
    with pytest.raises(ValueError):
        t, g = utils.gamma(2, 0.1, -tsample)

    for tau in [0.001, 0.01, 0.1]:
        for n in [1, 2, 5]:
            t, g = utils.gamma(n, tau, tsample)
            npt.assert_equal(np.arange(0, t[-1] + tsample / 2.0, tsample), t)
            if n > 1:
                npt.assert_equal(g[0], 0.0)

            # Make sure area under the curve is normalized
            npt.assert_almost_equal(np.trapz(np.abs(g), dx=tsample), 1.0,
                                    decimal=2)

            # Make sure peak sits correctly
            npt.assert_almost_equal(g.argmax() * tsample, tau * (n - 1)) 
Example 20
Project: CLMM   Author: LSSTDESC   File: test_polaraveraging.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_compute_tangential_shear():
    shear1, shear2, phi = 0.15, 0.08, 0.52
    expected_tangential_shear = -0.14492537676438383
    tangential_shear = pa._compute_tangential_shear(shear1, shear2, phi)
    testing.assert_allclose(tangential_shear, expected_tangential_shear)

    shear1 = np.array([0.15, 0.40])
    shear2 = np.array([0.08, 0.30])
    phi = np.array([0.52, 1.23])
    expected_tangential_shear = [-0.14492537676438383, 0.1216189244145496]
    tangential_shear = pa._compute_tangential_shear(shear1, shear2, phi)
    testing.assert_allclose(tangential_shear, expected_tangential_shear)

    # test for reasonable values
    testing.assert_almost_equal(pa._compute_tangential_shear(100., 0., 0.), -100.0)
    testing.assert_almost_equal(pa._compute_tangential_shear(0., 100., np.pi/4.), -100.0)
    testing.assert_almost_equal(pa._compute_tangential_shear(0., 0., 0.3), 0.) 
Example 21
Project: tf-object-detection   Author: ndaidong   File: tf_example_parser_test.py    MIT License 6 votes vote down vote up
def testBoundingBoxParser(self):
    bounding_boxes = np.array([[0.0, 0.5, 0.3], [0.0, 0.1, 0.6],
                               [1.0, 0.6, 0.8], [1.0, 0.6, 0.7]]).transpose()
    features = {
        'ymin': self._FloatFeature(bounding_boxes[:, 0]),
        'xmin': self._FloatFeature(bounding_boxes[:, 1]),
        'ymax': self._FloatFeature(bounding_boxes[:, 2]),
        'xmax': self._FloatFeature(bounding_boxes[:, 3])
    }

    example = tf.train.Example(features=tf.train.Features(feature=features))

    parser = tf_example_parser.BoundingBoxParser('xmin', 'ymin', 'xmax', 'ymax')
    result = parser.parse(example)
    self.assertIsNotNone(result)
    np_testing.assert_almost_equal(result, bounding_boxes)

    parser = tf_example_parser.BoundingBoxParser('xmin', 'ymin', 'xmax',
                                                 'another_ymax')
    result = parser.parse(example)
    self.assertIsNone(result) 
Example 22
Project: tenpy   Author: tenpy   File: test_mps.py    GNU General Public License v3.0 6 votes vote down vote up
def test_mps_add():
    s = site.SpinHalfSite(conserve='Sz')
    u, d = 'up', 'down'
    psi1 = mps.MPS.from_product_state([s] * 4, [u, u, d, u], bc='finite')
    psi2 = mps.MPS.from_product_state([s] * 4, [u, d, u, u], bc='finite')
    psi_sum = psi1.add(psi2, 0.5**0.5, -0.5**0.5)
    npt.assert_almost_equal(psi_sum.norm, 1.)
    npt.assert_almost_equal(psi_sum.overlap(psi1), 0.5**0.5)
    npt.assert_almost_equal(psi_sum.overlap(psi2), -0.5**0.5)
    # check overlap with singlet state
    psi = mps.MPS.from_singlets(s, 4, [(1, 2)], lonely=[0, 3], up=u, down=d, bc='finite')
    #  ov = psi.overlap(psi_sum.copy())
    print("total charge psi1", psi1.get_total_charge())
    print("total charge psi2", psi2.get_total_charge())
    print("total charge psi_sum", psi_sum.get_total_charge())
    print("total charge psi", psi.get_total_charge())
    npt.assert_almost_equal(psi_sum.overlap(psi), 1.)

    psi2_prime = mps.MPS.from_product_state([s] * 4, [u, u, u, u], bc='finite')
    psi2_prime.apply_local_op(1, 'Sm', False, False)
    # now psi2_prime is psi2 up to gauging of charges.
    # can MPS.add handle this?
    psi_sum_prime = psi1.add(psi2_prime, 0.5**0.5, -0.5**0.5)
    npt.assert_almost_equal(psi_sum_prime.overlap(psi), 1.) 
Example 23
Project: tenpy   Author: tenpy   File: test_mps.py    GNU General Public License v3.0 6 votes vote down vote up
def test_expectation_value_multisite():
    s = spin_half
    psi = mps.MPS.from_singlets(s, 6, [(0, 1), (2, 3), (4, 5)], lonely=[], bc='finite')
    SpSm = npc.outer(s.Sp.replace_labels(['p', 'p*'], ['p0', 'p0*']),
                     s.Sm.replace_labels(['p', 'p*'], ['p1', 'p1*']))
    psi1 = psi.copy()
    ev = psi.expectation_value(SpSm)
    npt.assert_almost_equal(ev, [-0.5, 0., -0.5, 0., -0.5])
    env1 = mps.MPSEnvironment(psi1, psi)
    ev = env1.expectation_value(SpSm)
    npt.assert_almost_equal(ev, [-0.5, 0., -0.5, 0., -0.5])

    psi1.apply_local_op(2, SpSm)  # multi-site operator
    ev = psi1.expectation_value(SpSm)  # normalized!
    npt.assert_almost_equal(ev, [-0.5, 0., 0.0, 0., -0.5])
    env1 = mps.MPSEnvironment(psi1, psi)
    ev = env1.expectation_value(SpSm) / psi1.overlap(psi)  # normalize
    npt.assert_almost_equal(ev, [-0.5, 0., -1., 0., -0.5]) 
Example 24
Project: tenpy   Author: tenpy   File: test_site.py    GNU General Public License v3.0 6 votes vote down vote up
def check_spin_site(S, SpSmSz=['Sp', 'Sm', 'Sz'], SxSy=['Sx', 'Sy']):
    """Test whether the spins operators behave as expected.

    `S` should be a :class:`site.Site`. Set `SxSy` to `None` to ignore Sx and Sy (if they don't
    exist as npc.Array due to conservation).
    """
    Sp, Sm, Sz = SpSmSz
    Sp, Sm, Sz = S.get_op(Sp).to_ndarray(), S.get_op(Sm).to_ndarray(), S.get_op(Sz).to_ndarray()
    npt.assert_almost_equal(commutator(Sz, Sp), Sp, 13)
    npt.assert_almost_equal(commutator(Sz, Sm), -Sm, 13)
    if SxSy is not None:
        Sx, Sy = SxSy
        Sx, Sy = S.get_op(Sx).to_ndarray(), S.get_op(Sy).to_ndarray()
        npt.assert_equal(Sx + 1.j * Sy, Sp)
        npt.assert_equal(Sx - 1.j * Sy, Sm)
        for i in range(3):
            Sa, Sb, Sc = ([Sx, Sy, Sz] * 2)[i:i + 3]
            npt.assert_almost_equal(commutator(Sa, Sb), 1.j * Sc, 13)
            if S == 0.5:
                # for pauli matrices ``sigma_a . sigma_b = 1.j * epsilon_{a,b,c} sigma_c``
                # with ``Sa = 0.5 sigma_a``, we get ``Sa . Sb = 0.5j epsilon_{a,b,c} Sc``.
                npt.assert_almost_equal(np.dot(Sa, Sb), 0.5j * Sc, 13)  # holds only for S=1/2 
Example 25
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: common_tests.py    GNU General Public License v3.0 6 votes vote down vote up
def check_moment(distfn, arg, m, v, msg):
    m1 = distfn.moment(1, *arg)
    m2 = distfn.moment(2, *arg)
    if not np.isinf(m):
        npt.assert_almost_equal(m1, m, decimal=10, err_msg=msg +
                            ' - 1st moment')
    else:                     # or np.isnan(m1),
        npt.assert_(np.isinf(m1),
               msg + ' - 1st moment -infinite, m1=%s' % str(m1))

    if not np.isinf(v):
        npt.assert_almost_equal(m2 - m1 * m1, v, decimal=10, err_msg=msg +
                            ' - 2ndt moment')
    else:                     # or np.isnan(m2),
        npt.assert_(np.isinf(m2),
               msg + ' - 2nd moment -infinite, m2=%s' % str(m2)) 
Example 26
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 5 votes vote down vote up
def test_dft_2d(self):
        """Test the discrete Fourier transform on 2D data"""
        N = 16
        da = xr.DataArray(np.random.rand(N,N), dims=['x','y'],
                        coords={'x':range(N),'y':range(N)}
                         )
        ft = xrft.dft(da, shift=False)
        npt.assert_almost_equal(ft.values, np.fft.fftn(da.values))

        ft = xrft.dft(da, shift=False, window=True, detrend='constant')
        dim = da.dims
        window = np.hanning(N) * np.hanning(N)[:, np.newaxis]
        da_prime = (da - da.mean(dim=dim)).values
        npt.assert_almost_equal(ft.values, np.fft.fftn(da_prime*window)) 
Example 27
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 5 votes vote down vote up
def test_dft_3d_dask(self, dask):
        """Test the discrete Fourier transform on 3D dask array data"""
        N=16
        da = xr.DataArray(np.random.rand(N,N,N), dims=['time','x','y'],
                          coords={'time':range(N),'x':range(N),
                                  'y':range(N)}
                         )
        if dask:
            da = da.chunk({'time': 1})
            daft = xrft.dft(da, dim=['x','y'], shift=False)
            npt.assert_almost_equal(daft.values,
                                   np.fft.fftn(da.chunk({'time': 1}).values,
                                              axes=[1,2])
                                   )
            da = da.chunk({'x': 1})
            with pytest.raises(ValueError):
                xrft.dft(da, dim=['x'])
            with pytest.raises(ValueError):
                xrft.dft(da, dim='x')

            da = da.chunk({'time':N})
            daft = xrft.dft(da, dim=['time'],
                           shift=False, detrend='linear')
            da_prime = sps.detrend(da, axis=0)
            npt.assert_almost_equal(daft.values,
                                   np.fft.fftn(da_prime, axes=[0])
                                   )
            npt.assert_array_equal(daft.values,
                                   xrft.dft(da, dim='time',
                                            shift=False, detrend='linear')
                                   ) 
Example 28
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 5 votes vote down vote up
def test_cross_spectrum(self, dask):
        """Test the cross spectrum function"""
        N = 16
        dim = ['x','y']
        da = xr.DataArray(np.random.rand(2,N,N), dims=['time','x','y'],
                          coords={'time':np.array(['2019-04-18', '2019-04-19'],
                                                 dtype='datetime64'),
                                 'x':range(N), 'y':range(N)})
        da2 = xr.DataArray(np.random.rand(2,N,N), dims=['time','x','y'],
                          coords={'time':np.array(['2019-04-18', '2019-04-19'],
                                                 dtype='datetime64'),
                                  'x':range(N), 'y':range(N)})
        if dask:
            da = da.chunk({'time': 1})
            da2 = da2.chunk({'time': 1})

        daft = xrft.dft(da, dim=dim, shift=True, detrend='constant',
                        window=True)
        daft2 = xrft.dft(da2, dim=dim, shift=True, detrend='constant',
                        window=True)
        cs = xrft.cross_spectrum(da, da2, dim=dim, window=True, density=False,
                                detrend='constant')
        npt.assert_almost_equal(cs.values, np.real(daft*np.conj(daft2)))
        npt.assert_almost_equal(np.ma.masked_invalid(cs).mask.sum(), 0.)

        cs = xrft.cross_spectrum(da, da2, dim=dim, shift=True, window=True,
                                detrend='constant')
        test = (daft * np.conj(daft2)).real.values/N**4

        dk = np.diff(np.fft.fftfreq(N, 1.))[0]
        test /= dk**2
        npt.assert_almost_equal(cs.values, test)
        npt.assert_almost_equal(np.ma.masked_invalid(cs).mask.sum(), 0.) 
Example 29
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 5 votes vote down vote up
def test_cross_phase_1d(self, dask):
        N = 32
        x = np.linspace(0, 1, num=N, endpoint=False)
        f = 6
        phase_offset = np.pi/2
        signal1 = np.cos(2*np.pi*f*x)  # frequency = 1/(2*pi)
        signal2 = np.cos(2*np.pi*f*x - phase_offset)
        da1 = xr.DataArray(data=signal1, name='a', dims=['x'], coords={'x': x})
        da2 = xr.DataArray(data=signal2, name='b', dims=['x'], coords={'x': x})

        if dask:
            da1 = da1.chunk({'x': 32})
            da2 = da2.chunk({'x': 32})
        cp = xrft.cross_phase(da1, da2, dim=['x'])

        actual_phase_offset = cp.sel(freq_x=f).values
        npt.assert_almost_equal(actual_phase_offset, phase_offset)
        assert cp.name == 'a_b_phase'

        xrt.assert_equal(xrft.cross_phase(da1, da2), cp)

        with pytest.raises(ValueError):
            xrft.cross_phase(da1, da2.isel(x=0).drop('x'))

        with pytest.raises(ValueError):
            xrft.cross_phase(da1, da2.rename({'x':'y'})) 
Example 30
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 5 votes vote down vote up
def test_isotropic_ps_slope(N=512, dL=1., amp=1e1, s=-3.):
    """Test the spectral slope of isotropic power spectrum."""

    theta = xr.DataArray(_synthetic_field(N, dL, amp, s),
                        dims=['y', 'x'],
                        coords={'y':range(N), 'x':range(N)})
    iso_ps = xrft.isotropic_powerspectrum(theta, detrend='constant',
                                         density=True)
    npt.assert_almost_equal(np.ma.masked_invalid(iso_ps[1:]).mask.sum(), 0.)
    y_fit, a, b = xrft.fit_loglog(iso_ps.freq_r.values[4:],
                                 iso_ps.values[4:])

    npt.assert_allclose(a, s, atol=.1) 
Example 31
Project: xrft   Author: xgcm   File: test_xrft.py    MIT License 5 votes vote down vote up
def test_isotropic_cs():
    """Test isotropic cross spectrum"""
    N = 16
    da = xr.DataArray(np.random.rand(N,N),
                    dims=['y','x'], coords={'y':range(N),'x':range(N)})
    da2 = xr.DataArray(np.random.rand(N,N),
                    dims=['y','x'], coords={'y':range(N),'x':range(N)})

    iso_cs = xrft.isotropic_crossspectrum(da, da2, window=True)
    npt.assert_almost_equal(np.ma.masked_invalid(iso_cs[1:]).mask.sum(), 0.)

    da2 = xr.DataArray(np.random.rand(N,N),
                    dims=['lat','lon'],
                    coords={'lat':range(N),'lon':range(N)})
    with pytest.raises(ValueError):
        xrft.isotropic_crossspectrum(da, da2)

    da = xr.DataArray(np.random.rand(2,5,5,16,32),
                  dims=['time','zz','z','y', 'x'],
                  coords={'time': np.array(['2019-04-18', '2019-04-19'],
                                          dtype='datetime64'),
                         'zz': np.arange(5), 'z': np.arange(5),
                         'y': np.arange(16), 'x': np.arange(32)})
    da2 = xr.DataArray(np.random.rand(2,5,5,16,32),
                  dims=['time','zz','z','y', 'x'],
                  coords={'time': np.array(['2019-04-18', '2019-04-19'],
                                          dtype='datetime64'),
                         'zz': np.arange(5), 'z': np.arange(5),
                         'y': np.arange(16), 'x': np.arange(32)})
    with pytest.raises(ValueError):
        xrft.isotropic_crossspectrum(da, da2, dim=['y','x'])
    da = da[:,0,:,:,:].drop(['zz'])
    da2 = da2[:,0,:,:,:].drop(['zz'])
    with pytest.raises(ValueError):
        xrft.isotropic_crossspectrum(da, da2, dim=['z','y','x'])

    iso_cs = xrft.isotropic_crossspectrum(da, da2, dim=['y','x'],
                                         window=True).values
    npt.assert_almost_equal(np.ma.masked_invalid(iso_cs[:,:,1:]).mask.sum(), 0.) 
Example 32
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: onnx_import_test.py    Apache License 2.0 5 votes vote down vote up
def test_bvlc_googlenet():
    """ Tests Googlenet model"""
    model_path, inputs, outputs = get_test_files('bvlc_googlenet')
    logging.info("Translating Googlenet model from ONNX to Mxnet")
    sym, arg_params, aux_params = onnx_mxnet.import_model(model_path)
    metadata = onnx_mxnet.get_model_metadata(model_path)
    assert len(metadata) == 2
    assert metadata.get('input_tensor_data')
    assert metadata.get('input_tensor_data') == [(u'data_0', (1, 3, 224, 224))]
    assert metadata.get('output_tensor_data')
    assert metadata.get('output_tensor_data') == [(u'prob_1', (1, 1000))]
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    # run test for each test file
    for input_data, output_data in zip(inputs, outputs):
        # create module
        mod = mx.mod.Module(symbol=sym, data_names=data_names, context=mx.cpu(), label_names=None)
        mod.bind(for_training=False, data_shapes=[(data_names[0], input_data.shape)], label_shapes=None)
        mod.set_params(arg_params=arg_params, aux_params=aux_params,
                       allow_missing=True, allow_extra=True)
        # run inference
        batch = namedtuple('Batch', ['data'])
        mod.forward(batch([mx.nd.array(input_data)]), is_train=False)

        # verify the results
        npt.assert_equal(mod.get_outputs()[0].shape, output_data.shape)
        npt.assert_almost_equal(output_data, mod.get_outputs()[0].asnumpy(), decimal=3)
    logging.info("Googlenet model conversion Successful") 
Example 33
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: onnx_import_test.py    Apache License 2.0 5 votes vote down vote up
def test_bvlc_rcnn_ilsvrc13():
    """Tests the bvlc rcnn model"""
    model_path, inputs, outputs = get_test_files('bvlc_reference_rcnn_ilsvrc13')
    logging.info("Translating rcnn_ilsvrc13 model from ONNX to Mxnet")
    sym, arg_params, aux_params = onnx_mxnet.import_model(model_path)
    metadata = onnx_mxnet.get_model_metadata(model_path)
    assert len(metadata) == 2
    assert metadata.get('input_tensor_data')
    assert metadata.get('input_tensor_data') == [(u'data_0', (1, 3, 224, 224))]
    assert metadata.get('output_tensor_data')
    assert metadata.get('output_tensor_data') == [(u'fc-rcnn_1', (1, 200))]
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    # run test for each test file
    for input_data, output_data in zip(inputs, outputs):
        # create module
        mod = mx.mod.Module(symbol=sym, data_names=data_names, context=mx.cpu(), label_names=None)
        mod.bind(for_training=False, data_shapes=[(data_names[0], input_data.shape)], label_shapes=None)
        mod.set_params(arg_params=arg_params, aux_params=aux_params,
                       allow_missing=True, allow_extra=True)
        # run inference
        batch = namedtuple('Batch', ['data'])
        mod.forward(batch([mx.nd.array(input_data)]), is_train=False)

        # verify the results
        npt.assert_equal(mod.get_outputs()[0].shape, output_data.shape)
        npt.assert_almost_equal(output_data, mod.get_outputs()[0].asnumpy(), decimal=3)
    logging.info("rcnn_ilsvrc13 model conversion Successful") 
Example 34
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: mxnet_export_test.py    Apache License 2.0 5 votes vote down vote up
def test_models(model_name, input_shape, output_shape):
    """ Tests Googlenet model for both onnx import and export"""
    model_path, inputs, outputs = get_test_files(model_name)
    logging.info("Translating model from ONNX model zoo to Mxnet")
    sym, arg_params, aux_params = onnx_mxnet.import_model(model_path)
    params = {}
    params.update(arg_params)
    params.update(aux_params)

    dir_path = os.path.dirname(model_path)
    new_model_name = "exported_" + model_name + ".onnx"
    onnx_file = os.path.join(dir_path, new_model_name)

    logging.info("Translating converted model from mxnet to ONNX")
    converted_model_path = onnx_mxnet.export_model(sym, params, [input_shape], np.float32, onnx_file)

    sym, arg_params, aux_params = onnx_mxnet.import_model(converted_model_path)

    metadata = onnx_mxnet.get_model_metadata(converted_model_path)
    assert len(metadata) == 2
    assert metadata.get('input_tensor_data')
    assert metadata.get('input_tensor_data')[0][1] == input_shape
    assert metadata.get('output_tensor_data')
    assert metadata.get('output_tensor_data')[0][1] == output_shape
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    logging.info("Running inference on onnx re-import model in mxnet")
    # run test for each test file
    for input_data, output_data in zip(inputs, outputs):
        result = forward_pass(sym, arg_params, aux_params, data_names, input_data)

        # verify the results
        npt.assert_equal(result.shape, output_data.shape)
        npt.assert_almost_equal(output_data, result, decimal=3)
    logging.info(model_name + " conversion successful") 
Example 35
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: mxnet_export_test.py    Apache License 2.0 5 votes vote down vote up
def test_model_accuracy(model_name, input_shape):
    """ Imports ONNX model, runs inference, exports and imports back
        run inference, compare result with the previous inference result"""
    model_path, inputs, outputs = get_test_files(model_name)
    logging.info("Translating model from ONNX model zoo to Mxnet")
    sym, arg_params, aux_params = onnx_mxnet.import_model(model_path)

    metadata = onnx_mxnet.get_model_metadata(model_path)
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    expected_result= []
    for input_data, output_data in zip(inputs, outputs):
        result = forward_pass(sym, arg_params, aux_params, data_names, input_data)
        expected_result.append(result)

    params = {}
    params.update(arg_params)
    params.update(aux_params)

    dir_path = os.path.dirname(model_path)
    new_model_name = "exported_" + model_name + ".onnx"
    onnx_file = os.path.join(dir_path, new_model_name)

    logging.info("Translating converted model from mxnet to ONNX")
    converted_model_path = onnx_mxnet.export_model(sym, params, [input_shape], np.float32,
                                                   onnx_file)

    sym, arg_params, aux_params = onnx_mxnet.import_model(converted_model_path)

    metadata = onnx_mxnet.get_model_metadata(converted_model_path)
    data_names = [input_name[0] for input_name in metadata.get('input_tensor_data')]

    actual_result = []
    for input_data, output_data in zip(inputs, outputs):
        result = forward_pass(sym, arg_params, aux_params, data_names, input_data)
        actual_result.append(result)

    # verify the results
    for expected, actual in zip(expected_result, actual_result):
        npt.assert_equal(expected.shape, actual.shape)
        npt.assert_almost_equal(expected, actual, decimal=3) 
Example 36
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: mxnet_export_test.py    Apache License 2.0 5 votes vote down vote up
def test_spacetodepth():
    n, c, h, w = shape = (1, 1, 4, 6)
    input1 = np.random.rand(n, c, h, w).astype("float32")
    blocksize = 2
    inputs = [helper.make_tensor_value_info("input1", TensorProto.FLOAT, shape=shape)]

    outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, shape=(1, 4, 2, 3))]

    nodes = [helper.make_node("SpaceToDepth", ["input1"], ["output"], block_size=blocksize)]

    graph = helper.make_graph(nodes,
                              "spacetodepth_test",
                              inputs,
                              outputs)

    spacetodepth_model = helper.make_model(graph)

    bkd_rep = backend.prepare(spacetodepth_model)
    output = bkd_rep.run([input1])

    tmp = np.reshape(input1, [n, c,
                    h // blocksize, blocksize,
                    w // blocksize, blocksize])
    tmp = np.transpose(tmp, [0, 3, 5, 1, 2, 4])
    numpy_op = np.reshape(tmp, [n, c * (blocksize**2),
                    h // blocksize,
                    w // blocksize])

    npt.assert_almost_equal(output[0], numpy_op) 
Example 37
Project: stfinv   Author: seismology   File: tests_stream.py    GNU General Public License v3.0 5 votes vote down vote up
def test_calc_amplitude_misfit():

    data_test = [0.0, 0.0, 1.0, 2.0, 1.0, 0.0, 0.0]
    tr_test = obspy.Trace(np.array(data_test),
                          header=dict(station='AAA',
                                      location='00',
                                      delta=0.1))
    st_ref = Stream(tr_test)
    tr_test = obspy.Trace(np.array(data_test),
                          header=dict(station='BBB',
                                      location='00',
                                      delta=0.1))
    st_ref.append(tr_test)

    st_mult = st_ref.copy()

    st_mult.select(station='AAA')[0].data *= 2
    st_mult.select(station='BBB')[0].data *= 0.5

    dA = st_mult.calc_amplitude_misfit(st_ref)

    npt.assert_almost_equal(dA['AAA.00'], 2.0, decimal=5)
    npt.assert_almost_equal(dA['BBB.00'], 0.5, decimal=5)

    # Check when order is mixed up
    st_mult = st_ref.copy()

    st_mult.select(station='AAA')[0].data *= 2
    st_mult.select(station='BBB')[0].data *= 0.5

    st_mult.sort(keys=['station'], reverse=True)

    dA = st_mult.calc_amplitude_misfit(st_ref)

    npt.assert_almost_equal(dA['AAA.00'], 2.0, decimal=5)
    npt.assert_almost_equal(dA['BBB.00'], 0.5, decimal=5) 
Example 38
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 5 votes vote down vote up
def test_fix1d():
    x = np.random.randn(5000)
    bins = 25
    w = np.random.uniform(0.5, 1.0, 5000)

    pygram_h, __ = pygram11.fix1d(x, bins=25, range=(-3, 3))
    numpy_h, __ = np.histogram(x, bins=np.linspace(-3, 3, 26))
    npt.assert_almost_equal(pygram_h, numpy_h, 5)

    pygram_h, __ = pygram11.fix1d(x, bins=25, range=(-3, 3), weights=w)
    numpy_h, __ = np.histogram(x, bins=np.linspace(-3, 3, 26), weights=w)
    npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 39
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 5 votes vote down vote up
def test_var1d():
    x = np.random.randn(5000)
    bins = [-1.2, -1, -0.2, 0.7, 1.5, 2.1]
    w = np.random.uniform(0.5, 1.9, 5000)

    pygram_h, __ = pygram11.var1d(x, bins=bins)
    numpy_h, __ = np.histogram(x, bins=bins)
    npt.assert_almost_equal(pygram_h, numpy_h, 5)

    pygram_h, __ = pygram11.var1d(x, bins=bins, weights=w)
    numpy_h, __ = np.histogram(x, bins=bins, weights=w)
    npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 40
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 5 votes vote down vote up
def test_var2d():
    x = np.random.randn(5000)
    y = np.random.randn(5000)
    xbins = [-1.2, -1, 0.2, 0.7, 1.5, 2.1]
    ybins = [-1.1, -1, 0.1, 0.8, 1.2, 2.2]
    w = np.random.uniform(0.25, 1, 5000)

    pygram_h, __ = pygram11.var2d(x, y, xbins, ybins)
    numpy_h, __, __ = np.histogram2d(x, y, bins=[xbins, ybins])
    npt.assert_almost_equal(pygram_h, numpy_h, 5)

    pygram_h, __ = pygram11.var2d(x, y, xbins, ybins, weights=w)
    numpy_h, __, __ = np.histogram2d(x, y, bins=[xbins, ybins], weights=w)
    npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 41
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 5 votes vote down vote up
def test_numpyAPI_fix1d():
    x = np.random.randn(5000)
    bins = 25
    w = np.random.uniform(0.8, 1, 5000)

    pygram_h, __ = pygram11.histogram(x, bins=25, range=(-3, 3))
    numpy_h, __ = np.histogram(x, bins=np.linspace(-3, 3, 26))
    npt.assert_almost_equal(pygram_h, numpy_h, 5)

    pygram_h, __ = pygram11.histogram(x, bins=25, range=(-3, 3), weights=w)
    numpy_h, __ = np.histogram(x, bins=np.linspace(-3, 3, 26), weights=w)
    npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 42
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 5 votes vote down vote up
def test_numpyAPI_var2d():
    x = np.random.randn(5000)
    y = np.random.randn(5000)
    xbins = [-1.2, -1, 0.2, 0.7, 1.5, 2.1]
    ybins = [-1.1, -1, 0.1, 0.8, 1.2, 2.2]
    w = np.random.uniform(0.25, 1, 5000)

    pygram_h, __ = pygram11.histogram2d(x, y, bins=[xbins, ybins])
    numpy_h, __, __ = np.histogram2d(x, y, bins=[xbins, ybins])
    npt.assert_almost_equal(pygram_h, numpy_h, 5)

    pygram_h, __ = pygram11.histogram2d(x, y, bins=[xbins, ybins], weights=w)
    numpy_h, __, __ = np.histogram2d(x, y, bins=[xbins, ybins], weights=w)
    npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 43
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 5 votes vote down vote up
def test_fix1d_omp():
        x = np.random.randn(5000)
        bins = 25
        w = np.random.uniform(-0.2, 0.8, 5000)

        pygram_h, __ = pygram11.fix1d(x, bins=25, range=(-3, 3), omp=True)
        numpy_h, __ = np.histogram(x, bins=np.linspace(-3, 3, 26))
        npt.assert_almost_equal(pygram_h, numpy_h, 5)

        pygram_h, __ = pygram11.fix1d(x, bins=25, range=(-3, 3), weights=w, omp=True)
        numpy_h, __ = np.histogram(x, bins=np.linspace(-3, 3, 26), weights=w)
        npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 44
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 5 votes vote down vote up
def test_var1d_omp():
        x = np.random.randn(5000)
        bins = [-1.2, -1, -0.2, 0.7, 1.5, 2.1]
        w = np.random.uniform(-0.1, 0.8, 5000)

        pygram_h, __ = pygram11.var1d(x, bins=bins, omp=True)
        numpy_h, __ = np.histogram(x, bins=bins)
        npt.assert_almost_equal(pygram_h, numpy_h, 5)

        pygram_h, __ = pygram11.var1d(x, bins=bins, weights=w, omp=True)
        numpy_h, __ = np.histogram(x, bins=bins, weights=w)
        npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 45
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 5 votes vote down vote up
def test_density_fix1d():
    x = np.random.randn(5000)
    bins = 25
    w = np.random.uniform(0.5, 1.0, 5000)

    pygram_h, __ = pygram11.fix1d(x, bins=25, range=(-3, 3), density=True)
    numpy_h, __ = np.histogram(x, bins=np.linspace(-3, 3, 26), density=True)
    npt.assert_almost_equal(pygram_h, numpy_h, 5)

    pygram_h, __ = pygram11.fix1d(x, bins=25, range=(-3, 3), weights=w, density=True)
    numpy_h, __ = np.histogram(x, bins=np.linspace(-3, 3, 26), weights=w, density=True)
    npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 46
Project: pygram11   Author: douglasdavis   File: test_histogram.py    MIT License 5 votes vote down vote up
def test_density_var1d():
    x = np.random.randn(5000)
    bins = [-1.2, -1, -0.2, 0.7, 1.5, 2.1]
    w = np.random.uniform(0.5, 1.9, 5000)

    pygram_h, __ = pygram11.var1d(x, bins=bins, density=True)
    numpy_h, __ = np.histogram(x, bins=bins, density=True)
    npt.assert_almost_equal(pygram_h, numpy_h, 5)

    pygram_h, __ = pygram11.var1d(x, bins=bins, weights=w, density=True)
    numpy_h, __ = np.histogram(x, bins=bins, weights=w, density=True)
    npt.assert_almost_equal(pygram_h, numpy_h, 5) 
Example 47
Project: derplearning   Author: notkarol   File: test_shapes.py    MIT License 5 votes vote down vote up
def test_unit_vector(self):
		npt.assert_almost_equal(self.test0.unit_vector([345.345, 0]), np.array([1., 0.]) , decimal=7)
		npt.assert_almost_equal(self.test0.unit_vector([0, 345.345]), np.array([0., 1.]) , decimal=7)
		npt.assert_almost_equal(self.test0.unit_vector([-345.345, 0]), np.array([-1., 0.]) , decimal=7)
		npt.assert_almost_equal(self.test0.unit_vector([0, -345.345]), np.array([0., -1.]) , decimal=7)
		npt.assert_almost_equal(self.test0.unit_vector([-3, -4]), np.array([-.6, -.8]) , decimal=7) 
Example 48
Project: derplearning   Author: notkarol   File: test_roadgen3d.py    MIT License 5 votes vote down vote up
def test_unit_vector(self):
		npt.assert_almost_equal(self.test0.unit_vector([345.345, 0]), np.array([1., 0.]) , decimal=7)
		npt.assert_almost_equal(self.test0.unit_vector([0, 345.345]), np.array([0., 1.]) , decimal=7)
		npt.assert_almost_equal(self.test0.unit_vector([-345.345, 0]), np.array([-1., 0.]) , decimal=7)
		npt.assert_almost_equal(self.test0.unit_vector([0, -345.345]), np.array([0., -1.]) , decimal=7)
		npt.assert_almost_equal(self.test0.unit_vector([-3, -4]), np.array([-.6, -.8]) , decimal=7) 
Example 49
Project: derplearning   Author: notkarol   File: test_roadgen3d.py    MIT License 5 votes vote down vote up
def test_rot_by_vector(self):
		t_a0 = np.array([ 1, 0])
		t_a1 = np.array([ 0, 1])
		t_a2 = np.array([-1, 0])
		t_a3 = np.array([ 0,-1])
		t_a4 = np.array([22, 0])
		t_a5 = np.array([ 0, 5])
		t_a6 = np.array([ 3, 4])
		
		npt.assert_almost_equal(self.test0.rot_by_vector(t_a2, t_a3), t_a1 , decimal=7)
		npt.assert_almost_equal(self.test0.rot_by_vector(t_a5, t_a4), np.array([0, -22]) , decimal=7)
		npt.assert_almost_equal(self.test0.rot_by_vector(t_a6, t_a5), [4, 3] , decimal=7) 
Example 50
Project: derplearning   Author: notkarol   File: test_roadgen3d.py    MIT License 5 votes vote down vote up
def test_xz_to_xy(self):

		#Verify that the four corners are correctly mapped.
		four_corners_mm = np.array([
			[-self.test0.cam_far_rad, self.test0.cam_far_rad, 
			  self.test0.cam_near_rad, -self.test0.cam_near_rad],
			[self.test0.cam_max_range, self.test0.cam_max_range,
			 self.test0.cam_min_range, self.test0.cam_min_range] ] )
		four_corners_pix = np.array([
			[0, self.test0.view_res[0], self.test0.view_res[0], 0], 
			[0, 0, self.test0.view_res[1], self.test0.view_res[1] ] ])

		bot_right_mm = np.array([ [self.test0.cam_near_rad], [self.test0.cam_min_range]] )
		bot_right_pix = np.array([ [self.test0.view_res[0] ], [self.test0.view_res[1]] ] )

		bot_left_mm =  np.array([ [-self.test0.cam_near_rad], [self.test0.cam_min_range]] )
		bot_left_pix = np.array([ [0 ], [self.test0.view_res[1]] ] )

		top_right_mm = np.array([ [self.test0.cam_far_rad], [self.test0.cam_max_range]] )
		top_right_pix = np.array([ [self.test0.view_res[0] ], [0] ] )

		top_left_mm = np.array([ [-self.test0.cam_far_rad], [self.test0.cam_max_range]] )
		top_left_pix = np.array([ [0 ], [0] ] )

		npt.assert_almost_equal(self.test0.xz_to_xy(four_corners_mm), four_corners_pix , decimal=0)
		npt.assert_almost_equal(self.test0.xz_to_xy(bot_right_mm), bot_right_pix , decimal=0)
		npt.assert_almost_equal(self.test0.xz_to_xy(bot_left_mm), bot_left_pix , decimal=0)
		npt.assert_almost_equal(self.test0.xz_to_xy(top_right_mm), top_right_pix , decimal=0)
		npt.assert_almost_equal(self.test0.xz_to_xy(top_left_mm), top_left_pix , decimal=0)