Construct the corresponding 1D mesh from 1D array for pcolormesh() in ```matplotlib```
337471
def construct_mesh_for_1d_array(x_values):
    """"""

    if not isinstance(x_values, np.ndarray):
        try: x_values = np.array(x_values)
        except: raise TypeError("Can not convert to numpy.ndarray: {0}".format(x_values))
    else: assert (x_values.ndim == 1) and (x_values.size >= 2)

    x_mid_points = 0.5 * (x_values[1:] + x_values[:-1])

    x_min_point = x_values[0] - (x_mid_points[0] - x_values[0])
    x_max_point = x_values[-1] + (x_values[-1] - x_mid_points[-1])

    x_mesh_values = np.empty((len(x_values)+1,), dtype=float)
    x_mesh_values[0] = x_min_point
    x_mesh_values[-1] = x_max_point
    x_mesh_values[1:-1] = x_mid_points

    return x_mesh_values
864249
def reshape_1d(df):
    """"""
    shape = df.shape
    if len(shape) == 1:
        return df.reshape(shape[0], 1)
    else:
        return df
425964
def make_grid(xx, yy):
    
    n = len(xx)
    xx, yy = np.meshgrid(xx, yy)
    grid = np.array([xx.ravel(), yy.ravel()]).T
    x = grid[:, 0].reshape(n, n)
    y = grid[:, 1].reshape(n, n)
    return x, y
676382
def boundaries(nside, pix, step=1, nest=False):
    """"""
    pix = np.asarray(pix)
    if pix.ndim > 1:
        # For consistency with healpy we only support scalars or 1D arrays
        raise ValueError("Array has to be one dimensional")
    lon, lat = boundaries_lonlat(pix, step, nside, order='nested' if nest else 'ring')
    rep_sph = UnitSphericalRepresentation(lon, lat)
    rep_car = rep_sph.to_cartesian().xyz.value.swapaxes(0, 1)
    if rep_car.shape[0] == 1:
        return rep_car[0]
    else:
        return rep_car
596078
def from_dicts(cls, mesh_name, vert_dict, normal_dict):
        """"""

        # Put header in string
        wavefront_str = "o {name}\n".format(name=mesh_name)

        # Write Vertex data from vert_dict
        for wall in vert_dict:
            for vert in vert_dict[wall]:
                wavefront_str += "v {0} {1} {2}\n".format(*vert)

        # Write (false) UV Texture data
        wavefront_str += "vt 1.0 1.0\n"

        # Write Normal data from normal_dict
        for wall, norm in normal_dict.items():
            wavefront_str += "vn {0} {1} {2}\n".format(*norm)

        # Write Face Indices (1-indexed)
        vert_idx = 0
        for wall in vert_dict:
            for _ in range(0, len(vert_dict[wall]), 3):
                wavefront_str += 'f '
                for vert in range(3): # 3 vertices in each face
                    vert_idx += 1
                    wavefront_str += "{v}/1/{n} ".format(v=vert_idx, n=wall+1)
                wavefront_str = wavefront_str[:-1] + '\n'  # Cutoff trailing space and add a newline.

        # Return Wavefront string
        return WavefrontWriter(string=wavefront_str)
983860
def mesh_nmasked(self):
        

        return self._make_2d_array(
            np.ma.count_masked(self._data_sigclip, axis=1))
492780
def as_2d_array(theta):
    
    v = theta.view(np.float)
    N = theta.shape[0]
    v.shape = (N, - 1)
    # raise an error if v cannot be reshaped without creating a copy
    return v
1009461
def interp1d(x,Z,xout,spline=False,kind='linear',fill_value=np.NaN,**kwargs):
    

    linear = not spline
    
    
    nx=len(x)
    
    if linear :
        
        try :
            f = scipy.interpolate.interp1d(x, Z, kind=kind,bounds_error=False,fill_value=fill_value,**kwargs)
            Zout = f(xout)
        except RuntimeError : Zout = np.repeat(np.NaN,nx)

    else :
        tck = scipy.interpolate.splrep(x,Z,s=0)
        try : Zout = scipy.interpolate.splev(xout,tck,der=0,**kwargs)
        except RuntimeError : Zout = np.repeat(np.NaN,nx)

    return Zout
1135256
def _init_from_npy2d(self, mat, missing):
        
        if len(mat.shape) != 2:
            raise ValueError('Input numpy.ndarray must be 2 dimensional')
        data = np.array(mat.reshape(mat.size), dtype=np.float32)
        self.handle = ctypes.c_void_p()
        _check_call(_LIB.XGDMatrixCreateFromMat(data.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
                                                mat.shape[0], mat.shape[1],
                                                ctypes.c_float(missing),
                                                ctypes.byref(self.handle)))
266229
def _from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False):
    
    if is_rgb: has_components = True
    ndim = data.ndim
    if has_components:
        ndim -= 1
    dtype = data.dtype.name
    ptype = _npy_to_itk_map[dtype]

    data = np.array(data)

    if origin is None: origin = tuple([0.]*ndim)
    if spacing is None: spacing = tuple([1.]*ndim)
    if direction is None: direction = np.eye(ndim)

    libfn = utils.get_lib_fn('fromNumpy%s%i' % (_ntype_type_map[dtype], ndim))

    if not has_components:
        itk_image = libfn(data, data.shape[::-1])
        ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=1, pointer=itk_image)
        ants_image.set_origin(origin)
        ants_image.set_spacing(spacing)
        ants_image.set_direction(direction)
        ants_image._ndarr = data
    else:
        arrays = [data[i,...].copy() for i in range(data.shape[0])]
        data_shape = arrays[0].shape
        ants_images = []
        for i in range(len(arrays)):
            tmp_ptr = libfn(arrays[i], data_shape[::-1])
            tmp_img = iio.ANTsImage(pixeltype=ptype,
                                    dimension=ndim,
                                    components=1,
                                    pointer=tmp_ptr)
            tmp_img.set_origin(origin)
            tmp_img.set_spacing(spacing)
            tmp_img.set_direction(direction)
            tmp_img._ndarr = arrays[i]
            ants_images.append(tmp_img)
        ants_image = utils.merge_channels(ants_images)
        if is_rgb: ants_image = ants_image.vector_to_rgb()
    return ants_image
731555
def make_gradients(dims=DEFAULT_DIMS):
    
    return np.meshgrid(
        np.linspace(0.0, 1.0, dims[0]),
        np.linspace(0.0, 1.0, dims[1])
    )
1033922
def merge_mesh( x1, ngroups1, conns1, x2, ngroups2, conns2, cmap, eps = 1e-8 ):
    """"""
    n1 = x1.shape[0]
    n2 = x2.shape[0]

    err = nm.sum( nm.sum( nm.abs( x1[cmap[:,0],:-1] - x2[cmap[:,1],:-1] ) ) )
    if abs( err ) > (10.0 * eps):
        print 'nonmatching meshes!', err
        raise ValueError

    mask = nm.ones( (n2,), dtype = nm.int32 )
    mask[cmap[:,1]] = 0
#    print mask, nm.cumsum( mask )
    remap = nm.cumsum( mask ) + n1 - 1
    remap[cmap[:,1]] = cmap[:,0]
#    print remap

    i2 = nm.setdiff1d( nm.arange(  n2, dtype = nm.int32 ),
                       cmap[:,1] )
    xx = nm.r_[x1, x2[i2]]
    ngroups = nm.r_[ngroups1, ngroups2[i2]]

    conns = []
    for ii in xrange( len( conns1 ) ):
        conn = nm.vstack( (conns1[ii], remap[conns2[ii]]) )
        conns.append( conn )
    
    return xx, ngroups, conns
1268808
def out_shape_from_array(arr):
    """"""
    arr = np.asarray(arr)
    if arr.ndim == 1:
        return arr.shape
    else:
        return (arr.shape[1],)
278933
def grid_from_coordinate_transform(numPix, Mpix2coord, ra_at_xy_0, dec_at_xy_0):
    
    a = np.arange(numPix)
    matrix = np.dstack(np.meshgrid(a, a)).reshape(-1, 2)
    x_grid = matrix[:, 0]
    y_grid = matrix[:, 1]
    ra_grid = x_grid * Mpix2coord[0, 0] + y_grid * Mpix2coord[0, 1] + ra_at_xy_0
    dec_grid = x_grid * Mpix2coord[1, 0] + y_grid * Mpix2coord[1, 1] + dec_at_xy_0
    return ra_grid, dec_grid
1226472
def splinefit2d(x, y, z, px, py, mask=None):
    ''''''
    
    if mask is None:
        V = np.array(spline_matrix2d(x, y, px, py))
        a = np.array(z.T.flatten())
        pz = np.linalg.lstsq(V.T, a.T)[0].T
    else:
        V = np.array(spline_matrix2d(x,y,px,py,mask))
        indices = np.nonzero(np.array(mask).T.flatten())
        if len(indices[0])==0:
            pz = np.zeros((len(py),len(px)))
        #indices is empty when mask changes to all zeros
        else:
            a = np.array((z.T.flatten()[indices[0]]))
            pz = np.linalg.lstsq(V.T, a.T)[0].T
            
    pz=pz.reshape((len(py),len(px)))
    return pz.transpose()
934316
def cube(
    xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, zmin=0.0, zmax=1.0, nx=11, ny=11, nz=11
):
    
    # Generate suitable ranges for parametrization
    x_range = numpy.linspace(xmin, xmax, nx)
    y_range = numpy.linspace(ymin, ymax, ny)
    z_range = numpy.linspace(zmin, zmax, nz)

    # Create the vertices.
    x, y, z = numpy.meshgrid(x_range, y_range, z_range, indexing="ij")
    # Alternative with slightly different order:
    # ```
    # nodes = numpy.stack([x, y, z]).T.reshape(-1, 3)
    # ```
    nodes = numpy.array([x, y, z]).T.reshape(-1, 3)

    # Create the elements (cells).
    # There is 1 way to split a cube into 5 tetrahedra,
    # and 12 ways to split it into 6 tetrahedra.
    # See
    # <http://www.baumanneduard.ch/Splitting%20a%20cube%20in%20tetrahedras2.htm>
    # Also interesting: <http://en.wikipedia.org/wiki/Marching_tetrahedrons>.

    a0 = numpy.add.outer(numpy.array(range(nx - 1)), nx * numpy.array(range(ny - 1)))
    a = numpy.add.outer(a0, nx * ny * numpy.array(range(nz - 1)))

    # The general scheme here is:
    #  * Initialize everything with `a`, equivalent to
    #    [i + nx * j + nx*ny * k].
    #  * Add the "even" elements.
    #  * Switch the element styles for every other element to make sure the
    #    edges match at the faces of the cubes.
    # The last step requires adapting the original pattern at
    #     [1::2, 0::2, 0::2, :]
    #     [0::2, 1::2, 0::2, :]
    #     [0::2, 0::2, 1::2, :]
    #     [1::2, 1::2, 1::2, :]
    #

    # Tetrahedron 0:
    # [
    # i   + nx*j     + nx*ny * k,
    # i   + nx*(j+1) + nx*ny * k,
    # i+1 + nx*j     + nx*ny * k,
    # i   + nx*j     + nx*ny * (k+1)
    # ]
    # TODO get
    # ```
    # elems0 = numpy.stack([a, a + nx, a + 1, a + nx*ny]).T
    # ```
    # back.
    elems0 = numpy.concatenate(
        [a[..., None], a[..., None] + nx, a[..., None] + 1, a[..., None] + nx * ny],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * j     + nx*ny * k,
    # i+1 + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1)
    # ]
    elems0[1::2, 0::2, 0::2, 0] += 1
    elems0[0::2, 1::2, 0::2, 0] += 1
    elems0[0::2, 0::2, 1::2, 0] += 1
    elems0[1::2, 1::2, 1::2, 0] += 1

    elems0[1::2, 0::2, 0::2, 1] += 1
    elems0[0::2, 1::2, 0::2, 1] += 1
    elems0[0::2, 0::2, 1::2, 1] += 1
    elems0[1::2, 1::2, 1::2, 1] += 1

    elems0[1::2, 0::2, 0::2, 2] -= 1
    elems0[0::2, 1::2, 0::2, 2] -= 1
    elems0[0::2, 0::2, 1::2, 2] -= 1
    elems0[1::2, 1::2, 1::2, 2] -= 1

    elems0[1::2, 0::2, 0::2, 3] += 1
    elems0[0::2, 1::2, 0::2, 3] += 1
    elems0[0::2, 0::2, 1::2, 3] += 1
    elems0[1::2, 1::2, 1::2, 3] += 1

    # Tetrahedron 1:
    # [
    # i   + nx*(j+1) + nx*ny * k,
    # i+1 + nx*(j+1) + nx*ny * k,
    # i+1 + nx*j     + nx*ny * k,
    # i+1 + nx*(j+1) + nx*ny * (k+1)
    # ]
    # elems1 = numpy.stack([a + nx, a + 1 + nx, a + 1, a + 1 + nx + nx*ny]).T
    elems1 = numpy.concatenate(
        [
            a[..., None] + nx,
            a[..., None] + 1 + nx,
            a[..., None] + 1,
            a[..., None] + 1 + nx + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * (j+1) + nx*ny * k,
    # i   + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * k,
    # i   + nx * (j+1) + nx*ny * (k+1)
    # ]
    elems1[1::2, 0::2, 0::2, 0] += 1
    elems1[0::2, 1::2, 0::2, 0] += 1
    elems1[0::2, 0::2, 1::2, 0] += 1
    elems1[1::2, 1::2, 1::2, 0] += 1

    elems1[1::2, 0::2, 0::2, 1] -= 1
    elems1[0::2, 1::2, 0::2, 1] -= 1
    elems1[0::2, 0::2, 1::2, 1] -= 1
    elems1[1::2, 1::2, 1::2, 1] -= 1

    elems1[1::2, 0::2, 0::2, 2] -= 1
    elems1[0::2, 1::2, 0::2, 2] -= 1
    elems1[0::2, 0::2, 1::2, 2] -= 1
    elems1[1::2, 1::2, 1::2, 2] -= 1

    elems1[1::2, 0::2, 0::2, 3] -= 1
    elems1[0::2, 1::2, 0::2, 3] -= 1
    elems1[0::2, 0::2, 1::2, 3] -= 1
    elems1[1::2, 1::2, 1::2, 3] -= 1

    # Tetrahedron 2:
    # [
    # i   + nx*(j+1) + nx*ny * k,
    # i+1 + nx*j     + nx*ny * k,
    # i   + nx*j     + nx*ny * (k+1),
    # i+1 + nx*(j+1) + nx*ny * (k+1)
    # ]
    # elems2 = numpy.stack([a + nx, a + 1, a + nx*ny, a + 1 + nx + nx*ny]).T
    elems2 = numpy.concatenate(
        [
            a[..., None] + nx,
            a[..., None] + 1,
            a[..., None] + nx * ny,
            a[..., None] + 1 + nx + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1)
    # ]
    elems2[1::2, 0::2, 0::2, 0] += 1
    elems2[0::2, 1::2, 0::2, 0] += 1
    elems2[0::2, 0::2, 1::2, 0] += 1
    elems2[1::2, 1::2, 1::2, 0] += 1

    elems2[1::2, 0::2, 0::2, 1] -= 1
    elems2[0::2, 1::2, 0::2, 1] -= 1
    elems2[0::2, 0::2, 1::2, 1] -= 1
    elems2[1::2, 1::2, 1::2, 1] -= 1

    elems2[1::2, 0::2, 0::2, 2] += 1
    elems2[0::2, 1::2, 0::2, 2] += 1
    elems2[0::2, 0::2, 1::2, 2] += 1
    elems2[1::2, 1::2, 1::2, 2] += 1

    elems2[1::2, 0::2, 0::2, 3] -= 1
    elems2[0::2, 1::2, 0::2, 3] -= 1
    elems2[0::2, 0::2, 1::2, 3] -= 1
    elems2[1::2, 1::2, 1::2, 3] -= 1

    # Tetrahedron 3:
    # [
    # i   + nx * (j+1) + nx*ny * k,
    # i   + nx * j     + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1),
    # i+1 + nx * (j+1) + nx*ny * (k+1)
    # ]
    # elems3 = numpy.stack([
    #     a + nx,
    #     a + nx*ny,
    #     a + nx + nx*ny,
    #     a + 1 + nx + nx*ny
    #     ]).T
    elems3 = numpy.concatenate(
        [
            a[..., None] + nx,
            a[..., None] + nx * ny,
            a[..., None] + nx + nx * ny,
            a[..., None] + 1 + nx + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i+1 + nx * (j+1) + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1),
    # i+1 + nx * (j+1) + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1)
    # ]
    elems3[1::2, 0::2, 0::2, 0] += 1
    elems3[0::2, 1::2, 0::2, 0] += 1
    elems3[0::2, 0::2, 1::2, 0] += 1
    elems3[1::2, 1::2, 1::2, 0] += 1

    elems3[1::2, 0::2, 0::2, 1] += 1
    elems3[0::2, 1::2, 0::2, 1] += 1
    elems3[0::2, 0::2, 1::2, 1] += 1
    elems3[1::2, 1::2, 1::2, 1] += 1

    elems3[1::2, 0::2, 0::2, 2] += 1
    elems3[0::2, 1::2, 0::2, 2] += 1
    elems3[0::2, 0::2, 1::2, 2] += 1
    elems3[1::2, 1::2, 1::2, 2] += 1

    elems3[1::2, 0::2, 0::2, 3] -= 1
    elems3[0::2, 1::2, 0::2, 3] -= 1
    elems3[0::2, 0::2, 1::2, 3] -= 1
    elems3[1::2, 1::2, 1::2, 3] -= 1

    # Tetrahedron 4:
    # [
    # i+1 + nx * j     + nx*ny * k,
    # i   + nx * j     + nx*ny * (k+1),
    # i+1 + nx * (j+1) + nx*ny * (k+1),
    # i+1 + nx * j     + nx*ny * (k+1)
    # ]
    # elems4 = numpy.stack([
    #     a + 1,
    #     a + nx*ny,
    #     a + 1 + nx + nx*ny,
    #     a + 1 + nx*ny
    #     ]).T
    elems4 = numpy.concatenate(
        [
            a[..., None] + 1,
            a[..., None] + nx * ny,
            a[..., None] + 1 + nx + nx * ny,
            a[..., None] + 1 + nx * ny,
        ],
        axis=3,
    )

    # Every other element cube:
    # [
    # i   + nx * j     + nx*ny * k,
    # i+1 + nx * j     + nx*ny * (k+1),
    # i   + nx * (j+1) + nx*ny * (k+1),
    # i   + nx * j     + nx*ny * (k+1)
    # ]
    elems4[1::2, 0::2, 0::2, 0] -= 1
    elems4[0::2, 1::2, 0::2, 0] -= 1
    elems4[0::2, 0::2, 1::2, 0] -= 1
    elems4[1::2, 1::2, 1::2, 0] -= 1

    elems4[1::2, 0::2, 0::2, 1] += 1
    elems4[0::2, 1::2, 0::2, 1] += 1
    elems4[0::2, 0::2, 1::2, 1] += 1
    elems4[1::2, 1::2, 1::2, 1] += 1

    elems4[1::2, 0::2, 0::2, 2] -= 1
    elems4[0::2, 1::2, 0::2, 2] -= 1
    elems4[0::2, 0::2, 1::2, 2] -= 1
    elems4[1::2, 1::2, 1::2, 2] -= 1

    elems4[1::2, 0::2, 0::2, 3] -= 1
    elems4[0::2, 1::2, 0::2, 3] -= 1
    elems4[0::2, 0::2, 1::2, 3] -= 1
    elems4[1::2, 1::2, 1::2, 3] -= 1

    elems = numpy.vstack(
        [
            elems0.reshape(-1, 4),
            elems1.reshape(-1, 4),
            elems2.reshape(-1, 4),
            elems3.reshape(-1, 4),
            elems4.reshape(-1, 4),
        ]
    )

    return nodes, elems
1068598
def color_reducer(c1, c2):
    """"""
    return tuple(v1 + v2 for v1, v2 in itertools.izip(c1, c2))