numpy.floor

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

172 Examples 7

Example 1

Project: mavelous Source File: mp_elevation.py
Function: get_elevation
    def GetElevation(self, latitude, longitude):
        '''Returns the altitude (m ASL) of a given lat/long pair'''
        if latitude == 0 or longitude == 0:
            return 0
        if self.database == 'srtm':
            TileID = (numpy.floor(latitude), numpy.floor(longitude))
            if TileID in self.tileDict:
                alt = self.tileDict[TileID].getAltitudeFromLatLon(latitude, longitude)
            else:
                tile = self.downloader.getTile(numpy.floor(latitude), numpy.floor(longitude))
                if tile == 0:
                    return -1
                self.tileDict[TileID] = tile
                alt = tile.getAltitudeFromLatLon(latitude, longitude)
        if self.database == 'geoscience':
             alt = self.mappy.getAltitudeAtPoint(latitude, longitude)
        return alt

Example 2

Project: dash-hack Source File: camera_calibration.py
Function: texture
def texture(xy):
    x,y = xy
    xa = numpy.floor(x * 512)
    ya = numpy.floor(y * 512)
    a = (512 * ya) + xa
    safe = (0 <= x) & (0 <= y) & (x < 1) & (y < 1)
    if 0:
        a = numpy.where(safe, a, 0).astype(numpy.int)
        return numpy.where(safe, numpy.take(lena, a), 0.0)
    else:
        xi = numpy.floor(x * 11).astype(numpy.int)
        yi = numpy.floor(y * 11).astype(numpy.int)
        inside = (1 <= xi) & (xi < 10) & (2 <= yi) & (yi < 9)
        checker = (xi & 1) ^ (yi & 1)
        final = numpy.where(inside, checker, 1.0)
        return numpy.where(safe, final, 0.5)

Example 3

Project: GPflow Source File: test_custom_op.py
def np_vec_to_tri(vec):
    ml = None
    for svec in vec:
        n = int(np.floor((vec.shape[1] * 8 + 1) ** 0.5 / 2.0 - 0.5))
        m = np.zeros((n, n))
        m[np.tril_indices(n, 0)] = svec
        ml = m[:, :, None] if ml is None else np.dstack((ml, m))
    return np.rollaxis(ml, 2, 0)

Example 4

Project: facerec Source File: feature.py
    def spatially_enhanced_histogram(self, X):
        # calculate the LBP image
        L = self.lbp_operator(X)
        # calculate the grid geometry
        lbp_height, lbp_width = L.shape
        grid_rows, grid_cols = self.sz
        py = int(np.floor(lbp_height/grid_rows))
        px = int(np.floor(lbp_width/grid_cols))
        E = []
        for row in range(0,grid_rows):
            for col in range(0,grid_cols):
                C = L[row*py:(row+1)*py,col*px:(col+1)*px]
                H = np.histogram(C, bins=2**self.lbp_operator.neighbors, range=(0, 2**self.lbp_operator.neighbors), normed=True)[0]
                # probably useful to apply a mapping?
                E.extend(H)
        return np.asarray(E)

Example 5

Project: iGAN Source File: gui_vis.py
Function: mouse_press_event
    def mousePressEvent(self, event):
        pos = event.pos()
        if event.button() == Qt.LeftButton:
            x_select = np.floor(pos.x() / float(self.width))
            y_select = np.floor(pos.y() / float(self.width))
            new_id = y_select * self.grid_size[0] + x_select
            print('pos=(%d,%d) (x,y)=(%d,%d) image_id=%d' % (int(pos.x()), int(pos.y()), x_select, y_select, new_id))
            if new_id != self.select_id:
                self.select_id = new_id
                self.update_vis()
                self.update()
                self.emit(SIGNAL('update_image_id'), self.select_id)

Example 6

Project: CostSensitiveClassification Source File: regression.py
Function: predict
    def predict(self, X, cut_point=0.5):
        """Predicted class.

        Parameters
        ----------
        X : array-like, shape = [n_samples, n_features]

        Returns
        -------
        T : array-like, shape = [n_samples]
            Returns the prediction of the sample..
        """
        return np.floor(self.predict_proba(X)[:, 1] + (1 - cut_point))

Example 7

Project: QSTK Source File: tradesim.py
def _nearest_interger(f_x):

    """
    @summary Return the nearest integer to the float number
    @param x: single float number
    @return: nearest integer to x
    """
    if f_x >= 0:
        return np.floor(f_x)
    else :
        return np.ceil(f_x)

Example 8

Project: volumina Source File: patchAccessor.py
    def getPatchBounds(self, blockNum, overlap = 0):
        rest = blockNum % (self._cX*self._cY)
        y = int(numpy.floor(rest / self._cX))
        x = rest % self._cX

        startx = max(0, x*self._blockSize - overlap)
        endx = min(self.size_x, (x+1)*self._blockSize + overlap)
        if x+1 >= self._cX:
            endx = self.size_x

        starty = max(0, y*self._blockSize - overlap)
        endy = min(self.size_y, (y+1)*self._blockSize + overlap)
        if y+1 >= self._cY:
            endy = self.size_y

        return [startx,endx,starty,endy]

Example 9

Project: pytides Source File: astro.py
Function: jd
def JD(t):
	Y, M = t.year, t.month
	D = (
		t.day
		+ t.hour / (24.0)
		+ t.minute / (24.0*60.0)
		+ t.second / (24.0*60.0*60.0)
		+ t.microsecond / (24.0 * 60.0 * 60.0 * 1e6)
	)
	if M <= 2:
		Y = Y - 1
		M = M + 12
	A = np.floor(Y / 100.0)
	B = 2 - A + np.floor(A / 4.0)
	return np.floor(365.25*(Y+4716)) + np.floor(30.6001*(M+1)) + D + B - 1524.5

Example 10

Project: kwiklib Source File: selection.py
def slice_to_indices(indices, stop=None, lenindices=None, keys=None):
    start, step = (indices.start or 0), (indices.step or 1)
    if not stop:
        assert lenindices is not None
        # Infer stop such that indices and values have the same size.
        stop = np.floor(start + step*lenindices)
    indices = np.arange(start, stop, step).astype(np.int32)
    if keys is not None:
        indices = np.array(keys)[indices]
    if not lenindices:
        lenindices = len(indices)
    assert len(indices) == lenindices
    return indices

Example 11

Project: PoissonSamplingGenerator Source File: poisson.py
Function: cache_sort
    def cache_sort(self, points, sorting_buckets):
        if sorting_buckets < 1:
            return points
        if self.num_dim == 3:
            points_discretized = np.floor(points * [sorting_buckets,-sorting_buckets, sorting_buckets])
            indices_cache_space = np.array(points_discretized[:,2] * sorting_buckets * 4 + points_discretized[:,1] * sorting_buckets * 2 + points_discretized[:,0])
            points = points[np.argsort(indices_cache_space)]
        elif self.num_dim == 2:
            points_discretized = np.floor(points * [sorting_buckets,-sorting_buckets])
            indices_cache_space = np.array(points_discretized[:,1] * sorting_buckets * 2 + points_discretized[:,0])
            points = points[np.argsort(indices_cache_space)]        
        else:
            points_discretized = np.floor(points * [sorting_buckets])
            indices_cache_space = np.array(points_discretized[:,0])
            points = points[np.argsort(indices_cache_space)]
        return points

Example 12

Project: CyLP Source File: GomoryCutGenerator.py
Function: is_int
def isInt(x):
    '''
    Return True if x is an integer, or if x is a numpy array
    with all integer elements, False otherwise
    '''
    if isinstance(x, (int, long, float)):
        return abs(math.floor(x) - x) < epsilon
    return (np.abs(np.floor(x) - x) < epsilon).all()

Example 13

Project: convolupy Source File: planes.py
    @staticmethod
    def _offsets_from_filter_size(fsize):
        """
        Given filter size, calculate the offsets at the borders of 
        the input image.
        """
        return [np.floor(dim / 2) for dim in fsize]

Example 14

Project: kaggle-galaxies Source File: load_data.py
def hms(seconds):
    seconds = np.floor(seconds)
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)

    return "%02d:%02d:%02d" % (hours, minutes, seconds)

Example 15

Project: reseg Source File: helper_dataset.py
Function: gaussian_filter
def gaussian_filter(kernel_shape):

    x = zeros((kernel_shape, kernel_shape), dtype='float32')

    def gauss(x, y, sigma=2.0):
        Z = 2 * pi * sigma**2
        return 1./Z * exp(-(x**2 + y**2) / (2. * sigma**2))

    mid = floor(kernel_shape/ 2.)
    for i in xrange(0,kernel_shape):
        for j in xrange(0,kernel_shape):
            x[i, j] = gauss(i-mid, j-mid)

    return x / sum(x)

Example 16

Project: galry Source File: grid_processor.py
Function: get_ticks
def get_ticks(x0, x1):
    nticks = NTICKS
    r = nicenum(x1 - x0, False)
    d = nicenum(r / (nticks - 1), True)
    g0 = np.floor(x0 / d) * d
    g1 = np.ceil(x1 / d) * d
    nfrac = int(max(-np.floor(np.log10(d)), 0))
    return np.arange(g0, g1 + .5 * d, d), nfrac

Example 17

Project: PySAR Source File: multi_looking.py
def multilook(ifg,lksy,lksx):
    rows,cols=ifg.shape
    lksx = int(lksx)
    lksy = int(lksy)
    rows_lowres=int(np.floor(rows/lksy))
    cols_lowres=int(np.floor(cols/lksx))
    #thr = np.floor(lksx*lksy/2)
    ifg_Clowres=np.zeros((rows,cols_lowres))
    ifg_lowres =np.zeros((rows_lowres,cols_lowres))
    
    for c in range(int(cols_lowres)):  ifg_Clowres[:,c]=np.sum(ifg[:,(c)*lksx:(c+1)*lksx],1)
    for r in range(int(rows_lowres)):  ifg_lowres[r,:] =np.sum(ifg_Clowres[(r)*lksy:(r+1)*lksy,:],0)
    #for c in range(lksx):   ifg_Clowres = ifg_Clowres +         ifg[:,range(c,cols_lowres*lksx,lksx)]
    #for r in range(lksy):   ifg_lowres  = ifg_lowres  + ifg_Clowres[  range(r,rows_lowres*lksy,lksy),:]
    ifg_lowres=ifg_lowres/(lksy*lksx) 

    return ifg_lowres

Example 18

Project: anna Source File: layers.py
Function: get_output_shape
    def get_output_shape(self):
        output_shape = list(self.input_layer.get_output_shape())
        if self.ignore_border:
            output_shape[-1] = int(numpy.floor(float(output_shape[-1]) /
                                               self.ds_factor))
        else:
            output_shape[-1] = int(numpy.ceil(float(output_shape[-1]) /
                                              self.ds_factor))
        return tuple(output_shape)

Example 19

Project: kaggle_diabetic_retinopathy Source File: utils.py
def padtosquare(im):
    w, l = im.shape

    if w < l:
        pad_size = (l - w) / 2.0
        im_new = skimage.util.pad(im, pad_width=((int(np.floor(pad_size)),
                                                  int(np.ceil(pad_size))),
                                                 (0, 0)),
                                  mode='constant',
                                  constant_values=(1, 1))
    else:
        pad_size = (w - l) / 2.0
        im_new = skimage.util.pad(im, pad_width=((0, 0),
                                                 (int(np.floor(pad_size)),
                                                  int(np.ceil(pad_size)))),
                                  mode='constant',
                                  constant_values=(1, 1))

    return im_new

Example 20

Project: zipline Source File: position.py
    def earn_stock_dividend(self, stock_dividend):
        """
        Register the number of shares we held at this dividend's ex date so
        that we can pay out the correct amount on the dividend's pay date.
        """
        return {
            'payment_asset': stock_dividend.payment_asset,
            'share_count': np.floor(
                self.amount * float(stock_dividend.ratio)
            )
        }

Example 21

Project: klustaviewa Source File: traceview.py
Function: get_ticks
    def get_ticks(self, x0, x1):
        x0 = self.interaction_manager.get_processor('viewport').normalizer.unnormalize_x(x0)
        x1 = self.interaction_manager.get_processor('viewport').normalizer.unnormalize_x(x1)
        r = self.nicenum(x1 - x0 - 1e-6, False)
        d = self.nicenum(r / (self.parent.data_manager.nticks - 1), True)
        g0 = np.floor(x0 / d) * d
        g1 = np.ceil(x1 / d) * d
        nfrac = int(max(-np.floor(np.log10(d)), 0))
        return np.arange(g0, g1 + .5 * d, d), nfrac

Example 22

Project: AlephNull Source File: test_algorithms.py
Function: handle_data
    def handle_data(self, data):
        if self.target_shares == 0:
            assert 0 not in self.portfolio.positions
            self.order(0, 10)
            self.target_shares = 10
            return
        else:
            assert self.portfolio.positions[0]['amount'] == \
                self.target_shares, "Orders not filled immediately."
            assert self.portfolio.positions[0]['last_sale_price'] == \
                data[0].price, "Orders not filled at current price."

        self.order_percent(0, .001)
        self.target_shares += np.floor((.001 *
                                        self.portfolio.portfolio_value)
                                       / data[0].price)

Example 23

Project: chemlab Source File: one.py
def A_array(l1,l2,PA,PB,CP,g):
    """
    THO eq. 2.18 and 3.1

    >>> A_array(0,0,0,0,0,1)
    [1.0]
    >>> A_array(0,1,1,1,1,1)
    [1.0, -1.0]
    >>> A_array(1,1,1,1,1,1)
    [1.5, -2.5, 1.0]
    """
    Imax = l1+l2+1
    A = [0]*Imax
    for i in range(Imax):
        for r in range(int(floor(i/2)+1)):
            for u in range(int(floor((i-2*r)/2)+1)):
                I = i-2*r-u
                A[I] = A[I] + A_term(i,r,u,l1,l2,PA,PB,CP,g)
    return A

Example 24

Project: tfdeploy Source File: tfdeploy.py
Function: floor
@Operation.factory
def Floor(a):
    """
    Floor round op.
    """
    return np.floor(a),

Example 25

Project: abstract_rendering Source File: fast_project.py
def _project_element(viewxform, inputs, output):
    tx, ty, sx, sy = viewxform
    x, y, w, h = inputs
    x2 = x + w
    y2 = y + h
    np.floor(sx * x + tx, out=output[0,:])
    np.floor(sy * y + ty, out=output[1,:])
    np.floor(sx * x2 + tx, out=output[2,:])
    np.floor(sy * y2 + ty, out=output[3,:])

Example 26

Project: SimpleCV2 Source File: TemporalColorTracker.py
    def _findSteadyState(self,windowSzPrct=0.05):
        # slide a window across each of the signals
        # find where the std dev of the window is minimal
        # this is the steady state (e.g. where the
        # assembly line has nothing moving)
        # save the mean and sd of this value
        # as a tuple in the steadyStateDict
        self._steadyState = {}
        for key in self.data.keys():
            wndwSz = int(np.floor(windowSzPrct*len(self.data[key])))
            signal = self.data[key]
            # slide the window and get the std
            data = [np.std(signal[i:i+wndwSz]) for i in range(0,len(signal)-wndwSz)]
            # find the first spot where sd is minimal
            index = np.where(data==np.min(data))[0][0]
            # find the mean for the window
            mean = np.mean(signal[index:index+wndwSz])
            self._steadyState[key]=(mean,data[index])

Example 27

Project: pydem Source File: my_types.py
    def _get_lon_dms(self):
        deg = np.floor(abs(self.lon))
        min = np.floor((abs(self.lon) - deg) * 60.0)
        sec = np.round((abs(self.lon) - deg - min / 60.0) * 3600.0,
                       4)  # round to 4 decimal places.
        return (np.sign(self.lon) * deg, min, sec)

Example 28

Project: PyFunt Source File: spatial_up_sampling_nearest.py
Function: init
    def __init__(self, scale):
        super(SpatialUpSamplingNearest, self).__init__()
        self.scale_factor = scale
        if self.scale_factor < 1:
            raise Exception('scale_factor must be greater than 1')
        if np.floor(self.scale_factor) != self.scale_factor:
            raise Exception('scale_factor must be integer')

Example 29

Project: bdol-ml Source File: MLP.py
  def dpp_dropout(self, dropoutProb):
    if dropoutProb == 0:
      return

    W_n = self.W[0:-1, :]
    L = (W_n.dot(W_n.T))**2
    D, V = dpp.decompose_kernel(L)
    
    k = int(np.floor((1-dropoutProb)*self.W.shape[0]))
    J = dpp.sample_k(k, D, V)
    d_idx = np.ones((self.W.shape[0]-1, 1))
    d_idx[J.astype(int)] = 0
  
    self.prevZ[:, 0:-1] = self.prevZ[:, 0:-1]*d_idx.T

Example 30

Project: CostSensitiveClassification Source File: directcost.py
Function: predict
    def predict(self, y_prob):
        """ Calculate the prediction using the ThresholdingOptimization.

        Parameters
        ----------
        y_prob : array-like of shape = [n_samples, 2]
            Predicted probabilities.

        Returns
        -------
        y_pred : array-like of shape = [n_samples]
            Predicted class
        """
        y_pred = np.floor(y_prob[:, 1] + (1 - self.threshold_))

        return y_pred

Example 31

Project: attention-lvcsr Source File: test_sp2.py
Function: test_op
    def test_op(self):
        n = tensor.lscalar()
        f = theano.function([self.p, n], multinomial(n, self.p))

        _n = 5
        tested = f(self._p, _n)
        assert tested.shape == self._p.shape
        assert numpy.allclose(numpy.floor(tested.todense()), tested.todense())
        assert tested[2, 1] == _n

        n = tensor.lvector()
        f = theano.function([self.p, n], multinomial(n, self.p))

        _n = numpy.asarray([1, 2, 3, 4], dtype='int64')
        tested = f(self._p, _n)
        assert tested.shape == self._p.shape
        assert numpy.allclose(numpy.floor(tested.todense()), tested.todense())
        assert tested[2, 1] == _n[2]

Example 32

Project: bci-challenge-ner-2015 Source File: classif.py
def baggingIterator(opts,users):
    mdls = opts['bagging']['models']
    bag_size = 1-opts['bagging']['bag_size']
    bag_size = numpy.floor(bag_size*len(users))
    if bag_size == 0:
        return [[u] for u in users]
    else:
        return [numpy.random.choice(users,size=bag_size,replace=False) for i in range(mdls)]

Example 33

Project: deep_recommend_system Source File: poisson_test.py
  def testPoissonMode(self):
    with self.test_session():
      lam_v = [1.0, 3.0, 2.5, 3.2, 1.1, 0.05]
      poisson = tf.contrib.distributions.Poisson(lam=lam_v)
      self.assertEqual(poisson.mode().get_shape(), (6,))
      self.assertAllClose(poisson.mode().eval(), np.floor(lam_v))

Example 34

Project: pycortex Source File: mayavi_aligner.py
    @on_trait_change("epi_filter, filter_strength")
    def update_epifilter(self):
        if self.epi_filter is None:
            self.epi = self.epi_orig.copy()
        elif self.epi_filter == "median":
            fstr = np.floor(self.filter_strength / 2)*2+1
            self.epi = volume.detrend_median(self.epi_orig.T, fstr).T
        elif self.epi_filter == "gradient":
            self.epi = volume.detrend_gradient(self.epi_orig.T, self.filter_strength).T
        
        self.update_brightness()

Example 35

Project: python-oceans Source File: RPSstuff.py
def s2hms(secs):
    """
    Converts seconds to integer hour,minute,seconds
    Usage: hour, min, sec = s2hms(secs)

    Example
    -------
    >>> s2hms(3600 + 60 + 1)
    (1.0, 1.0, 1)

    """
    hr = np.floor(secs / 3600)
    mi = np.floor(np.remainder(secs, 3600) / 60)
    sc = np.round(np.remainder(secs, 60))

    return hr, mi, sc

Example 36

Project: radiotool Source File: track.py
    def loudest_time(self, start=0, duration=0):
        """Find the loudest time in the window given by start and duration
        Returns frame number in context of entire track, not just the window.

        :param integer start: Start frame
        :param integer duration: Number of frames to consider from start
        :returns: Frame number of loudest frame
        :rtype: integer
        """
        if duration == 0:
            duration = self.sound.nframes
        self.current_frame = start
        arr = self.read_frames(duration)
        # get the frame of the maximum amplitude
        # different names for the same thing...
        # max_amp_sample = a.argmax(axis=0)[a.max(axis=0).argmax()]
        max_amp_sample = int(np.floor(arr.argmax()/2)) + start
        return max_amp_sample

Example 37

Project: pyquante2 Source File: one.py
def overlap1d(l1,l2,PAx,PBx,gamma):
    """
    The one-dimensional component of the overlap integral. Taken from THO eq. 2.12
    >>> isclose(overlap1d(0,0,0,0,1),1.0)
    True
    """
    total = 0
    for i in range(1+int(floor(0.5*(l1+l2)))):
        total += binomial_prefactor(2*i,l1,l2,PAx,PBx)* \
                 fact2(2*i-1)/pow(2*gamma,i)
    return total

Example 38

Project: refinery Source File: LearnAlg.py
  def isFirstBatch(self, lapFrac):
    ''' Returns True/False for whether given batch is last (for current lap)
    '''
    if self.lapFracInc == 1.0: # Special case, nBatch == 1
      isFirstBatch = True
    else:
      isFirstBatch = np.allclose(lapFrac - np.floor(lapFrac), self.lapFracInc)
    return isFirstBatch

Example 39

Project: Theano-Lights Source File: toolbox.py
Function: conv
def conv(X, w, b=None):
    # z = dnn_conv(X, w, border_mode=int(np.floor(w.get_value().shape[-1]/2.)))
    s = int(np.floor(w.get_value().shape[-1]/2.))
    z = conv2d(X, w, border_mode='full')[:, :, s:-s, s:-s]
    if b is not None:
        z += b.dimshuffle('x', 0, 'x', 'x')
    return z

Example 40

Project: pyvision Source File: Rect.py
Function: as_int
    def asInt(self):
        '''
        Return a dictionary representing the rectangle with integer values
        '''
        x = int(np.floor(self.x))
        y = int(np.floor(self.y))
        w = int(np.floor(self.w))
        h = int(np.floor(self.h))
        return {'x':x,'y':y,'w':w,'h':h}

Example 41

Project: scikit-datasmooth Source File: regularsmooth.py
    def _submatrix_of_integration_matrix(self, B):
        """Return integration matrix whose size matches derivative matrix."""
        d = self.d
        start = int(np.floor(d/2))
        end = -start if is_even(d) else -(start + 1)
        b_slice = slice(start, end)
        return B[b_slice, b_slice]

Example 42

Project: GNSS-DSP-tools Source File: nco.py
Function: mix
@jit(nopython=True,locals={'dp': numba.int64, 'df': numba.int64})
def mix_(x,f,p,tab):
  n = len(x)
  dp = int(np.floor(p*NT*(1<<50)))
  df = int(np.floor(f*NT*(1<<50)))
  for i in range(n):
    idx = dp>>50
    x[i] *= tab[idx&(NT-1)]
    dp += df

Example 43

Project: MCEdit-Unified Source File: clone.py
    def _draggingOrigin(self):
        dragPos = map(int, map(numpy.floor, self.positionOnDraggingPlane()))
        delta = map(lambda s, e: e - int(numpy.floor(s)), self.draggingStartPoint, dragPos)

        if self.snapCloneKey == 1:
            ad = map(abs, delta)
            midx = ad.index(max(ad))
            d = [0, 0, 0]
            d[midx] = delta[midx]
            dragY = self.draggingFace >> 1
            d[dragY] = delta[dragY]
            delta = d

        p = self.destPoint + delta
        if self.chunkAlign:
            p = [i // 16 * 16 for i in p]
        return Vector(*p)

Example 44

Project: FreqShow Source File: views.py
	def render_spectrogram(self, screen):
		# Grab spectrogram data.
		freqs = self.model.get_data()
		# Scale frequency values to fit on the screen based on the min and max
		# intensity values.
		x, y, width, height = screen.get_rect()
		freqs = height-np.floor(((freqs-self.model.min_intensity)/self.model.range)*height)
		# Render frequency graph.
		screen.fill(freqshow.MAIN_BG)
		# Draw line segments to join each FFT result bin.
		ylast = freqs[0]
		for i in range(1, width):
			y = freqs[i]
			pygame.draw.line(screen, freqshow.INSTANT_LINE, (i-1, ylast), (i, y))
			ylast = y

Example 45

Project: scipy Source File: go_funcs_C.py
Function: fun
    def fun(self, x, *args):
        self.nfev += 1

        d = [1., 1000., 10., 100.]
        r = 0
        for j in range(4):
            zj = floor(abs(x[j] / 0.2) + 0.49999) * sign(x[j]) * 0.2
            if abs(x[j] - zj) < 0.05:
                r += 0.15 * ((zj - 0.05 * sign(zj)) ** 2) * d[j]
            else:
                r += d[j] * x[j] * x[j]
        return r

Example 46

Project: GNSS-DSP-tools Source File: p.py
Function: code
def code(prn,chips,frac,incr,n):
  len = np.int(np.floor(n*incr)+5)
  c = p_code(prn,chips,len).astype('int')
  idx = frac + incr*np.arange(n)
  idx = np.floor(idx).astype('int')
  x = c[idx]
  return 1.0 - 2.0*x

Example 47

Project: python-oceans Source File: RPSstuff.py
def h2hms(hours):
    """
    Converts hours to hours, minutes, and seconds.

    Example
    -------
    >>> h2hms(12.51)
    (12.0, 30.0, 36.0)

    """
    hour = np.floor(hours)
    mins = np.remainder(hours, 1.) * 60.
    mn = np.floor(mins)
    secs = np.round(np.remainder(mins, 1.) * 60.)
    return hour, mn, secs

Example 48

Project: attention-lvcsr Source File: test_sp2.py
Function: test_op
    def test_op(self):
        for sp_format in sparse.sparse_formats:
            for o_type in sparse.float_dtypes:
                f = theano.function(
                    self.inputs,
                    Binomial(sp_format, o_type)(*self.inputs))

                tested = f(*self._inputs)

                assert tested.shape == tuple(self._shape)
                assert tested.format == sp_format
                assert tested.dtype == o_type
                assert numpy.allclose(numpy.floor(tested.todense()),
                                   tested.todense())

Example 49

Project: qualityvis Source File: OWPCA.py
    def on_cutoff_moved(self, value):
        """Cutoff curve was moved by the user.
        """
        components = int(np.floor(value)) + 1
        # Did the number of components actually change
        self.max_components = components
        self.variance_covered = self.variances_cuemsum[components - 1] * 100
        if self.currently_selected != self.number_of_selected_components():
            self.update_components_if()

Example 50

Project: gammatone Source File: gtgram.py
def gtgram_strides(fs, window_time, hop_time, filterbank_cols):
    """
    Calculates the window size for a gammatonegram.
    
    @return a tuple of (window_size, hop_samples, output_columns)
    """
    nwin        = int(round_half_away_from_zero(window_time * fs))
    hop_samples = int(round_half_away_from_zero(hop_time * fs))
    columns     = (1
                    + int(
                        np.floor(
                            (filterbank_cols - nwin)
                            / hop_samples
                        )
                    )
                  )
        
    return (nwin, hop_samples, columns)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3 Page 4