Python numpy.fmod() 使用实例

The following are code examples for showing how to use . They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don’t like. You can also save this page to your account.

Example 1

def M(self):
        """Returns the :math:`M` matrix of integers that determine points at which the
        functions are sampled in the unit cell.

        Examples:
            For `S = [2, 2, 1]`, the returned matrix is:

        .. code-block:: python

            np.ndarray([[0,0,0],
                        [1,0,0],
                        [0,1,0],
                        [1,1,0]], dtype=int)
        """
        if self._M is None:
            ms = np.arange(np.prod(self.S, dtype=int))
            m1 = np.fmod(ms, self.S[0])
            m2 = np.fmod(np.floor(ms/self.S[0]), self.S[1])
            m3 = np.fmod(np.floor(ms/(self.S[0]*self.S[1])), self.S[2])
            #Make sure we explicitly use an integer array; it's faster.
            self._M = np.asarray(np.vstack((m1, m2, m3)).T, dtype=int)
        return self._M 

Example 2

def setRotation(self, rot, smallangle=True):
        '''
        Rotation angle in degrees
        '''
        rad = np.deg2rad(rot)
        if smallangle:
            # bring rad close to zero.
            rad = np.fmod(rad, 2.*pi)
            if rad > pi:
                rad -= 2.*pi
            if rad < -pi:
                rad += 2.*pi
            self.T = [ 0., -rad, rad, 0. ]
        else:
            cr = np.cos(rad)
            sr = np.sin(rad)
            self.T = [ cr - 1, -sr, sr, cr - 1 ] 

Example 3

def single_spectrogram(inseq,fs,wlen,h,imag=False):
    """
        imag: Return Imaginary Data of the STFT on True 
    """
    NFFT = int(2**(np.ceil(np.log2(wlen)))) 
    K = np.sum(hamming(wlen, False))/wlen
    raw_data = inseq.astype('float32')
    raw_data = raw_data/np.amax(np.absolute(raw_data))
    stft_data,_,_ = STFT(raw_data,wlen,h,NFFT,fs)
    s = np.absolute(stft_data)/wlen/K;
    if np.fmod(NFFT,2):
        s[1:,:] *=2
    else:
        s[1:-2] *=2        
    real_data = np.transpose(20*np.log10(s + 10**-6)).astype(np.float32)
    if imag:
        imag_data = np.angle(stft_data).astype(np.float32)
        return real_data,imag_data 
    return real_data 

Example 4

def dataistft(realdata,imgdata,fs,wlen,h):
    nfft = int(2**(np.ceil(np.log2(wlen))))

    K = np.sum(hamming(wlen, False))/wlen

    realdata = np.power(20,realdata/20) - 1e-6
    if np.fmod(nfft,2):
        realdata[1:-1,:] /=2 
    else:
        realdata[1:-2,:] /=2 
    realdata *= wlen*K
    prewav = realdata.transpose()*np.exp(1j*imgdata) 
    istft_data,_ = ISTFT(prewav, h, nfft, fs)
    max_dt = np.abs(istft_data).max()
    istft_data /= max_dt  
    return istft_data 

Example 5

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
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 6

def func(func, minkind=None, maxkind=None):
    @ophelper
    def function(*args):
        if allConstantNodes(args):
            return ConstantNode(func(*[x.value for x in args]))
        kind = commonKind(args)
        if kind in ('int', 'long'):
            # Exception for following NumPy casting rules
            #FIXME: this is not always desirable. The following
            # functions which return ints (for int inputs) on numpy
            # but not on numexpr: copy, abs, fmod, ones_like
            kind = 'double'
        else:
            # Apply regular casting rules
            if minkind and kind_rank.index(minkind) > kind_rank.index(kind):
                kind = minkind
            if maxkind and kind_rank.index(maxkind) < kind_rank.index(kind):
                kind = maxkind
        return FuncNode(func.__name__, args, kind)

    return function 

Example 7

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
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 8

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
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 9

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
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 10

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
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 11

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
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 12

def fmodulo(x1: Number = 1.0, x2: Number = 1.0) -> Float:
    return np.fmod(x1, x2) 

Example 13

def calculate_bin_indices(
            self, tstart, tsamp, data_size):
        """Calculate the bin that each time sample should be
            added to
        @param[in] tstart Time of the first element (s)
        @param[in] tsamp Difference between the times of
            consecutive elements (s)
        @param[in] data_size Number of elements
        @return Which bin each sample is folded into
        """
        arrival_time = tstart + tsamp * np.arange(data_size)
        phase = np.fmod(arrival_time, self.period)
        return np.floor(phase / self.period * self.bins).astype(int) 

Example 14

def dihedral_angle(a, b, c, d):
    """
    Calculate the dihedral angle between 4 vectors,
    representing 4 connected points. The angle is in range [-180, 180].

    @param a: the four points that define the dihedral angle
    @type a: array

    @return: angle in [-180, 180]
    """
    
    v = b - c
    m = numpy.cross((a - b), v)
    m /= norm(m)
    n = numpy.cross((d - c), v)
    n /= norm(n)

    c = numpy.dot(m, n)
    s = numpy.dot(numpy.cross(n, m), v) / norm(v)
    
    angle = math.degrees(math.atan2(s, c))        

    if angle > 0:
        return numpy.fmod(angle + 180, 360) - 180
    else:
        return numpy.fmod(angle - 180, 360) + 180 

Example 15

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
            ]

        # These functions still return NotImplemented. Will be fixed in
        # future.
        # bad = [np.greater, np.greater_equal, np.less, np.less_equal, np.not_equal]

        a = np.array('1')
        b = 1
        for f in binary_funcs:
            assert_raises(TypeError, f, a, b) 

Example 16

def compute_zero_padding_values(self, number):
        """During zero padding, we want to fill zeros before and after signal.
        This function computes the number of zeros"""

        number_of_zeros_before_signal = np.floor(number / 2)
        if np.fmod(number, 2) == 1:
            number_of_zeros_after_signal = number_of_zeros_before_signal + 1
        else:
            number_of_zeros_after_signal = number_of_zeros_before_signal

        return number_of_zeros_before_signal, number_of_zeros_after_signal 

Example 17

def wav_to_image(filename, wlen, mindata, maxdata, save=False, name_save=None, ):
	h = wlen/4
	K = np.sum(hamming(wlen, False))/wlen

	nfft = int(2**(np.ceil(np.log2(wlen))))
	Fs, data_seq = wavfile.read(filename) 
	raw_data = data_seq.astype('float32')
	max_dt = np.amax(np.absolute(raw_data))
	raw_data = raw_data/max_dt
	stft_data,_,_ = STFT(raw_data,wlen,h,nfft,Fs)
	s = abs(stft_data)/wlen/K;
	if np.fmod(nfft,2):
	    s[1:,:] *=2
	else:
	    s[1:-2] *=2        
	data_temp = 20*np.log10(s + 10**-6)
	outdata = data_temp.transpose()

	"""Scaling"""
	mindata = np.amin(outdata, axis=0, keepdims = True)
	maxdata = np.amax(outdata, axis=0, keepdims = True)
	outdata -=mindata
	outdata /=(maxdata-mindata)
	outdata *=0.8
	outdata +=0.1
	figmin = np.zeros((5,outdata.shape[1]))
	figmax = np.ones((5,outdata.shape[1]))
	outdata = np.concatenate((outdata,figmin,figmax), axis=0)

	dpi = 96
	a = float(outdata.shape[0])/dpi
	b = float(outdata.shape[1])/dpi

	f = plt.figure(figsize=(b,a), dpi=dpi)
	f.figimage(outdata)
	if save:
		f.savefig(name_save, dpi=f.dpi)
	return f 

Example 18

def ISTFT(data, h, nfft, fs):
    # function: [x, t] = istft(stft, h, nfft, fs)
    # stft - STFT matrix (only unique points, time across columns, freq across rows)
    # h - hop size
    # nfft - number of FFT points
    # fs - sampling frequency, Hz
    # x - signal in the time domain
    # t - time vector, s

    # estimate the length of the signal
    coln = data.shape[1]
    xlen = nfft + (coln-1)*h
    x = np.zeros((xlen,))

    # form a periodic hamming window
    win = hamming(nfft, False)

    # perform IFFT and weighted-OLA
    if np.fmod(nfft,2):
        lst_idx = -1
    else:
        lst_idx = -2

    for b in range (0, h*(coln-1),h):
        # extract FFT points
        X = data[:,1+b/h] 
        X = np.concatenate((X, np.conjugate(X[lst_idx:0:-1])))

        # IFFT
        xprim = np.real(np.fft.ifft(X))

        # weighted-OLA
        x[b:b+nfft] = x[b:b+nfft] + np.transpose(xprim*win)
    
    W0 = np.sum(win*win)
    x *= h/W0
    # calculate the time vector
    actxlen = x.shape[0]
    t = np.arange(0,actxlen-1,dtype=np.float32)/fs
    return x, t 

Example 19

def constrainAngle( self, x):
    x = np.fmod( x+180, 360)
    if x < 0:
      x+= 360
    return x-180 

Example 20

def constrainAngle( self, x):
    x = np.fmod( x+180, 360)
    if x < 0:
      x+= 360
    return x-180 

Example 21

def constrainAngle( self, x):
    x = np.fmod( x+180, 360)
    if x < 0:
      x+= 360
    return x-180 

Example 22

def normaliseAngle(value):
    angle = np.fmod(value, 2 * np.pi);

    if (angle <= -np.pi):
        angle += np.pi * 2;

    if (angle > np.pi):
        angle -= 2 * np.pi;

    return angle; 

Example 23

def wrap1(x):
    return numpy.fmod(x + 1 - numpy.ceil(x), 1) 

Example 24

def clamp_longitude( lons ):
    lons = np.asarray(lons)
    lons = np.fmod(lons, 360.)
    lons[np.where(lons < -180.)] += 360.
    lons[np.where(lons > 180.)] -= 360.
    return lons 

Example 25

def visiting(self, x, step, temperature):
        dim = x.size
        if step < dim:
            # Changing all coordinates with a new visting value
            visits = np.array([self.visit_fn(
                temperature) for _ in range(dim)])
            upper_sample = self.rs.random_sample()
            lower_sample = self.rs.random_sample()
            visits[visits > self.tail_limit] = self.tail_limit * upper_sample
            visits[visits < -self.tail_limit] = -self.tail_limit * lower_sample
            x_visit = visits + x
            a = x_visit - self.lower
            b = np.fmod(a, self.b_range) + self.b_range
            x_visit = np.fmod(b, self.b_range) + self.lower
            x_visit[np.fabs(
                x_visit - self.lower) < self.min_visit_bound] += 1.e-10
        else:
            # Changing only one coordinate at a time based on Markov chain step
            x_visit = np.copy(x)
            visit = self.visit_fn(temperature)
            if visit > self.tail_limit:
                visit = self.tail_limit * self.rs.random_sample()
            elif visit < -self.tail_limit:
                visit = -self.tail_limit * self.rs.random_sample()
            index = step - dim
            x_visit[index] = visit + x[index]
            a = x_visit[index] - self.lower[index]
            b = np.fmod(a, self.b_range[index]) + self.b_range[index]
            x_visit[index] = np.fmod(b, self.b_range[
                index]) + self.lower[index]
            if np.fabs(x_visit[index] - self.lower[
                    index]) < self.min_visit_bound:
                x_visit[index] += self.min_visit_bound
        return x_visit 

Example 26

def testFloat(self):
    x = [0.5, 0.7, 0.3]
    for dtype in [np.float32, np.double]:
      # Test scalar and vector versions.
      for denom in [x[0], [x[0]] * 3]:
        x_np = np.array(x, dtype=dtype)
        with self.test_session():
          x_tf = constant_op.constant(x_np, shape=x_np.shape)
          y_tf = math_ops.mod(x_tf, denom)
          y_tf_np = y_tf.eval()
          y_np = np.fmod(x_np, denom)
        self.assertAllClose(y_tf_np, y_np, atol=1e-2) 
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注