numpy.ma.array

Here are the examples of the python api numpy.ma.array taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

199 Examples 7

Example 1

Project: pykalman
Source File: test_unscented.py
View license
def check_unscented_prediction(method, mu_true, sigma_true):
    '''Check output of a method against true mean and covariances'''
    Z = ma.array([0, 1, 2, 3], mask=[True, False, False, False])
    (mu_est, sigma_est) = method(Z)
    mu_est, sigma_est = mu_est[1:], sigma_est[1:]

    assert_array_almost_equal(mu_true, mu_est, decimal=8)
    assert_array_almost_equal(sigma_true, sigma_est, decimal=8)

Example 2

Project: pykalman
Source File: test_unscented.py
View license
def test_additive_filter_update():
    kf = build_unscented_filter(AdditiveUnscentedKalmanFilter)
    Z = ma.array([0, 1, 2, 3], mask=[True, False, False, False])

    mu_filt, sigma_filt = kf.filter(Z)
    mu_filt2, sigma_filt2 = np.zeros(mu_filt.shape), np.zeros(sigma_filt.shape)
    for t in range(mu_filt.shape[0] - 1):
        if t == 0:
            mu_filt2[t] = mu_filt[t]
            sigma_filt2[t] = sigma_filt[t]
        mu_filt2[t + 1], sigma_filt2[t + 1] = (
            kf.filter_update(mu_filt2[t], sigma_filt2[t], Z[t + 1])
        )

    assert_array_almost_equal(mu_filt, mu_filt2)
    assert_array_almost_equal(sigma_filt, sigma_filt2)

Example 3

Project: pykalman
Source File: test_unscented.py
View license
def check_unscented_prediction(method, mu_true, sigma_true):
    '''Check output of a method against true mean and covariances'''
    Z = ma.array([0, 1, 2, 3], mask=[True, False, False, False])
    (mu_est, sigma_est) = method(Z)
    mu_est, sigma_est = mu_est[1:], sigma_est[1:]

    assert_array_almost_equal(mu_true, mu_est, decimal=8)
    assert_array_almost_equal(sigma_true, sigma_est, decimal=8)

Example 4

Project: pykalman
Source File: test_unscented.py
View license
def test_unscented_filter_update():
    kf = build_unscented_filter(UnscentedKalmanFilter)
    Z = ma.array([0, 1, 2, 3], mask=[True, False, False, False])

    mu_filt, sigma_filt = kf.filter(Z)
    mu_filt2, sigma_filt2 = np.zeros(mu_filt.shape), np.zeros(sigma_filt.shape)
    for t in range(mu_filt.shape[0] - 1):
        if t == 0:
            mu_filt2[t] = mu_filt[0]
            sigma_filt2[t] = sigma_filt[t]
        mu_filt2[t + 1], sigma_filt2[t + 1] = (
            kf.filter_update(mu_filt2[t], sigma_filt2[t], Z[t + 1])
        )

    assert_array_almost_equal(mu_filt, mu_filt2)
    assert_array_almost_equal(sigma_filt, sigma_filt2)

Example 5

Project: pykalman
Source File: test_unscented.py
View license
def test_additive_filter_update():
    kf = build_unscented_filter(AdditiveUnscentedKalmanFilter)
    Z = ma.array([0, 1, 2, 3], mask=[True, False, False, False])

    mu_filt, sigma_filt = kf.filter(Z)
    mu_filt2, sigma_filt2 = np.zeros(mu_filt.shape), np.zeros(sigma_filt.shape)
    for t in range(mu_filt.shape[0] - 1):
        if t == 0:
            mu_filt2[t] = mu_filt[0]
            sigma_filt2[t] = sigma_filt[t]
        mu_filt2[t + 1], sigma_filt2[t + 1] = (
            kf.filter_update(mu_filt2[t], sigma_filt2[t], Z[t + 1])
        )

    assert_array_almost_equal(mu_filt, mu_filt2)
    assert_array_almost_equal(sigma_filt, sigma_filt2)

Example 6

Project: mpop
Source File: image.py
View license
    def putalpha(self, alpha):
        """Adds an *alpha* channel to the current image, or replaces it with
        *alpha* if it already exists.
        """
        alpha = np.ma.array(alpha)
        if(not (alpha.shape[0] == 0 and
                self.shape[0] == 0) and
           alpha.shape != self.shape):
            raise ValueError("Alpha channel shape should match image shape")

        if(not self.mode.endswith("A")):
            self.convert(self.mode + "A")
        if not self.is_empty():
            self.channels[-1] = alpha

Example 7

Project: mpop
Source File: test_image.py
View license
    def setUp(self):
        channel = np.ma.array([[0, 0.5, 0.5], [0.5, 0.25, 0.25]],
                              mask = [[1, 1, 1], [1, 1, 0]])
        self.img = image.Image(channels = [channel] * 3,
                               mode = "RGB")
        self.modes = ["L", "LA", "RGB", "RGBA", "YCbCr", "YCbCrA", "P", "PA"]

Example 8

Project: mpop
Source File: test_image.py
View license
    def setUp(self):
        channel = np.ma.array([[0, 0.5, 0.5], [0.5, 0.25, 0.25]],
                              mask = [[1, 1, 1], [1, 1, 1]])
        self.img = image.Image(channels = [channel] * 3,
                               mode = "RGB")
        self.modes = ["L", "LA", "RGB", "RGBA", "YCbCr", "YCbCrA", "P", "PA"]

Example 9

Project: pyresample
Source File: kd_tree.py
View license
def _remask_data(data, is_to_be_masked=True):
    """Interprets half the array as mask for the other half"""

    channels = data.shape[-1]
    if is_to_be_masked:
        mask = data[..., (channels // 2):]
        # All pixels affected by masked pixels are masked out
        mask = (mask != 0)
        data = np.ma.array(data[..., :(channels // 2)], mask=mask)
    else:
        data = data[..., :(channels // 2)]

    if data.shape[-1] == 1:
        data = data.reshape(data.shape[:-1])
    return data

Example 10

Project: pyoptools
Source File: misc.py
View license
def spot_info(C):
    """Retorna una tupla con el radio promedio y el centro de masa
    de los rayos que impactaron el CCD C"""
    X=[]
    Y=[]
    for hl in C.hit_list:
        x,y,z=hl[0]
        X.append(x)
        Y.append(y)
    xm=mean(X)
    ym=mean(Y)
    X=array(X)-xm
    Y=array(Y)-ym
    R=sqrt(X**2+Y**2)
    XR=sqrt(X**2)
    YR=sqrt(Y**2)
    return mean(R),(xm,ym),(mean(XR),mean(YR)),R.max()

Example 11

Project: scipy
Source File: test_mstats_extras.py
View license
    def test_trimmedmeanci(self):
        "Tests the confidence intervals of the trimmed mean."
        data = ma.array([545,555,558,572,575,576,578,580,
                         594,605,635,651,653,661,666])
        assert_almost_equal(ms.trimmed_mean(data,0.2), 596.2, 1)
        assert_equal(np.round(ms.trimmed_mean_ci(data,(0.2,0.2)),1),
                     [561.8, 630.6])

Example 12

Project: iris
Source File: __init__.py
View license
def _message_values(grib_message, shape):
    gribapi.grib_set_double(grib_message, 'missingValue', np.nan)
    data = gribapi.grib_get_double_array(grib_message, 'values')
    data = data.reshape(shape)

    # Handle missing values in a sensible way.
    mask = np.isnan(data)
    if mask.any():
        data = ma.array(data, mask=mask, fill_value=np.nan)
    return data

Example 13

Project: iris
Source File: test_netcdf.py
View license
    def test_lazy_mask_preserve_fill_value(self):
        cube = iris.cube.Cube(np.ma.array([0, 1], mask=[False, True],
                                          fill_value=-1))
        with self.temp_filename(suffix='.nc') as filename, \
                self.temp_filename(suffix='.nc') as other_filename:
            iris.save(cube, filename, unlimited_dimensions=[])
            ncube = iris.load_cube(filename)
            # Lazy save of the masked cube
            iris.save(ncube, other_filename, unlimited_dimensions=[])
            ds = nc.Dataset(other_filename, 'r')
            avar = ds['unknown']
            self.assertEqual(avar._FillValue, -1)

Example 14

Project: iris
Source File: test_analysis.py
View license
    def setUp(self):
        self.cube_with_nan = tests.stock.simple_2d()

        data = self.cube_with_nan.data.astype(np.float32)
        self.cube_with_nan.data = data.copy()
        self.cube_with_nan.data[1, 0] = np.nan
        self.cube_with_nan.data[2, 2] = np.nan
        self.cube_with_nan.data[2, 3] = np.nan

        self.cube_with_mask = tests.stock.simple_2d()
        self.cube_with_mask.data = ma.array(self.cube_with_nan.data,
                                                  mask=np.isnan(self.cube_with_nan.data))

Example 15

Project: iris
Source File: test_analysis.py
View license
    def setUp(self):
        data = ma.array([[1, 2], [4, 5]], dtype=np.float32,
                        mask=[[False, True], [False, True]])
        cube = iris.cube.Cube(data, long_name="test_data", units="1")
        lat_coord = iris.coords.DimCoord(np.array([1, 2], dtype=np.float32),
                                         long_name="lat", units="1")
        lon_coord = iris.coords.DimCoord(np.array([3, 4], dtype=np.float32),
                                         long_name="lon", units="1")
        cube.add_dim_coord(lat_coord, 0)
        cube.add_dim_coord(lon_coord, 1)
        self.cube = cube

Example 16

Project: iris
Source File: test_analysis.py
View license
    def test_single_coord_mdtol(self):
        self.cube.data.mask = np.array([[False, True], [False, False]])
        collapsed = self.cube.collapsed(
            self.cube.coord('lat'), iris.analysis.MEAN, mdtol=0.5)
        t = ma.array([2.5, 5], mask=[False, False])
        self.assertMaskedArrayEqual(collapsed.data, t)

Example 17

Project: iris
Source File: test_analysis.py
View license
    def test_single_coord_mdtol_alt(self):
        self.cube.data.mask = np.array([[False, True], [False, False]])
        collapsed = self.cube.collapsed(
            self.cube.coord('lat'), iris.analysis.MEAN, mdtol=0.4)
        t = ma.array([2.5, 5], mask=[False, True])
        self.assertMaskedArrayEqual(collapsed.data, t)

Example 18

Project: iris
Source File: test_analysis.py
View license
    def test_multi_coord_mdtol(self):
        collapsed = self.cube.collapsed(
            [self.cube.coord('lat'), self.cube.coord('lon')],
            iris.analysis.MEAN, mdtol=0.4)
        t = ma.array(2.5, mask=True)
        self.assertMaskedArrayEqual(collapsed.data, t)

Example 19

Project: iris
Source File: test_analysis.py
View license
    def test_longitude_masked(self):
        self.cube.data = ma.array(self.cube.data,
                                  mask=[[True, True, True, True],
                                        [True, False, True, True],
                                        [False, False, False, False]])
        res_cube = self.cube.rolling_window('longitude',
                                            iris.analysis.MEAN,
                                            window=2)

        expected_result = np.ma.array([[-99., -99., -99.],
                                       [12., 12., -99.],
                                       [15., 11., 8.]],
                                      mask=[[True, True, True],
                                            [False, False, True],
                                            [False, False, False]],
                                      dtype=np.float64)

        self.assertMaskedArrayEqual(expected_result, res_cube.data)

Example 20

Project: iris
Source File: test_divide.py
View license
    def test_masked_div_zero(self):
        # Ensure cube behaviour matches numpy operator behaviour for the
        # handling of arrays containing 0.
        dat_a = np.ma.array([0., 0., 0., 0.], mask=False)
        dat_b = np.ma.array([2., 2., 2., 2.], mask=False)

        cube_a = Cube(dat_a)
        cube_b = Cube(dat_b)

        com = self.data_op(dat_b, dat_a)
        res = self.cube_func(cube_b, cube_a).data

        self.assertMaskedArrayEqual(com, res, strict=True)

Example 21

Project: iris
Source File: __init__.py
View license
    def _test_partial_mask(self, in_place):
        # Helper method for masked data tests.
        dat_a = np.ma.array([2., 2., 2., 2.], mask=[1, 0, 1, 0])
        dat_b = np.ma.array([2., 2., 2., 2.], mask=[1, 1, 0, 0])

        cube_a = Cube(dat_a)
        cube_b = Cube(dat_b)

        com = self.data_op(dat_b, dat_a)
        res = self.cube_func(cube_b, cube_a, in_place=in_place)

        return com, res, cube_b

Example 22

Project: iris
Source File: test_pearsonr.py
View license
    def test_mdtol(self):
        cube_small = self.cube_a[:, 0, 0]
        cube_small_masked = cube_small.copy()
        cube_small_masked.data = ma.array(
            cube_small.data, mask=np.array([0, 0, 0, 1, 1, 1], dtype=bool))
        r1 = stats.pearsonr(cube_small, cube_small_masked)
        r2 = stats.pearsonr(cube_small, cube_small_masked, mdtol=0.49)
        self.assertArrayAlmostEqual(r1.data, np.array([0.74586593]))
        self.assertMaskedArrayEqual(r2.data, ma.array([0], mask=[True]))

Example 23

Project: iris
Source File: test_pearsonr.py
View license
    def test_common_mask_simple(self):
        cube_small = self.cube_a[:, 0, 0]
        cube_small_masked = cube_small.copy()
        cube_small_masked.data = ma.array(
            cube_small.data, mask=np.array([0, 0, 0, 1, 1, 1], dtype=bool))
        r = stats.pearsonr(cube_small, cube_small_masked, common_mask=True)
        self.assertArrayAlmostEqual(r.data, np.array([1.]))

Example 24

Project: iris
Source File: test_pearsonr.py
View license
    def test_common_mask_broadcast(self):
        cube_small = self.cube_a[:, 0, 0]
        cube_small_2d = self.cube_a[:, 0:2, 0]
        cube_small.data = ma.array(
            cube_small.data,  mask=np.array([0, 0, 0, 0, 0, 1], dtype=bool))
        cube_small_2d.data = ma.array(
            np.tile(cube_small.data[:, np.newaxis], 2),
            mask=np.zeros((6, 2), dtype=bool))
        # 2d mask varies on unshared coord:
        cube_small_2d.data.mask[0, 1] = 1
        r = stats.pearsonr(cube_small, cube_small_2d,
                           weights=self.weights[:, 0, 0], common_mask=True)
        self.assertArrayAlmostEqual(r.data, np.array([1., 1.]))
        # 2d mask does not vary on unshared coord:
        cube_small_2d.data.mask[0, 0] = 1
        r = stats.pearsonr(cube_small, cube_small_2d, common_mask=True)
        self.assertArrayAlmostEqual(r.data, np.array([1., 1.]))

Example 25

Project: iris
Source File: test_Aggregator.py
View license
    def setUp(self):
        self.TEST = Aggregator('test', None)
        self.array = ma.array([[1, 2, 3],
                               [4, 5, 6]],
                              mask=[[False, True, False],
                                    [True, False, False]],
                              dtype=np.float64)
        self.expected_result_axis0 = ma.array([1, 2, 3], mask=None)
        self.expected_result_axis1 = ma.array([4, 5], mask=None)

Example 26

Project: iris
Source File: test_Aggregator.py
View license
    def test_returning_scalar_mdtol(self):
        # Test the case when the data aggregation function returns a scalar and
        # turns it into a masked array.
        axis = -1
        data = self.array.flatten()
        mock_return = 2
        with mock.patch.object(self.TEST, 'call_func',
                               return_value=mock_return) as mock_method:
            result = self.TEST.aggregate(data, axis, mdtol=1)
            self.assertMaskedArrayEqual(result, ma.array(2, mask=False))
        mock_method.assert_called_once_with(data, axis=axis)

Example 27

Project: iris
Source File: test_Aggregator.py
View license
    def test_returning_scalar_mdtol_alt(self):
        # Test the case when the data aggregation function returns a scalar
        # with no tolerance for missing data values and turns it into a masked
        # array.
        axis = -1
        data = self.array.flatten()
        mock_return = 2
        with mock.patch.object(self.TEST, 'call_func',
                               return_value=mock_return) as mock_method:
            result = self.TEST.aggregate(data, axis, mdtol=0)
            self.assertMaskedArrayEqual(result, ma.array(2, mask=True))
        mock_method.assert_called_once_with(data, axis=axis)

Example 28

Project: iris
Source File: test_Aggregator.py
View license
    def test_returning_non_masked_array_from_masked_array(self):
        # Providing a masked array, call_func returning a non-masked array,
        # resulting in a masked array output.
        axis = 0
        mock_return = self.expected_result_axis0.data.copy()
        result_axis_0 = ma.array(mock_return, mask=[True, True, False])
        with mock.patch.object(self.TEST, 'call_func',
                               return_value=mock_return) as mock_method:
            result = self.TEST.aggregate(self.array, axis, mdtol=.45)
            self.assertMaskedArrayAlmostEqual(result, result_axis_0)
        mock_method.assert_called_once_with(self.array, axis=axis)

        axis = 1
        mock_return = self.expected_result_axis1.data.copy()
        with mock.patch.object(self.TEST, 'call_func',
                               return_value=mock_return) as mock_method:
            result = self.TEST.aggregate(self.array, axis, mdtol=.45)
            self.assertMaskedArrayEqual(result, self.expected_result_axis1)
        mock_method.assert_called_once_with(self.array, axis=axis)

Example 29

Project: iris
Source File: test_RMS.py
View license
    def test_masked(self):
        # masked entries should be completely ignored
        data = ma.array([5, 10, 2, 11, 6, 4],
                        mask=[False, True, False, True, False, False],
                        dtype=np.float64)
        expected_rms = 4.5
        rms = RMS.aggregate(data, 0)
        self.assertAlmostEqual(rms, expected_rms)

Example 30

Project: iris
Source File: test_RMS.py
View license
    def test_masked_weighted(self):
        # weights should work properly with masked arrays
        data = ma.array([4, 7, 18, 10, 11, 8],
                        mask=[False, False, True, False, True, False],
                        dtype=np.float64)
        weights = np.array([1, 4, 5, 3, 8, 2], dtype=np.float64)
        expected_rms = 8.0
        rms = RMS.aggregate(data, 0, weights=weights)
        self.assertAlmostEqual(rms, expected_rms)

Example 31

Project: iris
Source File: test_Cube__operators.py
View license
    def build_lazy_cube(self):
        data = ma.array([[1., 1.], [1., 100000.]], mask=[[0, 0], [0, 1]])
        data = biggus.NumpyArrayAdapter(data)
        cube = iris.cube.Cube(data, standard_name='air_temperature', units='K')
        lat = iris.coords.DimCoord([-10, 10], 'latitude')
        lon = iris.coords.DimCoord([10, 20], 'longitude')
        cube.add_dim_coord(lat, 0)
        cube.add_dim_coord(lon, 1)
        return cube

Example 32

Project: iris
Source File: test_ProtoCube.py
View license
    def test_noise(self):
        # Test a massive set of all defn diffs to make sure it's not noise.
        self.cube1.var_name = "Arthur"
        cube2 = self.cube1[1:]
        cube2.data = cube2.data.astype(np.int8)
        cube2.data = ma.array(cube2.data)
        cube2.standard_name = "air_pressure"
        cube2.var_name = "Nudge"
        cube2.attributes['stuffed'] = 'yes'
        cube2.attributes['mint'] = 'waffer-thin'
        cube2.add_cell_method(iris.coords.CellMethod('monty', ('python',)))

        # Check the actual message, so we've got a readable reference text.
        self.cube2 = cube2
        msg = self.check_merge_fails_with_message()
        self.assertString(msg, self.result_path(ext='txt'))

Example 33

Project: iris
Source File: test_IrisTest.py
View license
    def test_nomask(self):
        # Test that an assertion is raised when comparing a masked array
        # containing masked and unmasked values with a masked array with
        # 'nomask'.
        arr1 = np.ma.array([1, 2, 3, 4])
        with self.assertRaises(AssertionError):
            self._func(arr1, self.arr2, strict=False)

Example 34

Project: iris
Source File: test_IrisTest.py
View license
    def test_nomask_unmasked(self):
        # Ensure that a masked array with 'nomask' can compare with an entirely
        # unmasked array.
        arr1 = np.ma.array([1, 2, 3, 4])
        arr2 = np.ma.array([1, 2, 3, 4], mask=False)
        self._func(arr1, arr2, strict=False)

Example 35

Project: iris
Source File: test_broadcast_to_shape.py
View license
    def test_masked(self):
        # masked arrays are also accepted
        a = np.random.random([2, 3])
        m = ma.array(a, mask=[[0, 1, 0], [0, 1, 1]])
        b = broadcast_to_shape(m, (5, 3, 4, 2), (3, 1))
        for i in range(5):
            for j in range(4):
                self.assertMaskedArrayEqual(b[i, :, j, :].T, m)

Example 36

Project: iris
Source File: test_broadcast_to_shape.py
View license
    def test_masked_degenerate(self):
        # masked arrays can have degenerate masks too
        a = np.random.random([2, 3])
        m = ma.array(a)
        b = broadcast_to_shape(m, (5, 3, 4, 2), (3, 1))
        for i in range(5):
            for j in range(4):
                self.assertMaskedArrayEqual(b[i, :, j, :].T, m)

Example 37

Project: iris
Source File: test_rolling_window.py
View license
    def test_1d_masked(self):
        # 1-d masked array input
        a = ma.array([0, 1, 2, 3, 4], mask=[0, 0, 1, 0, 0],
                     dtype=np.int32)
        expected_result = ma.array([[0, 1], [1, 2], [2, 3], [3, 4]],
                                   mask=[[0, 0], [0, 1], [1, 0], [0, 0]],
                                   dtype=np.int32)
        result = rolling_window(a, window=2)
        self.assertMaskedArrayEqual(result, expected_result)

Example 38

Project: iris
Source File: test_rolling_window.py
View license
    def test_2d_masked(self):
        # 2-d masked array input
        a = ma.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]],
                     mask=[[0, 0, 1, 0, 0], [1, 0, 1, 0, 0]],
                     dtype=np.int32)
        expected_result = ma.array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]],
                                    [[5, 6, 7], [6, 7, 8], [7, 8, 9]]],
                                   mask=[[[0, 0, 1], [0, 1, 0], [1, 0, 0]],
                                         [[1, 0, 1], [0, 1, 0], [1, 0, 0]]],
                                   dtype=np.int32)
        result = rolling_window(a, window=3, axis=1)
        self.assertMaskedArrayEqual(result, expected_result)

Example 39

Project: iris
Source File: test_rolling_window.py
View license
    def test_degenerate_mask(self):
        a = ma.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], dtype=np.int32)
        expected_result = ma.array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]],
                                    [[5, 6, 7], [6, 7, 8], [7, 8, 9]]],
                                   mask=[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
                                         [[0, 0, 0], [0, 0, 0], [0, 0, 0]]],
                                   dtype=np.int32)
        result = rolling_window(a, window=3, axis=1)
        self.assertMaskedArrayEqual(result, expected_result)

Example 40

Project: hickle
Source File: hickle.py
View license
def create_np_array_dataset(py_obj, h_group, call_id=0, **kwargs):
    """ dumps an ndarray object to h5py file

    Args:
        py_obj: python object to dump; should be a numpy array or np.ma.array (masked)
        h_group (h5.File.group): group to dump data into.
        call_id (int): index to identify object's relative location in the iterable.
    """
    if isinstance(py_obj, type(np.ma.array([1]))):
        d = h_group.create_dataset('data_%i' % call_id, data=py_obj, **kwargs)
        #m = h_group.create_dataset('mask_%i' % call_id, data=py_obj.mask, **kwargs)
        m = h_group.create_dataset('data_%i_mask' % call_id, data=py_obj.mask, **kwargs)
        d.attrs["type"] = ['ndarray_masked_data']
        m.attrs["type"] = ['ndarray_masked_mask']
    else:
        d = h_group.create_dataset('data_%i' % call_id, data=py_obj, **kwargs)
        d.attrs["type"] = ['ndarray']

Example 41

Project: hickle
Source File: test_hickle.py
View license
def test_masked():
    """ Test masked numpy array """
    filename, mode = 'test.h5', 'w'    
    a = np.ma.array([1,2,3,4], dtype='float32', mask=[0,1,0,0])
    
    dump(a, filename, mode)
    a_hkl = load(filename)
    
    try:
        assert a_hkl.dtype == a.dtype
        assert np.all((a_hkl, a))
        os.remove(filename)
    except AssertionError:
        os.remove(filename)
        print a_hkl
        print a
        raise

Example 42

Project: hickle
Source File: test_hickle.py
View license
def test_ndarray_masked():

    a = np.ma.array([1,2,3])
    b = np.ma.array([2,3,4], mask=[True, False, True])
    z = (a, b)

    print "Original:"
    pprint(z)
    dump(z, 'test.hkl', mode='w')

    print "\nReconstructed:"
    z = load('test.hkl')
    pprint(z)

Example 43

Project: CommPy
Source File: ldpc.py
View license
def min_sum_update(cnode_idx, cnode_adj_list, cnode_deg_list, cnode_msgs,
                   vnode_msgs, cnode_vnode_map, max_cnode_deg, max_vnode_deg):

    start_idx = cnode_idx*max_cnode_deg
    offset = cnode_deg_list[cnode_idx]
    vnode_list = cnode_adj_list[start_idx:start_idx+offset]
    vnode_list_msgs = vnode_msgs[vnode_list*max_vnode_deg +
                                      cnode_vnode_map[start_idx:start_idx+offset]]
    vnode_list_msgs = np.ma.array(vnode_list_msgs, mask=False)

    # Compute messages on outgoing edges using the incoming messages
    for i in range(start_idx, start_idx+offset):
        vnode_list_msgs.mask[i-start_idx] = True
        cnode_msgs[i] = np.prod(np.sign(vnode_list_msgs))*np.min(np.abs(vnode_list_msgs))
        vnode_list_msgs.mask[i-start_idx] = False

Example 44

Project: windspharm
Source File: test_error_handling.py
View license
    @raises(ValueError)
    def test_masked_values(self):
        # masked values in inputs should raise an error
        solution = reference_solutions(self.interface, self.gridtype)
        mask = np.empty(solution['uwnd'].shape, dtype=np.bool)
        mask[:] = False
        mask[1, 1] = True
        u = ma.array(solution['uwnd'], mask=mask, fill_value=1.e20)
        v = ma.array(solution['vwnd'], mask=mask, fill_value=1.e20)
        vw = solvers[self.interface](u, v, gridtype=self.gridtype)

Example 45

Project: windspharm
Source File: test_error_handling.py
View license
    @raises(ValueError)
    def test_gradient_masked_values(self):
        # masked values in gradient input should raise an error
        solution = reference_solutions(self.interface, self.gridtype)
        vw = solvers[self.interface](solution['uwnd'], solution['vwnd'],
                                     gridtype=self.gridtype)
        mask = np.empty(solution['uwnd'].shape, dtype=np.bool)
        mask[:] = False
        mask[1, 1] = True
        chi = ma.array(solution['chi'], mask=mask, fill_value=1.e20)
        uchi, vchi = vw.gradient(chi)

Example 46

Project: healpy
Source File: projaxes.py
View license
    def inverse(self, value):
        if not self.scaled():
            raise ValueError("Not invertible until scaled")

        if matplotlib.cbook.iterable(value):
            vtype='array'
            val = np.ma.array(value)
        else:
            vtype='scalar'
            val = np.ma.array([value])
        result = np.ma.array(self._lininterp(val, self.yval, self.xval),
                              mask=np.ma.getmask(val))
        result[np.isinf(val.data)] = -np.inf
        if vtype == 'scalar':
            result = result[0]
        return result

Example 47

Project: robothon
Source File: test_mrecords.py
View license
    def setup(self):
        "Generic setup"
        ilist = [1,2,3,4,5]
        flist = [1.1,2.2,3.3,4.4,5.5]
        slist = ['one','two','three','four','five']
        ddtype = [('a',int),('b',float),('c','|S8')]
        mask = [0,1,0,0,1]
        self.base = ma.array(zip(ilist,flist,slist), mask=mask, dtype=ddtype)

Example 48

Project: robothon
Source File: test_mrecords.py
View license
    def test_filled(self):
        "Test filling the array"
        _a = ma.array([1,2,3],mask=[0,0,1],dtype=int)
        _b = ma.array([1.1,2.2,3.3],mask=[0,0,1],dtype=float)
        _c = ma.array(['one','two','three'],mask=[0,0,1],dtype='|S8')
        ddtype = [('a',int),('b',float),('c','|S8')]
        mrec = fromarrays([_a,_b,_c], dtype=ddtype,
                          fill_value=(99999,99999.,'N/A'))
        mrecfilled = mrec.filled()
        assert_equal(mrecfilled['a'], np.array((1,2,99999), dtype=int))
        assert_equal(mrecfilled['b'], np.array((1.1,2.2,99999.), dtype=float))
        assert_equal(mrecfilled['c'], np.array(('one','two','N/A'), dtype='|S8'))

Example 49

Project: robothon
Source File: test_mrecords.py
View license
    def test_tolist(self):
        "Test tolist."
        _a = ma.array([1,2,3],mask=[0,0,1],dtype=int)
        _b = ma.array([1.1,2.2,3.3],mask=[0,0,1],dtype=float)
        _c = ma.array(['one','two','three'],mask=[1,0,0],dtype='|S8')
        ddtype = [('a',int),('b',float),('c','|S8')]
        mrec = fromarrays([_a,_b,_c], dtype=ddtype,
                          fill_value=(99999,99999.,'N/A'))
        #
        assert_equal(mrec.tolist(),
                     [(1,1.1,None),(2,2.2,'two'),(None,None,'three')])

Example 50

Project: robothon
Source File: test_mrecords.py
View license
    def setup(self):
        "Generic setup"
        _a = ma.array([1,2,3],mask=[0,0,1],dtype=int)
        _b = ma.array([1.1,2.2,3.3],mask=[0,0,1],dtype=float)
        _c = ma.array(['one','two','three'],mask=[0,0,1],dtype='|S8')
        ddtype = [('a',int),('b',float),('c','|S8')]
        mrec = fromarrays([_a,_b,_c], dtype=ddtype,
                          fill_value=(99999,99999.,'N/A'))
        nrec = recfromarrays((_a._data,_b._data,_c._data), dtype=ddtype)
        self.data = (mrec, nrec, ddtype)