當前位置: 首頁>>代碼示例>>Python>>正文


Python numpy.mod方法代碼示例

本文整理匯總了Python中numpy.mod方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.mod方法的具體用法?Python numpy.mod怎麽用?Python numpy.mod使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在numpy的用法示例。


在下文中一共展示了numpy.mod方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: heuristic_fn_vec

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def heuristic_fn_vec(n1, n2, n_ori, step_size):
  # n1 is a vector and n2 is a single point.
  dx = (n1[:,0] - n2[0,0])/step_size
  dy = (n1[:,1] - n2[0,1])/step_size
  dt = n1[:,2] - n2[0,2]
  dt = np.mod(dt, n_ori)
  dt = np.minimum(dt, n_ori-dt)

  if n_ori == 6:
    if dx*dy > 0:
      d = np.maximum(np.abs(dx), np.abs(dy))
    else:
      d = np.abs(dy-dx)
  elif n_ori == 4:
    d = np.abs(dx) + np.abs(dy)

  return (d + dt).reshape((-1,1)) 
開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:19,代碼來源:graph_utils.py

示例2: toc

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def toc(self, average=True, log_at=-1, log_str='', type='calls'):
    if self.start_time == 0:
      logging.error('Timer not started by calling tic().')
    t = time.time()
    diff = time.time() - self.start_time
    self.total_time += diff
    self.calls += 1.
    self.time_per_call = self.total_time/self.calls

    if type == 'calls' and log_at > 0 and np.mod(self.calls, log_at) == 0:
      _ = []
      logging.info('%s: %f seconds.', log_str, self.time_per_call)
    elif type == 'time' and log_at > 0 and t - self.last_log_time >= log_at:
      _ = []
      logging.info('%s: %f seconds.', log_str, self.time_per_call)
      self.last_log_time = t

    if average:
      return self.time_per_call
    else:
      return diff 
開發者ID:ringringyi,項目名稱:DOTA_models,代碼行數:23,代碼來源:utils.py

示例3: bounds_back

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def bounds_back(problem, X):
    only_1d = (X.ndim == 1)
    X = at_least_2d_array(X)

    if problem.xl is not None and problem.xu is not None:
        xl = np.repeat(problem.xl[None, :], X.shape[0], axis=0)
        xu = np.repeat(problem.xu[None, :], X.shape[0], axis=0)

        # otherwise bounds back into the feasible space
        _range = xu - xl
        X[X < xl] = (xl + np.mod((xl - X), _range))[X < xl]
        X[X > xu] = (xu - np.mod((X - xu), _range))[X > xu]

    if only_1d:
        return X[0, :]
    else:
        return X 
開發者ID:msu-coinlab,項目名稱:pymoo,代碼行數:19,代碼來源:bounds_back_repair.py

示例4: test_NotImplemented_not_returned

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def test_NotImplemented_not_returned(self):
        # See gh-5964 and gh-2091. Some of these functions are not operator
        # related and were fixed for other reasons in the past.
        binary_funcs = [
            np.power, np.add, np.subtract, np.multiply, np.divide,
            np.true_divide, np.floor_divide, np.bitwise_and, np.bitwise_or,
            np.bitwise_xor, np.left_shift, np.right_shift, np.fmax,
            np.fmin, np.fmod, np.hypot, np.logaddexp, np.logaddexp2,
            np.logical_and, np.logical_or, np.logical_xor, np.maximum,
            np.minimum, np.mod,
            np.greater, np.greater_equal, np.less, np.less_equal,
            np.equal, np.not_equal]

        a = np.array('1')
        b = 1
        c = np.array([1., 2.])
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b)
            assert_raises(TypeError, f, c, a) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:21,代碼來源:test_ufunc.py

示例5: compute

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def compute(self, inp):
        try:
            pos = inp.atoms.positions
            pos = pos.flatten()
        except AttributeError:
            try:
                pos = inp.flatten()
            except AttributeError:
                raise ValueError('must pass an atom group or a ndarray')

        n = pos.shape[0]
        if np.mod(n, 9) > 0:  # 3 atoms x 3 coordinates
            raise ValueError('number of atoms in group not a multiple of 3')

        n = n // 3
        pos = pos.reshape(n, 3, 3)
        if self.QR is True:
            return np.asarray([np.linalg.qr(A)[0] for A in pos])
        else:
            return np.asarray([self._modified_GS(A) for A in pos]) 
開發者ID:Marcello-Sega,項目名稱:pytim,代碼行數:22,代碼來源:basic_observables.py

示例6: discriminator

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def discriminator(self, image, y=None, reuse=False):
        if reuse:
            tf.get_variable_scope().reuse_variables()

        s = self.output_size
        if np.mod(s, 16) == 0:
            h0 = lrelu(conv2d(image, self.df_dim, name='d_h0_conv'))
            h1 = lrelu(self.d_bn1(conv2d(h0, self.df_dim*2, name='d_h1_conv')))
            h2 = lrelu(self.d_bn2(conv2d(h1, self.df_dim*4, name='d_h2_conv')))
            h3 = lrelu(self.d_bn3(conv2d(h2, self.df_dim*8, name='d_h3_conv')))
            h4 = linear(tf.reshape(h3, [self.batch_size, -1]), 1, 'd_h3_lin')

            return tf.nn.sigmoid(h4), h4
        else:
            h0 = lrelu(conv2d(image, self.df_dim, name='d_h0_conv'))
            h1 = lrelu(self.d_bn1(conv2d(h0, self.df_dim*2, name='d_h1_conv')))
            h2 = linear(tf.reshape(h1, [self.batch_size, -1]), 1, 'd_h2_lin')
            if not self.config.use_kernel:
              return tf.nn.sigmoid(h2), h2
            else:
              return tf.nn.sigmoid(h2), h2, h1, h0 
開發者ID:djsutherland,項目名稱:opt-mmd,代碼行數:23,代碼來源:model_mmd.py

示例7: mps2lat_idx

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def mps2lat_idx(self, i):
        """Translate MPS index `i` to lattice indices ``(x_0, ..., x_{dim-1}, u)``.

        Parameters
        ----------
        i : int | array_like of int
            MPS index/indices.

        Returns
        -------
        lat_idx : array
            First dimensions like `i`, last dimension has len `dim`+1 and contains the lattice
            indices ``(x_0, ..., x_{dim-1}, u)`` corresponding to `i`.
            For `i` accross the MPS unit cell and "infinite" `bc_MPS`, we shift `x_0` accordingly.
        """
        if self.bc_MPS == 'infinite':
            # allow `i` outsit of MPS unit cell for bc_MPS infinite
            i0 = i
            i = np.mod(i, self.N_sites)
            if np.any(i0 != i):
                lat = self.order[i].copy()
                lat[..., 0] += (i0 - i) * self.N_rings // self.N_sites
                # N_sites_per_ring might not be set for IrregularLattice
                return lat
        return self.order[i].copy() 
開發者ID:tenpy,項目名稱:tenpy,代碼行數:27,代碼來源:lattice.py

示例8: get_lattice

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def get_lattice(lattice_name):
    """Given the name of a :class:`Lattice` class, get the lattice class itself.

    Parameters
    ----------
    lattice_name : str
        Name of a :class:`Lattice` class defined in the module :mod:`~tenpy.models.lattice`,
        for example ``"Chain", "Square", "Honeycomb", ...``.

    Returns
    -------
    LatticeClass : :class:`Lattice`
        The lattice class (type, not instance) specified by `lattice_name`.
    """
    LatticeClass = globals()[lattice_name]
    assert issubclass(LatticeClass, Lattice)
    return LatticeClass 
開發者ID:tenpy,項目名稱:tenpy,代碼行數:19,代碼來源:lattice.py

示例9: save_hdf5

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def save_hdf5(self, hdf5_saver, h5gr, subpath):
        """Export `self` into a HDF5 file.

        This method saves all the data it needs to reconstruct `self` with :meth:`from_hdf5`.

        It stores the :attr:`names` under the path ``"names"``, and
        :attr:`mod` as dataset ``"U1_ZN"``.

        Parameters
        ----------
        hdf5_saver : :class:`~tenpy.tools.hdf5_io.Hdf5Saver`
            Instance of the saving engine.
        h5gr : :class`Group`
            HDF5 group which is supposed to represent `self`.
        subpath : str
            The `name` of `h5gr` with a ``'/'`` in the end.
        """
        h5gr.attrs['num_charges'] = self._qnumber
        hdf5_saver.save(self._mod, subpath + "U1_ZN")
        hdf5_saver.save(self.names, subpath + "names") 
開發者ID:tenpy,項目名稱:tenpy,代碼行數:22,代碼來源:charges.py

示例10: drop

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def drop(cls, chinfo, charge=None):
        """Remove a charge from a :class:`ChargeInfo`.

        Parameters
        ----------
        chinfo : :class:`ChargeInfo`
            The ChargeInfo from where to drop/remove a charge.
        charge : int | str
            Number or `name` of the charge (within `chinfo`) which is to be dropped.
            ``None`` means dropping all charges.

        Returns
        -------
        chinfo : :class:`ChargeInfo`
            ChargeInfo where the specified charge is dropped.
        """
        if charge is None:
            return cls()  # trivial charge
        if isinstance(charge, str):
            charge = chinfo.names.index(charge)
        names = list(chinfo.names)
        names.pop(charge)
        return cls(np.delete(chinfo.mod, charge), names) 
開發者ID:tenpy,項目名稱:tenpy,代碼行數:25,代碼來源:charges.py

示例11: change

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def change(cls, chinfo, charge, new_qmod, new_name=''):
        """Change the `qmod` of a given charge.

        Parameters
        ----------
        chinfo : :class:`ChargeInfo`
            The ChargeInfo for which `qmod` of `charge` should be changed.
        new_qmod : int
            The new `qmod` to be set.
        new_name : str
            The new name of the charge.

        Returns
        -------
        chinfo : :class:`ChargeInfo`
            ChargeInfo where `qmod` of the specified charge was changed.
        """
        if isinstance(charge, str):
            charge = chinfo.names.index(charge)
        names = list(chinfo.names)
        names[charge] = new_name
        mod = chinfo.mod.copy()
        mod[charge] = new_qmod
        return cls(mod, names) 
開發者ID:tenpy,項目名稱:tenpy,代碼行數:26,代碼來源:charges.py

示例12: make_valid

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def make_valid(self, charges=None):
        """Take charges modulo self.mod.

        Parameters
        ----------
        charges : array_like or None
            1D or 2D array of charges, last dimension `self.qnumber`
            None defaults to trivial charges ``np.zeros(qnumber, dtype=QTYPE)``.

        Returns
        -------
        charges :
            A copy of `charges` taken modulo `mod`, but with ``x % 1 := x``
        """
        if charges is None:
            return np.zeros((self.qnumber, ), dtype=QTYPE)
        charges = np.asarray(charges, dtype=QTYPE)
        charges[..., self._mask] = np.mod(charges[..., self._mask], self._mod_masked)
        return charges 
開發者ID:tenpy,項目名稱:tenpy,代碼行數:21,代碼來源:charges.py

示例13: train_step

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def train_step(self,sess,counter):
        '''
        This is a generic function that will be called by the Trainer class
        once per iteration. The simplest body for this part would be simply
        "sess.run(self.train_op)". But you may have more complications.

        Running self.summary_op is handeled by Trainer.Supervisor and doesn't
        need to be addressed here

        Only counters, not epochs are explicitly kept track of
        '''

        ###You can wait until counter>N to do stuff for example:
        if self.config.pretrain_LabelerR and counter < self.config.pretrain_LabelerR_no_of_iters:
            sess.run(self.d_label_optim)

        else:
            if np.mod(counter, 3) == 0:

                sess.run(self.g_optim)
                sess.run([self.train_op,self.k_t_update,self.inc_step])#all ops

            else:
                sess.run([self.g_optim, self.k_t_update ,self.inc_step])
                sess.run(self.g_optim) 
開發者ID:mkocaoglu,項目名稱:CausalGAN,代碼行數:27,代碼來源:CausalGAN.py

示例14: BBox3DToKITTIObject

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def BBox3DToKITTIObject(bbox3d, velo_to_cam_transform):
  """Convert one bbox3d into KITTI's location, dimension, and rotation_y."""
  x, y, z, length, width, height, rot = bbox3d

  # Avoid transforming objects with invalid boxes. See _KITTIObjectHas3DInfo.
  if width == -1 or length == -1 or height == -1:
    return [-1000, -1000, -1000], [-1, -1, -1], -10

  # Convert our velodyne bbox rotation back to camera. Reverse the direction and
  # rotate by np.pi/2. See http://www.cvlibs.net/datasets/kitti/setup.php.
  rotation_y = rot + np.pi / 2.
  rotation_y = -rotation_y
  rotation_y = np.mod(rotation_y, 2 * np.pi)
  rotation_y = np.where(rotation_y >= np.pi, rotation_y - 2 * np.pi, rotation_y)

  # Reposition z so that it is at the bottom of the object.
  if height > 0:
    z -= height / 2.

  camera_xyz = np.dot(velo_to_cam_transform, np.asarray([x, y, z, 1.]))
  location = camera_xyz.tolist()[:3]
  dimensions = height, width, length

  return location, dimensions, rotation_y 
開發者ID:tensorflow,項目名稱:lingvo,代碼行數:26,代碼來源:kitti_data.py

示例15: preprocess

# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import mod [as 別名]
def preprocess(self, data):
        # random hue and saturation
        data = cv2.cvtColor(data, cv2.COLOR_RGB2HSV);
        delta = (np.random.random() * 2 - 1) * 0.2
        data[:, :, 0] = np.mod(data[:,:,0] + (delta * 360 + 360.), 360.)

        delta_sature = np.random.random() + 0.5
        data[:, :, 1] *= delta_sature
        data[:,:, 1] = np.maximum( np.minimum(data[:,:,1], 1), 0 )
        data = cv2.cvtColor(data, cv2.COLOR_HSV2RGB)

        # adjust brightness
        delta = (np.random.random() * 2 - 1) * 0.3
        data += delta

        # adjust contrast
        mean = data.mean(axis=2, keepdims=True)
        data = (data - mean) * (np.random.random() + 0.5) + mean
        data = np.minimum(np.maximum(data, 0), 1)
        return data 
開發者ID:princeton-vl,項目名稱:pytorch_stacked_hourglass,代碼行數:22,代碼來源:dp.py


注:本文中的numpy.mod方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。