Python numpy.sign() Examples

The following are 30 code examples of numpy.sign(). 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 also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: pgd_whitebox.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def perturb(self, x_nat, y, sess):
    """Given a set of examples (x_nat, y), returns a set of adversarial
       examples within epsilon of x_nat in l_infinity norm."""
    if self.rand:
      x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape)
    else:
      x = np.copy(x_nat)

    for i in range(self.k):
      grad = sess.run(self.grad, feed_dict={self.model.x_input: x,
                                            self.model.y_input: y})

      x += self.a * np.sign(grad)

      x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon)
      x = np.clip(x, 0, 1) # ensure valid pixel range

    return x 
Example #2
Source File: sympart.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _evaluate(self, X, out, *args, **kwargs):
        if self.w == 0:
            X1 = X[:, 0]
            X2 = X[:, 1]
        else:
            # If rotated, we rotate it back by applying the inverted rotation matrix to X
            Y = np.array([np.matmul(self.IRM, x) for x in X])
            X1 = Y[:, 0]
            X2 = Y[:, 1]

        a, b, c = self.a, self.b, self.c
        t1_hat = sign(X1) * ceil((abs(X1) - a - c / 2) / (2 * a + c))
        t2_hat = sign(X2) * ceil((abs(X2) - b / 2) / b)
        one = ones(len(X))
        t1 = sign(t1_hat) * min(np.vstack((abs(t1_hat), one)), axis=0)
        t2 = sign(t2_hat) * min(np.vstack((abs(t2_hat), one)), axis=0)

        p1 = X1 - t1 * c
        p2 = X2 - t2 * b

        f1 = (p1 + a) ** 2 + p2 ** 2
        f2 = (p1 - a) ** 2 + p2 ** 2
        out["F"] = np.vstack((f1, f2)).T 
Example #3
Source File: tlib.py    From TOPFARM with GNU Affero General Public License v3.0 6 votes vote down vote up
def move(self, P0, P1):
        """
        Move a point P0 to a new legal location

        :param P0: ndarray[2]
        :param P1: ndarray[2]
        :return: ndarray[2]
        """
        x_dist, y_dist = P1 - P0
        tdist = np.sqrt(y_dist**2+x_dist**2)

        if self.is_in(P1):
            return P1
        else:
            x_steps = int(np.sign(x_dist) * np.ceil(abs(x_dist / self.dx)))#, self.max_step
            y_steps = int(np.sign(y_dist) * np.ceil(abs(y_dist / self.dy)))#, self.max_step
            i0, j0 = self.locate_ij(P0)
            P2 = self.locate_xy(i0, j0)
            P_off = P2 - P0
            self.loop_i = 0
            i1, j1 = self.valid_move(i0, j0, x_steps, y_steps, P_off)
            P2 = self.locate_xy(i1, j1) + P_off

            return P2 
Example #4
Source File: so_pattern_search.py    From pymoo with Apache License 2.0 6 votes vote down vote up
def _pattern_move(self, _current, _next):

        # get the direction and assign the corresponding delta value
        direction = (_next.X - _current.X)

        # get the delta sign adjusted
        sign = np.sign(direction)
        sign[sign == 0] = -1
        self.explr_delta = sign * np.abs(self.explr_delta)

        # calculate the new X and repair out of bounds if necessary
        X = _current.X + self.pattern_step * direction
        repair_out_of_bounds_manually(X, *self.problem.bounds())

        # create the new center individual without evaluating it
        trial = Individual(X=X)

        return trial 
Example #5
Source File: gym_utils.py    From fine-lm with MIT License 6 votes vote down vote up
def step(self, action):
    ob, rew, done, info = self.env.step(action)

    if BreakoutWrapper.find_ball(ob) is None and self.ball_down_skip != 0:
      for _ in range(self.ball_down_skip):
        # We assume that nothing interesting happens during ball_down_skip
        # and discard all information.
        # We fire all the time to start new game
        ob, _, _, _ = self.env.step(BreakoutWrapper.FIRE_ACTION)
        self.direction_info.append(BreakoutWrapper.find_ball(ob))

    ob = self.process_observation(ob)

    self.points_gained = self.points_gained or rew > 0

    if self.reward_clipping:
      rew = np.sign(rew)

    return ob, rew, done, info 
Example #6
Source File: retinotopy.py    From neuropythy with GNU Affero General Public License v3.0 6 votes vote down vote up
def _retinotopic_field_sign_triangles(m, retinotopy):
    t = m.tess if isinstance(m, geo.Mesh) or isinstance(m, geo.Topology) else m
    # get the polar angle and eccen data as a complex number in degrees
    if pimms.is_str(retinotopy):
        (x,y) = as_retinotopy(retinotopy_data(m, retinotopy), 'geographical')
    elif retinotopy is Ellipsis:
        (x,y) = as_retinotopy(retinotopy_data(m, 'any'),      'geographical')
    else:
        (x,y) = as_retinotopy(retinotopy,                     'geographical')
    # Okay, now we want to make some coordinates...
    coords = np.asarray([x, y])
    us = coords[:, t.indexed_faces[1]] - coords[:, t.indexed_faces[0]]
    vs = coords[:, t.indexed_faces[2]] - coords[:, t.indexed_faces[0]]
    (us,vs) = [np.concatenate((xs, np.full((1, t.face_count), 0.0))) for xs in [us,vs]]
    xs = np.cross(us, vs, axis=0)[2]
    xs[np.isclose(xs, 0)] = 0
    return np.sign(xs) 
Example #7
Source File: laplace.py    From differential-privacy-library with MIT License 6 votes vote down vote up
def randomise(self, value):
        self.check_inputs(value)

        if self._scale is None:
            self._scale = self._find_scale()

        value = min(value, self._upper_bound)
        value = max(value, self._lower_bound)

        unif_rv = random()
        unif_rv *= self._cdf(self._upper_bound - value) - self._cdf(self._lower_bound - value)
        unif_rv += self._cdf(self._lower_bound - value)
        unif_rv -= 0.5

        unif_rv = min(unif_rv, 0.5 - 1e-10)

        return value - self._scale * np.sign(unif_rv) * np.log(1 - 2 * np.abs(unif_rv)) 
Example #8
Source File: laplace.py    From differential-privacy-library with MIT License 6 votes vote down vote up
def randomise(self, value):
        """Randomise `value` with the mechanism.

        Parameters
        ----------
        value : float
            The value to be randomised.

        Returns
        -------
        float
            The randomised value.

        """
        self.check_inputs(value)

        scale = self._sensitivity / (self._epsilon - np.log(1 - self._delta))

        unif_rv = random() - 0.5

        return value - scale * np.sign(unif_rv) * np.log(1 - 2 * np.abs(unif_rv)) 
Example #9
Source File: pgd_cw_whitebox.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def perturb(self, x_nat, y, sess):
    """Given a set of examples (x_nat, y), returns a set of adversarial
       examples within epsilon of x_nat in l_infinity norm."""
    if self.rand:
      x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape)
    else:
      x = np.copy(x_nat)

    for i in range(self.k):
      grad = sess.run(self.grad, feed_dict={self.model.x_input: x,
                                            self.model.y_input: y})

      x += self.a * np.sign(grad)

      x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon)
      x = np.clip(x, 0, 1) # ensure valid pixel range

    return x 
Example #10
Source File: pgd_cw_whitebox.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def perturb(self, x_nat, y, sess):
    """Given a set of examples (x_nat, y), returns a set of adversarial
       examples within epsilon of x_nat in l_infinity norm."""
    if self.rand:
      x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape)
    else:
      x = np.copy(x_nat)

    for i in range(self.k):
      grad = sess.run(self.grad, feed_dict={self.model.x_input: x,
                                            self.model.y_input: y})

      x += self.a * np.sign(grad)

      x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon)
      x = np.clip(x, 0, 1) # ensure valid pixel range

    return x 
Example #11
Source File: pgd_whitebox.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def perturb(self, x_nat, y, sess):
    """Given a set of examples (x_nat, y), returns a set of adversarial
       examples within epsilon of x_nat in l_infinity norm."""
    if self.rand:
      x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape)
    else:
      x = np.copy(x_nat)

    for i in range(self.k):
      grad = sess.run(self.grad, feed_dict={self.model.x_input: x,
                                            self.model.y_input: y})

      x += self.a * np.sign(grad)

      x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon)
      x = np.clip(x, 0, 1) # ensure valid pixel range

    return x 
Example #12
Source File: pgd_cw_whitebox.py    From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def perturb(self, x_nat, y, sess):
    """Given a set of examples (x_nat, y), returns a set of adversarial
       examples within epsilon of x_nat in l_infinity norm."""
    if self.rand:
      x = x_nat + np.random.uniform(-self.epsilon, self.epsilon, x_nat.shape)
    else:
      x = np.copy(x_nat)

    for i in range(self.k):
      grad = sess.run(self.grad, feed_dict={self.model.x_input: x,
                                            self.model.y_input: y})

      x += self.a * np.sign(grad)

      x = np.clip(x, x_nat - self.epsilon, x_nat + self.epsilon)
      x = np.clip(x, 0, 1) # ensure valid pixel range

    return x 
Example #13
Source File: elm.py    From Python-ELM with MIT License 6 votes vote down vote up
def predict(self, X):
        """
        predict classify result

        Args:
        X [[float]] array: feature vectors of learnig data

        Returns:
        [int]: labels of classification result
        """
        _H = self._sigmoid(np.dot(self.W, self._add_bias(X).T))
        y = np.dot(_H.T, self.beta)

        if self.out_num == 1:
            return np.sign(y)
        else:
            return np.argmax(y, 1) + np.ones(y.shape[0]) 
Example #14
Source File: rsp_findpeaks.py    From NeuroKit with MIT License 6 votes vote down vote up
def _rsp_findpeaks_outliers(rsp_cleaned, extrema, amplitude_min=0.3):

    # Only consider those extrema that have a minimum vertical distance to
    # their direct neighbor, i.e., define outliers in absolute amplitude
    # difference between neighboring extrema.
    vertical_diff = np.abs(np.diff(rsp_cleaned[extrema]))
    median_diff = np.median(vertical_diff)
    min_diff = np.where(vertical_diff > (median_diff * amplitude_min))[0]
    extrema = extrema[min_diff]

    # Make sure that the alternation of peaks and troughs is unbroken. If
    # alternation of sign in extdiffs is broken, remove the extrema that
    # cause the breaks.
    amplitudes = rsp_cleaned[extrema]
    extdiffs = np.sign(np.diff(amplitudes))
    extdiffs = np.add(extdiffs[0:-1], extdiffs[1:])
    removeext = np.where(extdiffs != 0)[0] + 1
    extrema = np.delete(extrema, removeext)
    amplitudes = np.delete(amplitudes, removeext)

    return extrema, amplitudes 
Example #15
Source File: test_quantization.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_quantize_float32_to_int8():
    shape = rand_shape_nd(4)
    data = rand_ndarray(shape, 'default', dtype='float32')
    min_range = mx.nd.min(data)
    max_range = mx.nd.max(data)
    qdata, min_val, max_val = mx.nd.contrib.quantize(data, min_range, max_range, out_type='int8')
    data_np = data.asnumpy()
    min_range = min_range.asscalar()
    max_range = max_range.asscalar()
    real_range = np.maximum(np.abs(min_range), np.abs(max_range))
    quantized_range = 127.0
    scale = quantized_range / real_range
    assert qdata.dtype == np.int8
    assert min_val.dtype == np.float32
    assert max_val.dtype == np.float32
    assert same(min_val.asscalar(), -real_range)
    assert same(max_val.asscalar(), real_range)
    qdata_np = (np.sign(data_np) * np.minimum(np.abs(data_np) * scale + 0.5, quantized_range)).astype(np.int8)
    assert_almost_equal(qdata.asnumpy(), qdata_np, atol = 1) 
Example #16
Source File: naive_bayes.py    From differential-privacy-library with MIT License 6 votes vote down vote up
def _noisy_class_counts(self, y):
        unique_y = np.unique(y)
        n_total = y.shape[0]

        # Use 1/3 of total epsilon budget for getting noisy class counts
        mech = GeometricTruncated().set_epsilon(self.epsilon / 3).set_sensitivity(1).set_bounds(1, n_total)
        noisy_counts = np.array([mech.randomise((y == y_i).sum()) for y_i in unique_y])

        argsort = np.argsort(noisy_counts)
        i = 0 if noisy_counts.sum() > n_total else len(unique_y) - 1

        while np.sum(noisy_counts) != n_total:
            _i = argsort[i]
            sgn = np.sign(n_total - noisy_counts.sum())
            noisy_counts[_i] = np.clip(noisy_counts[_i] + sgn, 1, n_total)

            i = (i - sgn) % len(unique_y)

        return noisy_counts 
Example #17
Source File: DecisionStump.py    From fuku-ml with MIT License 6 votes vote down vote up
def __init__(self):

        """init"""

        self.status = 'empty'
        self.train_X = []
        self.train_Y = []
        self.W = []
        self.data_num = 0
        self.data_demension = 0
        self.test_X = []
        self.test_Y = []
        self.feature_transform_mode = ''
        self.feature_transform_degree = 1

        self.sign = 1
        self.feature_index = 0
        self.theta = 0
        self.u = None 
Example #18
Source File: SVM.py    From weiboanalysis with Apache License 2.0 5 votes vote down vote up
def h(self, X, w, b):
        return np.sign(np.dot(w.T, X.T) + b).astype(int)
    # 预测错误 
Example #19
Source File: gym_utils.py    From fine-lm with MIT License 5 votes vote down vote up
def step(self, action):
    ob, rew, done, info = self.env.step(action)

    if self.easy_freeway:
      if rew > 0:
        self.half_way_reward = 1
      chicken_height = self.chicken_height(ob)
      if chicken_height < 105:
        rew += self.half_way_reward
        self.half_way_reward = 0

    if self.reward_clipping:
      rew = np.sign(rew)

    return ob, rew, done, info 
Example #20
Source File: atari_wrappers.py    From lirpg with MIT License 5 votes vote down vote up
def reward(self, reward):
        """Bin reward to {+1, 0, -1} by its sign."""
        return np.sign(reward) 
Example #21
Source File: utils.py    From quadcopter-simulation with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def RotToQuat(R):
    """
    ROTTOQUAT Converts a Rotation matrix into a Quaternion
    from the following website, deals with the case when tr<0
    http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
    takes in W_R_B rotation matrix
    """

    tr = R[0,0] + R[1,1] + R[2,2]
    if tr > 0:
        S = sqrt(tr+1.0) * 2 # S=4*qw
        qw = 0.25 * S
        qx = (R[2,1] - R[1,2]) / S
        qy = (R[0,2] - R[2,0]) / S
        qz = (R[1,0] - R[0,1]) / S
    elif (R[0,1] > R[1,1]) and (R[0,0] > R[2,2]):
        S = sqrt(1.0 + R[0,0] - R[1,1] - R[2,2]) * 2 # S=4*qx
        qw = (R[2,1] - R[1,2]) / S
        qx = 0.25 * S
        qy = (R[0,1] + R[1,0]) / S
        qz = (R[0,2] + R[2,0]) / S
    elif R[1,1] > R[2,2]:
        S = sqrt(1.0 + R[1,1] - R[0,0] - R[2,2]) * 2 # S=4*qy
        qw = (R[0,2] - R[2,0]) / S
        qx = (R[0,1] + R[1,0]) / S
        qy = 0.25 * S
        qz = (R[1,2] + R[2,1]) / S
    else:
        S = sqrt(1.0 + R[2,2] - R[0,0] - R[1,1]) * 2 # S=4*qz
        qw = (R[1,0] - R[0,1]) / S
        qx = (R[0,2] + R[2,0]) / S
        qy = (R[1,2] + R[2,1]) / S
        qz = 0.25 * S

    q = np.sign(qw) * np.array([qw, qx, qy, qz])
    return q 
Example #22
Source File: pywannier90.py    From pyscf with Apache License 2.0 5 votes vote down vote up
def g_r(grids_coor, site, l, mr, r, zona, x_axis = [1,0,0], z_axis = [0,0,1], unit = 'B'):
    r'''
    Evaluate the projection function g(r) or \Theta_{l,m_r}(\theta,\phi) on a grid
    ref: Chapter 3, wannier90 User Guide
    Attributes:
        grids_coor : a grids for the cell of interest
        site       : absolute coordinate (in Borh/Angstrom) of the g(r) in the cell
        l, mr      : l and mr value in the Table 3.1 and 3.2 of the ref
    Return:
        theta_lmr  : an array (ngrid, value) of g(r)

    '''

    unit_conv = 1
    if unit == 'A': unit_conv = param.BOHR


    r_vec = (grids_coor - site)
    r_vec = np.einsum('iv,uv ->iu', r_vec, transform(x_axis, z_axis))
    r_norm = np.linalg.norm(r_vec,axis=1)
    if (r_norm < 1e-8).any() == True:
        r_vec = (grids_coor - site - 1e-5)
        r_vec = np.einsum('iv,uv ->iu', r_vec, transform(x_axis, z_axis))
        r_norm = np.linalg.norm(r_vec,axis=1)
    cost = r_vec[:,2]/r_norm

    phi = np.empty_like(r_norm)
    for point in range(phi.shape[0]):
        if r_vec[point,0] > 1e-8:
            phi[point] = np.arctan(r_vec[point,1]/r_vec[point,0])
        elif r_vec[point,0] < -1e-8:
            phi[point] = np.arctan(r_vec[point,1]/r_vec[point,0]) + np.pi
        else:
            phi[point] = np.sign(r_vec[point,1]) * 0.5 * np.pi

    return theta_lmr(l, mr, cost, phi) * R_r(r_norm * unit_conv, r = r, zona = zona) 
Example #23
Source File: coords.py    From pyberny with Mozilla Public License 2.0 5 votes vote down vote up
def eval_geom(self, geom, template=None):
        geom = geom.supercell()
        q = np.array([coord.eval(geom.coords) for coord in self])
        if template is None:
            return q
        swapped = []  # dihedrals swapped by pi
        candidates = set()  # potentially swapped angles
        for i, dih in enumerate(self):
            if not isinstance(dih, Dihedral):
                continue
            diff = q[i] - template[i]
            if abs(abs(diff) - 2 * pi) < pi / 2:
                q[i] -= 2 * pi * np.sign(diff)
            elif abs(abs(diff) - pi) < pi / 2:
                q[i] -= pi * np.sign(diff)
                swapped.append(dih)
                candidates.update(dih.angles)
        for i, ang in enumerate(self):
            if not isinstance(ang, Angle) or ang not in candidates:
                continue
            # candidate angle was swapped if each dihedral that contains it was
            # either swapped or all its angles are candidates
            if all(
                dih in swapped or all(a in candidates for a in dih.angles)
                for dih in self.dihedrals
                if ang in dih.angles
            ):
                q[i] = 2 * pi - q[i]
        return q 
Example #24
Source File: scl.py    From libTLDA with MIT License 5 votes vote down vote up
def predict(self, Z):
        """
        Make predictions on new dataset.

        Parameters
        ----------
        Z : array
            new data set (M samples by D features)

        Returns
        -------
        preds : array
            label predictions (M samples by 1)

        """
        # Data shape
        M, D = Z.shape

        # If classifier is trained, check for same dimensionality
        if self.is_trained:
            if not self.train_data_dim == D:
                raise ValueError('''Test data is of different dimensionality
                                 than training data.''')

        # Check for augmentation
        if not self.train_data_dim == D:
            Z = np.concatenate((np.dot(Z, self.C), Z), axis=1)

        # Call scikit's predict function
        preds = self.clf.predict(Z)

        # For quadratic loss function, correct predictions
        if self.loss == 'quadratic':
            preds = (np.sign(preds)+1)/2.

        # Return predictions array
        return preds 
Example #25
Source File: sparse_half_cheetah.py    From cs294-112_hws with MIT License 5 votes vote down vote up
def step(self, action):
        #################################################
        ctrl = False
        relu = False
        threshold = 10.0
        #################################################
        xposbefore = self.sim.data.qpos[0]
        self.do_simulation(action, self.frame_skip)
        xposafter = self.sim.data.qpos[0]
        ob = self._get_obs()
        # reward_ctrl = - 0.1 * np.square(action).sum()
        # reward_run = (xposafter - xposbefore)/self.dt
        #################################################
        if ctrl:
            reward_ctrl = - 0.1 * np.square(action).sum()
        else:
            reward_ctrl = 0
        if abs(xposafter) <= threshold:
            reward_run = 0.0
        else:
            if relu:
                reward_run = np.sign(xposafter)*(xposafter - xposbefore)/self.dt
            else:
                reward_run = 1.0
        #################################################
        reward = reward_ctrl + reward_run
        done = False
        return ob, reward, done, dict(reward_run=reward_run, reward_ctrl=reward_ctrl) 
Example #26
Source File: atari_wrappers.py    From cs294-112_hws with MIT License 5 votes vote down vote up
def _step(self, action):
        obs, reward, done, info = self.env.step(action)
        return obs, np.sign(reward), done, info 
Example #27
Source File: motor.py    From soccer-matlab with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _convert_to_torque_from_pwm(self, pwm, current_motor_velocity):
    """Convert the pwm signal to torque.

    Args:
      pwm: The pulse width modulation.
      current_motor_velocity: The motor velocity at the current time step.
    Returns:
      actual_torque: The torque that needs to be applied to the motor.
      observed_torque: The torque observed by the sensor.
    """
    observed_torque = np.clip(
        self._torque_constant * (pwm * self._voltage / self._resistance),
        -OBSERVED_TORQUE_LIMIT, OBSERVED_TORQUE_LIMIT)

    # Net voltage is clipped at 50V by diodes on the motor controller.
    voltage_net = np.clip(pwm * self._voltage -
                          (self._torque_constant + self._viscous_damping)
                          * current_motor_velocity,
                          -VOLTAGE_CLIPPING, VOLTAGE_CLIPPING)
    current = voltage_net / self._resistance
    current_sign = np.sign(current)
    current_magnitude = np.absolute(current)

    # Saturate torque based on empirical current relation.
    actual_torque = np.interp(current_magnitude, self._current_table,
                              self._torque_table)
    actual_torque = np.multiply(current_sign, actual_torque)
    return actual_torque, observed_torque 
Example #28
Source File: motor.py    From soccer-matlab with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _convert_to_torque_from_pwm(self, pwm, true_motor_velocity):
    """Convert the pwm signal to torque.

    Args:
      pwm: The pulse width modulation.
      true_motor_velocity: The true motor velocity at the current moment. It is
        used to compute the back EMF voltage and the viscous damping.
    Returns:
      actual_torque: The torque that needs to be applied to the motor.
      observed_torque: The torque observed by the sensor.
    """
    observed_torque = np.clip(
        self._torque_constant *
        (np.asarray(pwm) * self._voltage / self._resistance),
        -OBSERVED_TORQUE_LIMIT, OBSERVED_TORQUE_LIMIT)

    # Net voltage is clipped at 50V by diodes on the motor controller.
    voltage_net = np.clip(
        np.asarray(pwm) * self._voltage -
        (self._torque_constant + self._viscous_damping) *
        np.asarray(true_motor_velocity), -VOLTAGE_CLIPPING, VOLTAGE_CLIPPING)
    current = voltage_net / self._resistance
    current_sign = np.sign(current)
    current_magnitude = np.absolute(current)
    # Saturate torque based on empirical current relation.
    actual_torque = np.interp(current_magnitude, self._current_table,
                              self._torque_table)
    actual_torque = np.multiply(current_sign, actual_torque)
    actual_torque = np.multiply(self._strength_ratios, actual_torque)
    return actual_torque, observed_torque 
Example #29
Source File: Rotations.py    From fullrmc with GNU Affero General Public License v3.0 5 votes vote down vote up
def transform_coordinates(self, coordinates, argument=None):
        """
        Rotate coordinates.

        :Parameters:
            #. coordinates (np.ndarray): The coordinates on which to apply
               the rotation.
            #. argument (object): Not used here.

        :Returns:
            #. coordinates (np.ndarray): The new coordinates after applying
               the rotation.
        """
        if coordinates.shape[0]<=1:
            # atoms where removed, fall back to random translation
            return coordinates+generate_random_vector(minAmp=self.__amplitude[0],
                                                      maxAmp=self.__amplitude[1])
        else:
           # create flip flag
            if self.__flip is None:
                flip = FLOAT_TYPE( np.sign(1-2*generate_random_float()) )
            elif self.__flip:
                flip = FLOAT_TYPE(-1)
            else:
                flip = FLOAT_TYPE(1)
            # get group axis
            groupAxis = self.__get_group_axis__(coordinates)
            # get align axis within offset angle
            orientationAxis = flip*self.__get_orientation_axis__()
            orientationAxis = generate_vectors_in_solid_angle(direction=orientationAxis,
                                                              maxAngle=self.__maximumOffsetAngle,
                                                              numberOfVectors=1)[0]
            # get coordinates center
            center = np.array(np.sum(coordinates, 0)/coordinates.shape[0] , dtype=FLOAT_TYPE)
            # translate to origin
            rotatedCoordinates = coordinates-center
            # align coordinates
            rotatedCoordinates = orient(rotatedCoordinates, groupAxis, orientationAxis)
            # translate back to center and return rotated coordinates
            return np.array(rotatedCoordinates+center, dtype=FLOAT_TYPE) 
Example #30
Source File: Translations.py    From fullrmc with GNU Affero General Public License v3.0 5 votes vote down vote up
def transform_coordinates(self, coordinates, argument=None):
        """
        translate coordinates.

        :Parameters:
            #. coordinates (np.ndarray): The coordinates on which to apply
               the translation.

        :Returns:
            #. coordinates (np.ndarray): The new coordinates after applying
               the translation.
            #. argument (object): Not used here.
        """
        if coordinates.shape[0]<=1:
            # atoms where removed, fall back to random translation
            return coordinates+generate_random_vector(minAmp=self.__amplitude[0],
                                                      maxAmp=self.__amplitude[1])
        else:
            # get axis
            _,_,_,_,X,Y,Z =get_principal_axis(coordinates)
            axis = [X,Y,Z][self.axis]
            # generate translation axis
            translationAxis = generate_vectors_in_solid_angle(direction=axis,
                                                              maxAngle=self.__angle,
                                                              numberOfVectors=1)[0]
            # get translation amplitude
            maxAmp = self.amplitude[1]-self.amplitude[0]
            if self.direction is None:
                amplitude = (1-2*generate_random_float())*maxAmp
            elif self.direction:
                amplitude = generate_random_float()*maxAmp
            else:
                amplitude = -generate_random_float()*maxAmp
            # compute baseVector
            baseVector = FLOAT_TYPE(np.sign(amplitude)*translationAxis*self.amplitude[0])
            # compute translation vector
            vector = baseVector + translationAxis*FLOAT_TYPE(amplitude)
            # translate and return
            return coordinates+vector