Python numpy.around() Examples

The following are 30 code examples for showing how to use numpy.around(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: dataiku-contrib   Author: dataiku   File: coco.py    License: Apache License 2.0 7 votes vote down vote up
def build_coco_results(dataset, image_ids, rois, class_ids, scores, masks):
    """Arrange resutls to match COCO specs in http://cocodataset.org/#format
    """
    # If no results, return an empty list
    if rois is None:
        return []

    results = []
    for image_id in image_ids:
        # Loop through detections
        for i in range(rois.shape[0]):
            class_id = class_ids[i]
            score = scores[i]
            bbox = np.around(rois[i], 1)
            mask = masks[:, :, i]

            result = {
                "image_id": image_id,
                "category_id": dataset.get_source_class_id(class_id, "coco"),
                "bbox": [bbox[1], bbox[0], bbox[3] - bbox[1], bbox[2] - bbox[0]],
                "score": score,
                "segmentation": maskUtils.encode(np.asfortranarray(mask))
            }
            results.append(result)
    return results 
Example 2
Project: QCElemental   Author: MolSSI   File: molecule.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def float_prep(array, around):
    """
    Rounds floats to a common value and build positive zeros to prevent hash conflicts.
    """
    if isinstance(array, (list, np.ndarray)):
        # Round array
        array = np.around(array, around)
        # Flip zeros
        array[np.abs(array) < 5 ** (-(around + 1))] = 0

    elif isinstance(array, (float, int)):
        array = round(array, around)
        if array == -0.0:
            array = 0.0
    else:
        raise TypeError("Type '{}' not recognized".format(type(array).__name__))

    return array 
Example 3
Project: dataiku-contrib   Author: dataiku   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def minimize_mask(bbox, mask, mini_shape):
    """Resize masks to a smaller version to reduce memory load.
    Mini-masks can be resized back to image scale using expand_masks()
    See inspect_data.ipynb notebook for more details.
    """
    mini_mask = np.zeros(mini_shape + (mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        # Pick slice and cast to bool in case load_mask() returned wrong dtype
        m = mask[:, :, i].astype(bool)
        y1, x1, y2, x2 = bbox[i][:4]
        m = m[y1:y2, x1:x2]
        if m.size == 0:
            raise Exception("Invalid bounding box with area of zero")
        # Resize with bilinear interpolation
        m = resize(m, mini_shape)
        mini_mask[:, :, i] = np.around(m).astype(np.bool)
    return mini_mask 
Example 4
Project: dataiku-contrib   Author: dataiku   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def expand_mask(bbox, mini_mask, image_shape):
    """Resizes mini masks back to image size. Reverses the change
    of minimize_mask().
    See inspect_data.ipynb notebook for more details.
    """
    mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        m = mini_mask[:, :, i]
        y1, x1, y2, x2 = bbox[i][:4]
        h = y2 - y1
        w = x2 - x1
        # Resize with bilinear interpolation
        m = resize(m, (h, w))
        mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool)
    return mask


# TODO: Build and use this function to reduce code duplication 
Example 5
Project: recruit   Author: Frank-qlu   File: testutils.py    License: Apache License 2.0 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example 6
Project: recruit   Author: Frank-qlu   File: test_panel.py    License: Apache License 2.0 6 votes vote down vote up
def test_numpy_round(self):
        values = [[[-3.2, 2.2], [0, -4.8213], [3.123, 123.12],
                   [-1566.213, 88.88], [-12, 94.5]],
                  [[-5.82, 3.5], [6.21, -73.272], [-9.087, 23.12],
                   [272.212, -99.99], [23, -76.5]]]
        evalues = [[[float(np.around(i)) for i in j] for j in k]
                   for k in values]
        p = Panel(values, items=['Item1', 'Item2'],
                  major_axis=date_range('1/1/2000', periods=5),
                  minor_axis=['A', 'B'])
        expected = Panel(evalues, items=['Item1', 'Item2'],
                         major_axis=date_range('1/1/2000', periods=5),
                         minor_axis=['A', 'B'])
        result = np.round(p)
        assert_panel_equal(expected, result)

        msg = "the 'out' parameter is not supported"
        with pytest.raises(ValueError, match=msg):
            np.round(p, out=p)

    # removing Panel before NumPy enforces, so just ignore 
Example 7
Project: recruit   Author: Frank-qlu   File: test_alter_index.py    License: Apache License 2.0 6 votes vote down vote up
def test_reindex_nearest():
    s = Series(np.arange(10, dtype='int64'))
    target = [0.1, 0.9, 1.5, 2.0]
    actual = s.reindex(target, method='nearest')
    expected = Series(np.around(target).astype('int64'), target)
    assert_series_equal(expected, actual)

    actual = s.reindex_like(actual, method='nearest')
    assert_series_equal(expected, actual)

    actual = s.reindex_like(actual, method='nearest', tolerance=1)
    assert_series_equal(expected, actual)
    actual = s.reindex_like(actual, method='nearest',
                            tolerance=[1, 2, 3, 4])
    assert_series_equal(expected, actual)

    actual = s.reindex(target, method='nearest', tolerance=0.2)
    expected = Series([0, 1, np.nan, 2], target)
    assert_series_equal(expected, actual)

    actual = s.reindex(target, method='nearest',
                       tolerance=[0.3, 0.01, 0.4, 3])
    expected = Series([0, np.nan, np.nan, 2], target)
    assert_series_equal(expected, actual) 
Example 8
Project: buzzard   Author: airware   File: tools.py    License: Apache License 2.0 6 votes vote down vote up
def make_tif(path, tloffset=(0, 0), reso=(0.25, -0.25), rsize=(20, 10),
             proj=SRS[0]['wkt'], channel_count=1, dtype=gdal.GDT_Float32):
    """Create a tiff files and return info about it"""
    tl = ROOT_TL + tloffset
    reso = np.asarray(reso)
    fp = buzz.Footprint(tl=tl, rsize=rsize, size=np.abs(reso * rsize))
    x, y = fp.meshgrid_spatial
    x = np.abs(x) - abs(ROOT_TL[0])
    y = abs(ROOT_TL[1]) - np.abs(y)
    x *= 15
    y *= 15
    a = x / 2 + y / 2
    a = np.around(a).astype('float32')
    driver = gdal.GetDriverByName('GTiff')
    dataset = driver.Create(path, rsize[0], rsize[1], channel_count, dtype)
    dataset.SetGeoTransform(fp.gt)
    dataset.SetProjection(proj)
    for i in range(channel_count):
        dataset.GetRasterBand(i + 1).WriteArray(a)
        dataset.GetRasterBand(i + 1).SetNoDataValue(-32000.)
    dataset.FlushCache()
    return path, fp, a 
Example 9
Project: mars   Author: mars-project   File: test_arithmetic_execution.py    License: Apache License 2.0 6 votes vote down vote up
def testAroundExecution(self):
        data = np.random.randn(10, 20)
        x = tensor(data, chunk_size=3)

        t = x.round(2)

        res = self.executor.execute_tensor(t, concat=True)[0]
        expected = np.around(data, decimals=2)

        np.testing.assert_allclose(res, expected)

        data = sps.random(10, 20, density=.2)
        x = tensor(data, chunk_size=3)

        t = x.round(2)

        res = self.executor.execute_tensor(t, concat=True)[0]
        expected = np.around(data.toarray(), decimals=2)

        np.testing.assert_allclose(res.toarray(), expected) 
Example 10
Project: phoenics   Author: aspuru-guzik-group   File: sampler.py    License: Apache License 2.0 6 votes vote down vote up
def _get_random_proposals(self, current_best, num_samples):
		# get uniform samples first
		uniform_samples = []
		for var_index, full_var_dict in enumerate(self.var_dicts):
			var_dict = full_var_dict[self.var_names[var_index]]
			sampled_values = self.random_number_generator.generate(var_dict, size = (self.var_sizes[var_index], self.total_size * num_samples))
			uniform_samples.extend(sampled_values)
		uniform_samples = np.array(uniform_samples).transpose()

		proposals = np.array(uniform_samples)

		num_narrows = int(0.25 * num_samples) + 1
		for sd in [0.03, 0.01, 0.003, 0.001, 0.0003]:
			# also get some samples around the current best
			# TODO: this only works for floats!!
			gauss_samples = current_best + np.random.normal(0., sd * self.var_p_ranges, size = (self.total_size * num_narrows, len(current_best)))
			gauss_samples = np.where(gauss_samples < self.var_p_lows, self.var_p_lows, gauss_samples)
			gauss_samples = np.where(self.var_p_highs < gauss_samples, self.var_p_highs, gauss_samples)

			proposals = np.concatenate([proposals, gauss_samples])
		return np.array(proposals) 
Example 11
Project: phoenics   Author: aspuru-guzik-group   File: sampler.py    License: Apache License 2.0 6 votes vote down vote up
def _proposal_optimization_thread(self, batch_index, return_dict = None):
		print('starting process for ', batch_index)
		# prepare penalty function
		def penalty(x):
			num, den = self.penalty_contributions(x)
			return (num + self.lambda_values[batch_index]) / den

		optimized = []
#		for sample in self.proposals:
#			if np.random.uniform() < 0.5:
#				optimized.append(sample)
#				continue
#			res = minimize(penalty, sample, method = 'L-BFGS-B', options = {'maxiter': 25})
#
#			# FIXME
#			if np.any(res.x < self.var_lows) or np.any(res.x > self.var_highs):
#				optimized.append(sample)
#			else:
#				optimized.append(res.x)
	
		for sample in self.proposals:

			# set some entries to zero!
			set_to_zero = self._gen_set_to_zero_vector(sample)
			nulls = np.where(set_to_zero == 0)[0]

			opt = self.local_opt.optimize(penalty, sample * set_to_zero, max_iter = 10, ignore = nulls)

			optimized.append(opt)


		optimized = np.array(optimized)
		optimized[:, self._ints] = np.around(optimized[:, self._ints])
		optimized[:, self._cats] = np.around(optimized[:, self._cats])

		print('finished process for ', batch_index)
		if return_dict.__class__.__name__ == 'DictProxy':
			return_dict[batch_index] = optimized
		else:
			return optimized 
Example 12
Project: numcodecs   Author: zarr-developers   File: quantize.py    License: MIT License 6 votes vote down vote up
def encode(self, buf):

        # normalise input
        arr = ensure_ndarray(buf).view(self.dtype)

        # apply scaling
        precision = 10. ** -self.digits
        exp = math.log(precision, 10)
        if exp < 0:
            exp = int(math.floor(exp))
        else:
            exp = int(math.ceil(exp))
        bits = math.ceil(math.log(10. ** -exp, 2))
        scale = 2. ** bits
        enc = np.around(scale * arr) / scale

        # cast dtype
        enc = enc.astype(self.astype, copy=False)

        return enc 
Example 13
Project: numcodecs   Author: zarr-developers   File: fixedscaleoffset.py    License: MIT License 6 votes vote down vote up
def encode(self, buf):

        # normalise input
        arr = ensure_ndarray(buf).view(self.dtype)

        # flatten to simplify implementation
        arr = arr.reshape(-1, order='A')

        # compute scale offset
        enc = (arr - self.offset) * self.scale

        # round to nearest integer
        enc = np.around(enc)

        # convert dtype
        enc = enc.astype(self.astype, copy=False)

        return enc 
Example 14
Project: dgl   Author: dmlc   File: bitcoinotc.py    License: Apache License 2.0 6 votes vote down vote up
def _load(self, filename):
        data = np.loadtxt(filename, delimiter=',').astype(np.int64)
        data[:, 0:2] = data[:, 0:2] - data[:, 0:2].min()
        num_nodes = data[:, 0:2].max() - data[:, 0:2].min() + 1
        delta = datetime.timedelta(days=14).total_seconds()
        # The source code is not released, but the paper indicates there're
        # totally 137 samples. The cutoff below has exactly 137 samples.
        time_index = np.around(
            (data[:, 3] - data[:, 3].min())/delta).astype(np.int64)
        for i in range(time_index.max()):
            g = DGLGraph()
            g.add_nodes(num_nodes)
            row_mask = time_index <= i
            edges = data[row_mask][:, 0:2]
            rate = data[row_mask][:, 2]
            g.add_edges(edges[:, 0], edges[:, 1])
            g.edata['h'] = rate.reshape(-1, 1)
            self.graphs.append(g) 
Example 15
Project: PanopticSegmentation   Author: dmechea   File: utils.py    License: MIT License 6 votes vote down vote up
def minimize_mask(bbox, mask, mini_shape):
    """Resize masks to a smaller version to reduce memory load.
    Mini-masks can be resized back to image scale using expand_masks()

    See inspect_data.ipynb notebook for more details.
    """
    mini_mask = np.zeros(mini_shape + (mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        # Pick slice and cast to bool in case load_mask() returned wrong dtype
        m = mask[:, :, i].astype(bool)
        y1, x1, y2, x2 = bbox[i][:4]
        m = m[y1:y2, x1:x2]
        if m.size == 0:
            raise Exception("Invalid bounding box with area of zero")
        # Resize with bilinear interpolation
        m = resize(m, mini_shape)
        mini_mask[:, :, i] = np.around(m).astype(np.bool)
    return mini_mask 
Example 16
Project: PanopticSegmentation   Author: dmechea   File: utils.py    License: MIT License 6 votes vote down vote up
def expand_mask(bbox, mini_mask, image_shape):
    """Resizes mini masks back to image size. Reverses the change
    of minimize_mask().

    See inspect_data.ipynb notebook for more details.
    """
    mask = np.zeros(image_shape[:2] + (mini_mask.shape[-1],), dtype=bool)
    for i in range(mask.shape[-1]):
        m = mini_mask[:, :, i]
        y1, x1, y2, x2 = bbox[i][:4]
        h = y2 - y1
        w = x2 - x1
        # Resize with bilinear interpolation
        m = resize(m, (h, w))
        mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool)
    return mask


# TODO: Build and use this function to reduce code duplication 
Example 17
Project: lambda-packs   Author: ryfeus   File: testutils.py    License: MIT License 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example 18
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: testutils.py    License: MIT License 6 votes vote down vote up
def almost(a, b, decimal=6, fill_value=True):
    """
    Returns True if a and b are equal up to decimal places.

    If fill_value is True, masked values considered equal. Otherwise,
    masked values are considered unequal.

    """
    m = mask_or(getmask(a), getmask(b))
    d1 = filled(a)
    d2 = filled(b)
    if d1.dtype.char == "O" or d2.dtype.char == "O":
        return np.equal(d1, d2).ravel()
    x = filled(masked_array(d1, copy=False, mask=m), fill_value).astype(float_)
    y = filled(masked_array(d2, copy=False, mask=m), 1).astype(float_)
    d = np.around(np.abs(x - y), decimal) <= 10.0 ** (-decimal)
    return d.ravel() 
Example 19
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: fromnumeric.py    License: MIT License 6 votes vote down vote up
def round_(a, decimals=0, out=None):
    """
    Round an array to the given number of decimals.

    Refer to `around` for full documentation.

    See Also
    --------
    around : equivalent function

    """
    try:
        round = a.round
    except AttributeError:
        return _wrapit(a, 'round', decimals, out)
    return round(decimals, out) 
Example 20
Project: tensor2tensor   Author: tensorflow   File: env_problem.py    License: Apache License 2.0 6 votes vote down vote up
def process_rewards(self, rewards):
    """Clips the rewards, optionally rounds them and casts to integer.

    Args:
      rewards: numpy array of raw (float) rewards.

    Returns:
      processed_rewards: numpy array of np.int64
    """

    min_reward, max_reward = self.reward_range

    # Clips at min and max reward.
    rewards = np.clip(rewards, min_reward, max_reward)

    if self._discrete_rewards:
      # Round to (nearest) int and convert to integral type.
      rewards = np.around(rewards, decimals=0).astype(np.int64)
    return rewards 
Example 21
Project: OpenFermion-Cirq   Author: quantumlib   File: fermionic_simulation.py    License: Apache License 2.0 5 votes vote down vote up
def _diagram_exponent(self,
                          args: cirq.CircuitDiagramInfoArgs,
                          *,
                          ignore_global_phase: bool = True):
        if not isinstance(self._exponent, (int, float)):
            return self._exponent
        result = float(self._exponent)
        if args.precision is not None:
            result = np.around(result, args.precision)
        return result 
Example 22
Project: IntroToDeepLearning   Author: robb-brown   File: TensorFlowInterface.py    License: MIT License 5 votes vote down vote up
def conv2d(x,W,strides=[1,1,1,1],name=None):
	# return an op that convolves x with W
	strides = np.array(strides)
	if strides.size == 1:
		strides = np.array([1,strides,strides,1])
	elif strides.size == 2:
		strides = np.array([1,strides[0],strides[1],1])
	if np.any(strides < 1):
		strides = np.around(1./strides).astype(np.uint8)
		return tf.nn.conv2d_transpose(x,W,strides=strides.tolist(),padding='SAME',name=name)
	else:
		return tf.nn.conv2d(x,W,strides=strides.tolist(),padding='SAME',name=name) 
Example 23
Project: IntroToDeepLearning   Author: robb-brown   File: TensorFlowInterface.py    License: MIT License 5 votes vote down vote up
def conv3d(x,W,strides=1,name=None):
	# return an op that convolves x with W
	strides = np.array(strides)
	if strides.size == 1:
		strides = np.array([1,strides,strides,strides[0],1])
	elif strides.size == 3:
		strides = np.array([1,strides[0],strides[1],strides[2],1])
	if np.any(strides < 1):
		strides = np.around(1./strides).astype(np.uint8)
		return tf.nn.conv3d_transpose(x,W,strides=strides.tolist(),padding='SAME',name=name)
	else:
		return tf.nn.conv3d(x,W,strides=strides.tolist(),padding='SAME',name=name) 
Example 24
Project: pyscf   Author: pyscf   File: geom.py    License: Apache License 2.0 5 votes vote down vote up
def argsort_coords(coords, decimals=None):
    if decimals is None:
        decimals = int(-numpy.log10(TOLERANCE)) - 1
    coords = numpy.around(coords, decimals=decimals)
    idx = numpy.lexsort((coords[:,2], coords[:,1], coords[:,0]))
    return idx 
Example 25
Project: pyscf   Author: pyscf   File: geom.py    License: Apache License 2.0 5 votes vote down vote up
def search_c2x(self, zaxis, n):
        '''C2 axis which is perpendicular to z-axis'''
        decimals = int(-numpy.log10(TOLERANCE)) - 1
        for lst in self.group_atoms_by_distance:
            if len(lst) > 1:
                r0 = self.atoms[lst,1:]
                zcos = numpy.around(numpy.einsum('ij,j->i', r0, zaxis),
                                    decimals=decimals)
                uniq_zcos = numpy.unique(zcos)
                maybe_c2x = []
                for d in uniq_zcos:
                    if d > TOLERANCE:
                        mirrord = abs(zcos+d)<TOLERANCE
                        if mirrord.sum() == (zcos==d).sum():
                            above = r0[zcos==d]
                            below = r0[mirrord]
                            nelem = len(below)
                            maybe_c2x.extend([above[0] + below[i]
                                              for i in range(nelem)])
                    elif abs(d) < TOLERANCE: # plane which crosses the orig
                        r1 = r0[zcos==d][0]
                        maybe_c2x.append(r1)
                        r2 = numpy.dot(rotation_mat(zaxis, numpy.pi*2/n), r1)
                        if abs(r1+r2).sum() > TOLERANCE:
                            maybe_c2x.append(r1+r2)
                        else:
                            maybe_c2x.append(r2-r1)

                if len(maybe_c2x) > 0:
                    idx = norm(maybe_c2x, axis=1) > TOLERANCE
                    maybe_c2x = _normalize(maybe_c2x)[idx]
                    maybe_c2x = _remove_dupvec(maybe_c2x)
                    for c2x in maybe_c2x:
                        if (not parallel_vectors(c2x, zaxis) and
                            self.has_rotation(c2x, 2)):
                            return c2x 
Example 26
Project: pyscf   Author: pyscf   File: geom.py    License: Apache License 2.0 5 votes vote down vote up
def _degeneracy(e, decimals):
    e = numpy.around(e, decimals)
    u, idx = numpy.unique(e, return_inverse=True)
    degen = numpy.array([numpy.count_nonzero(idx==i) for i in range(len(u))])
    return degen, u 
Example 27
Project: ncvx   Author: cvxgrp   File: integer.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _project(self, matrix):
        return np.around(matrix)

    # Constrain all entries to be the value in the matrix. 
Example 28
Project: ncvx   Author: cvxgrp   File: boolean.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _project(self, matrix):
        return np.around(matrix) #> 0

    # Constrain all entries to be the value in the matrix. 
Example 29
Project: baseband   Author: mhvk   File: header.py    License: GNU General Public License v3.0 5 votes vote down vote up
def infer_kday(self, ref_time):
        """Uses a reference time to set a header's ``kday``.

        Parameters
        ----------
        ref_time : `~astropy.time.Time`
            Reference time within 500 days of the observation time.
        """
        self.kday = np.around(ref_time.mjd - self.jday,
                              decimals=-3).astype(int) 
Example 30
Project: baseband   Author: mhvk   File: header.py    License: GNU General Public License v3.0 5 votes vote down vote up
def fraction(self, fraction):
        ns = np.around(fraction * 1.e9)
        # From inspecting sample files, the fraction appears to be truncated,
        # not rounded.
        fraction = (ns / 100000).astype(int)
        self['bcd_fraction'] = bcd_encode(fraction)