numpy.sign

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

200 Examples 7

Example 1

Project: cells
Source File: cells.py
View license
def get_next_move(old_x, old_y, x, y):
    ''' Takes the current position, old_x and old_y, and a desired future position, x and y,
    and returns the position (x,y) resulting from a unit move toward the future position.'''
    dx = numpy.sign(x - old_x)
    dy = numpy.sign(y - old_y)
    return (old_x + dx, old_y + dy)

Example 2

Project: cells
Source File: benvolution.py
View license
    def would_bump(self, me, view, dir_x, dir_y):
        grid = self.get_available_space_grid(me, view)
        dx = numpy.sign(dir_x)
        dy = numpy.sign(dir_y)
        adj_dx = dx + 1
        adj_dy = dy + 1
        return grid[adj_dx,adj_dy] == 0

Example 3

Project: cells
Source File: benvolution_genetic.py
View license
    def would_bump(self, me, view, dir_x, dir_y):
        grid = self.get_available_space_grid(me, view)
        dx = numpy.sign(dir_x)
        dy = numpy.sign(dir_y)
        adj_dx = dx + 1
        adj_dy = dy + 1
        return grid[adj_dx,adj_dy] == 0

Example 4

Project: pypot
Source File: motor.py
View license
    @property
    def goal_speed(self):
        """ Goal speed (in degrees per second) of the motor.

            This property can be used to control your motor in speed. Setting a goal speed will automatically change the moving speed and sets the goal position as the angle limit.

            .. note:: The motor will turn until reaching the angle limit. But this is not a wheel mode, so the motor will stop at its limits.

            """
        return numpy.sign(self.goal_position) * self.moving_speed

Example 5

Project: pypot
Source File: primitive.py
View license
    @property
    def goal_speed(self):
        """ Goal speed (in degrees per second) of the motor.

            This property can be used to control your motor in speed. Setting a goal speed will automatically change the moving speed and sets the goal position as the angle limit.

            .. note:: The motor will turn until reaching the angle limit. But this is not a wheel mode, so the motor will stop at its limits.

            """
        return numpy.sign(self.goal_position) * self.moving_speed

Example 6

Project: pypot
Source File: primitive.py
View license
    @goal_speed.setter
    def goal_speed(self, value):
        if abs(value) < sys.float_info.epsilon:
            self.goal_position = self.present_position

        else:
            # 0.7 corresponds approx. to the min speed that will be converted into 0
            # and as 0 corredsponds to setting the max speed, we have to check this case
            value = numpy.sign(value) * 0.7 if abs(value) < 0.7 else value

            self.goal_position = numpy.sign(value) * self.max_pos
            self.moving_speed = abs(value)

Example 7

Project: pysb
Source File: anneal_mod.py
View license
    def update_guess(self, x0):
        x0 = asarray(x0)
        u = squeeze(random.uniform(0.0, 1.0, size=self.dims))
        T = self.T
        y = sign(u-0.5)*T*((1+1.0/T)**abs(2*u-1)-1.0)
        xc = y*(self.upper - self.lower)
        xnew = x0 + xc
        return xnew

Example 8

Project: pyspeckit
Source File: ratosexagesimal.py
View license
def dectos(dec):
    deg = sign(dec) * (abs(dec) - (abs(dec) % 1))
    deg -= (deg%1)
    min = (abs(dec) % 1) * 60.
    sec = (min % 1) * 60
    min -= (min % 1)
    decs = "%+02.0f:%02.0f:%05.3f" % (deg,min,sec)
    return decs

Example 9

Project: python-acoustics
Source File: generator.py
View license
def heaviside(N):
    """Heaviside.
    
    Returns the value 0 for `x < 0`, 1 for `x > 0`, and 1/2 for `x = 0`.
    """
    return 0.5 * (np.sign(N) + 1)

Example 10

Project: tfdeploy
Source File: tfdeploy.py
View license
@Operation.factory
def Sign(a):
    """
    Sign op.
    """
    return np.sign(a),

Example 11

Project: attention-lvcsr
Source File: test_nlinalg.py
View license
    def test_uplo(self):
        S = self.S
        a = theano.tensor.matrix(dtype=self.dtype)
        wu, vu = [out.eval({a: S}) for out in self.op(a, 'U')]
        wl, vl = [out.eval({a: S}) for out in self.op(a, 'L')]
        assert_array_almost_equal(wu, wl)
        assert_array_almost_equal(vu * numpy.sign(vu[0, :]),
                                  vl * numpy.sign(vl[0, :]))

Example 12

Project: amodem
Source File: test_equalizer.py
View license
def test_signal():
    length = 120
    x = np.sign(RandomState(0).normal(size=length))
    x[-20:] = 0  # make sure the signal has bounded support
    den = np.array([1, -0.6, 0.1])
    num = np.array([0.5])
    y = utils.lfilter(x=x, b=num, a=den)

    lookahead = 2
    h = equalizer.train(
        signal=y, expected=x, order=len(den), lookahead=lookahead)
    assert dsp.norm(h[:lookahead]) < 1e-12

    h = h[lookahead:]
    assert_approx(h, den / num)

    x_ = utils.lfilter(x=y, b=h, a=[1])
    assert_approx(x_, x)

Example 13

Project: polylearn
Source File: test_cd_linear.py
View license
def check_cd_linear_clf(loss):
    alpha = 1e-3
    y_bin = np.sign(y)

    w = _fit_linear(X, y_bin, alpha, n_iter, loss)
    y_pred = np.dot(X, w)
    accuracy = np.mean(np.sign(y_pred) == y_bin)

    assert_greater_equal(accuracy, 0.97,
                         msg="classification loss {}".format(loss))

Example 14

View license
def check_classification_losses(loss, degree):
    y = np.sign(_poly_predict(X, P, lams, kernel="anova", degree=degree))
    clf = FactorizationMachineClassifier(degree=degree, loss=loss, beta=1e-3,
                                         fit_lower=None, fit_linear=False,
                                         tol=1e-3, random_state=0)
    clf.fit(X, y)
    assert_equal(1.0, clf.score(X, y))

Example 15

View license
def check_classification_losses(loss, degree):
    y = np.sign(_lifted_predict(U[:degree], X))

    clf = PolynomialNetworkClassifier(degree=degree, n_components=n_components,
                                      loss=loss, beta=1e-4, tol=1e-2,
                                      random_state=0)
    clf.fit(X, y)
    assert_equal(1.0, clf.score(X, y))

Example 16

Project: iris
Source File: test_util.py
View license
    def assertMonotonic(self, array, direction=None, **kwargs):
        if direction is not None:
            mono, dir = iris.util.monotonic(array, return_direction=True, **kwargs)
            if not mono:
                self.fail('Array was not monotonic:/n %r' % array)
            if dir != np.sign(direction):
                self.fail('Array was monotonic but not in the direction expected:'
                          '/n  + requested direction: %s/n  + resultant direction: %s' % (direction, dir))
        else:
            mono = iris.util.monotonic(array, **kwargs)
            if not mono:
                self.fail('Array was not monotonic:/n %r' % array)

Example 17

Project: statsmodels
Source File: contrast_tools.py
View license
def signstr(x, noplus=False):
    if x in [-1,0,1]:
        if not noplus:
            return '+' if np.sign(x)>=0 else '-'
        else:
            return '' if np.sign(x)>=0 else '-'
    else:
        return str(x)

Example 18

Project: MACS
Source File: test_callsummits.py
View license
def maxima ( signal, window_size=51 ):
    """return the local maxima in a signal after applying a 2nd order
    Savitsky-Golay (polynomial) filter using window_size specified  
    """
    #data1 = savitzky_golay(signal, window_size, order=2, deriv=1)
    #data2 = savitzky_golay(signal, window_size, order=2, deriv=2)
    #m = np.where(np.diff(np.sign( data1 )) <= -1)[0].astype('int32')

    #data1 = savitzky_golay_order2(signal, window_size, deriv=1)
    data1 = savitzky_golay(signal, window_size, order=2, deriv=1)
    m = np.where( np.diff( np.sign( data1 ) ) <= -1)[0].astype('int32')
    #m = np.where( np.logical_and( data2 < 0 , abs(data1) <= 1e-10) ) [0].astype('int32')
    return m

Example 19

Project: semisup-learn
Source File: qns3vm.py
View license
    def __getTrainingPredictions(self, X, real_valued=False):
        preds = self.__KNR * self.__c[0:self.__dim-1,:] + self.__c[self.__dim-1,:]
        if real_valued == True:
            return preds.flatten(1).tolist()[0]
        else:
            return np.sign(np.sign(preds)+0.1).flatten(1).tolist()[0]

Example 20

Project: DQN-chainer
Source File: dqn_agent.py
View license
    def end(self, reward):  # Episode Terminated

        # Learning Phase
        if self.policyFrozen is False:  # Learning ON/OFF
            self.dqn.learn(self.last_state, self.last_action, reward, self.last_state, True)

        # Simple text based visualization
        print('  REWARD %.1f   / EPSILON  %.5f' % (np.sign(reward), self.epsilon))

Example 21

Project: DQN-chainer
Source File: dqn_agent_cpu.py
View license
    def end(self, reward):  # Episode Terminated

        # Learning Phase
        if self.policyFrozen is False:  # Learning ON/OFF
            self.dqn.learn(self.last_state, self.last_action, reward, self.last_state, True)

        # Simple text based visualization
        print('  REWARD %.1f   / EPSILON  %.5f' % (np.sign(reward), self.epsilon))

Example 22

Project: DQN-chainer
Source File: dqn_agent_nips.py
View license
    def agent_end(self, reward):  # Episode Terminated

        # Learning Phase
        if self.policyFrozen is False:  # Learning ON/OFF
            self.DQN.stockExperience(self.time, self.last_state, self.lastAction.intArray[0], reward, self.last_state, True)
            self.DQN.experienceReplay(self.time)

        # Simple text based visualization
        print '  REWARD %.1f   / EPSILON  %.5f' % (np.sign(reward), self.epsilon)

        # Time count
        if not self.policyFrozen:
            self.time += 1

Example 23

Project: deer
Source File: ALE_env.py
View license
    def act(self, action):
        action = self._actions[action]
        
        reward = 0
        for _ in range(self._frame_skip):
            reward += self._ale.act(action)
            if self.inTerminalState():
                break
            
        self._ale.getScreenGrayscale(self._screen)
        cv2.resize(self._screen, (84, 84), self._reduced_screen, interpolation=cv2.INTER_NEAREST)
  
        self._mode_score += reward
        return np.sign(reward)

Example 24

Project: deer
Source File: PLE_env.py
View license
    def act(self, action):
        action = self._actions[action]
        
        reward = 0
        for _ in range(self._frame_skip):
            reward += self._ple.act(action)
            if self.inTerminalState():
                break
            
        self._screen = self._ple.getScreenGrayscale()
        cv2.resize(self._screen, (48, 48), self._reduced_screen, interpolation=cv2.INTER_NEAREST)
  
        self._mode_score += reward
        return np.sign(reward)

Example 25

Project: vispy
Source File: scene_test_1.py
View license
    def on_mouse_wheel(self, event):
        prof = Profiler()  # noqa
        if not event.modifiers:
            dx = np.sign(event.delta[1])*.05
            x0, y0 = self._normalize(event.pos)
            pan_x, pan_y = self._pz.pan
            zoom_x, zoom_y = self._pz.zoom
            zoom_x_new, zoom_y_new = (zoom_x * math.exp(2.5 * dx),
                                      zoom_y * math.exp(2.5 * dx))
            self._pz.zoom = (zoom_x_new, zoom_y_new)
            self._pz.pan = (pan_x - x0 * (1./zoom_x - 1./zoom_x_new),
                            pan_y + y0 * (1./zoom_y - 1./zoom_y_new))
            self.update()

Example 26

Project: vispy
Source File: realtime_signals.py
View license
    def on_mouse_wheel(self, event):
        dx = np.sign(event.delta[1]) * .05
        scale_x, scale_y = self.program['u_scale']
        scale_x_new, scale_y_new = (scale_x * math.exp(2.5*dx),
                                    scale_y * math.exp(0.0*dx))
        self.program['u_scale'] = (max(1, scale_x_new), max(1, scale_y_new))
        self.update()

Example 27

Project: vispy
Source File: signals.py
View license
    def on_mouse_wheel(self, event):
        dx = np.sign(event.delta[1])*.05
        scale_x, scale_y = self.program['u_scale']
        scale_x_new, scale_y_new = (scale_x * math.exp(2.5*dx),
                                    scale_y * math.exp(2.5*dx))
        self.program['u_scale'] = (scale_x_new, scale_y_new)
        self.update()

Example 28

Project: drmad
Source File: test_scalar_ops.py
View license
def test_sign():
    fun = lambda x : 3.0 * np.sign(x)
    d_fun = grad(fun)
    check_grads(fun, 1.1)
    check_grads(fun, -1.1)
    check_grads(d_fun, 1.1)
    check_grads(d_fun, -1.1)

Example 29

Project: socialsent
Source File: lexicons.py
View license
def make_qwn_lexicon():
    polarities = collections.defaultdict(float)
    for line in util.lines(constants.LEXICONS + "qwn/turneyLittman_propSyn_08_mcr30-noAntGloss.dict"):
        info = line.split("\t")
        if info[1] == "neg":
            mod = -1
        else:
            mod = 1
        for word in info[2].split(", "):
            if not "_" in word:
                polarities[word.split("#")[0]] += mod
    polarities = {word:np.sign(val) for word, val in polarities.iteritems() if val != 0}
    util.write_json(polarities, constants.PROCESSED_LEXICONS + 'qwn.json')

Example 30

Project: tia
Source File: trd.py
View license
    def decrease(self, qty, px, fees=0, **kwargs):
        if not self.is_open():
            raise Exception('decrease position failed: no position currently open')
        if np.sign(self._live_qty) != -np.sign(qty):
            msg = 'decrease position failed: trade quantity {0} is same sign as live quantity {1}'
            raise Exception(msg.format(qty, self._live_qty))
        self._order(qty, px, fees, **kwargs)

Example 31

Project: tia
Source File: trd.py
View license
    def increase(self, qty, px, fees=0, **kwargs):
        if not self.is_open():
            raise Exception('increase position failed: no position currently open')
        if np.sign(self._live_qty) != np.sign(qty):
            msg = 'increase position failed: trade quantity {0} is different sign as live quantity {1}'
            raise Exception(msg.format(qty, self._live_qty))
        self._order(qty, px, fees, **kwargs)

Example 32

Project: ML-lib
Source File: svm.py
View license
    def predict(self, x):
        """
        Args:
            X (np.ndarray): Training data of shape[n_samples, n_features]

        Returns:
            np.ndarray: shape[n_samples, 1], the predicted values

        Raises:
            ValueError if model has not been fit
        """
        if not self.learned:
            raise NameError('Fit model first')
        prediction = 0
        for SV in range(len(self.SValphas)):
            prediction += self.SValphas[SV] * self.SVoutputs[SV] * self.kernel(self.SVinputs[SV], x)
        prediction += self.intercept
        return np.sign(prediction)

Example 33

Project: ProxImaL
Source File: norm1.py
View license
    def _prox(self, rho, v, *args, **kwargs):
        """x = sign(v)*(|v| - |W|/rho)_+
        """
        idxs = self.weight != 0
        np.sign(v[idxs], self.v_sign[idxs])
        np.absolute(v[idxs], v[idxs])
        v[idxs] -= np.absolute(self.weight[idxs]) / rho
        np.maximum(v[idxs], 0, v[idxs])
        v[idxs] *= self.v_sign[idxs]
        return v

Example 34

Project: bctpy
Source File: miscellaneous_utilities.py
View license
def cuberoot(x):
    '''
    Correctly handle the cube root for negative weights, instead of uselessly
    crashing as in python or returning the wrong root as in matlab
    '''
    return np.sign(x) * np.abs(x)**(1 / 3)

Example 35

Project: pymote
Source File: network.py
View license
    def modify_avg_degree(self, value):
        """
        Modifies (increases) average degree based on given value by
        modifying nodes commRange."""
        # assert all nodes have same commRange
        assert allclose([n.commRange for n in self], self.nodes()[0].commRange)
        #TODO: implement decreasing of degree, preserve connected network
        assert value + settings.DEG_ATOL > self.avg_degree()  # only increment
        step_factor = 7.
        steps = [0]
        #TODO: while condition should call validate
        while not allclose(self.avg_degree(), value, atol=settings.DEG_ATOL):
            steps.append((value - self.avg_degree())*step_factor)
            for node in self:
                node.commRange += steps[-1]
            # variable step_factor for step size for over/undershoot cases
            if len(steps)>2 and sign(steps[-2])!=sign(steps[-1]):
                step_factor /= 2
        logger.debug("Modified degree to %f" % self.avg_degree())

Example 36

Project: pymote
Source File: networkgenerator.py
View license
    def _are_conditions_satisfied(self, net):
        cr = net.nodes()[0].commRange
        if self.connected and not is_connected(net):
            logger.debug("Not connected")
            return round(0.2*cr)
        elif self.degree:
            logger.debug("Degree not satisfied %f" % net.avg_degree())
            diff = self.degree-net.avg_degree()
            diff = sign(diff)*min(abs(diff), 7)
            return round((sign(diff)*(round(diff))**2)*cr/100)
        return 0

Example 37

Project: polar2grid
Source File: readers.py
View license
def get_lats_from_cartesian(x__, y__, z__, thr=0.8):
    """Get latitudes from cartesian coordinates.
    """
    # if we are at low latitudes - small z, then get the
    # latitudes only from z. If we are at high latitudes (close to the poles)
    # then derive the latitude using x and y:
    lats = numpy.where((z__ < thr * EARTH_RADIUS) & (z__ > -thr * EARTH_RADIUS),
                       90 - rad2deg(arccos(z__/EARTH_RADIUS)),
                       sign(z__) * (90 - rad2deg(arcsin(sqrt(x__ ** 2 + y__ ** 2) / EARTH_RADIUS))))
    return lats

Example 38

Project: gammatone
Source File: gtgram.py
View license
def round_half_away_from_zero(num):
    """ Implement the round-half-away-from-zero rule, where fractional parts of
    0.5 result in rounding up to the nearest positive integer for positive
    numbers, and down to the nearest negative number for negative integers.
    """
    return np.sign(num) * np.floor(np.abs(num) + 0.5)

Example 39

Project: crbm-drum-patterns
Source File: npmat.py
View license
    def sign(self, target = None):

        if target is None:
            target = empty(self.shape)

        target.resize(self.shape)

        target.numpy_array[:] = np.sign(self.numpy_array)

        return target

Example 40

View license
def predict_binary(X, theta):
    """Makes classification predictions for the data in X using theta.

    For a given data item x, the prediction is +1 if x.dot(theta) >= 0, and -1
    otherwise. Note that this also works for logistic regression since for
    x.dot(theta) >= 0 the sigmoid is >= 0.5 which we also consider +1.

    X: (k, n) k rows of data items, each having n features; augmented.
    theta: (n, 1) regression parameters.

    Returns yhat (k, 1) - either +1 or -1 classification for each item.
    """
    yhat = X.dot(theta)
    # Fix the cases where yhat == 0 to be positive; otherwise np.sign would
    # return 0. Note that it should be exceedingly rare in practice to get an
    # exact 0 for some result.
    yhat[yhat == 0] = 1
    return np.sign(yhat)

Example 41

Project: Psignifit-3.x
Source File: psigobservers.py
View license
    def __updateTrace ( self, traces, d ):
        """sum up the traces and update"""
        Ec = 0
        for k,t in enumerate(traces):
            newtrace = t-N.sign(t)*d
            if newtrace*t < 0: # Sign change of traces ~> the trace died here
                traces.pop(k)
            else:
                traces[k] = newtrace
                Ec += newtrace
        return Ec

Example 42

Project: PyCV-time
Source File: turing.py
View license
    def process_scale(a_lods, lod):
        d = a_lods[lod] - cv2.pyrUp(a_lods[lod+1])
        for i in xrange(lod):
            d = cv2.pyrUp(d)
        v = cv2.GaussianBlur(d*d, (3, 3), 0)
        return np.sign(d), v

Example 43

Project: PyCV-time
Source File: turing.py
View license
    def process_scale(a_lods, lod):
        d = a_lods[lod] - cv2.pyrUp(a_lods[lod+1])
        for i in xrange(lod):
            d = cv2.pyrUp(d)
        v = cv2.GaussianBlur(d*d, (3, 3), 0)
        return np.sign(d), v

Example 44

Project: fuku-ml
Source File: DecisionStump.py
View license
    def score_function(self, x, W):
        # need refector

        '''
        Score function to calculate score
        '''

        score = self.sign * np.sign(x[self.feature_index] - self.theta)

        return score

Example 45

Project: fuku-ml
Source File: KernelRidgeRegression.py
View license
    def score_function(self, x, W):

        score = super(BinaryClassifier, self).score_function(x, W)
        score = np.sign(score)

        return score

Example 46

Project: fuku-ml
Source File: NeuralNetwork.py
View license
    def score_function(self, x, W):

        score = super(BinaryClassifier, self).score_function(x, W)
        score = np.sign(score)

        return score

Example 47

Project: misvm
Source File: misvm.py
View license
def _update_classes(x):
    classes = np.sign(x)
    # If classification happened to
    # be zero, make it 1.0
    classes[np.nonzero(classes == 0.0)] = 1.0
    # Guarantee that at least one
    # instance is positive
    classes[np.argmax(x)] = 1.0
    return classes.reshape((-1, 1))

Example 48

Project: BetFair_Arbitrer
Source File: kelly.py
View license
def int_o_db(odds,bet):
	odds = filter(lambda x: np.sign(x[1])==np.sign(bet), odds)
	
	amIBacking = (bet>0)
	odds =  sorted(odds, key=itemgetter(0), reverse=amIBacking)


	result=0
	rest_bet=abs(bet)
	for o,v in odds:
		v=abs(v)
		result+=o*min(v,rest_bet)
		rest_bet-=v
		if rest_bet<=0:
			break
	if rest_bet>0 and bet<0:
		return -999999
	return result*np.sign(bet)

Example 49

Project: pyglmnet
Source File: pyglmnet.py
View license
    def _prox(self, beta, thresh):
        """Proximal operator."""
        if self.group is None:
            # The default case: soft thresholding
            return np.sign(beta) * (np.abs(beta) - thresh) * \
                (np.abs(beta) > thresh)
        else:
            # Group sparsity case: apply group sparsity operator
            group_ids = np.unique(self.group)
            group_norms = np.abs(beta)

            for group_id in group_ids:
                if group_id != 0:
                    group_norms[self.group == group_id] = \
                        np.linalg.norm(beta[self.group == group_id], 2)

            return (beta - thresh * beta / group_norms) * \
                (group_norms > thresh)

Example 50

Project: glumpy
Source File: collection-update.py
View license
@window.event
def on_mouse_scroll(x, y, dx, dy):
    index = get_index(x,y)
    dx = -np.sign(dy) * .05
    lines["xscale"][index] *= np.exp(2.5*dx)
    lines["xscale"][index] = min(max(1.0, lines["xscale"][index]),100)