Python numpy.copysign() Examples

The following are 30 code examples for showing how to use numpy.copysign(). 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: hope   Author: jakeret   File: test_op_div.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_cross_div(dtypea, dtypeb, dtypec):
    if dtypea == np.int8 and dtypeb == np.int8:
        pytest.skip("Different behaviour in c++ and python for int8 / int8".format(dtypea, dtypeb))
    def fkt(a, b, c):
        c[:] = a / b
    hfkt = hope.jit(fkt)
    (ao, ah), (bo, bh), (co, ch) = random(dtypea, [10]), random(dtypeb, [10]), random(dtypec, [10])
    ao, ah, bo, bh = ao.astype(np.float64), ah.astype(np.float64), bo.astype(np.float64), bh.astype(np.float64)
    ao, ah = np.copysign(np.power(np.abs(ao), 1. / 4.), ao).astype(dtypea), np.copysign(np.power(np.abs(ah), 1. / 4.), ah).astype(dtypea)
    bo, bh = np.copysign(np.power(np.abs(bo), 1. / 4.), bo).astype(dtypeb), np.copysign(np.power(np.abs(bh), 1. / 4.), bh).astype(dtypeb)
    if np.count_nonzero(bo == 0) > 0: bo[bo == 0] += 1
    if np.count_nonzero(bh == 0) > 0: bh[bh == 0] += 1
    fkt(ao, bo, co),  hfkt(ah, bh, ch)
    assert check(co, ch)
    fkt(ao, bo, co),  hfkt(ah, bh, ch)
    assert check(co, ch) 
Example 2
Project: qstrader   Author: mhallsmoore   File: transaction.py    License: MIT License 6 votes vote down vote up
def __init__(
        self,
        asset,
        quantity,
        dt,
        price,
        order_id,
        commission=0.0
    ):
        self.asset = asset
        self.quantity = quantity
        self.direction = np.copysign(1, self.quantity)
        self.dt = dt
        self.price = price
        self.order_id = order_id
        self.commission = commission 
Example 3
Project: geoist   Author: igp-gravity   File: pymm_convert.py    License: MIT License 6 votes vote down vote up
def to_geodetic(z_coord, hypot_xy):
        """ Get geodetic coordinates calculated by the Ferrarri's solution. """
        ee4 = WGS84_EPS2**2
        pa2 = (hypot_xy / WGS84_A)**2
        zt = (1.0 - WGS84_EPS2) * (z_coord / WGS84_A)**2
        rh = (pa2 + zt - ee4)/6.0
        ss = (0.25*ee4) * zt * pa2
        rh3 = rh**3
        tmp = rh3 + ss + sqrt(ss*(ss+2.0*rh3))
        tt = copysign(fabs(tmp)**(1.0/3.0), tmp)
        uu = rh + tt + rh**2 / tt
        vv = sqrt(uu**2 + ee4*zt)
        ww = (0.5*WGS84_EPS2) * (uu + vv - zt)/vv
        kp = 1.0 + WGS84_EPS2*(sqrt(uu + vv + ww**2) + ww)/(uu + vv)
        zkp = kp * z_coord
        return (
            RAD2DEG*arctan2(zkp, hypot_xy),
            hypot(hypot_xy, zkp)*(1.0/kp - 1.0 + WGS84_EPS2)/WGS84_EPS2
        ) 
Example 4
Project: corrscope   Author: corrscope   File: triggers.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def custom_line(
        self, name: str, data: np.ndarray, offset: bool, invert: bool = True
    ):
        """
        :param offset:
        - True, for untriggered wave data:
            - line will be shifted and triggered (by offset_viewport()).
        - False, for triggered data and buffers:
            - line is immune to offset_viewport().

        :param invert:
        - True, for wave (data and buffers):
            - If wave data is inverted (edge_direction = -1),
              data will be plotted inverted.
        - False, for buffers and autocorrelated wave data:
            - Data is plotted as-is.
        """
        if self._renderer is None:
            return
        data = data / abs_max(data, 0.01) / 2
        if invert:
            data *= np.copysign(1, self._wave.amplification)
        self._renderer.update_custom_line(
            name, self._wave_idx, self._stride, data, offset=offset
        ) 
Example 5
Project: Carnets   Author: holzschu   File: angle_utilities.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def dms_to_degrees(d, m, s=None):
    """
    Convert degrees, arcminute, arcsecond to a float degrees value.
    """

    _check_minute_range(m)
    _check_second_range(s)

    # determine sign
    sign = np.copysign(1.0, d)

    try:
        d = np.floor(np.abs(d))
        if s is None:
            m = np.abs(m)
            s = 0
        else:
            m = np.floor(np.abs(m))
            s = np.abs(s)
    except ValueError:
        raise ValueError(format_exception(
            "{func}: dms values ({1[0]},{2[1]},{3[2]}) could not be "
            "converted to numbers.", d, m, s))

    return sign * (d + m / 60. + s / 3600.) 
Example 6
Project: Carnets   Author: holzschu   File: angle_utilities.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hms_to_hours(h, m, s=None):
    """
    Convert hour, minute, second to a float hour value.
    """

    check_hms_ranges(h, m, s)

    # determine sign
    sign = np.copysign(1.0, h)

    try:
        h = np.floor(np.abs(h))
        if s is None:
            m = np.abs(m)
            s = 0
        else:
            m = np.floor(np.abs(m))
            s = np.abs(s)
    except ValueError:
        raise ValueError(format_exception(
            "{func}: HMS values ({1[0]},{2[1]},{3[2]}) could not be "
            "converted to numbers.", h, m, s))

    return sign * (h + m / 60. + s / 3600.) 
Example 7
Project: VIP   Author: vortex-exoplanet   File: utils.py    License: MIT License 6 votes vote down vote up
def idl_round(x):
    """
    Round to the *nearest* integer, half-away-from-zero.

    Parameters
    ----------
    x : array-like
        Number or array to be rounded

    Returns
    -------
    r_rounded : array-like
        note that the returned values are floats

    Notes
    -----
    IDL ``ROUND`` rounds to the *nearest* integer (commercial rounding),
    unlike numpy's round/rint, which round to the nearest *even*
    value (half-to-even, financial rounding) as defined in IEEE-754
    standard.

    """
    return np.trunc(x + np.copysign(0.5, x)) 
Example 8
Project: chainerrl   Author: chainer   File: orthogonal.py    License: MIT License 5 votes vote down vote up
def __call__(self, array):
        if self.dtype is not None:
            assert array.dtype == self.dtype
        xp = cuda.get_array_module(array)
        if not array.shape:  # 0-dim case
            array[...] = self.scale * (2 * numpy.random.randint(2) - 1)
        elif not array.size:
            raise ValueError('Array to be initialized must be non-empty.')
        else:
            # numpy.prod returns float value when the argument is empty.
            out_dim = len(array)
            in_dim = size_of_shape(array.shape[1:])
            if (in_dim > out_dim and self._checks[0]) or (
                    in_dim < out_dim and self._checks[1]):
                raise ValueError(
                    'Cannot make orthogonal {}.'
                    'shape = {}, interpreted as '
                    '{}-dim input and {}-dim output.'.format(
                        self.mode, array.shape, in_dim, out_dim))
            transpose = in_dim > out_dim
            a = numpy.random.normal(size=(out_dim, in_dim))
            if transpose:
                a = a.T
            # cupy.linalg.qr requires cusolver in CUDA 8+
            q, r = numpy.linalg.qr(a)
            q *= numpy.copysign(self.scale, numpy.diag(r))
            if transpose:
                q = q.T
            array[...] = xp.asarray(q.reshape(array.shape)) 
Example 9
Project: recruit   Author: Frank-qlu   File: test_umath.py    License: Apache License 2.0 5 votes vote down vote up
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1))) 
Example 10
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1))) 
Example 11
Project: vnpy_crypto   Author: birforce   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1))) 
Example 12
Project: Computable   Author: ktraunmueller   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1))) 
Example 13
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1))) 
Example 14
Project: pywasm   Author: mohanson   File: execution.py    License: MIT License 5 votes vote down vote up
def f32_copysign(config: Configuration, i: binary.Instruction):
        b = config.stack.pop().f32()
        a = config.stack.pop().f32()
        r = Value.from_f32(numpy.copysign(a, b))
        config.stack.append(r) 
Example 15
Project: pywasm   Author: mohanson   File: execution.py    License: MIT License 5 votes vote down vote up
def f64_copysign(config: Configuration, i: binary.Instruction):
        b = config.stack.pop().f64()
        a = config.stack.pop().f64()
        r = Value.from_f64(numpy.copysign(a, b))
        config.stack.append(r) 
Example 16
Project: chainer   Author: chainer   File: orthogonal.py    License: MIT License 5 votes vote down vote up
def __call__(self, array):
        if self.dtype is not None:
            assert array.dtype == self.dtype,\
                '{} != {}'.format(array.dtype, self.dtype)
        if not array.shape:  # 0-dim case
            if self.rng is None:
                a = numpy.random.randint(2)
            else:
                a = self.rng.randint(2)
            a = int(a)
            array[...] = self.scale * (2 * a - 1)
        elif not array.size:
            raise ValueError('Array to be initialized must be non-empty.')
        else:
            # numpy.prod returns float value when the argument is empty.
            out_dim = len(array)
            in_dim = utils.size_of_shape(array.shape[1:])
            if (in_dim > out_dim and self._checks[0]) or (
                    in_dim < out_dim and self._checks[1]):
                raise ValueError(
                    'Cannot make orthogonal {}. '
                    'shape = {}, interpreted as '
                    '{}-dim input and {}-dim output.'.format(
                        self.mode, array.shape, in_dim, out_dim))
            transpose = in_dim > out_dim
            if self.rng is None:
                a = numpy.random.normal(size=(out_dim, in_dim))
            else:
                a_tmp = self.rng.normal(size=(out_dim, in_dim))
                a = numpy.empty(a_tmp.shape, dtype=a_tmp.dtype)
                backend.copyto(a, a_tmp)
            if transpose:
                a = a.T
            # cupy.linalg.qr requires cusolver in CUDA 8+
            q, r = numpy.linalg.qr(a)
            q *= numpy.copysign(self.scale, numpy.diag(r))
            if transpose:
                q = q.T
            backend.copyto(array, q.reshape(array.shape).astype(
                array.dtype, copy=False)) 
Example 17
Project: GraphicDesignPatternByPython   Author: Relph1119   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1))) 
Example 18
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1))) 
Example 19
Project: cupy   Author: cupy   File: test_erf.py    License: MIT License 5 votes vote down vote up
def _boundary_inputs(boundary, rtol, atol):
    left = boundary * (1 - numpy.copysign(rtol, boundary)) - atol
    right = boundary * (1 + numpy.copysign(rtol, boundary)) + atol
    return [left, boundary, right] 
Example 20
Project: pySINDy   Author: luckystarufo   File: test_umath.py    License: MIT License 5 votes vote down vote up
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1))) 
Example 21
Project: gdshelpers   Author: HelgeGehring   File: resonator.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def opposite_side_port_out(self):
        return self.port.parallel_offset(np.copysign(2 * self.radius + self.vertical_race_length, self.opposite_gap)
                                         + self._offset + self._offset_opposite) 
Example 22
Project: gdshelpers   Author: HelgeGehring   File: resonator.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def opposite_side_port_in(self):
        return self._origin_port.parallel_offset(
            np.copysign(2 * self.radius + self.vertical_race_length, self.opposite_gap)
            + self._offset + self._offset_opposite).inverted_direction

    # Conventional naming of ports 
Example 23
Project: gdshelpers   Author: HelgeGehring   File: resonator.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def center_coordinates(self):
        return self._origin_port.longitudinal_offset(self.race_length / 2.).parallel_offset(
            self._offset + np.copysign(self.radius + 0.5 * self.vertical_race_length, self.gap)).origin 
Example 24
Project: gdshelpers   Author: HelgeGehring   File: resonator.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _offset(self):
        return math.copysign(abs(self.gap) + (self.width + self.res_wg_width) / 2., self.gap) 
Example 25
Project: gdshelpers   Author: HelgeGehring   File: resonator.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _offset_opposite(self):
        return math.copysign(abs(self.opposite_gap) + (self.width + self.res_wg_width) / 2., self.opposite_gap) 
Example 26
Project: mxnet-lambda   Author: awslabs   File: test_umath.py    License: Apache License 2.0 5 votes vote down vote up
def test_copysign():
    assert_(np.copysign(1, -1) == -1)
    with np.errstate(divide="ignore"):
        assert_(1 / np.copysign(0, -1) < 0)
        assert_(1 / np.copysign(0, 1) > 0)
    assert_(np.signbit(np.copysign(np.nan, -1)))
    assert_(not np.signbit(np.copysign(np.nan, 1))) 
Example 27
Project: ray-optics   Author: mjhoptics   File: sequential.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update_model(self):
        # delta n across each surface interface must be set to some
        #  reasonable default value. use the index at the central wavelength
        osp = self.opt_model.optical_spec
        ref_wl = osp.spectral_region.reference_wvl

        self.wvlns = osp.spectral_region.wavelengths
        self.rndx = self.calc_ref_indices_for_spectrum(self.wvlns)
        n_before = self.rndx[0]

        self.z_dir = []
        z_dir_before = 1

        for i, s in enumerate(self.ifcs):
            z_dir_after = copysign(1, z_dir_before)
            if s.interact_mode == 'reflect':
                z_dir_after = -z_dir_after

            # leave rndx data unsigned, track change of sign using z_dir
            n_after = self.rndx[i]
            if z_dir_after < 0:
                n_after = [-n for n in n_after]
            s.delta_n = n_after[ref_wl] - n_before[ref_wl]
            n_before = n_after

            z_dir_before = z_dir_after
            self.z_dir.append(z_dir_after)
            # call update() on the surface interface
            s.update()

        self.gbl_tfrms = self.compute_global_coords()
        self.lcl_tfrms = self.compute_local_transforms()

        if len(self.ifcs) > 2:
            osp.update_model()

            self.set_clear_apertures() 
Example 28
Project: ray-optics   Author: mjhoptics   File: sequential.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gen_sequence(surf_data_list, **kwargs):
    """ create a sequence iterator from the surf_data_list

    Args:
        surf_data_list: a list of lists containing:
                        [curvature, thickness, refractive_index, v-number]
        **kwargs: keyword arguments

    Returns:
        (**ifcs**, **gaps**, **rndx**, **lcl_tfrms**, **z_dir**)
    """
    ifcs = []
    gaps = []
    rndx = []
    lcl_tfrms = []
    z_dir = []

    for surf_data in surf_data_list:
        s, g, rn, tfrm = create_surface_and_gap(surf_data, **kwargs)
        ifcs.append(s)
        gaps.append(g)
        rndx.append(rn)
        lcl_tfrms.append(tfrm)
        z_dir.append(1)

    n_before = 1.0
    z_dir_before = 1
    for i, s in enumerate(ifcs):
        z_dir_after = copysign(1, z_dir_before)
        n_after = np.copysign(rndx[i], n_before)
        if s.interact_mode == 'reflect':
            n_after = -n_after
            z_dir_after = -z_dir_after

        n_before = n_after
        rndx[i] = n_after
        z_dir_before = z_dir_after
        z_dir[i] = z_dir_after

    seq = itertools.zip_longest(ifcs, gaps[:-2], lcl_tfrms, rndx, z_dir)
    return seq 
Example 29
Project: wasabi2d   Author: lordmauve   File: tanks.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def update(self, dt: float = 1 / 60):
        """Update the primitive."""
        self.speed *= self.drag ** dt
        if keyboard.up:
            self.speed += self.acceleration * dt
        elif keyboard.down:
            self.speed -= self.acceleration * dt

        if keyboard.left:
            self.primitive.angle -= np.copysign(self.turn * dt, self.speed)
        elif keyboard.right:
            self.primitive.angle += np.copysign(self.turn * dt, self.speed)

        displacement = self.speed * dt
        self.primitive.pos += displacement * self.forward_vector() 
Example 30
Project: wasabi2d   Author: lordmauve   File: base.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def scale(self):
        p = np.product(np.diagonal(self._scale))
        return np.copysign(np.sqrt(abs(p)), p)