python类indices()的实例源码

test_tree.py 文件源码 项目:Parallel-SGD 作者: angadgill 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def test_xor():
    # Check on a XOR problem
    y = np.zeros((10, 10))
    y[:5, :5] = 1
    y[5:, 5:] = 1

    gridx, gridy = np.indices(y.shape)

    X = np.vstack([gridx.ravel(), gridy.ravel()]).T
    y = y.ravel()

    for name, Tree in CLF_TREES.items():
        clf = Tree(random_state=0)
        clf.fit(X, y)
        assert_equal(clf.score(X, y), 1.0,
                     "Failed with {0}".format(name))

        clf = Tree(random_state=0, max_features=1)
        clf.fit(X, y)
        assert_equal(clf.score(X, y), 1.0,
                     "Failed with {0}".format(name))
sphere_transforms_numpy.py 文件源码 项目:spherical_image_editing 作者: henryseg 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def apply_SL2C_elt_to_image(M_SL2C, src_image, out_size=None):

    s_im = np.atleast_3d(src_image)
    in_size = s_im.shape[:-1]
    if out_size is None:
        out_size = in_size
    #We are going to find the location in the source image that each pixel in the output image comes from

    #least squares matrix inversion (find X such that M @ X = I ==> X = inv(M) @ I = inv(M))
    Minv = np.linalg.lstsq(M_SL2C, np.eye(2))[0]
    #all of the x,y pairs in o_im:
    pts_out = np.indices(out_size).reshape((2,-1)) #results in a 2 x (num pixels) array of indices
    pts_out_a = angles_from_pixel_coords(pts_out, out_size)
    pts_out_s = sphere_from_angles(pts_out_a)
    pts_out_c = CP1_from_sphere(pts_out_s)
    pts_in_c = np.dot(Minv, pts_out_c) # (2x2) @ (2xn) => (2xn)
    pts_in_s = sphere_from_CP1(pts_in_c)
    pts_in_a = angles_from_sphere(pts_in_s)
    pts_in = pixel_coords_from_angles(pts_in_a, in_size)
    #reshape pts into 2 x image_shape for the interpolation
    o_im = get_interpolated_pixel_color(pts_in.reshape((2,)+out_size), s_im, in_size)

    return o_im
qcqp.py 文件源码 项目:qcqp 作者: cvxgrp 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def improve_ipopt(x0, prob, *args, **kwargs):
    try:
        import pyipopt
    except ImportError:
        raise Exception("PyIpopt package is not installed.")

    lb = pyipopt.NLP_LOWER_BOUND_INF
    ub = pyipopt.NLP_UPPER_BOUND_INF
    g_L = np.zeros(prob.m)
    for i in range(prob.m):
        if prob.fs[i].relop == '<=':
            g_L[i] = lb
    g_U = np.zeros(prob.m)

    def eval_grad_f(x, user_data = None):
        return 2*prob.f0.P.dot(x) + prob.f0.qarray
    def eval_g(x, user_data = None):
        return np.array([f.eval(x) for f in prob.fs])

    jac_grid = np.indices((prob.m, prob.n))
    jac_r = jac_grid[0].ravel()
    jac_c = jac_grid[1].ravel()
    def eval_jac_g(x, flag, user_data = None):
        if flag:
            return (jac_r, jac_c)
        else:
            return np.vstack([2*f.P.dot(x)+f.qarray for f in prob.fs])

    nlp = pyipopt.create(
        prob.n, lb*np.ones(prob.n), ub*np.ones(prob.n),
        prob.m, g_L, g_U, prob.m*prob.n, 0,
        prob.f0.eval, eval_grad_f,
        eval_g, eval_jac_g
    )
    try:
        x, zl, zu, constraint_multipliers, obj, status = nlp.solve(x0)
    except:
        pass

    return x
geometry.py 文件源码 项目:prysm 作者: brandondube 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def check(p1, p2, base_array):
    ''' Checks if the values in the base array fall inside of the triangle
        enclosed in the points (p1, p2, (0,0)).

    Args:
        p1 (`iterable`): iterable containing (x,y) coordinates of a point.

        p2 (`iterable`): iterable containing (x,y) coordinates of a point.

        base_array (`numpy.ndarray`): a logical array.

    Returns:
        `numpy.ndarray`: array with True value inside and False value outside bounds

    '''
    # Create 3D array of indices
    idxs = np.indices(base_array.shape)

    # ensure points are floats
    p1 = p1.astype(float)
    p2 = p2.astype(float)

    # Calculate max column idx for each row idx based on interpolated line between two points
    max_col_idx = (idxs[0] - p1[0]) / (p2[0] - p1[0]) * (p2[1] - p1[1]) + p1[1]
    sign = np.sign(p2[0] - p1[0])
    return idxs[1] * sign <= max_col_idx * sign
grid.py 文件源码 项目:pysheds 作者: mdbartos 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _select_surround(self, i, j):
        """
        Select the eight indices surrounding a given index.
        """
        return ([i - 1, i - 1, i + 0, i + 1, i + 1, i + 1, i + 0, i - 1],
                [j + 0, j + 1, j + 1, j + 1, j + 0, j - 1, j - 1, j - 1])
grid.py 文件源码 项目:pysheds 作者: mdbartos 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _select_surround_ravel(self, i, shape):
        """
        Select the eight indices surrounding a flattened index.
        """
        offset = shape[1]
        return np.array([i + 0 - offset,
                         i + 1 - offset,
                         i + 1 + 0,
                         i + 1 + offset,
                         i + 0 + offset,
                         i - 1 + offset,
                         i - 1 + 0,
                         i - 1 - offset]).T
utils.py 文件源码 项目:MOSFiT 作者: guillochon 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def rebin(a, newshape):
    """Rebin an array to a new shape."""
    assert len(a.shape) == len(newshape)

    slices = [slice(0, old, float(old) / new)
              for old, new in zip(a.shape, newshape)]
    coordinates = np.mgrid[slices]
    indices = coordinates.astype('i')
    return a[tuple(indices)]
polyCrystal.py 文件源码 项目:Graphene 作者: ashivni 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def rotatedCrystal(V, size=(2, 2, 1), a=1.3968418, cType='gr'):
    """
    Generates a triangular crystal lattice of the given size and rotates it so that the new unit vectors
    align with the columns of V. The positions are set so that the center atom is at the
    origin. Size is expected to be even in all directions.
    'a' is the atomic distance between the atoms of the hexagonal lattice daul to this crystal.
    In other words, a*sqrt(3) is the lattice constant of the triangular lattice.
    The returned object is of ase.Atoms type
    """
    if cType == 'gr':
        cr = GB.grapheneCrystal(1, 1, 'armChair').aseCrystal(ccBond=a)

    elif cType == 'tr':
        numbers = [6.0]
        cell = numpy.array([[a * (3.0 ** 0.5), 0, 0], [0.5 * a * (3.0 ** 0.5), 1.5 * a, 0], [0, 0, 10 * a]])
        positions = numpy.array([[0, 0, 0]])
        cr = ase.Atoms(numbers=numbers, positions=positions, cell=cell, pbc=[True, True, True])

    elif cType == 'tr-or':
        numbers = [6.0, 6.0]
        cell = numpy.array([[a * (3.0 ** 0.5), 0, 0], [0, 3.0 * a, 0], [0, 0, 10 * a]])
        positions = numpy.array([[0, 0, 0], [0.5 * a * (3.0 ** 0.5), 1.5 * a, 0]])
        cr = ase.Atoms(numbers=numbers, positions=positions, cell=cell, pbc=[True, True, True])  # Repeating

    ix = numpy.indices(size, dtype=int).reshape(3, -1)
    tvecs = numpy.einsum('ki,kj', ix, cr.cell)
    rPos = numpy.ndarray((len(cr) * len(tvecs), 3))
    for i in range(len(cr)):
        rPos[i * len(tvecs):(i + 1) * len(tvecs)] = tvecs + cr.positions[i]
    # New cell size
    for i in range(3):
        cr.cell[i] *= size[i]

    cr = Atoms(symbols=['C'] * len(rPos), positions=rPos, cell=cr.cell, pbc=[True, True, True])
    center = numpy.sum(cr.cell, axis=0) * 0.5
    cr.positions = cr.positions - center

    cr.cell = numpy.einsum('ik,jk', cr.cell, V)
    cr.positions = numpy.einsum('ik,jk', cr.positions, V)

    return cr
grainBdr.py 文件源码 项目:Graphene 作者: ashivni 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def rotatedCrystal(V,size=(2,2,1),a=1.3968418):
    """
    Generates a triangular crystal lattice of the given size and rotates it so that the new unit vectors 
    align with the columns of V. The positions are set so that the center atom is at the 
    origin. Size is expected to be even in all directions.
    'a' is the atomic distance between the atoms of the hexagonal lattice daul to this crystal.
    In other words, a*sqrt(3) is the lattice constant of the triangular lattice.
    The returned object is of ase.Atoms type
    """
    numbers = [6.0]
    cell = numpy.array([[a*(3.0**0.5),0,0],[0.5*a*(3.0**0.5),1.5*a,0],[0,0,10*a]])
    positions = numpy.array([[0,0,0]])
    cr = ase.Atoms(numbers=numbers,positions=positions,cell=cell,pbc=[True,True,True])

    # Repeating
    ix = numpy.indices(size, dtype=int).reshape(3,-1)
    tvecs = numpy.einsum('ki,kj',ix,cr.cell)
    rPos = numpy.ndarray((len(cr)*len(tvecs),3))
    for i in range(len(cr)):
        rPos[i*len(tvecs):(i+1)*len(tvecs)] = tvecs + cr.positions[i]
    # New cell size
    for i in range(3):
        cr.cell[i]*=size[i]

    cr = Atoms(symbols=['C']*len(rPos), positions=rPos, cell = cr.cell, pbc=[True,True,True])
    center = numpy.sum(cr.cell,axis=0)*0.5
    cr.positions = cr.positions - center

    cr.cell = numpy.einsum('ik,jk',cr.cell,V)
    cr.positions = numpy.einsum('ik,jk',cr.positions,V)

    return cr
test_regression.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_copy_detection_zero_dim(self, level=rlevel):
        # Ticket #658
        np.indices((0, 3, 4)).T.reshape(-1, 3)
test_regression.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_copy_detection_corner_case(self, level=rlevel):
        # Ticket #658
        np.indices((0, 3, 4)).T.reshape(-1, 3)

    # Cannot test if NPY_RELAXED_STRIDES_CHECKING changes the strides.
    # With NPY_RELAXED_STRIDES_CHECKING the test becomes superfluous,
    # 0-sized reshape itself is tested elsewhere.
test_regression.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_copy_detection_corner_case2(self, level=rlevel):
        # Ticket #771: strides are not set correctly when reshaping 0-sized
        # arrays
        b = np.indices((0, 3, 4)).T.reshape(-1, 3)
        assert_equal(b.strides, (3 * b.itemsize, b.itemsize))
test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_take(self):
        tgt = [2, 3, 5]
        indices = [1, 2, 4]
        a = [1, 2, 3, 4, 5]

        out = np.take(a, indices)
        assert_equal(out, tgt)
test_numeric.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_results(self):
        a = np.arange(1*2*3*4).reshape(1, 2, 3, 4).copy()
        aind = np.indices(a.shape)
        assert_(a.flags['OWNDATA'])
        for (i, j) in self.tgtshape:
            # positive axis, positive start
            res = np.rollaxis(a, axis=i, start=j)
            i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
            assert_(np.all(res[i0, i1, i2, i3] == a))
            assert_(res.shape == self.tgtshape[(i, j)], str((i,j)))
            assert_(not res.flags['OWNDATA'])

            # negative axis, positive start
            ip = i + 1
            res = np.rollaxis(a, axis=-ip, start=j)
            i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
            assert_(np.all(res[i0, i1, i2, i3] == a))
            assert_(res.shape == self.tgtshape[(4 - ip, j)])
            assert_(not res.flags['OWNDATA'])

            # positive axis, negative start
            jp = j + 1 if j < 4 else j
            res = np.rollaxis(a, axis=i, start=-jp)
            i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
            assert_(np.all(res[i0, i1, i2, i3] == a))
            assert_(res.shape == self.tgtshape[(i, 4 - jp)])
            assert_(not res.flags['OWNDATA'])

            # negative axis, negative start
            ip = i + 1
            jp = j + 1 if j < 4 else j
            res = np.rollaxis(a, axis=-ip, start=-jp)
            i0, i1, i2, i3 = aind[np.array(res.shape) - 1]
            assert_(np.all(res[i0, i1, i2, i3] == a))
            assert_(res.shape == self.tgtshape[(4 - ip, 4 - jp)])
            assert_(not res.flags['OWNDATA'])
test_multiarray.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def test_swapaxes(self):
        a = np.arange(1*2*3*4).reshape(1, 2, 3, 4).copy()
        idx = np.indices(a.shape)
        assert_(a.flags['OWNDATA'])
        b = a.copy()
        # check exceptions
        assert_raises(ValueError, a.swapaxes, -5, 0)
        assert_raises(ValueError, a.swapaxes, 4, 0)
        assert_raises(ValueError, a.swapaxes, 0, -5)
        assert_raises(ValueError, a.swapaxes, 0, 4)

        for i in range(-4, 4):
            for j in range(-4, 4):
                for k, src in enumerate((a, b)):
                    c = src.swapaxes(i, j)
                    # check shape
                    shape = list(src.shape)
                    shape[i] = src.shape[j]
                    shape[j] = src.shape[i]
                    assert_equal(c.shape, shape, str((i, j, k)))
                    # check array contents
                    i0, i1, i2, i3 = [dim-1 for dim in c.shape]
                    j0, j1, j2, j3 = [dim-1 for dim in src.shape]
                    assert_equal(src[idx[j0], idx[j1], idx[j2], idx[j3]],
                                 c[idx[i0], idx[i1], idx[i2], idx[i3]],
                                 str((i, j, k)))
                    # check a view is always returned, gh-5260
                    assert_(not c.flags['OWNDATA'], str((i, j, k)))
                    # check on non-contiguous input array
                    if k == 1:
                        b = c
core.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def __getslice__(self, i, j):
        """
        x.__getslice__(i, j) <==> x[i:j]

        Return the slice described by (i, j).  The use of negative indices
        is not supported.

        """
        return self.__getitem__(slice(i, j))
core.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def argmax(self, axis=None, fill_value=None, out=None):
        """
        Returns array of indices of the maximum values along the given axis.
        Masked values are treated as if they had the value fill_value.

        Parameters
        ----------
        axis : {None, integer}
            If None, the index is into the flattened array, otherwise along
            the specified axis
        fill_value : {var}, optional
            Value used to fill in the masked values.  If None, the output of
            maximum_fill_value(self._data) is used instead.
        out : {None, array}, optional
            Array into which the result can be placed. Its type is preserved
            and it must be of the right shape to hold the output.

        Returns
        -------
        index_array : {integer_array}

        Examples
        --------
        >>> a = np.arange(6).reshape(2,3)
        >>> a.argmax()
        5
        >>> a.argmax(0)
        array([1, 1, 1])
        >>> a.argmax(1)
        array([2, 2])

        """
        if fill_value is None:
            fill_value = maximum_fill_value(self._data)
        d = self.filled(fill_value).view(ndarray)
        return d.argmax(axis, out=out)
core.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def take(a, indices, axis=None, out=None, mode='raise'):
    """
    """
    a = masked_array(a)
    return a.take(indices, axis=axis, out=out, mode=mode)


问题


面经


文章

微信
公众号

扫码关注公众号