code
stringlengths
1
18.2k
None: return imageio.imsave(filename, im, format) elif PIL is not None: pim = PIL.Image.fromarray(im) pim.save(filename, format) else: raise RuntimeError("imsave requires the imageio or PIL package.")
def _check_img_lib(): """Utility to search for imageio or PIL""" # Import imageio or PIL imageio = PIL = None try: import imageio except ImportError: try: import PIL.Image except ImportError: pass return imageio, PIL
def read_from_user(input_type, *args, **kwargs): ''' Helper function to prompt user for input of a specific type e.g. float, str, int Designed to work with both python 2 and 3 Yes I know this is ugly. ''' def _read_in(*args, **kwargs): while True: try: tmp = raw_input(*args, **kwargs) except NameError: tmp = input(*arg...
def load_builtin_slots(): ''' Helper function to load builtin slots from the data location ''' builtin_slots = {} for index, line in enumerate(open(BUILTIN_SLOTS_LOCATION)): o = line.strip().split('\t') builtin_slots[index] = {'name' : o[0], 'description' : o[1] } return builtin_slots
def timer(logger=None, level=logging.INFO, fmt="function %(function_name)s execution time: %(execution_time).3f", *func_or_func_args, **timer_kwargs): """ Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor. """ # store Timer kwargs in local variab...
= { 'function_name': f.__name__, 'execution_time': t.elapsed, } if logger: logger.log( level, fmt % context, extra=context) else: print(fmt % context) return out return wrapped if (len(func_or_func_args) == 1 and isinstance(func_or_func_args[0], collections.Callable)): return wrapped_f(func_or_func_args[0]) else: retur...
def append(self, points, indices, **kwargs): """ Append a new set of vertices to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- points : np.array Vertices composing the triangles indices : np.array Indices describing triangles color : list, ...
* itemsize, dtype=self.vtype) for name in self.vtype.names: if name not in ['collection_index', 'position']: V[name] = kwargs.get(name, self._defaults[name]) V["position"] = points # Uniforms if self.utype: U = np.zeros(itemcount, dtype=self.utype) for name in self.utype.names: if name not in ["__unused__"]: U[name] = ...
def _mpl_to_vispy(fig): """Convert a given matplotlib figure to vispy This function is experimental and subject to change! Requires matplotlib and mplexporter. Parameters ---------- fig : instance of matplotlib Figure The populated figure to display. Returns ------- canvas : instance of Canvas The resulting vispy Canva...
def show(block=False): """Show current figures using vispy Parameters ---------- block : bool If True, blocking mode will be used. If False, then non-blocking / interactive mode will be used. Returns ------- canvases : list List of the vispy canvases that were created. """ if not has_matplotlib(): raise ImportError('Re...
0: cs[0].app.run() return cs
def _mpl_ax_to(self, mplobj, output='vb'): """Helper to get the parent axes of a given mplobj""" for ax in self._axs.values(): if ax['ax'] is mplobj.axes: return ax[output] raise RuntimeError('Parent axes could not be found!')
def random(adjacency_mat, directed=False, random_state=None): """ Place the graph nodes at random places. Parameters ---------- adjacency_mat : matrix or sparse The graph adjacency matrix directed : bool Whether the graph is directed. If this is True, is will also generate the vertices for arrows, which can be passed t...
be None to use ``np.random``. Yields ------ (node_vertices, line_vertices, arrow_vertices) : tuple Yields the node and line vertices in a tuple. This layout only yields a single time, and has no builtin animation """ if random_state is None: random_state = np.random elif not isinstance(random_state, np.random.RandomSta...
1 num_nodes = adjacency_mat.shape[0] node_coords = random_state.rand(num_nodes, 2) line_vertices, arrows = _straight_line_vertices(adjacency_mat, node_coords, directed) yield node_coords, line_vertices, arrows
def isocurve(data, level, connected=False, extend_to_edge=False): """ Generate isocurve from 2D data using marching squares algorithm. Parameters ---------- data : ndarray 2D numpy array of scalar values level : float The level at which to generate an isosurface connected : bool If False, return a single long list of p...
better for drawing continuous lines) extend_to_edge : bool If True, extend the curves to reach the exact edges of the data. """ # This function is SLOW; plenty of room for optimization here. if extend_to_edge: d2 = np.empty((data.shape[0]+2, data.shape[1]+2), dtype=data.dtype) d2[1:-1, 1:-1] = data d2[0, 1:-1] = data[0...
= d2[0, 1] d2[0, -1] = d2[1, -1] d2[-1, 0] = d2[-1, 1] d2[-1, -1] = d2[-1, -2] data = d2 side_table = [ [], [0, 1], [1, 2], [0, 2], [0, 3], [1, 3], [0, 1, 2, 3], [2, 3], [2, 3], [0, 1, 2, 3], [1, 3], [0, 3], [0, 2], [1, 2], [0, 1], [] ] edge_key = [ [(0, 1),
(0, 0)], [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), (0, 1)] ] level = float(level) lines = [] # mark everything below the isosurface level mask = data < level ## make four sub-fields and compute indexes for grid cells index = np.zeros([x-1 for x in data.shape], dtype=np.ubyte) fields = np.empty((2, 2), dtype=object) ...
in [0, 1]: for j in [0, 1]: fields[i, j] = mask[slices[i], slices[j]] vertIndex = i+2*j index += (fields[i, j] * 2**vertIndex).astype(np.ubyte) # add lines for i in range(index.shape[0]): # data x-axis for j in range(index.shape[1]): # data y-axis sides = side_table[index[i, j]] for l in range(0, len(sides), 2): # face...
[0, 1]: # points in this face # p1, p2 are points at either side of an edge p1 = edge_key[edges[m]][0] p2 = edge_key[edges[m]][1] # v1 and v2 are the values at p1 and p2 v1 = data[i+p1[0], j+p1[1]] v2 = data[i+p2[0], j+p2[1]] f = (level-v1) / (v2-v1) fi = 1.0 - f # interpolate between corners p = (p1[0]*fi + p2[0]*f + ...
+ 0.5, p1[1]*fi + p2[1]*f + j + 0.5) if extend_to_edge: # check bounds p = (min(data.shape[0]-2, max(0, p[0]-1)), min(data.shape[1]-2, max(0, p[1]-1))) if connected: gridKey = (i + (1 if edges[m] == 2 else 0), j + (1 if edges[m] == 3 else 0), edges[m] % 2) # give the actual position and a key identifying the # grid loc...
gridKey)) else: pts.append(p) lines.append(pts) if not connected: return lines # turn disjoint list of segments into continuous lines points = {} # maps each point to its connections for a, b in lines: if a[1] not in points: points[a[1]] = [] points[a[1]].append([a, b]) if b[1] not in points: points[b[1]] = [] points[b...
points[k] except KeyError: # already used this point elsewhere continue for chain in chains: x = None while True: if x == chain[-1][1]: break # nothing left to do on this chain x = chain[-1][1] if x == k: # chain has looped; we're done and can ignore the opposite # chain break y = chain[-2][1] connects = points[x] for ...
conn[1][1] != y: chain.extend(conn[1:]) del points[x] if chain[0][1] == chain[-1][1]: # looped chain; no need to continue the other direction chains.pop() break # extract point locations lines = [] for chain in points.values(): if len(chain) == 2: # join together ends of chain chain = chain[1][1:][::-1] + chain[0] else...
def pos(self): """ The position of this event in the local coordinate system of the visual. """ if self._pos is None: tr = self.visual.get_transform('canvas', 'visual') self._pos = tr.map(self.mouse_event.pos) return self._pos
def last_event(self): """ The mouse event immediately prior to this one. This property is None when no mouse buttons are pressed. """ if self.mouse_event.last_event is None: return None ev = self.copy() ev.mouse_event = self.mouse_event.last_event return ev
def press_event(self): """ The mouse press event that initiated a mouse drag, if any. """ if self.mouse_event.press_event is None: return None ev = self.copy() ev.mouse_event = self.mouse_event.press_event return ev
def check_enum(enum, name=None, valid=None): """ Get lowercase string representation of enum. """ name = name or 'enum' # Try to convert res = None if isinstance(enum, int): if hasattr(enum, 'name') and enum.name.startswith('GL_'): res = enum.name[3:].lower() elif isinstance(enum, string_types): res = enum.lower() # Ch...
valid: raise ValueError('Value of %s must be one of %r, not %r' % (name, valid, enum)) return res
def draw_texture(tex): """Draw a 2D texture to the current viewport Parameters ---------- tex : instance of Texture2D The texture to draw. """ from .program import Program program = Program(vert_draw, frag_draw) program['u_texture'] = tex program['a_position'] = [[-1., -1.], [-1., 1.], [1., -1.], [1., 1.]] program['a_t...
def _get_dpi_from(cmd, pattern, func): """Match pattern against the output of func, passing the results as floats to func. If anything fails, return None. """ try: out, _ = run_subprocess([cmd]) except (OSError, CalledProcessError): pass else: match = re.search(pattern, out) if match: return func(*map(float, match.grou...
def get_dpi(raise_error=True): """Get screen DPI from the OS Parameters ---------- raise_error : bool If True, raise an error if DPI could not be determined. Returns ------- dpi : float Dots per inch of the primary screen. """ # If we are running without an X server (e.g. OSMesa), use a fixed DPI if 'DISPLAY' not in os...
dots per inch', lambda x_dpi, y_dpi: (x_dpi + y_dpi) / 2) if from_xdpyinfo is not None: return from_xdpyinfo from_xrandr = _get_dpi_from( 'xrandr', r'(\d+)x(\d+).*?(\d+)mm x (\d+)mm', lambda x_px, y_px, x_mm, y_mm: 25.4 * (x_px / x_mm + y_px / y_mm) / 2) if from_xrandr is not None: return from_xrandr if raise_error: ra...
def set_data(self, adjacency_mat=None, **kwargs): """Set the data Parameters ---------- adjacency_mat : ndarray | None The adjacency matrix. **kwargs : dict Keyword arguments to pass to the arrows. """ if adjacency_mat is not None: if adjacency_mat.shape[0] != adjacency_mat.shape[1]: raise ValueError("Adjacency matrix ...
translated, kwargs.pop(k)) arrow_kwargs = {} for k in self._arrow_kwargs: if k in kwargs: translated = (self._arrow_kw_trans[k] if k in self._arrow_kw_trans else k) arrow_kwargs[translated] = kwargs.pop(k) node_kwargs = {} for k in self._node_kwargs: if k in kwargs: translated = (self._node_kw_trans[k] if k in self._no...
actual data is set in GraphVisual.animate_layout or # GraphVisual.set_final_layout self._arrow_data = arrow_kwargs self._node_data = node_kwargs if not self._animate: self.set_final_layout()
def calc_size(rect, orientation): """Calculate a size Parameters ---------- rect : rectangle The rectangle. orientation : str Either "bottom" or "top". """ (total_halfx, total_halfy) = rect.center if orientation in ["bottom", "top"]: (total_major_axis, total_minor_axis) = (total_halfx, total_halfy) else: (total_major_a...
clamp minor_axis = np.minimum(minor_axis, total_minor_axis * (1.0 - ColorBarWidget.minor_axis_padding)) return (major_axis, minor_axis)
def dtype_reduce(dtype, level=0, depth=0): """ Try to reduce dtype up to a given level when it is possible dtype = [ ('vertex', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('normal', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('color', [('r', 'f4'), ('g', 'f4'), ('b', 'f4'), ('a', 'f4')])] level 0: ['color,vertex,normal,'...
fields = dtype.fields # No fields if fields is None: if len(dtype.shape): count = reduce(mul, dtype.shape) else: count = 1 # size = dtype.itemsize / count if dtype.subdtype: name = str(dtype.subdtype[0]) else: name = str(dtype) return ['', count, name] else: items = [] name = '' # Get reduced fields for key, value in f...
is str: items.append([key, l[1], l[2]]) else: items.append(l) name += key + ',' # Check if we can reduce item list ctype = None count = 0 for i, item in enumerate(items): # One item is a list, we cannot reduce if type(item[0]) is not str: return items else: if i == 0: ctype = item[2] count += item[1] else: if item[2] !...
items count += item[1] if depth >= level: return [name, count, ctype] else: return items
def fetchcode(utype, prefix=""): """ Generate the GLSL code needed to retrieve fake uniform values from a texture. uniforms : sampler2D Texture to fetch uniforms from uniforms_shape: vec3 Size of texture (width,height,count) where count is the number of float to be fetched. collection_index: float Attribute giving the ...
python side. """ utype = np.dtype(utype) _utype = dtype_reduce(utype, level=1) header = """ uniform sampler2D uniforms; uniform vec3 uniforms_shape; attribute float collection_index; """ # Header generation (easy) types = {1: 'float', 2: 'vec2 ', 3: 'vec3 ', 4: 'vec4 ', 9: 'mat3 ', 16: 'mat4 '} for name, count, _ in _u...
name) # Body generation (not so easy) body = """\nvoid fetch_uniforms() { float rows = uniforms_shape.x; float cols = uniforms_shape.y; float count = uniforms_shape.z; float index = collection_index; int index_x = int(mod(index, (floor(cols/(count/4.0))))) * int(count/4.0); int index_y = int(floor(index / (floor(cols/(...
int i = index_x; vec4 _uniform;\n""" _utype = dict([(name, count) for name, count, _ in _utype]) store = 0 # Be very careful with utype name order (_utype.keys is wrong) for name in utype.names: if name == '__unused__': continue count, shift = _utype[name], 0 size = count while count: if store == 0: body += "\n _unifor...
4 if store == 4: a = "xyzw" elif store == 3: a = "yzw" elif store == 2: a = "zw" elif store == 1: a = "w" if shift == 0: b = "xyzw" elif shift == 1: b = "yzw" elif shift == 2: b = "zw" elif shift == 3: b = "w" i = min(min(len(b), count), len(a)) if size
> 1: body += " %s%s.%s = _uniform.%s;\n" % (prefix, name, b[:i], a[:i]) # noqa else: body += " %s%s = _uniform.%s;\n" % (prefix, name, a[:i]) count -= i shift += i store -= i body += """}\n\n""" return header + body
def create_cube(): """ Generate vertices & indices for a filled and outlined cube Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. filled : array Indices to use to produce a filled cube. outline : array Indices to use to produce an outline of the cube. """ vtype = [('position', np....
np.float32, 4)] itype = np.uint32 # Vertices positions p = np.array([[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1]]) # Face Normals n = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0], [-1, 0, 1], [0, -1, 0], [0, 0, -1]]) # Vertice colors c = np.array([[1, 1,
1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [1, 0, 1, 1], [1, 0, 0, 1], [1, 1, 0, 1], [0, 1, 0, 1], [0, 0, 0, 1]]) # Texture coords t = np.array([[0, 0], [0, 1], [1, 1], [1, 0]]) faces_p = [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3,
2, 4, 7, 6, 5] faces_c = [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5] faces_n = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5] faces_t = [0, 1, 2, 3, 0,
1, 2, 3, 0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, 3, 0, 1, 2, 3] vertices = np.zeros(24, vtype) vertices['position'] = p[faces_p] vertices['normal'] = n[faces_n] vertices['color'] = c[faces_c] vertices['texcoord'] = t[faces_t] filled = np.resize( np.array([0, 1, 2, 0, 2, 3], dtype=itype), 6 * (2 * 3)) filled += np.repeat(4 * n...
= np.resize( np.array([0, 1, 1, 2, 2, 3, 3, 0], dtype=itype), 6 * (2 * 4)) outline += np.repeat(4 * np.arange(6, dtype=itype), 8) return vertices, filled, outline
def create_plane(width=1, height=1, width_segments=1, height_segments=1, direction='+z'): """ Generate vertices & indices for a filled and outlined plane. Parameters ---------- width : float Plane width. height : float Plane height. width_segments : int Plane segments count along the width. height_segments : float Plan...
: array Array of vertices suitable for use as a VertexBuffer. faces : array Indices to use to produce a filled plane. outline : array Indices to use to produce an outline of the plane. References ---------- .. [1] Cabello, R. (n.d.). PlaneBufferGeometry.js. Retrieved May 12, 2015, from http://git.io/vU1Fh """ x_grid = ...
+ 1 # Positions, normals and texcoords. positions = np.zeros(x_grid1 * y_grid1 * 3) normals = np.zeros(x_grid1 * y_grid1 * 3) texcoords = np.zeros(x_grid1 * y_grid1 * 2) y = np.arange(y_grid1) * height / y_grid - height / 2 x = np.arange(x_grid1) * width / x_grid - width / 2 positions[::3] = np.tile(x, y_grid1) positio...
/ x_grid, y_grid1) texcoords[1::2] = np.repeat(1 - np.arange(y_grid1) / y_grid, x_grid1) # Faces and outline. faces, outline = [], [] for i_y in range(y_grid): for i_x in range(x_grid): a = i_x + x_grid1 * i_y b = i_x + x_grid1 * (i_y + 1) c = (i_x + 1) + x_grid1 * (i_y + 1) d = (i_x + 1) + x_grid1 * i_y
faces.extend(((a, b, d), (b, c, d))) outline.extend(((a, b), (b, c), (c, d), (d, a))) positions = np.reshape(positions, (-1, 3)) texcoords = np.reshape(texcoords, (-1, 2)) normals = np.reshape(normals, (-1, 3)) faces = np.reshape(faces, (-1, 3)).astype(np.uint32) outline = np.reshape(outline, (-1, 2)).astype(np.uint32)...
in ('-z', '+z'): shift, neutral_axis = 0, 2 sign = -1 if '-' in direction else 1 positions = np.roll(positions, shift, -1) normals = np.roll(normals, shift, -1) * sign colors = np.ravel(positions) colors = np.hstack((np.reshape(np.interp(colors, (np.min(colors), np.max(colors)), (0, 1)), positions.shape), np.ones((posi...
vertices['texcoord'] = texcoords vertices['normal'] = normals vertices['color'] = colors return vertices, faces, outline
def create_box(width=1, height=1, depth=1, width_segments=1, height_segments=1, depth_segments=1, planes=None): """ Generate vertices & indices for a filled and outlined box. Parameters ---------- width : float Box width. height : float Box height. depth : float Box depth. width_segments : int Box segments count along ...
array_like Any combination of ``{'-x', '+x', '-y', '+y', '-z', '+z'}`` Included planes in the box construction. Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. faces : array Indices to use to produce a filled box. outline : array Indices to use to produce an outline of the box. ""...
planes is None else [d.lower() for d in planes]) w_s, h_s, d_s = width_segments, height_segments, depth_segments planes_m = [] if '-z' in planes: planes_m.append(create_plane(width, depth, w_s, d_s, '-z')) planes_m[-1][0]['position'][..., 2] -= height / 2 if '+z' in planes: planes_m.append(create_plane(width, depth, w_...
if '+y' in planes: planes_m.append(create_plane(height, width, h_s, w_s, '+y')) planes_m[-1][0]['position'][..., 1] += depth / 2 if '-x' in planes: planes_m.append(create_plane(depth, height, d_s, h_s, '-x')) planes_m[-1][0]['position'][..., 0] -= width / 2 if '+x' in planes: planes_m.append(create_plane(depth, height,...
dtype=np.uint32) outline = np.zeros((0, 2), dtype=np.uint32) offset = 0 for vertices_p, faces_p, outline_p in planes_m: positions = np.vstack((positions, vertices_p['position'])) texcoords = np.vstack((texcoords, vertices_p['texcoord'])) normals = np.vstack((normals, vertices_p['normal'])) faces = np.vstack((faces, fac...
np.max(colors)), (0, 1)), positions.shape), np.ones((positions.shape[0], 1)))) vertices['position'] = positions vertices['texcoord'] = texcoords vertices['normal'] = normals vertices['color'] = colors return vertices, faces, outline
def create_sphere(rows=10, cols=10, depth=10, radius=1.0, offset=True, subdivisions=3, method='latitude'): """Create a sphere Parameters ---------- rows : int Number of rows (for method='latitude' and 'cube'). cols : int Number of columns (for method='latitude' and 'cube'). depth : int Number of depth segments (for met...
subdivisions to perform (for method='ico') method : str Method for generating sphere. Accepts 'latitude' for latitude- longitude, 'ico' for icosahedron, and 'cube' for cube based tessellation. Returns ------- sphere : MeshData Vertices and faces computed for a spherical surface. """ if method == 'latitude': return _lat...
radius) else: raise Exception("Invalid method. Accepts: 'latitude', 'ico', 'cube'")
def create_cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False): """Create a cylinder Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : tuple of float Cylinder radii. length : float Length of the cylinder. offset : bool Rotate each row by half a column. Returns -------...
np.empty((rows+1, cols, 3), dtype=np.float32) if isinstance(radius, int): radius = [radius, radius] # convert to list # compute vertices th = np.linspace(2 * np.pi, 0, cols).reshape(1, cols) # radius as a function of z r = np.linspace(radius[0], radius[1], num=rows+1, endpoint=True).reshape(rows+1, 1) verts[..., 2] = n...
/ cols) * np.arange(rows+1).reshape(rows+1, 1)) verts[..., 0] = r * np.cos(th) # x = r cos(th) verts[..., 1] = r * np.sin(th) # y = r sin(th) # just reshape: no redundant vertices... verts = verts.reshape((rows+1)*cols, 3) # compute faces faces = np.empty((rows*cols*2, 3), dtype=np.uint32) rowtemplate1 = (((np.arange(c...
np.array([[0, 1, 1]])) % cols) + np.array([[cols, 0, cols]])) for row in range(rows): start = row * cols * 2 faces[start:start+cols] = rowtemplate1 + row * cols faces[start+cols:start+(cols*2)] = rowtemplate2 + row * cols return MeshData(vertices=verts, faces=faces)
def create_cone(cols, radius=1.0, length=1.0): """Create a cone Parameters ---------- cols : int Number of faces. radius : float Base cone radius. length : float Length of the cone. Returns ------- cone : MeshData Vertices and faces computed for a cone surface. """ verts = np.empty((cols+1, 3), dtype=np.float32) # comp...
= radius * np.cos(th[0, :-1]) # x = r cos(th) verts[:-1, 1] = radius * np.sin(th[0, :-1]) # y = r sin(th) # Add the extremity verts[-1, 0] = 0.0 verts[-1, 1] = 0.0 verts[-1, 2] = length verts = verts.reshape((cols+1), 3) # just reshape: no redundant vertices # compute faces faces = np.empty((cols, 3), dtype=np.uint32) ...
faces[pos, :-1] = template + pos faces[:, 2] = cols faces[-1, 1] = 0 return MeshData(vertices=verts, faces=faces)
def create_arrow(rows, cols, radius=0.1, length=1.0, cone_radius=None, cone_length=None): """Create a 3D arrow using a cylinder plus cone Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : float Base cylinder radius. length : float Length of the arrow. cone_radius : float Radius of ...
Length of the cone. If None, then this defaults to 1/3 of the arrow length. Returns ------- arrow : MeshData Vertices and faces computed for a cone surface. """ # create the cylinder md_cyl = None if cone_radius is None: cone_radius = radius*2.0 if cone_length is None: con_L = length/3.0 cyl_L = length*2.0/3.0 else: cy...
if cyl_L != 0: md_cyl = create_cylinder(rows, cols, radius=[radius, radius], length=cyl_L) # create the cone md_con = create_cone(cols, radius=cone_radius, length=con_L) verts = md_con.get_vertices() nbr_verts_con = verts.size//3 faces = md_con.get_faces() if md_cyl is not None: trans = np.array([[0.0, 0.0, cyl_L]]) ve...
def create_grid_mesh(xs, ys, zs): '''Generate vertices and indices for an implicitly connected mesh. The intention is that this makes it simple to generate a mesh from meshgrid data. Parameters ---------- xs : ndarray A 2d array of x coordinates for the vertices of the mesh. Must have the same dimensions as ys and zs. ...
the vertices of the mesh. Must have the same dimensions as xs and zs. zs : ndarray A 2d array of z coordinates for the vertices of the mesh. Must have the same dimensions as xs and ys. Returns ------- vertices : ndarray The array of vertices in the mesh. indices : ndarray The array of indices for the mesh. ''' shape = ...
length = shape[0] * shape[1] vertices = np.zeros((length, 3)) vertices[:, 0] = xs.reshape(length) vertices[:, 1] = ys.reshape(length) vertices[:, 2] = zs.reshape(length) basic_indices = np.array([0, 1, 1 + shape[1], 0, 0 + shape[1], 1 + shape[1]], dtype=np.uint32) inner_grid_length = (shape[0] - 1) * (shape[1] - 1) off...
+ offsets indices = indices.reshape((len(indices) // 3, 3)) return vertices, indices
def _straight_line_vertices(adjacency_mat, node_coords, directed=False): """ Generate the vertices for straight lines between nodes. If it is a directed graph, it also generates the vertices which can be passed to an :class:`ArrowVisual`. Parameters ---------- adjacency_mat : array The adjacency matrix of the graph nod...
is true it will also generate the vertices for arrows which can be passed to :class:`ArrowVisual`. Returns ------- vertices : tuple Returns a tuple containing containing (`line_vertices`, `arrow_vertices`) """ if not issparse(adjacency_mat): adjacency_mat = np.asarray(adjacency_mat, float) if (adjacency_mat.ndim != 2 o...
arrow_vertices = node_coords[arrows.ravel()] arrow_vertices = arrow_vertices.reshape((len(arrow_vertices)/2, 4)) return line_vertices, arrow_vertices
def _rescale_layout(pos, scale=1): """ Normalize the given coordinate list to the range [0, `scale`]. Parameters ---------- pos : array Coordinate list scale : number The upperbound value for the coordinates range Returns ------- pos : array The rescaled (normalized) coordinates in the range [0, `scale`]. Notes ----- C...
def get_handle(): ''' Get unique FT_Library handle ''' global __handle__ if not __handle__: __handle__ = FT_Library() error = FT_Init_FreeType(byref(__handle__)) if error: raise RuntimeError(hex(error)) return __handle__
def version(): ''' Return the version of the FreeType library being used as a tuple of ( major version number, minor version number, patch version number ) ''' amajor = FT_Int() aminor = FT_Int() apatch = FT_Int() library = get_handle() FT_Library_Version(library, byref(amajor), byref(aminor), byref(apatch)) return (am...
def make_camera(cam_type, *args, **kwargs): """ Factory function for creating new cameras using a string name. Parameters ---------- cam_type : str May be one of: * 'panzoom' : Creates :class:`PanZoomCamera` * 'turntable' : Creates :class:`TurntableCamera` * None : Creates :class:`Camera` Notes ----- All extra argument...
PanZoomCamera, PerspectiveCamera, TurntableCamera, FlyCamera, ArcballCamera): cam_types[camType.__name__[:-6].lower()] = camType try: return cam_types[cam_type](*args, **kwargs) except KeyError: raise KeyError('Unknown camera type "%s". Options are: %s' % (cam_type, cam_types.keys()))
def set_data_values(self, label, x, y, z): """ Set the position of the datapoints """ # TODO: avoid re-allocating an array every time self.layers[label]['data'] = np.array([x, y, z]).transpose() self._update()
def SegmentCollection(mode="agg-fast", *args, **kwargs): """ mode: string - "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness) - "agg" (speed: slower, size: medium, output: perfect, no dash) """ if mode == "raw": return RawSegmentCollection(*args, **kwargs) return AggSegmentCollection(*args, **kwa...
def surface(func, umin=0, umax=2 * np.pi, ucount=64, urepeat=1.0, vmin=0, vmax=2 * np.pi, vcount=64, vrepeat=1.0): """ Computes the parameterization of a parametric surface func: function(u,v) Parametric function used to build the surface """ vtype = [('position', np.float32, 3), ('texcoord', np.float32, 2), ('normal',...
1 ucount += 1 n = vcount * ucount Un = np.repeat(np.linspace(0, 1, ucount, endpoint=True), vcount) Vn = np.tile(np.linspace(0, 1, vcount, endpoint=True), ucount) U = umin + Un * (umax - umin) V = vmin + Vn * (vmax - vmin) vertices = np.zeros(n, dtype=vtype) for i, (u, v) in enumerate(zip(U, V)): vertices["position"][i]...
= Vn * vrepeat indices = [] for i in range(ucount - 1): for j in range(vcount - 1): indices.append(i * (vcount) + j) indices.append(i * (vcount) + j + 1) indices.append(i * (vcount) + j + vcount + 1) indices.append(i * (vcount) + j + vcount) indices.append(i * (vcount) + j + vcount + 1) indices.append(i * (vcount) + j)...
dtype=itype) vertices["normal"] = normals(vertices["position"], indices.reshape(len(indices) / 3, 3)) return vertices, indices
def PointCollection(mode="raw", *args, **kwargs): """ mode: string - "raw" (speed: fastest, size: small, output: ugly) - "agg" (speed: fast, size: small, output: beautiful) """ if mode == "raw": return RawPointCollection(*args, **kwargs) return AggPointCollection(*args, **kwargs)