How to use the numpy.where function in numpy

To help you get started, we’ve selected a few numpy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github TerrainBento / terrainbento / tests / test_base_class_erosion_model_boundary_handers.py View on Github external
simple_square_grid,
        modify_core_nodes=True,
        function=lambda grid, t: -(grid.x_of_node + grid.y_of_node + (0 * t)),
    )
    params = {
        "grid": simple_square_grid,
        "clock": clock_simple,
        "boundary_handlers": {"mynew_bh": gfblh},
    }

    model = Basic(**params)
    bh = model.boundary_handlers["mynew_bh"]

    # assertion tests
    assert "mynew_bh" in model.boundary_handlers
    assert_array_equal(np.where(bh.nodes_to_lower)[0], model.grid.core_nodes)

    step = 10.0
    model.run_one_step(step)

    dzdt = -(model.grid.x_of_node + model.grid.y_of_node)
    truth_z = -1.0 * dzdt * step
    assert_array_equal(
        model.z[model.grid.core_nodes], truth_z[model.grid.core_nodes]
    )
github AthenaEPI / dmipy / dmipy / tissue_response / three_tissue_response.py View on Github external
acquisition_scheme, data[mask_GM_refine][indices_gm_selected])

    # for GM, the 10% highest SDM valued voxels are selected.
    N_threshold = int(np.sum(mask_CSF_refine) * csf_perc)
    indices_csf_selected = np.argsort(SDM[mask_CSF_refine])[::-1][:N_threshold]
    S0_csf, TR1_csf_model = estimate_TR1_isotropic_tissue_response_model(
        acquisition_scheme, data[mask_CSF_refine][indices_csf_selected])

    # generate selected WM/GM/CSF response function voxels masks.
    pos_WM_refine = np.c_[np.where(mask_WM_refine)]
    mask_WM_selected = np.zeros_like(mask_WM_refine)
    pos_WM_selected = pos_WM_refine[indices_wm_selected]
    for pos in pos_WM_selected:
        mask_WM_selected[pos[0], pos[1], pos[2]] = 1

    pos_GM_refine = np.c_[np.where(mask_GM_refine)]
    mask_GM_selected = np.zeros_like(mask_GM_refine)
    pos_GM_selected = pos_GM_refine[indices_gm_selected]
    for pos in pos_GM_selected:
        mask_GM_selected[pos[0], pos[1], pos[2]] = 1

    pos_CSF_refine = np.c_[np.where(mask_CSF_refine)]
    mask_CSF_selected = np.zeros_like(mask_CSF_refine)
    pos_CSF_selected = pos_CSF_refine[indices_csf_selected]
    for pos in pos_CSF_selected:
        mask_CSF_selected[pos[0], pos[1], pos[2]] = 1

    three_tissue_selection = np.array(
        [mask_WM_selected, mask_GM_selected, mask_CSF_selected], dtype=float)
    three_tissue_selection = np.transpose(three_tissue_selection, (1, 2, 3, 0))

    return ([S0_wm, S0_gm, S0_csf],
github DeokO / Text-classification-with-CNN-RNN-with-Tensorflow / Ch01_Data_load / utils.py View on Github external
def length(batch_x):
    non_unk = [x > 0 for x in batch_x]
    leng = []
    del_list = []
    for idx, token in enumerate(non_unk):
        tmp = np.where(token)[0]
        if len(tmp) != 0:
            if tmp[-1] == 0:
                del_list.append(idx)
            else:
                leng.append(tmp[-1])
        else:
            del_list.append(idx)

    return np.array(leng), del_list
github tensorflow / tpu / models / official / retinanet / anchors.py View on Github external
keep = []
  while order.size > 0:
    i = order[0]
    keep.append(i)
    xx1 = np.maximum(x1[i], x1[order[1:]])
    yy1 = np.maximum(y1[i], y1[order[1:]])
    xx2 = np.minimum(x2[i], x2[order[1:]])
    yy2 = np.minimum(y2[i], y2[order[1:]])

    w = np.maximum(0.0, xx2 - xx1 + 1)
    h = np.maximum(0.0, yy2 - yy1 + 1)
    intersection = w * h
    overlap = intersection / (areas[i] + areas[order[1:]] - intersection)

    inds = np.where(overlap <= thresh)[0]
    order = order[inds + 1]
  return keep
github scikit-hep / root_numpy / examples / tmva / plot_twoclass.py View on Github external
plt.subplot(121)
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                     np.arange(y_min, y_max, plot_step))

Z = evaluate_reader(reader, 'Fisher', np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, cmap=cmap, vmin=Z.min(), vmax=Z.max(),
             levels=np.linspace(Z.min(), Z.max(), 50))
plt.contour(xx, yy, Z, levels=[0], linestyles='dashed')
plt.axis("tight")

# Plot the training points
for i, n, c in zip([-1, 1], class_names, plot_colors):
    idx = np.where(y == i)
    plt.scatter(X[idx, 0], X[idx, 1],
                c=c, cmap=cmap,
                label="Class %s" % n)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.legend(loc='upper right')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Decision Boundary')

# Plot the two-class decision scores
ax = plt.subplot(122)
ax.xaxis.grid(False)
for i, n, c in zip([-1, 1], class_names, plot_colors):
    plt.hist(twoclass_output[y_test == i],
             bins=20,
github piannucci / blurt / blurt_py_80211 / wifi80211.py View on Github external
def synchronize(self, input):
        score = self.autocorrelate(input)
        # look for points outstanding in their neighborhood
        # by explicit comparison
        l = 25
        M = scipy.linalg.toeplitz(np.r_[score, np.zeros(2*l)], np.zeros(2*l+1)).T
        ext_input = np.r_[np.zeros(l), score, np.zeros(l)]
        M[:l] = M[:l] < ext_input
        M[l+1:] = M[l+1:] < ext_input
        M[l] = True
        idx = np.where(M.all(0))[0] - l
        startIndex = 16*idx - 64
        startIndex[np.where(startIndex<0)] = 0
        return startIndex
github sfepy / sfepy / sfepy / mesh / bspline.py View on Github external
t : array
            The parametric vector.
        knots : array
            The knot vector.
        n : int
            The number of intervals.

        Returns
        -------
        bfun : array
           The spline basis function evaluated for given values.
        """
        nt = len(t)
        bfun = nm.zeros((nt,n), dtype=nm.float64)
        for ii in range(n):
            idxs = nm.where(nm.logical_and(knots[ii] <= t,
                                           t < knots[ii + 1]))[0]
            bfun[idxs,ii] = 1.0

        return bfun
github mikedh / trimesh / trimesh / voxel / creation.py View on Github external
center[2] - radius:center[2] + radius + 1]
    local_origin = point - radius * pitch  # origin of local voxels

    # Fill internal regions
    if fill:
        regions, n = ndimage.measurements.label(~voxels)
        distance = ndimage.morphology.distance_transform_cdt(~voxels)
        representatives = [
            np.unravel_index((distance * (regions == i)).argmax(),
                             distance.shape) for i in range(1, n + 1)]
        contains = mesh.contains(
            np.asarray(representatives) *
            pitch +
            local_origin)

        where = np.where(contains)[0] + 1
        # use in1d vs isin for older numpy versions
        internal = np.in1d(regions.flatten(), where).reshape(regions.shape)

        voxels = np.logical_or(voxels, internal)

    return base.VoxelGrid(voxels, tr.translation_matrix(local_origin))
github deepinsight / insightface / RetinaFace / rcnn / PY_OP / rpn_fpn_ohem3.py View on Github external
# sort ohem scores

            if self.mode==0:
              disable_inds = np.random.choice(bg_inds, size=(len(bg_inds) - num_bg), replace=False)
              labels[disable_inds] = -1
            else:
              neg_ohem_scores = fg_score[bg_inds]
              order_neg_ohem_scores = neg_ohem_scores.ravel().argsort()[::-1]
              sampled_inds = bg_inds[order_neg_ohem_scores[:num_bg]]
              #print('sampled_inds_bg', sampled_inds, file=sys.stderr)
              labels[bg_inds] = -1
              labels[sampled_inds] = 0

          if n_fg>0:
            order0_labels = labels.reshape( (1, A, -1) ).transpose( (0, 2, 1) ).reshape( (-1,) )
            bbox_fg_inds = np.where(order0_labels>0)[0]
            #print('bbox_fg_inds, order0 ', bbox_fg_inds, file=sys.stderr)
            _anchor_weight[bbox_fg_inds,:] = 1.0
          anchor_weight[ibatch] = _anchor_weight
          valid_count[ibatch][0] = n_fg

          #if self.prefix=='face':
          #  #print('fg-bg', self.stride, n_fg, num_bg)
          #  STAT[0]+=1
          #  STAT[self.stride][0] += config.TRAIN.RPN_BATCH_SIZE
          #  STAT[self.stride][1] += n_fg
          #  STAT[self.stride][2] += np.sum(fg_score[fg_inds]>=0)
          #  #_stat[0] += config.TRAIN.RPN_BATCH_SIZE
          #  #_stat[1] += n_fg
          #  #_stat[2] += np.sum(fg_score[fg_inds]>=0)
          #  #print('stride num_fg', self.stride, n_fg, file=sys.stderr)
          #  #ACC[self.stride] += np.sum(fg_score[fg_inds]>=0)