Python numpy.sign() Examples

The following are 30 code examples for showing how to use numpy.sign(). 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: neural-fingerprinting   Author: StephanZheng   File: pgd_cw_whitebox.py    License: 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
Project: neural-fingerprinting   Author: StephanZheng   File: pgd_whitebox.py    License: 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 3
Project: neural-fingerprinting   Author: StephanZheng   File: pgd_cw_whitebox.py    License: 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 4
Project: neural-fingerprinting   Author: StephanZheng   File: pgd_whitebox.py    License: 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 5
Project: neural-fingerprinting   Author: StephanZheng   File: pgd_cw_whitebox.py    License: 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 6
Project: neuropythy   Author: noahbenson   File: retinotopy.py    License: 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
Project: fuku-ml   Author: fukuball   File: DecisionStump.py    License: 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 8
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 9
Project: TOPFARM   Author: DTUWindEnergy   File: tlib.py    License: 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 10
Project: fine-lm   Author: akzaidi   File: gym_utils.py    License: 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 11
Project: differential-privacy-library   Author: IBM   File: naive_bayes.py    License: 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 12
Project: differential-privacy-library   Author: IBM   File: laplace.py    License: 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 13
Project: differential-privacy-library   Author: IBM   File: laplace.py    License: 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 14
Project: pymoo   Author: msu-coinlab   File: sympart.py    License: 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 15
Project: pymoo   Author: msu-coinlab   File: so_pattern_search.py    License: 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 16
Project: Python-ELM   Author: masaponto   File: elm.py    License: 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 17
Project: NeuroKit   Author: neuropsychology   File: rsp_findpeaks.py    License: 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 18
Project: libTLDA   Author: wmkouw   File: scl.py    License: 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 19
Project: libTLDA   Author: wmkouw   File: iw.py    License: 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.''')

        # 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 20
Project: libTLDA   Author: wmkouw   File: tca.py    License: 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.''')

        # Compute kernel for new data
        K = self.kernel(Z, self.XZ, type=self.kernel_type,
                        bandwidth=self.bandwidth, order=self.order)

        # Map new data onto transfer components
        Z = np.dot(K, self.C)

        # 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 21
Project: aospy   Author: spencerahill   File: vertcoord.py    License: Apache License 2.0 5 votes vote down vote up
def does_coord_increase_w_index(arr):
    """Determine if the array values increase with the index.

    Useful, e.g., for pressure, which sometimes is indexed surface to TOA and
    sometimes the opposite.
    """
    diff = np.diff(arr)
    if not np.all(np.abs(np.sign(diff))):
        raise ValueError("Array is not monotonic: {}".format(arr))
    # Since we know its monotonic, just test the first value.
    return bool(diff[0]) 
Example 22
Project: FRIDA   Author: LCAV   File: generators.py    License: MIT License 5 votes vote down vote up
def gen_dirty_img(visi, pos_mic_x, pos_mic_y, omega_band, sound_speed, phi_plt):
    """
    Compute the dirty image associated with the given measurements. Here the Fourier transform
    that is not measured by the microphone array is taken as zero.
    :param visi: the measured visibilites
    :param pos_mic_x: a vector contains microphone array locations (x-coordinates)
    :param pos_mic_y: a vector contains microphone array locations (y-coordinates)
    :param omega_band: mid-band (ANGULAR) frequency [radian/sec]
    :param sound_speed: speed of sound
    :param phi_plt: plotting grid (azimuth on the circle) to show the dirty image
    :return:
    """
    img = np.zeros(phi_plt.size, dtype=complex)
    x_plt, y_plt = polar2cart(1, phi_plt)
    num_mic = pos_mic_x.size

    pos_mic_x_normalised = pos_mic_x / (sound_speed / omega_band)
    pos_mic_y_normalised = pos_mic_y / (sound_speed / omega_band)

    count_visi = 0
    for q in xrange(num_mic):
        p_x_outer = pos_mic_x_normalised[q]
        p_y_outer = pos_mic_y_normalised[q]
        for qp in xrange(num_mic):
            if not q == qp:
                p_x_qqp = p_x_outer - pos_mic_x_normalised[qp]  # a scalar
                p_y_qqp = p_y_outer - pos_mic_y_normalised[qp]  # a scalar
                # <= the negative sign converts DOA to propagation vector
                img += visi[count_visi] * \
                       np.exp(-1j * (p_x_qqp * x_plt + p_y_qqp * y_plt))
                count_visi += 1
    return img / (num_mic * (num_mic - 1)) 
Example 23
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def sign_log_func(x):
    return np.sign(x) * np.log10(np.abs(x) + 1) 
Example 24
Project: models   Author: kipoi   File: dataloader.py    License: MIT License 5 votes vote down vote up
def sign_log_func_inverse(x):
    return np.sign(x) * (np.power(10, np.abs(x)) - 1) 
Example 25
Project: neuropythy   Author: noahbenson   File: util.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def tetrahedral_barycentric_coordinates(tetra, pt):
    '''
    tetrahedral_barycentric_coordinates(tetrahedron, point) yields a list of weights for each vertex
      in the given tetrahedron in the same order as the vertices given. If all weights are 0, then
      the point is not inside the tetrahedron.
    '''
    # I found a description of this algorithm here (Nov. 2017):
    # http://steve.hollasch.net/cgindex/geometry/ptintet.html
    tetra = np.asarray(tetra)
    pt = np.asarray(pt)
    if tetra.shape[0] != 4:
        if tetra.shape[1] == 4:
            if tetra.shape[0] == 3:
                tetra = np.transpose(tetra, (1,0) if len(tetra.shape) == 2 else (1,0,2))
            else:
                tetra = np.transpose(tetra, (1,2,0))
        elif tetra.shape[1] == 3:
            tetra = np.transpose(tetra, (2,1,0))
        else:
            tetra = np.transpose(tetra, (2,0,1))
    elif tetra.shape[1] != 3:
        tetra = np.transpose(tetra, (0,2,1))
    if pt.shape[0] != 3: pt = pt.T
    # Okay, calculate the determinants...
    d_ = det_4x3(tetra[0], tetra[1], tetra[2], tetra[3])
    d0 = det_4x3(pt,       tetra[1], tetra[2], tetra[3])
    d1 = det_4x3(tetra[0], pt,       tetra[2], tetra[3])
    d2 = det_4x3(tetra[0], tetra[1], pt,       tetra[3])
    d3 = det_4x3(tetra[0], tetra[1], tetra[2], pt)
    s_ = np.sign(d_)
    z_ = np.logical_or(np.any([s_ * si == -1 for si in np.sign([d0,d1,d2,d3])], axis=0),
                       np.isclose(d_,0))
    x_ = np.logical_not(z_)
    d_inv = x_ / (x_ * d_ + z_)
    return np.asarray([d_inv * dq for dq in (d0,d1,d2,d3)]) 
Example 26
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def jacobian(self, x, into=None):
        x = flattest(x)
        z = np.sign(x)
        z = sps.diags(z)
        return safe_into(into, z) 
Example 27
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def value(self, x): return np.sign(flattest(x)) 
Example 28
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def sign(f=Ellipsis):
    '''
    sign() yields a potential function equivalent to the sign of the input.
    sign(f) yields the sign of the potential function f.

    Note that sign has a derivative of 0 at all points; this is not mathematically correct, but it is
    useful for the purposes of numerical methods. If you want traditional behavior, it is suggested
    that one instead employ f/sqrt(f**2).
    '''
    f = to_potential(f)
    if is_const_potential(f): return const_potential(np.sign(f.c))
    elif is_identity_potential(f): return SignPotential()
    else: return compose(SignPotential(), f) 
Example 29
Project: neuropythy   Author: noahbenson   File: retinotopy.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _clean_angle_deg(polang):
    polang = np.asarray(polang)
    clean = np.mod(polang + 180, 360) - 180
    is180 = np.isclose(polang, -180)
    clean[is180] = np.abs(clean[is180]) * np.sign(polang[is180])
    return clean 
Example 30
Project: neuropythy   Author: noahbenson   File: retinotopy.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def retinotopic_field_sign(m, element='vertices', retinotopy=Ellipsis, invert_field=False):
    '''
    retinotopic_field_sign(mesh) yields a property array of the field sign of every vertex in the 
    mesh m; this value may not be exactly 1 (same as VF) or -1 (mirror-image) but some value
    in-between; this is because the field sign is calculated exactly (1, 0, or -1) for each triangle
    in the mesh then is average onto the vertices. To get only the triangle field signs, use
    retinotopic_field_sign(m, 'triangles').

    The following options are accepted:
      * element ('vertices') may be 'vertices' to specify that the vertex signs should be returned
        or 'triangles' (or 'faces') to specify that the triangle field signs should be returned.
      * retinotopy (Ellipsis) specifies the retinotopic dataset to be used. If se to 'empirical' or
        'predicted', the retinotopy data is auto-detected from the given categories; if set to
        Ellipsis, a property pair like 'polar_angle' and 'eccentricity' or 'lat' and 'lon' are
        searched for using the as_retinotopy function; otherwise, this may be a retinotopy dataset
        recognizable by as_retinotopy.
      * invert_field (False) specifies that the inverse of the field sign should be returned.
    '''
    tsign = _retinotopic_field_sign_triangles(m, retinotopy)
    t = m.tess if isinstance(m, geo.Mesh) or isinstance(m, geo.Topology) else m
    if invert_field: tsign = -tsign
    element = element.lower()
    if element == 'triangles' or element == 'faces': return tsign
    vfs = t.vertex_faces
    vfs = np.asarray([np.mean(tsign[list(ii)]) if len(ii) > 0 else 0 for ii in vfs])
    return vfs