text
stringlengths
81
112k
Remove the layer artist for good def remove(self): """ Remove the layer artist for good """ self._multivol.deallocate(self.id) ARRAY_CACHE.pop(self.id, None) PIXEL_CACHE.pop(self.id, None)
Inject functions and constants from PyOpenGL but leave out the names that are deprecated or that we provide in our API. def _inject(): """ Inject functions and constants from PyOpenGL but leave out the names that are deprecated or that we provide in our API. """ # Get namespaces NS = globa...
Alternative to `imp.find_module` that can also search in subpackages. def _find_module(name, path=None): """ Alternative to `imp.find_module` that can also search in subpackages. """ parts = name.split('.') for part in parts: if path is not None: path = [path] fh, pat...
Triangulate a set of vertices Parameters ---------- vertices : array-like The vertices. Returns ------- vertices : array-like The vertices. tringles : array-like The triangles. def triangulate(vertices): """Triangulate a set of vertices Parameters ----...
Do the triangulation def triangulate(self): """Do the triangulation """ self._initialize() pts = self.pts front = self._front ## Begin sweep (sec. 3.4) for i in range(3, pts.shape[0]): pi = pts[i] #debug("========== New p...
Force edge (i, j) to be present in mesh. This works by removing intersected triangles and filling holes up to the cutting edge. def _edge_event(self, i, j): """ Force edge (i, j) to be present in mesh. This works by removing intersected triangles and filling holes up to ...
Return the triangle that has edge[0] as one of its vertices and is bisected by edge. Return None if no triangle is found. def _find_cut_triangle(self, edge): """ Return the triangle that has edge[0] as one of its vertices and is bisected by edge. Retu...
Return the index where *edge* appears in the current front. If the edge is not in the front, return -1 def _edge_in_front(self, edge): """ Return the index where *edge* appears in the current front. If the edge is not in the front, return -1 """ e = (list(edge), list(edge)[::-1]...
Given a triangle, return the edge that is opposite point i. Vertexes are returned in the same orientation as in tri. def _edge_opposite_point(self, tri, i): """ Given a triangle, return the edge that is opposite point i. Vertexes are returned in the same orientation as in tri. """ ...
Given a triangle formed by edge and i, return the triangle that shares edge. *i* may be either a point or the entire triangle. def _adjacent_tri(self, edge, i): """ Given a triangle formed by edge and i, return the triangle that shares edge. *i* may be either a point or the entire trian...
Return the only tri that contains *edge*. If two tris share this edge, raise an exception. def _tri_from_edge(self, edge): """Return the only tri that contains *edge*. If two tris share this edge, raise an exception. """ edge = tuple(edge) p1 = self._edges_lookup.get(edg...
Return the edges in *tri*, excluding *edge*. def _edges_in_tri_except(self, tri, edge): """Return the edges in *tri*, excluding *edge*. """ edges = [(tri[i], tri[(i+1) % 3]) for i in range(3)] try: edges.remove(tuple(edge)) except ValueError: edges.remove...
Return True if *edge* is below the current front. One of the points in *edge* must be _on_ the front, at *front_index*. def _edge_below_front(self, edge, front_index): """Return True if *edge* is below the current front. One of the points in *edge* must be _on_ the front, at...
Given a list of *edges*, return the first that is intersected by *cut_edge*. def _intersected_edge(self, edges, cut_edge): """ Given a list of *edges*, return the first that is intersected by *cut_edge*. """ for edge in edges: if self._edges_intersect(edge, cut_edge)...
Return a dictionary containing, for each edge in self.edges, a list of the positions at which the edge should be split. def _find_edge_intersections(self): """ Return a dictionary containing, for each edge in self.edges, a list of the positions at which the edge should be split. ...
Return projection of (a,b) onto (a,c) Arguments are point locations, not indexes. def _projection(self, a, b, c): """Return projection of (a,b) onto (a,c) Arguments are point locations, not indexes. """ ab = b - a ac = c - a return a + ((ab*ac).sum() / (ac*ac).su...
Return 1 if edges intersect completely (endpoints excluded) def _edges_intersect(self, edge1, edge2): """ Return 1 if edges intersect completely (endpoints excluded) """ h12 = self._intersect_edge_arrays(self.pts[np.array(edge1)], self.pts[np.a...
Return a 2D array of intercepts such that intercepts[i, j] is the intercept of lines[i] onto lines[j]. *lines* must be an array of point locations with shape (N, 2, 2), where the axes are (lines, points_per_line, xy_per_point). The intercept is described in intersect_e...
Return the intercepts of all lines defined in *lines1* as they intersect all lines in *lines2*. Arguments are of shape (..., 2, 2), where axes are: 0: number of lines 1: two points per line 2: x,y pair per point Lines are compared elementwise across t...
Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1], -1 if counterclockwise, and 0 if parallel. def _orientation(self, edge, point): """ Returns +1 if edge[0]->point is clockwise from edge[0]->edge[1], -1 if counterclockwise, and 0 if parallel. """ v1 = self.pts[po...
Entry point of the IPython extension Parameters ---------- IPython : IPython interpreter An instance of the IPython interpreter that is handed over to the extension def load_ipython_extension(ipython): """ Entry point of the IPython extension Parameters ---------- IPytho...
Load the webgl backend for the IPython notebook def _load_webgl_backend(ipython): """ Load the webgl backend for the IPython notebook""" from .. import app app_instance = app.use_app("ipynb_webgl") if app_instance.backend_name == "ipynb_webgl": ipython.write("Vispy IPython module has loaded s...
Draw collection def draw(self, mode=None): """ Draw collection """ if self._need_update: self._update() program = self._programs[0] mode = mode or self._mode if self._indices_list is not None: program.draw(mode, self._indices_buffer) else: ...
Drop-in replacement for scipy.ndimage.gaussian_filter. (note: results are only approximately equal to the output of gaussian_filter) def gaussian_filter(data, sigma): """ Drop-in replacement for scipy.ndimage.gaussian_filter. (note: results are only approximately equal to the output of gaus...
Translate by an offset (x, y, z) . Parameters ---------- offset : array-like, shape (3,) Translation in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix describing the translation. def translate(offs...
Non-uniform scaling along the x, y, and z axes Parameters ---------- s : array-like, shape (3,) Scaling in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix describing the scaling. def scale(s, dtype=...
The 3x3 rotation matrix for rotation about a vector. Parameters ---------- angle : float The angle of rotation, in degrees. axis : ndarray The x, y, z coordinates of the axis direction vector. def rotate(angle, axis, dtype=None): """The 3x3 rotation matrix for rotation about a vect...
Create perspective projection matrix Parameters ---------- fovy : float The field of view along the y axis. aspect : float Aspect ratio of the view. znear : float Near coordinate of the field of view. zfar : float Far coordinate of the field of view. Returns...
Find a 3D transformation matrix that maps points1 onto points2. Arguments are specified as arrays of four 3D coordinates, shape (4, 3). def affine_map(points1, points2): """ Find a 3D transformation matrix that maps points1 onto points2. Arguments are specified as arrays of four 3D coordinates, shape (4,...
Add a final message; flush the message list if no parent profiler. def finish(self, msg=None): """Add a final message; flush the message list if no parent profiler. """ if self._finished or self.disable: return self._finished = True if msg is not None: ...
Create global Config object, parse command flags def _init(): """ Create global Config object, parse command flags """ global config, _data_path, _allowed_config_keys app_dir = _get_vispy_app_dir() if app_dir is not None: _data_path = op.join(app_dir, 'data') _test_data_path = op.j...
Transform vispy specific command line args to vispy config. Put into a function so that any variables dont leak in the vispy namespace. def _parse_command_line_arguments(): """ Transform vispy specific command line args to vispy config. Put into a function so that any variables dont leak in the vispy names...
Helper to get the default directory for storing vispy data def _get_vispy_app_dir(): """Helper to get the default directory for storing vispy data""" # Define default user directory user_dir = os.path.expanduser('~') # Get system app data dir path = None if sys.platform.startswith('win'): ...
Helper for the vispy config file def _get_config_fname(): """Helper for the vispy config file""" directory = _get_vispy_app_dir() if directory is None: return None fname = op.join(directory, 'vispy.json') if os.environ.get('_VISPY_CONFIG_TESTING', None) is not None: fname = op.join(...
Helper to load prefs from ~/.vispy/vispy.json def _load_config(): """Helper to load prefs from ~/.vispy/vispy.json""" fname = _get_config_fname() if fname is None or not op.isfile(fname): return dict() with open(fname, 'r') as fid: config = json.load(fid) return config
Save configuration keys to vispy config file Parameters ---------- **kwargs : keyword arguments Key/value pairs to save to the config file. def save_config(**kwargs): """Save configuration keys to vispy config file Parameters ---------- **kwargs : keyword arguments Key/val...
Set vispy data download directory Parameters ---------- directory : str | None The directory to use. create : bool If True, create directory if it doesn't exist. save : bool If True, save the configuration to the vispy config. def set_data_dir(directory=None, create=False, ...
Start profiling and register callback to print stats when the program exits. def _enable_profiling(): """ Start profiling and register callback to print stats when the program exits. """ import cProfile import atexit global _profiler _profiler = cProfile.Profile() _profiler.enable()...
Get relevant system and debugging information Parameters ---------- fname : str | None Filename to dump info to. Use None to simply print. overwrite : bool If True, overwrite file (if it exists). Returns ------- out : str The system information as a string. def sys...
Compact vertices and indices within given tolerance def compact(vertices, indices, tolerance=1e-3): """ Compact vertices and indices within given tolerance """ # Transform vertices into a structured array for np.unique to work n = len(vertices) V = np.zeros(n, dtype=[("pos", np.float32, 3)]) V["po...
Compute normals over a triangulated surface Parameters ---------- vertices : ndarray (n,3) triangles vertices indices : ndarray (p,3) triangles indices def normals(vertices, indices): """ Compute normals over a triangulated surface Parameters ---------- vertices...
Create the native widget if not already done so. If the widget is already created, this function does nothing. def create_native(self): """ Create the native widget if not already done so. If the widget is already created, this function does nothing. """ if self._backend is not ...
Connect a function to an event The name of the function should be on_X, with X the name of the event (e.g. 'on_draw'). This method is typically used as a decorator on a function definition for an event handler. Parameters ---------- fun : callable T...
The size of canvas/window def size(self): """ The size of canvas/window """ size = self._backend._vispy_get_size() return (size[0] // self._px_scale, size[1] // self._px_scale)
Show or hide the canvas Parameters ---------- visible : bool Make the canvas visible. run : bool Run the backend event loop. def show(self, visible=True, run=False): """Show or hide the canvas Parameters ---------- visible : bool...
Close the canvas Notes ----- This will usually destroy the GL context. For Qt, the context (and widget) will be destroyed only if the widget is top-level. To avoid having the widget destroyed (more like standard Qt behavior), consider making the widget a sub-widget. def...
Update the fps after every window def _update_fps(self, event): """Update the fps after every window""" self._frame_count += 1 diff = time() - self._basetime if (diff > self._fps_window): self._fps = self._frame_count / diff self._basetime = time() se...
Measure the current FPS Sets the update window, connects the draw event to update_fps and sets the callback function. Parameters ---------- window : float The time-window (in seconds) to calculate FPS. Default 1.0. callback : function | str The f...
Render the canvas to an offscreen buffer and return the image array. Returns ------- image : array Numpy array of type ubyte and shape (h, w, 4). Index [0, 0] is the upper-left corner of the rendered region. def render(self): """ Render the canvas to an...
Return a list of all mouse events in the current drag operation. Returns None if there is no current drag operation. def drag_events(self): """ Return a list of all mouse events in the current drag operation. Returns None if there is no current drag operation. """ if not self....
Return an (N, 2) array of mouse coordinates for every event in the current mouse drag operation. Returns None if there is no current drag operation. def trail(self): """ Return an (N, 2) array of mouse coordinates for every event in the current mouse drag operation. Returns No...
Set the minimum height of the widget Parameters ---------- height_min: float the minimum height of the widget def width_min(self, width_min): """Set the minimum height of the widget Parameters ---------- height_min: float the minimum h...
Set the maximum width of the widget. Parameters ---------- width_max: None | float the maximum width of the widget. if None, maximum width is unbounded def width_max(self, width_max): """Set the maximum width of the widget. Parameters ----------...
Set the minimum height of the widget Parameters ---------- height_min: float the minimum height of the widget def height_min(self, height_min): """Set the minimum height of the widget Parameters ---------- height_min: float the minimum...
Set the maximum height of the widget. Parameters ---------- height_max: None | float the maximum height of the widget. if None, maximum height is unbounded def height_max(self, height_max): """Set the maximum height of the widget. Parameters ---...
The rectangular area inside the margin, border, and padding. Generally widgets should avoid drawing or placing sub-widgets outside this rectangle. def inner_rect(self): """The rectangular area inside the margin, border, and padding. Generally widgets should avoid drawing or placing su...
Called whenever the clipper for this widget may need to be updated. def _update_clipper(self): """Called whenever the clipper for this widget may need to be updated. """ if self.clip_children and self._clipper is None: self._clipper = Clipper() elif not self.clip_children: ...
Update border line to match new shape def _update_line(self): """ Update border line to match new shape """ w = self._border_width m = self.margin # border is drawn within the boundaries of the widget: # # size = (8, 7) margin=2 # internal rect = (3, 3, 2, 1) ...
Add a Widget as a managed child of this Widget. The child will be automatically positioned and sized to fill the entire space inside this Widget (unless _update_child_widgets is redefined). Parameters ---------- widget : instance of Widget The widget to add....
Create a new Grid and add it as a child widget. All arguments are given to Grid(). def add_grid(self, *args, **kwargs): """ Create a new Grid and add it as a child widget. All arguments are given to Grid(). """ from .grid import Grid grid = Grid(*args, **kwargs...
Create a new ViewBox and add it as a child widget. All arguments are given to ViewBox(). def add_view(self, *args, **kwargs): """ Create a new ViewBox and add it as a child widget. All arguments are given to ViewBox(). """ from .viewbox import ViewBox view = Vi...
Remove a Widget as a managed child of this Widget. Parameters ---------- widget : instance of Widget The widget to remove. def remove_widget(self, widget): """ Remove a Widget as a managed child of this Widget. Parameters ---------- widget :...
Packs float values between [0,1] into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel def pack_unit(value): """Packs float values between [0,1] into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel """ pack = np.zeros(...
Packs float ieee binary representation into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel def pack_ieee(value): """Packs float ieee binary representation into 4 unsigned int8 Returns ------- pack: array packed interpolation kernel """ retu...
Load spatial-filters kernel Parameters ---------- packed : bool Whether or not the data should be in "packed" representation for use in GLSL code. Returns ------- kernel : array 16x1024x4 (packed float in rgba) or 16x1024 (unpacked float) 16 interpolatio...
List system fonts Returns ------- fonts : list of str List of system fonts. def list_fonts(): """List system fonts Returns ------- fonts : list of str List of system fonts. """ vals = _list_fonts() for font in _vispy_fonts: vals += [font] if font not in...
A decorator ensuring that the decorated function tun time does not exceeds the argument limit. :args limit: the time limit :type limit: int :args handler: the handler function called when the decorated function times out. :type handler: callable Example: >>>def timeout_handler(limit, ...
Simple utility to retrieve kwargs in predetermined order. Also checks whether the values of the backend arguments do not violate the backend capabilities. def _process_backend_kwargs(self, kwargs): """ Simple utility to retrieve kwargs in predetermined order. Also checks whether the val...
Reset the view. def _set_range(self, init): """ Reset the view. """ #PerspectiveCamera._set_range(self, init) # Stop moving self._speed *= 0.0 # Get window size (and store factor now to sync with resizing) w, h = self._viewbox.size w, h = float(w), flo...
Timer event handler Parameters ---------- event : instance of Event The event. def on_timer(self, event): """Timer event handler Parameters ---------- event : instance of Event The event. """ # Set relative speed and acc...
ViewBox key event handler Parameters ---------- event : instance of Event The event. def viewbox_key_event(self, event): """ViewBox key event handler Parameters ---------- event : instance of Event The event. """ Perspect...
ViewBox mouse event handler Parameters ---------- event : instance of Event The event. def viewbox_mouse_event(self, event): """ViewBox mouse event handler Parameters ---------- event : instance of Event The event. """ Pe...
Return True if there's something to read on stdin (posix version). def _stdin_ready_posix(): """Return True if there's something to read on stdin (posix version).""" infds, outfds, erfds = select.select([sys.stdin],[],[],0) return bool(infds)
Set PyOS_InputHook to callback and return the previous one. def set_inputhook(self, callback): """Set PyOS_InputHook to callback and return the previous one.""" # On platforms with 'readline' support, it's all too likely to # have a KeyboardInterrupt signal delivered *even before* an # ...
Set PyOS_InputHook to NULL and return the previous one. Parameters ---------- app : optional, ignored This parameter is allowed only so that clear_inputhook() can be called with a similar interface as all the ``enable_*`` methods. But the actual value of the param...
Clear IPython's internal reference to an application instance. Whenever we create an app for a user on qt4 or wx, we hold a reference to the app. This is needed because in some cases bad things can happen if a user doesn't hold a reference themselves. This method is provided to clear ...
Register a class to provide the event loop for a given GUI. This is intended to be used as a class decorator. It should be passed the names with which to register this GUI integration. The classes themselves should subclass :class:`InputHookBase`. :: ...
Switch amongst GUI input hooks by name. This is a higher level method than :meth:`set_inputhook` - it uses the GUI name to look up a registered object which enables the input hook for that GUI. Parameters ---------- gui : optional, string or None If None (or '...
Disable GUI event loop integration. If an application was registered, this sets its ``_in_event_loop`` attribute to False. It then calls :meth:`clear_inputhook`. def disable_gui(self): """Disable GUI event loop integration. If an application was registered, this sets i...
Make a canvas active. Used primarily by the canvas itself. def set_current_canvas(canvas): """ Make a canvas active. Used primarily by the canvas itself. """ # Notify glir canvas.context._do_CURRENT_command = True # Try to be quick if canvasses and canvasses[-1]() is canvas: return ...
Forget about the given canvas. Used by the canvas when closed. def forget_canvas(canvas): """ Forget about the given canvas. Used by the canvas when closed. """ cc = [c() for c in canvasses if c() is not None] while canvas in cc: cc.remove(canvas) canvasses[:] = [weakref.ref(c) for c in cc]
For the app backends to create the GLShared object. Parameters ---------- name : str The name. ref : object The reference. def create_shared(self, name, ref): """ For the app backends to create the GLShared object. Parameters ---------- ...
Flush Parameters ---------- event : instance of Event The event. def flush_commands(self, event=None): """ Flush Parameters ---------- event : instance of Event The event. """ if self._do_CURRENT_command: self...
Add a reference for the backend object that gives access to the low level context. Used in vispy.app.canvas.backends. The given name must match with that of previously added references. def add_ref(self, name, ref): """ Add a reference for the backend object that gives access to...
A reference (stored internally via a weakref) to an object that the backend system can use to obtain the low-level information of the "reference context". In Vispy this will typically be the CanvasBackend object. def ref(self): """ A reference (stored internally via a weakref) to an obj...
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. def get_dpi(raise_error=True): """Get screen DPI from the OS Parameters ---...
Link this Varying to another object from which it will derive its dtype. This method is used internally when assigning an attribute to a varying using syntax ``Function[varying] = attr``. def link(self, var): """ Link this Varying to another object from which it will derive its dtype. T...
Two Dimensional Shubert Function def obj(x): """Two Dimensional Shubert Function""" j = np.arange(1, 6) tmp1 = np.dot(j, np.cos((j+1)*x[0] + j)) tmp2 = np.dot(j, np.cos((j+1)*x[1] + j)) return tmp1 * tmp2
Function BESJ calculates Bessel function of first kind of order n Arguments: n - an integer (>=0), the order x - value at which the Bessel function is required -------------------- C++ Mathematical Library Converted from equivalent FORTRAN library Converte...
Create an exact copy of this quaternion. def copy(self): """ Create an exact copy of this quaternion. """ return Quaternion(self.w, self.x, self.y, self.z, False)
Returns the norm of the quaternion norm = w**2 + x**2 + y**2 + z**2 def norm(self): """ Returns the norm of the quaternion norm = w**2 + x**2 + y**2 + z**2 """ tmp = self.w**2 + self.x**2 + self.y**2 + self.z**2 return tmp**0.5
Make the quaternion unit length. def _normalize(self): """ Make the quaternion unit length. """ # Get length L = self.norm() if not L: raise ValueError('Quaternion cannot have 0-length.') # Correct self.w /= L self.x /= L self.y /= L ...
Obtain the conjugate of the quaternion. This is simply the same quaternion but with the sign of the imaginary (vector) parts reversed. def conjugate(self): """ Obtain the conjugate of the quaternion. This is simply the same quaternion but with the sign of the i...
returns q.conjugate()/q.norm()**2 So if the quaternion is unit length, it is the same as the conjugate. def inverse(self): """ returns q.conjugate()/q.norm()**2 So if the quaternion is unit length, it is the same as the conjugate. """ new = self...
Returns the exponent of the quaternion. (not tested) def exp(self): """ Returns the exponent of the quaternion. (not tested) """ # Init vecNorm = self.x**2 + self.y**2 + self.z**2 wPart = np.exp(self.w) q = Quaternion() ...
Returns the natural logarithm of the quaternion. (not tested) def log(self): """ Returns the natural logarithm of the quaternion. (not tested) """ # Init norm = self.norm() vecNorm = self.x**2 + self.y**2 + self.z**2 tmp = self.w / norm ...
Rotate a Point instance using this quaternion. def rotate_point(self, p): """ Rotate a Point instance using this quaternion. """ # Prepare p = Quaternion(0, p[0], p[1], p[2], False) # Do not normalize! q1 = self.normalize() q2 = self.inverse() # Apply rotation ...
Create a 4x4 homography matrix that represents the rotation of the quaternion. def get_matrix(self): """ Create a 4x4 homography matrix that represents the rotation of the quaternion. """ # Init matrix (remember, a matrix, not an array) a = np.zeros((4, 4), dtype=np.floa...
Get the axis-angle representation of the quaternion. (The angle is in radians) def get_axis_angle(self): """ Get the axis-angle representation of the quaternion. (The angle is in radians) """ # Init angle = 2 * np.arccos(max(min(self.w, 1.), -1.)) scale = (self...
Classmethod to create a quaternion from an axis-angle representation. (angle should be in radians). def create_from_axis_angle(cls, angle, ax, ay, az, degrees=False): """ Classmethod to create a quaternion from an axis-angle representation. (angle should be in radians). """ if...