Python numpy.roll() Examples

The following are 30 code examples for showing how to use numpy.roll(). 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: py360convert   Author: sunset1995   File: utils.py    License: MIT License 6 votes vote down vote up
def equirect_facetype(h, w):
    '''
    0F 1R 2B 3L 4U 5D
    '''
    tp = np.roll(np.arange(4).repeat(w // 4)[None, :].repeat(h, 0), 3 * w // 8, 1)

    # Prepare ceil mask
    mask = np.zeros((h, w // 4), np.bool)
    idx = np.linspace(-np.pi, np.pi, w // 4) / 4
    idx = h // 2 - np.round(np.arctan(np.cos(idx)) * h / np.pi).astype(int)
    for i, j in enumerate(idx):
        mask[:j, i] = 1
    mask = np.roll(np.concatenate([mask] * 4, 1), 3 * w // 8, 1)

    tp[mask] = 4
    tp[np.flip(mask, 0)] = 5

    return tp.astype(np.int32) 
Example 2
Project: AdaptiveWingLoss   Author: protossw512   File: utils.py    License: Apache License 2.0 6 votes vote down vote up
def fig2data(fig):
    """
    @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
    @param fig a matplotlib figure
    @return a numpy 3D array of RGBA values
    """
    # draw the renderer
    fig.canvas.draw ( )

    # Get the RGB buffer from the figure
    w,h = fig.canvas.get_width_height()
    buf = np.fromstring (fig.canvas.tostring_rgb(), dtype=np.uint8)
    buf.shape = (w, h, 3)

    # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
    buf = np.roll (buf, 3, axis=2)
    return buf 
Example 3
Project: HorizonNet   Author: sunset1995   File: inference.py    License: MIT License 6 votes vote down vote up
def augment_undo(x_imgs_augmented, aug_type):
    x_imgs_augmented = x_imgs_augmented.cpu().numpy()
    sz = x_imgs_augmented.shape[0] // len(aug_type)
    x_imgs = []
    for i, aug in enumerate(aug_type):
        x_img = x_imgs_augmented[i*sz : (i+1)*sz]
        if aug == 'flip':
            x_imgs.append(np.flip(x_img, axis=-1))
        elif aug.startswith('rotate'):
            shift = int(aug.split()[-1])
            x_imgs.append(np.roll(x_img, -shift, axis=-1))
        elif aug == '':
            x_imgs.append(x_img)
        else:
            raise NotImplementedError()

    return np.array(x_imgs) 
Example 4
Project: HorizonNet   Author: sunset1995   File: pano_lsd_align.py    License: MIT License 6 votes vote down vote up
def computeUVN_vec(n, in_, planeID):
    '''
    vectorization version of computeUVN
    @n         N x 3
    @in_      MN x 1
    @planeID   N
    '''
    n = n.copy()
    if (planeID == 2).sum():
        n[planeID == 2] = np.roll(n[planeID == 2], 2, axis=1)
    if (planeID == 3).sum():
        n[planeID == 3] = np.roll(n[planeID == 3], 1, axis=1)
    n = np.repeat(n, in_.shape[0] // n.shape[0], axis=0)
    assert n.shape[0] == in_.shape[0]
    bc = n[:, [0]] * np.sin(in_) + n[:, [1]] * np.cos(in_)
    bs = n[:, [2]]
    out = np.arctan(-bc / (bs + 1e-9))
    return out 
Example 5
Project: HorizonNet   Author: sunset1995   File: post_proc.py    License: MIT License 6 votes vote down vote up
def gen_ww(init_coorx, coory, z=50, coorW=1024, coorH=512, floorW=1024, floorH=512, tol=3, force_cuboid=True):
    gpid = get_gpid(init_coorx, coorW)
    coor = np.hstack([np.arange(coorW)[:, None], coory[:, None]])
    xy = np_coor2xy(coor, z, coorW, coorH, floorW, floorH)

    # Generate wall-wall
    if force_cuboid:
        xy_cor = gen_ww_cuboid(xy, gpid, tol)
    else:
        xy_cor = gen_ww_general(init_coorx, xy, gpid, tol)

    # Ceiling view to normal view
    cor = []
    for j in range(len(xy_cor)):
        next_j = (j + 1) % len(xy_cor)
        if xy_cor[j]['type'] == 1:
            cor.append((xy_cor[next_j]['val'], xy_cor[j]['val']))
        else:
            cor.append((xy_cor[j]['val'], xy_cor[next_j]['val']))
    cor = np_xy2coor(np.array(cor), z, coorW, coorH, floorW, floorH)
    cor = np.roll(cor, -2 * cor[::2, 0].argmin(), axis=0)

    return cor, xy_cor 
Example 6
Project: derplearning   Author: notkarol   File: test_end2end.py    License: MIT License 6 votes vote down vote up
def test_perturb_learnability(frame, source_config, target_config):
    bbox = derp.util.get_patch_bbox(target_config, source_config)
    train_table, test_table = [], []
    for shift in np.linspace(-0.4, 0.4, 51):
        for rotate in np.linspace(-4, 4, 51):
            p_frame = derp.util.perturb(frame.copy(), source_config, shift, rotate)
            p_patch = derp.util.crop(p_frame, bbox)
            table = test_table if shift == 0 or rotate == 0 else train_table
            table.append([p_patch, torch.FloatTensor(), torch.FloatTensor([shift * 2.5,
                                                                           rotate * 0.25])])
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") 
    train_fetcher, test_fetcher = Fetcher(train_table), Fetcher(test_table)
    train_loader = torch.utils.data.DataLoader(train_fetcher, 32, shuffle=True)
    test_loader = torch.utils.data.DataLoader(test_fetcher, len(test_fetcher))
    model = derp.model.Tiny(np.roll(train_table[0][0].shape, 1), 0, 2).to(device)
    optimizer = torch.optim.AdamW(model.parameters(), 1E-3)
    criterion = torch.nn.MSELoss().to(device)
    test_losses = []
    for epoch in range(5):
        train_loss = derp.model.train_epoch(device, model, optimizer, criterion, train_loader)
        test_loss = derp.model.test_epoch(device, model, criterion, test_loader)
        test_losses.append(test_loss)
    assert min(test_losses) < 2E-3 
Example 7
Project: recruit   Author: Frank-qlu   File: parsers.py    License: Apache License 2.0 6 votes vote down vote up
def detect_colspecs(self, infer_nrows=100, skiprows=None):
        # Regex escape the delimiters
        delimiters = ''.join(r'\%s' % x for x in self.delimiter)
        pattern = re.compile('([^%s]+)' % delimiters)
        rows = self.get_rows(infer_nrows, skiprows)
        if not rows:
            raise EmptyDataError("No rows from which to infer column width")
        max_len = max(map(len, rows))
        mask = np.zeros(max_len + 1, dtype=int)
        if self.comment is not None:
            rows = [row.partition(self.comment)[0] for row in rows]
        for row in rows:
            for m in pattern.finditer(row):
                mask[m.start():m.end()] = 1
        shifted = np.roll(mask, 1)
        shifted[0] = 0
        edges = np.where((mask ^ shifted) == 1)[0]
        edge_pairs = list(zip(edges[::2], edges[1::2]))
        return edge_pairs 
Example 8
Project: pytim   Author: Marcello-Sega   File: surface.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _compute_q_vectors(self, box):
        """ Compute the q-vectors compatible with the current box dimensions.

            Calculated quantities:
            q_vectors : two 2D arrays forming the grid of q-values, similar
                        to a meshgrid
            Qxy       : array of the different q-vectors
            Q         : squared module of Qxy with the first element missing
                        (no Q = 0.0)
        """
        self.box = np.roll(box, 2 - self.normal)
        nmax = list(map(int, np.ceil(self.box[0:2] / self.alpha)))
        self.q_vectors = np.mgrid[0:nmax[0], 0:nmax[1]] * 1.0
        self.q_vectors[0] *= 2. * np.pi / box[0]
        self.q_vectors[1] *= 2. * np.pi / box[1]
        self.modes_shape = self.q_vectors[0].shape
        qx = self.q_vectors[0][:, 0]
        qy = self.q_vectors[1][0]
        Qx = np.repeat(qx, len(qy))
        Qy = np.tile(qy, len(qx))
        self.Qxy = np.vstack((Qx, Qy)).T
        self.Q = np.sqrt(np.sum(self.Qxy * self.Qxy, axis=1)[1:]) 
Example 9
Project: subsync   Author: tympanix   File: media.py    License: Apache License 2.0 6 votes vote down vote up
def logloss(self, pred, actual, margin=12):
        blocks = secondsToBlocks(margin)
        logloss = np.ones(blocks*2)
        indices = np.ones(blocks*2)
        nonzero = np.nonzero(actual)[0]
        begin = max(nonzero[0]-blocks, 0)
        end = min(nonzero[-1]+blocks, len(actual)-1)
        pred = pred[begin:end]
        actual = actual[begin:end]
        for i, offset in enumerate(range(-blocks, blocks)):
            snippet = np.roll(actual, offset)
            try:
                logloss[i] = sklearn.metrics.log_loss(snippet[blocks:-blocks], pred[blocks:-blocks])
            except (ValueError, RuntimeWarning):
                pass
            indices[i] = offset

        return indices, logloss 
Example 10
Project: KAIR   Author: cszn   File: utils_deblur.py    License: MIT License 6 votes vote down vote up
def p2o(psf, shape):
    '''
    # psf: NxCxhxw
    # shape: [H,W]
    # otf: NxCxHxWx2
    '''
    otf = torch.zeros(psf.shape[:-2] + shape).type_as(psf)
    otf[...,:psf.shape[2],:psf.shape[3]].copy_(psf)
    for axis, axis_size in enumerate(psf.shape[2:]):
        otf = torch.roll(otf, -int(axis_size / 2), dims=axis+2)
    otf = torch.rfft(otf, 2, onesided=False)
    n_ops = torch.sum(torch.tensor(psf.shape).type_as(psf) * torch.log2(torch.tensor(psf.shape).type_as(psf)))
    otf[...,1][torch.abs(otf[...,1])<n_ops*2.22e-16] = torch.tensor(0).type_as(psf)
    return otf



# otf2psf: not sure where I got this one from. Maybe translated from Octave source code or whatever. It's just math. 
Example 11
Project: KAIR   Author: cszn   File: utils_sisr.py    License: MIT License 6 votes vote down vote up
def p2o(psf, shape):
    '''
    Args:
        psf: NxCxhxw
        shape: [H,W]

    Returns:
        otf: NxCxHxWx2
    '''
    otf = torch.zeros(psf.shape[:-2] + shape).type_as(psf)
    otf[...,:psf.shape[2],:psf.shape[3]].copy_(psf)
    for axis, axis_size in enumerate(psf.shape[2:]):
        otf = torch.roll(otf, -int(axis_size / 2), dims=axis+2)
    otf = torch.rfft(otf, 2, onesided=False)
    n_ops = torch.sum(torch.tensor(psf.shape).type_as(psf) * torch.log2(torch.tensor(psf.shape).type_as(psf)))
    otf[...,1][torch.abs(otf[...,1])<n_ops*2.22e-16] = torch.tensor(0).type_as(psf)
    return otf 
Example 12
Project: tenpy   Author: tenpy   File: mps.py    License: GNU General Public License v3.0 6 votes vote down vote up
def roll_mps_unit_cell(self, shift=1):
        """Shift the section we define as unit cellof an infinite MPS; in place.

        Suppose we have a unit cell with tensors ``[A, B, C, D]`` (repeated on both sites).
        With ``shift = 1``, the new unit cell will be ``[D, A, B, C]``,
        whereas ``shift = -1`` will give ``[B, C, D, A]``.

        Parameters
        ----------
        shift : int
            By how many sites to move the tensors to the right.
        """
        if self.finite:
            raise ValueError("makes only sense for infinite boundary conditions")
        inds = np.roll(np.arange(self.L), shift)
        self.sites = [self.sites[i] for i in inds]
        self.form = [self.form[i] for i in inds]
        self._B = [self._B[i] for i in inds]
        self._S = [self._S[i] for i in inds]
        self._S.append(self._S[0]) 
Example 13
Project: pycolab   Author: deepmind   File: extraterrestrial_marauders.py    License: Apache License 2.0 6 votes vote down vote up
def update(self, actions, board, layers, backdrop, things, the_plot):
    # Where are the laser bolts? Only bolts from the player kill a Marauder.
    bolts = np.logical_or.reduce([layers[c] for c in UPWARD_BOLT_CHARS], axis=0)
    hits = bolts & self.curtain                       # Any hits to Marauders?
    np.logical_xor(self.curtain, hits, self.curtain)  # If so, zap the marauder...
    the_plot.add_reward(np.sum(hits)*10)              # ...and supply a reward.
    # Save the identities of marauder-striking bolts in the Plot.
    the_plot['marauder_hitters'] = [chr(c) for c in board[hits]]

    # If no Marauders are left, or if any are sitting on row 10, end the game.
    if (not self.curtain.any()) or self.curtain[10, :].any():
      return the_plot.terminate_episode()  # i.e. return None.

    # We move faster if there are fewer Marauders. The odd divisor causes speed
    # jumps to align on the high sides of multiples of 8; so, speed increases as
    # the number of Marauders decreases to 32 (or 24 etc.), not 31 (or 23 etc.).
    if the_plot.frame % max(1, np.sum(self.curtain)//8.0000001): return
    # If any Marauder reaches either side of the screen, reverse horizontal
    # motion and advance vertically one row.
    if np.any(self.curtain[:, 0] | self.curtain[:, -1]):
      self._dx = -self._dx
      self.curtain[:] = np.roll(self.curtain, shift=1, axis=0)
    self.curtain[:] = np.roll(self.curtain, shift=self._dx, axis=1) 
Example 14
Project: mmdetection   Author: open-mmlab   File: structures.py    License: Apache License 2.0 5 votes vote down vote up
def _polygon_area(self, x, y):
        """Compute the area of a component of a polygon.

        Using the shoelace formula:
        https://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates

        Args:
            x (ndarray): x coordinates of the component
            y (ndarray): y coordinates of the component

        Return:
            float: the are of the component
        """  # noqa: 501
        return 0.5 * np.abs(
            np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1))) 
Example 15
Project: Deep_VoiceChanger   Author: pstuvwx   File: gla_util.py    License: MIT License 5 votes vote down vote up
def inverse(self, spectrum, in_phase=None):
        spectrum = spectrum.astype(complex)
        if in_phase is None:
            in_phase = self.phase
        self.spectrum_buffer[-1] = spectrum * in_phase
        self.absolute_buffer[-1] = spectrum

        for _ in range(self.loop_num):
            self.overwrap_buf *= 0
            waves = np.fft.ifft(self.spectrum_buffer, axis=1).real
            last = self.spectrum_buffer

            for i in range(self.buffer_size):
                self.overwrap_buf[i*self.wave_dif:i*self.wave_dif+self.wave_len] += waves[i]
            waves = np.vstack([self.overwrap_buf[i*self.wave_dif:i*self.wave_dif+self.wave_len]*self.window for i in range(self.buffer_size)])

            spectrum = np.fft.fft(waves, axis=1)
            self.spectrum_buffer = self.absolute_buffer * spectrum / (np.abs(spectrum)+1e-10)
            self.spectrum_buffer += 0.5 * (self.spectrum_buffer - last)

        waves = np.fft.ifft(self.spectrum_buffer[0]).real
        self.absolute_buffer = np.roll(self.absolute_buffer, -1, axis=0)
        self.spectrum_buffer = np.roll(self.spectrum_buffer, -1, axis=0)

        self.wave_buf = np.roll(self.wave_buf, -self.wave_dif)
        self.wave_buf[-self.wave_dif:] = 0
        self.wave_buf[self.wave_dif:] += waves
        return self.wave_buf[:self.wave_dif]*0.5 
Example 16
Project: neuropythy   Author: noahbenson   File: core.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def close_curves(*crvs, **kw):
    '''
    close_curves(crv1, crv2...) yields a single curve that merges all of the given list of curves
      together. The curves must be given in order, such that the i'th curve should be connected to
      to the (i+1)'th curve circularly to form a perimeter.

    The following optional parameters may be given:
      * grid may specify the number of grid-points to use in the initial search for a start-point
        (default: 16).
      * order may specify the order of the resulting curve; by default (None) uses the lowest order
        of all curves.
      * smoothing (None) the amount to smooth the points.
      * even_out (True) whether to even out the distances along the curve.
      * meta_data (None) an optional map of meta-data to give the spline representation.
    '''
    for k in six.iterkeys(kw):
        if k not in close_curves.default_options: raise ValueError('Unrecognized option: %s' % k)
    kw = {k:(kw[k] if k in kw else v) for (k,v) in six.iteritems(close_curves.default_options)}
    (grid, order) = (kw['grid'], kw['order'])
    crvs = [(crv if is_curve_spline(crv) else to_curve_spline(crv)).even_out() for crv in crvs]
    # find all intersections:
    isects = [curve_intersection(u,v, grid=grid)
              for (u,v) in zip(crvs, np.roll(crvs,-1))]
    # subsample curves
    crds = np.hstack([crv.subcurve(s1[1], s0[0]).coordinates[:,:-1]
                      for (crv,s0,s1) in zip(crvs, isects, np.roll(isects,1,0))])
    kw['order'] = np.min([crv.order for crv in crvs]) if order is None else order
    kw = {k:v for (k,v) in six.iteritems(kw)
          if v is not None and k in ('order','smoothing','even_out','meta_data')}
    return curve_spline(crds, periodic=True, **kw) 
Example 17
Project: OpenFermion-Cirq   Author: quantumlib   File: fermionic_simulation_test.py    License: Apache License 2.0 5 votes vote down vote up
def test_cubic_fermionic_simulation_gate_consistency_special(exponent, control):
    weights = tuple(np.eye(1, 3, control)[0] * 0.5 * np.pi)
    general_gate = ofc.CubicFermionicSimulationGate(weights, exponent=exponent)
    general_unitary = cirq.unitary(general_gate)

    indices = np.dot(list(itertools.product((0, 1), repeat=3)),
                     (2**np.roll(np.arange(3), -control))[::-1])
    special_gate = cirq.ControlledGate(cirq.ISWAP**-exponent)
    special_unitary = (
        cirq.unitary(special_gate)[indices[:, np.newaxis], indices])

    assert np.allclose(general_unitary, special_unitary) 
Example 18
Project: lirpg   Author: Hwhitetooth   File: acer_simple.py    License: MIT License 5 votes vote down vote up
def update_obs(self, obs, dones=None):
        if dones is not None:
            self.obs *= (1 - dones.astype(np.uint8))[:, None, None, None]
        self.obs = np.roll(self.obs, shift=-self.nc, axis=3)
        self.obs[:, :, :, -self.nc:] = obs[:, :, :, :] 
Example 19
Project: lirpg   Author: Hwhitetooth   File: vec_frame_stack.py    License: MIT License 5 votes vote down vote up
def step_wait(self):
        obs, rews, news, infos = self.venv.step_wait()
        self.stackedobs = np.roll(self.stackedobs, shift=-1, axis=-1)
        for (i, new) in enumerate(news):
            if new:
                self.stackedobs[i] = 0
        self.stackedobs[..., -obs.shape[-1]:] = obs
        return self.stackedobs, rews, news, infos 
Example 20
Project: HardRLWithYoutube   Author: MaxSobolMark   File: runner.py    License: MIT License 5 votes vote down vote up
def update_obs(self, obs, dones=None):
        #self.obs = obs
        if dones is not None:
            self.obs *= (1 - dones.astype(np.uint8))[:, None, None, None]
        self.obs = np.roll(self.obs, shift=-self.nc, axis=3)
        self.obs[:, :, :, -self.nc:] = obs[:, :, :, :] 
Example 21
Project: HardRLWithYoutube   Author: MaxSobolMark   File: vec_frame_stack.py    License: MIT License 5 votes vote down vote up
def step_wait(self):
        obs, rews, news, infos = self.venv.step_wait()
        self.stackedobs = np.roll(self.stackedobs, shift=-1, axis=-1)
        for (i, new) in enumerate(news):
            if new:
                self.stackedobs[i] = 0
        self.stackedobs[..., -obs.shape[-1]:] = obs
        return self.stackedobs, rews, news, infos 
Example 22
Project: py360convert   Author: sunset1995   File: utils.py    License: MIT License 5 votes vote down vote up
def sample_equirec(e_img, coor_xy, order):
    w = e_img.shape[1]
    coor_x, coor_y = np.split(coor_xy, 2, axis=-1)
    pad_u = np.roll(e_img[[0]], w // 2, 1)
    pad_d = np.roll(e_img[[-1]], w // 2, 1)
    e_img = np.concatenate([e_img, pad_d, pad_u], 0)
    return map_coordinates(e_img, [coor_y, coor_x],
                           order=order, mode='wrap')[..., 0] 
Example 23
Project: fin   Author: vsmolyakov   File: alpha_selection.py    License: MIT License 5 votes vote down vote up
def shift_mask_data(X, Y, upper_percentile=70, lower_percentile=30, n_fwd_days=1):
    # Shift X to match factors at t to returns at t+n_fwd_days (we want to predict future returns after all)
    shifted_X = np.roll(X, n_fwd_days+1, axis=0)
    
    # Slice off rolled elements
    X = shifted_X[n_fwd_days+1:]
    Y = Y[n_fwd_days+1:]
    
    n_time, n_stocks, n_factors = X.shape
    
    # Look for biggest up and down movers
    upper = np.nanpercentile(Y, upper_percentile, axis=1)[:, np.newaxis]
    lower = np.nanpercentile(Y, lower_percentile, axis=1)[:, np.newaxis]
  
    upper_mask = (Y >= upper)
    lower_mask = (Y <= lower)
    
    mask = upper_mask | lower_mask # This also drops nans
    mask = mask.flatten()
    
    # Only try to predict whether a stock moved up/down relative to other stocks
    Y_binary = np.zeros(n_time * n_stocks)
    Y_binary[upper_mask.flatten()] = 1
    Y_binary[lower_mask.flatten()] = -1
    
    # Flatten X
    X = X.reshape((n_time * n_stocks, n_factors))

    # Drop stocks that did not move much (i.e. are in the 30th to 70th percentile)
    X = X[mask]
    Y_binary = Y_binary[mask]
    
    return X, Y_binary
    

# Massage data to be in the form expected by shift_mask_data() 
Example 24
Project: HorizonNet   Author: sunset1995   File: inference.py    License: MIT License 5 votes vote down vote up
def augment(x_img, flip, rotate):
    x_img = x_img.numpy()
    aug_type = ['']
    x_imgs_augmented = [x_img]
    if flip:
        aug_type.append('flip')
        x_imgs_augmented.append(np.flip(x_img, axis=-1))
    for shift_p in rotate:
        shift = int(round(shift_p * x_img.shape[-1]))
        aug_type.append('rotate %d' % shift)
        x_imgs_augmented.append(np.roll(x_img, shift, axis=-1))
    return torch.FloatTensor(np.concatenate(x_imgs_augmented, 0)), aug_type 
Example 25
Project: HorizonNet   Author: sunset1995   File: post_proc.py    License: MIT License 5 votes vote down vote up
def get_gpid_idx(gpid, j):
    idx = np.where(gpid == j)[0]
    if idx[0] == 0 and idx[-1] != len(idx) - 1:
        _shift = -np.where(idx != np.arange(len(idx)))[0][0]
        idx = np.roll(idx, _shift)
    return idx 
Example 26
Project: visual_turing_test-tutorial   Author: mateuszmalinowski   File: input_output_space.py    License: MIT License 5 votes vote down vote up
def shift(X, new_vector=None, time_axis=1):
    """
    Shifts input X along time_axis by one. 
    At the new place it introduces new_word_id.
    The method doesn't change the size of X, so 
    the last column along time axis is forgotten.

    In:
        X - input array;
            X has to have one more dimension than time_axis,
            so if time_axis == 1 then X has 3 dimensions (0,1,2)
        new_vector - new vector that replaces the column at time axis;
            if None, then the last column is added at the first position;
            by default None
        time_axis - axis where shifting happens
    Out:
        shifted version of X along the time axis
    """
    tmp = np.roll(X, 1, time_axis)
    if new_vector is None:
        return tmp
    if time_axis==0:
        tmp[0,:] = new_vector 
    elif time_axis==1:
        tmp[:,0,:] = new_vector 
    elif time_axis==2:
        tmp[:,:,0,:] = new_vector 
    elif time_axis==3:
        tmp[:,:,:,0,:] = new_vector 
    else:
        raise NotImplementedError
    return tmp 
Example 27
Project: H3DNet   Author: zaiweizhang   File: box_util.py    License: MIT License 5 votes vote down vote up
def poly_area(x,y):
    """ Ref: http://stackoverflow.com/questions/24467972/calculate-area-of-polygon-given-x-y-coordinates """
    return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1))) 
Example 28
Project: H3DNet   Author: zaiweizhang   File: box_util.py    License: MIT License 5 votes vote down vote up
def is_clockwise(p):
    x = p[:,0]
    y = p[:,1]
    return np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)) > 0 
Example 29
Project: pydiogment   Author: SuperKogito   File: augt.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def shift_time(infile, tshift, direction):
    """
    Augment audio data by shifting the time in the file. Signal can be shifted
    to the left or right.

    Note:
        Time shifting is simply moving the audio to left/right with a random second.
        If shifting audio to left (fast forward) with x seconds, first x seconds will mark as 0 (i.e. silence).
        If shifting audio to right (back forward) with x seconds, last x seconds will mark as 0 (i.e. silence).

    Args:
        - infile    (str) : Input filename.
        - tshift    (int) : Signal time shift in seconds.
        - direction (str) : shift direction (to the left or right).
    """
    fs, sig = read_file(filename=infile)
    shift = int(tshift * fs) * int(direction == "left") - \
            int(tshift * fs) * int(direction == "right")

    # shift time
    augmented_sig = np.roll(sig, shift)

    # construct file names
    output_file_path = os.path.dirname(infile)
    name_attribute = "_augmented_%s_%s_shifted.wav" % (direction, tshift)

    # export data to file
    write_file(output_file_path=output_file_path,
               input_file_name=infile,
               name_attribute=name_attribute,
               sig=augmented_sig,
               fs=fs) 
Example 30
Project: seizure-prediction   Author: MichaelHills   File: transforms.py    License: MIT License 5 votes vote down vote up
def pfd_for_ch(self, ch):
        diff = np.diff(ch, n=1, axis=0)

        asign = np.sign(diff)
        sign_changes = ((np.roll(asign, 1) - asign) != 0).astype(int)
        N_delta = np.count_nonzero(sign_changes)

        n = len(ch)
        log10n = np.log10(n)
        return log10n / (log10n + np.log10(n / (n + 0.4 * N_delta)))