Python create sphere

23 Python code examples are found related to " create sphere". 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.
Example 1
Source File: active_contour.py    From aitom with GNU General Public License v3.0 9 votes vote down vote up
def create_sphere(cx,cy,cz, r, resolution=360):
    '''
    create sphere with center (cx, cy, cz) and radius r
    '''
    phi = np.linspace(0, 2*np.pi, 2*resolution)
    theta = np.linspace(0, np.pi, resolution)

    theta, phi = np.meshgrid(theta, phi)

    r_xy = r*np.sin(theta)
    x = cx + np.cos(phi) * r_xy
    y = cy + np.sin(phi) * r_xy
    z = cz + r * np.cos(theta)

    return np.stack([x,y,z]) 
Example 2
Source File: benchmarks_ot_solvers.py    From geomloss with MIT License 6 votes vote down vote up
def create_sphere(n_samples = 1000):
    """Creates a uniform sample on the unit sphere."""
    n_samples = int(n_samples)

    indices = np.arange(0, n_samples, dtype=float) + 0.5
    phi = np.arccos(1 - 2 * indices / n_samples)
    theta = np.pi * (1 + 5**0.5) * indices

    x, y, z = np.cos(theta) * np.sin(phi), np.sin(theta) * np.sin(phi), np.cos(phi);
    points  = np.vstack( (x, y, z)).T
    weights = np.ones(n_samples) / n_samples

    return tensor(weights), tensor(points)

############################################################
# Simple (slow) display routine: 
Example 3
Source File: material.py    From cats-blender-plugin with MIT License 5 votes vote down vote up
def create_sphere_texture(self, filepath, obj=None):
        """ create a texture slot for environment mapping textures of MMD models.

        Args:
            material: the material object to add a texture_slot
            filepath: the file path to environment mapping texture.

        Returns:
            bpy.types.MaterialTextureSlot object
        """
        texture_slot = self.__material.texture_slots.create(self.__SPHERE_TEX_SLOT)
        texture_slot.texture_coords = 'NORMAL'
        texture_slot.texture = self.__load_texture(filepath)
        self.update_sphere_texture_type(obj)
        return texture_slot 
Example 4
Source File: pointobject.py    From Det3D with Apache License 2.0 5 votes vote down vote up
def CreateSphere(self, origin, r):
        "Create a sphere with given origin (x,y,z) and radius r"
        sphere = vtk.vtkSphereSource()
        sphere.SetCenter(origin)
        sphere.SetRadius(r)
        sphere.SetPhiResolution(25)
        sphere.SetThetaResolution(25)
        sphere.Update()

        self.pd = vtk.vtkPolyData()
        self.pd.DeepCopy(sphere.GetOutput())
        self.scalars = None
        self.SetupPipelineMesh() 
Example 5
Source File: mesh.py    From cmr with MIT License 5 votes vote down vote up
def create_sphere(n_subdivide=3):
    # 3 makes 642 verts, 1280 faces,
    # 4 makes 2562 verts, 5120 faces
    verts, faces = meshzoo.iso_sphere(n_subdivide)
    return verts, faces 
Example 6
Source File: visualization_3d.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_sphere(self, X, Y, Z, fn, n_sphere=0, n_render=0, n_index=0, r=0.03):
        """
        Method to create the sphere that represent the surface_points points
        Args:
            X: X coord
            Y: Y coord
            Z: Z corrd
            fn (int): id
            n_sphere (int): Number of the sphere
            n_render (int): Number of the render where the sphere belongs
            n_index (int): index value in the PandasDataframe of InupData.surface_points
            r (float): radius of the sphere

        Returns:
            vtk.vtkSphereWidget
        """
        s = vtk.vtkSphereWidget()
        s.SetInteractor(self.interactor)
        s.SetRepresentationToSurface()
        s.SetPriority(2)
        Z = Z * self.ve
        s.r_f = self._e_d_avrg * r
        s.PlaceWidget(X - s.r_f, X + s.r_f, Y - s.r_f, Y + s.r_f, Z - s.r_f, Z + s.r_f)
        s.GetSphereProperty().SetColor(mcolors.hex2color(self.geo_model._surfaces.df.set_index('id')['color'][fn]))#self.C_LOT[fn])

        s.SetCurrentRenderer(self.ren_list[n_render])
        s.n_sphere = n_sphere
        s.n_render = n_render
        s.index = n_index
        s.AddObserver("EndInteractionEvent", self.sphereCallback)  # EndInteractionEvent
        s.AddObserver("InteractionEvent", self.Callback_camera_reset)

        s.On()

        return s 
Example 7
Source File: vista.py    From gempy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_sphere_widgets(self, surface_points: pd.core.frame.DataFrame,
                              test_callback: Union[bool, None] = True, **kwargs) \
            -> List[vtk.vtkInteractionWidgetsPython.vtkSphereWidget]:
        """Create sphere widgets for each surface points with the call back to
        recompute the model.

        Args:
            surface_points (pd.core.frame.DataFrame):
            test_callback (bool):
            **kwargs:

        Returns:
            List[vtkInteractionWidgetsPython.vtkSphereWidget]:
        """
        radius = kwargs.get('radius', None)
        if radius is None:
            _e = self.extent
            _e_dx = _e[1] - _e[0]
            _e_dy = _e[3] - _e[2]
            _e_dz = _e[5] - _e[4]
            _e_d_avrg = (_e_dx + _e_dy + _e_dz) / 3
            radius = _e_d_avrg * .01

            # This is Bane way. It gives me some error with index slicing
            centers = surface_points[['X', 'Y', 'Z']]

            # This is necessary to change the color of the widget if change id
            colors = self._get_color_lot(is_faults=True, is_basement=False)[surface_points['surface']]
            self._color_lot = self._get_color_lot(is_faults=True, is_basement=False, index='id')
            s = self.p.add_sphere_widget(self.call_back_sphere,
                                         center=centers, color=colors.values, pass_widget=True,
                                         test_callback=test_callback,
                                         indices=surface_points.index.values,
                                         radius=radius, **kwargs)
            if type(s) is not list:
                s = [s]
            return s 
Example 8
Source File: load_electrodes.py    From mmvt with GNU General Public License v3.0 5 votes vote down vote up
def create_sphere(loc, rad, my_layers, name):
    bpy.ops.mesh.primitive_uv_sphere_add(
        ring_count=30, size=rad, view_align=False, enter_editmode=False, location=loc, layers=my_layers)
    bpy.ops.object.shade_smooth()
    bpy.context.active_object.name = name 
Example 9
Source File: mmvt_utils.py    From mmvt with GNU General Public License v3.0 5 votes vote down vote up
def create_ico_sphere(location, layers, name, size=.3, subdivisions=2, rotation=(0.0, 0.0, 0.0)):
    bpy.ops.mesh.primitive_ico_sphere_add(
        location=location, layers=layers, size=size, subdivisions=subdivisions,rotation=rotation)
    bpy.ops.object.shade_smooth()
    bpy.context.active_object.name = name
    return bpy.context.active_object 
Example 10
Source File: mesh.py    From blender-cli-rendering with GNU General Public License v3.0 5 votes vote down vote up
def create_smooth_sphere(location: Tuple[float, float, float] = (0.0, 0.0, 0.0),
                         radius: float = 1.0,
                         subdivision_level: int = 1,
                         name: Optional[str] = None) -> bpy.types.Object:
    bpy.ops.mesh.primitive_uv_sphere_add(radius=radius, location=location, calc_uvs=True)

    current_object = bpy.context.object

    if name is not None:
        current_object.name = name

    set_smooth_shading(current_object.data)
    add_subdivision_surface_modifier(current_object, subdivision_level)

    return current_object 
Example 11
Source File: treeviewer.py    From director with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createSphere(params):
        d = DebugData()
        color = params.get("color", DEFAULT_COLOR)[:3]
        d.addSphere(center=(0, 0, 0), radius=params["radius"], color=color)
        return [d.getPolyData()] 
Example 12
Source File: ciftify_recon_all.py    From ciftify with MIT License 5 votes vote down vote up
def create_reg_sphere(settings, subject_id, meshes):

    FS_reg_sphere_name, MSMSulc_reg_sphere_name = get_reg_sphere_names()

    run_fs_reg_LR(subject_id, settings.ciftify_data_dir, settings.high_res,
            FS_reg_sphere_name, meshes['AtlasSpaceNative'])

    if settings.reg_name == 'MSMSulc':
        reg_sphere_name = MSMSulc_reg_sphere_name
        run_MSMSulc_registration(subject_id, settings.ciftify_data_dir,
                    meshes, reg_sphere_name, FS_reg_sphere_name, settings.msm_config)
    else :
        reg_sphere_name = FS_reg_sphere_name
    return reg_sphere_name 
Example 13
Source File: triangulation.py    From pygbe with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_unit_sphere( recursion_level=2 ):
    """
    It creates a unit sphere based on a recursive division of a octahedron.

    Arguments:
    ----------
    recursion_level: int, times we want to divide the octahedron.

    Returns:
    --------
    vertex_array   : array, vertices of the sphere triangles.
    index_array    : array, indices of the triangles.
    center         : array, contains centers of each triangle.

    """
    vertex_array, index_array = octahedron_vertices, octahedron_triangles
    for i in range( recursion_level - 1 ):
        vertex_array, index_array  = divide_all(vertex_array, index_array)

    center = numpy.zeros((len(index_array), 3))
    for i in range(len(index_array)):
        triangle = numpy.array([vertex_array[index_array[i,0]], vertex_array[
            index_array[i,1]], vertex_array[index_array[i,2]]])
        center[i,:] = numpy.dot(numpy.transpose(triangle), 1/3.*numpy.ones(3))
        
    return vertex_array, index_array, center 
Example 14
Source File: visualizer.py    From tinyik with MIT License 5 votes vote down vote up
def create_sphere(p, r=.1, color=None):
    if color is None:
        color = [.8, .8, .8]
    geo = o3d.geometry.TriangleMesh.create_sphere(radius=r)
    geo.compute_vertex_normals()
    geo.paint_uniform_color(color)
    geo.transform(translate(p))
    return geo 
Example 15
Source File: gui_utils.py    From spimagine with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_sphere_coords(rx,ry,rz,Nphi=50, Ntheta=30, return_normals = False):
    ts = np.arccos(np.linspace(-1.,1.,Ntheta))
    ps = np.linspace(0,2.*np.pi,Nphi+1)

    T,P = np.meshgrid(ts,ps, indexing = "ij")

    xs = np.array([rx*np.cos(P)*np.sin(T),ry*np.sin(P)*np.sin(T),rz*np.cos(T)])

    coords = []
    normals = []
    for i in range(len(ts)-1):
        for j in range(len(ps)-1):
            coords.append(xs[:,i,j])
            coords.append(xs[:,i+1,j])
            coords.append(xs[:,i+1,j+1])
            coords.append(xs[:,i,j])
            coords.append(xs[:,i+1,j+1])
            coords.append(xs[:,i,j+1])

            #FIXME, wrong for rx != ry ....
            normals.append(1.*xs[:,i,j]/rx)
            normals.append(1.*xs[:,i+1,j]/rx)
            normals.append(1.*xs[:,i+1,j+1]/rx)
            normals.append(1.*xs[:,i,j]/rx)
            normals.append(1.*xs[:,i,j+1]/rx)
            normals.append(1.*xs[:,i+1,j+1]/rx)
    if return_normals:
        return np.array(coords), np.array(normals)
    else:
        return np.array(coords) 
Example 16
Source File: recipe-578652.py    From code with MIT License 5 votes vote down vote up
def CreateMirrorSphere(cx, cy, cz, r, colorRGB, rc):
    print "Creating mirror sphere..."
    # sphere is set of voxels which have distance = r to center
    for z in range(imgz):
        for y in range(imgy):
            for x in range(imgx):
                dx = x - cx
                dy = y - cy
                dz = z - cz
                d = math.sqrt(dx * dx + dy * dy + dz * dz)
                if abs(d - r) < 1.0:
                    voxelRGB[z][y][x] = colorRGB
                    opacity[z][y][x] = 1
                    normal[z][y][x] = (dx / d, dy / d, dz / d)
                    reflectivity[z][y][x] = rc 
Example 17
Source File: DistributedShipDeployer.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createMinSphere(self):
        cSphere = CollisionSphere(0, 0, 0, self.minRadius)
        cSphere.setTangible(1)
        cSphereNode = CollisionNode(self.uniqueName('ShipDeploy-MinSphere'))
        cSphereNode.setFromCollideMask(BitMask32.allOff())
        cSphereNode.setIntoCollideMask(PiratesGlobals.ShipCollideBitmask)
        cSphereNode.addSolid(cSphere)
        self.minSphere = self.attachNewNode(cSphereNode) 
Example 18
Source File: GameFSMShip.py    From Pirates-Online-Rewritten with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def createGrappleProximitySphere(self):
        self.grappleProximityStr = self.ship.uniqueName('grappleProximity')
        collSphere = CollisionSphere(0, 0, 0, 200)
        collSphere.setTangible(0)
        collSphereNode = CollisionNode(self.grappleProximityStr)
        collSphereNode.addSolid(collSphere)
        collSphereNode.setCollideMask(PiratesGlobals.ShipCollideBitmask)
        collSphereNodePath = self.ship.attachNewNode(collSphereNode)
        self.grappleProximityCollision = collSphereNodePath
        self.stashGrappleProximitySphere() 
Example 19
Source File: simple_sphere.py    From blender-scripting with MIT License 5 votes vote down vote up
def createSphere(origin=(0, 0, 0)):
    # Create icosphere
    bpy.ops.mesh.primitive_ico_sphere_add(location=origin)
    obj = bpy.context.object
    return obj 
Example 20
Source File: chan.py    From wonambi with GNU General Public License v3.0 4 votes vote down vote up
def create_sphere_around_elec(xyz, template_mri, distance=8, freesurfer=None):
    """Create an MRI mask around an electrode location,

    Parameters
    ----------
    xyz : ndarray
        3x0 array
    template_mri : path or str (as path) or nibabel.Nifti
        (path to) MRI to be used as template
    distance : float
        distance in mm between electrode and selected voxels
    freesurfer : instance of Freesurfer
        to adjust RAS coordinates, see Notes

    Returns
    -------
    3d bool ndarray
        mask where True voxels are within selected distance to the electrode

    Notes
    -----
    Freesurfer uses two coordinate systems: one for volumes ("RAS") and one for
    surfaces ("tkReg", "tkRAS", and "Surface RAS"), so the electrodes might be
    stored in one of the two systems. If the electrodes are in surface
    coordinates (f.e. if you can plot surface and electrodes in the same space),
    then you need to convert the coordinate system. This is done by passing an
    instance of Freesurfer.
    """
    if freesurfer is None:
        shift = 0
    else:
        shift = freesurfer.surface_ras_shift

    if isinstance(template_mri, str) or isinstance(template_mri, Path):
        template_mri = nload(str(template_mri))

    mask = zeros(template_mri.shape, dtype='bool')
    for vox in ndindex(template_mri.shape):
        vox_ras = apply_affine(template_mri.affine, vox) - shift
        if norm(xyz - vox_ras) <= distance:
            mask[vox] = True

    return mask 
Example 21
Source File: sphere.py    From pyntcloud with MIT License 4 votes vote down vote up
def create_sphere(center=[0, 0, 0], radius=1, n_points=100):
    """
    Generate a point cloud with the shape of a sphere.

    Parameters
    ----------
    center: (3,) array-like
        Default: [0, 0, 0]
        These will be the coordinates of the centroid of the sphere.abs
    radius: int or float
        Default: 1
    n_points: int
        Default: 100
        The output PyntCloud will have this number of points.abs
        The higher this number is, the better the sphere surface
        is represented.

    Return
    ------
    sphere: pd.DataFrame
        A DataFrame suitable to be used for PyntCloud(sphere) instantiation.
    """
    np_axis = round(np.sqrt(n_points - 2), 0) + 1

    index = np.arange(0, np.square(np_axis) + 2, 1)
    sphere = pd.DataFrame(np.zeros([np.size(index, 0), 3]),
                       index=index, columns=['x', 'y', 'z'])

    zmin = center[2] - radius
    zmax = center[2] + radius

    tick = 2 * np.pi / (np_axis + 1)
    xx = np.arange(tick, 2 * np.pi, tick)
    yy = np.arange(tick, 2 * np.pi, tick)

    u, v = np.meshgrid(xx, yy)
    x = radius * np.cos(u) * np.sin(v) + center[0]
    y = radius * np.sin(u) * np.sin(v) + center[1]
    z = radius * np.cos(v) + center[2]

    X = np.arange(0, 1)
    Y = np.arange(0, 1)
    Z = np.arange(0, 1)

    X[0] = center[0]
    Y[0] = center[1]
    Z[0] = zmin

    X = np.append(X, x.reshape([1, np.size(x)]))
    Y = np.append(Y, y.reshape([1, np.size(y)]))
    Z = np.append(Z, z.reshape([1, np.size(z)]))

    X = np.append(X, center[0])
    Y = np.append(Y, center[1])
    Z = np.append(Z, zmax)

    sphere.x = np.round(X.T, 4).astype(np.float32)
    sphere.y = np.round(Y.T, 4).astype(np.float32)
    sphere.z = np.round(Z.T, 4).astype(np.float32)

    return sphere 
Example 22
Source File: earth.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def create_sphere(self):
        """Creates longitude/latitude as 2D points and returns the corresponding
        texture coordinates for those positions."""
        lon = np.linspace(-180.0, 180.0, self.__nmer)
        lat = np.linspace(-90.0, 90.0, self.__npar)
        lon_g, lat_g = np.meshgrid(lon, lat, indexing='ij')
        pos = np.vstack([lon_g.ravel(), lat_g.ravel()]).T
        # Now create the texture map
        tcgx, tcgy = np.meshgrid(
            np.linspace(0.0, 1.0, len(lon)),
            np.linspace(0.0, 1.0, len(lat)),
            indexing='ij')
        tex = np.vstack([tcgx.ravel(), tcgy.ravel()]).T
        return pos, tex 
Example 23
Source File: mask.py    From nltools with MIT License 4 votes vote down vote up
def create_sphere(coordinates, radius=5, mask=None):
    """ Generate a set of spheres in the brain mask space

    Args:
        radius: vector of radius.  Will create multiple spheres if
                len(radius) > 1
        centers: a vector of sphere centers of the form [px, py, pz] or
                [[px1, py1, pz1], ..., [pxn, pyn, pzn]]

    """
    from nltools.data import Brain_Data

    if mask is not None:
        if not isinstance(mask, nib.Nifti1Image):
            if isinstance(mask, six.string_types):
                if os.path.isfile(mask):
                    mask = nib.load(mask)
            else:
                raise ValueError("mask is not a nibabel instance or a valid "
                                 "file name")

    else:
        mask = nib.load(resolve_mni_path(MNI_Template)['mask'])

    def sphere(r, p, mask):
        """ create a sphere of given radius at some point p in the brain mask

        Args:
            r: radius of the sphere
            p: point (in coordinates of the brain mask) of the center of the
                sphere

        """
        dims = mask.shape
        m = [dims[0]/2, dims[1]/2, dims[2]/2]
        x, y, z = np.ogrid[-m[0]:dims[0]-m[0],
                           -m[1]:dims[1]-m[1],
                           -m[2]:dims[2]-m[2]]
        mask_r = x*x + y*y + z*z <= r*r

        activation = np.zeros(dims)
        activation[mask_r] = 1
        translation_affine = np.array([[1, 0, 0, p[0]-m[0]],
                                       [0, 1, 0, p[1]-m[1]],
                                       [0, 0, 1, p[2]-m[2]],
                                       [0, 0, 0, 1]])

        return nib.Nifti1Image(activation, affine=translation_affine)

    if any(isinstance(i, list) for i in coordinates):
        if isinstance(radius, list):
            if len(radius) != len(coordinates):
                raise ValueError('Make sure length of radius list matches'
                                 'length of coordinate list.')
        elif isinstance(radius, int):
            radius = [radius]*len(coordinates)
        out = Brain_Data(nib.Nifti1Image(np.zeros_like(mask.get_data()),
                                         affine=mask.affine), mask=mask)
        for r, c in zip(radius, coordinates):
            out = out + Brain_Data(sphere(r, c, mask), mask=mask)
    else:
        out = Brain_Data(sphere(radius, coordinates, mask), mask=mask)
    out = out.to_nifti()
    out.get_data()[out.get_data() > 0.5] = 1
    out.get_data()[out.get_data() < 0.5] = 0
    return out