text
stringlengths
81
112k
Convert a matplotlib image to a base64 png representation Parameters ---------- image : matplotlib image object The image to be converted. Returns ------- image_base64 : string The UTF8-encoded base64 string representation of the png image. def image_to_base64(image): """ ...
Activate the IPython hook for VisPy. If the app is not specified, the default is used. def set_interactive(enabled=True, app=None): """Activate the IPython hook for VisPy. If the app is not specified, the default is used. """ if enabled: inputhook_manager.enable_gui('vispy', app) else...
Resize buffers only if necessary def _resize_buffers(self, font_scale): """Resize buffers only if necessary""" new_sizes = (font_scale,) + self.size if new_sizes == self._current_sizes: # don't need resize return self._n_rows = int(max(self.size[1] / ...
Clear the console def clear(self): """Clear the console""" if hasattr(self, '_bytes_012'): self._bytes_012.fill(0) self._bytes_345.fill(0) self._text_lines = [] * self._n_rows self._pending_writes = []
Write text and scroll Parameters ---------- text : str Text to write. ``''`` can be used for a blank line, as a newline is automatically added to the end of each line. wrap : str If True, long messages will be wrapped to span multiple lines. def writ...
Do any pending text writes def _do_pending_writes(self): """Do any pending text writes""" for text, wrap in self._pending_writes: # truncate in case of *really* long messages text = text[-self._n_cols*self._n_rows:] text = text.split('\n') text = [t if le...
Insert text into bytes buffers def _insert_text_buf(self, line, idx): """Insert text into bytes buffers""" self._bytes_012[idx] = 0 self._bytes_345[idx] = 0 # Crop text if necessary I = np.array([ord(c) - 32 for c in line[:self._n_cols]]) I = np.clip(I, 0, len(__font_6x8...
Set verbatim code replacement It is strongly recommended to use function['$foo'] = 'bar' where possible because template variables are less likely to changed than the code itself in future versions of vispy. Parameters ---------- str1 : str S...
find all template variables in self._code, excluding the function name. def _parse_template_vars(self): """ find all template variables in self._code, excluding the function name. """ template_vars = set() for var in parsing.find_template_variables(self._code): ...
Return code, with new name, expressions, and replacements applied. def _get_replaced_code(self, names): """ Return code, with new name, expressions, and replacements applied. """ code = self._code # Modify name fname = names[self] code = code.replace(" " + self....
Return *code* with indentation and leading/trailing blank lines removed. def _clean_code(self, code): """ Return *code* with indentation and leading/trailing blank lines removed. """ lines = code.split("\n") min_indent = 100 for line in lines: if lin...
Create a new ChainFunction and attach to $var. def add_chain(self, var): """ Create a new ChainFunction and attach to $var. """ chain = FunctionChain(var, []) self._chains[var] = chain self[var] = chain
Append a new function to the end of this chain. def append(self, function, update=True): """ Append a new function to the end of this chain. """ self._funcs.append(function) self._add_dep(function) if update: self._update()
Insert a new function into the chain at *index*. def insert(self, index, function, update=True): """ Insert a new function into the chain at *index*. """ self._funcs.insert(index, function) self._add_dep(function) if update: self._update()
Remove a function from the chain. def remove(self, function, update=True): """ Remove a function from the chain. """ self._funcs.remove(function) self._remove_dep(function) if update: self._update()
Add an item to the list unless it is already present. If the item is an expression, then a semicolon will be appended to it in the final compiled code. def add(self, item, position=5): """Add an item to the list unless it is already present. If the item is an expressio...
Remove an item from the list. def remove(self, item): """Remove an item from the list. """ self.items.pop(item) self._remove_dep(item) self.order = None self.changed(code_changed=True)
Return an array (Nf, 3) of vertex indexes, three per triangular face in the mesh. If faces have not been computed for this mesh, the function computes them. If no vertices or faces are specified, the function returns None. def faces(self): """Return an array (Nf, 3) of vertex i...
Return an array (Nf, 3) of vertices. If only faces exist, the function computes the vertices and returns them. If no vertices or faces are specified, the function returns None. def vertices(self): """Return an array (Nf, 3) of vertices. If only faces exist, the function comput...
Return an array of vertex indexes representing the convex hull. If faces have not been computed for this mesh, the function computes them. If no vertices or faces are specified, the function returns None. def convex_hull(self): """Return an array of vertex indexes representing the conv...
Triangulates the set of vertices and stores the triangles in faces and the convex hull in convex_hull. def triangulate(self): """ Triangulates the set of vertices and stores the triangles in faces and the convex hull in convex_hull. """ npts = self._vertices.shape[0] ...
Locate a filename into the shader library. def find(name): """Locate a filename into the shader library.""" if op.exists(name): return name path = op.dirname(__file__) or '.' paths = [path] + config['include_path'] for path in paths: filename = op.abspath(op.join(path, name)) ...
Retrieve code from the given filename. def get(name): """Retrieve code from the given filename.""" filename = find(name) if filename is None: raise RuntimeError('Could not find %s' % name) with open(filename) as fid: return fid.read()
try many times as in times with sleep time def expect(func, args, times=7, sleep_t=0.5): """try many times as in times with sleep time""" while times > 0: try: return func(*args) except Exception as e: times -= 1 logger.debug("expect failed - attempts left: %...
convert a string to float def num(string): """convert a string to float""" if not isinstance(string, type('')): raise ValueError(type('')) try: string = re.sub('[^a-zA-Z0-9\.\-]', '', string) number = re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", string) return float(number[0]) ...
get the unit of number def get_number_unit(number): """get the unit of number""" n = str(float(number)) mult, submult = n.split('.') if float(submult) != 0: unit = '0.' + (len(submult)-1)*'0' + '1' return float(unit) else: return float(1)
get value of pip def get_pip(mov=None, api=None, name=None): """get value of pip""" # ~ check args if mov is None and api is None: logger.error("need at least one of those") raise ValueError() elif mov is not None and api is not None: logger.error("mov and api are exclusive") ...
Individual item sizes def itemsize(self): """ Individual item sizes """ return self._items[:self._count, 1] - self._items[:self._count, 0]
Set current capacity of the underlying array def reserve(self, capacity): """ Set current capacity of the underlying array""" if capacity >= self._data.size: capacity = int(2 ** np.ceil(np.log2(capacity))) self._data = np.resize(self._data, capacity)
Insert data before index Parameters ---------- index : int Index before which data will be inserted. data : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. ...
Append data to the end. Parameters ---------- data : array_like An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence. itemsize: int or 1-D array If `itemsize is an integer, N...
Solve an optimization problem using the DIRECT (Dividing Rectangles) algorithm. It can be used to solve general nonlinear programming problems of the form: .. math:: \min_ {x \in R^n} f(x) subject to .. math:: x_L \leq x \leq x_U Where :math:`x` are the...
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 ---...
Reset shader source if necesssary. def build_if_needed(self): """ Reset shader source if necesssary. """ if self._need_build: self._build() self._need_build = False self.update_variables()
Returns a function that maps a number n from range (a, b) onto a range (c, d). If no curvefn is given, linear mapping will be used. Optionally a normalisation function normfn can be provided to transform output. def nmap(a, b, c, d, curvefn=None, normfn=None): """ Returns a function that maps a number ...
Link this axis to a ViewBox This makes it so that the axis's domain always matches the visible range in the ViewBox. Parameters ---------- view : instance of ViewBox The ViewBox to link. def link_view(self, view): """Link this axis to a ViewBox Thi...
Linked view transform has changed; update ticks. def _view_changed(self, event=None): """Linked view transform has changed; update ticks. """ tr = self.node_transform(self._linked_view.scene) p1, p2 = tr.map(self._axis_ends()) if self.orientation in ('left', 'right'): ...
ViewBox mouse event handler Parameters ---------- event : instance of Event The mouse event. def viewbox_mouse_event(self, event): """ViewBox mouse event handler Parameters ---------- event : instance of Event The mouse event. ""...
Timer event handler Parameters ---------- event : instance of Event The timer event. def on_timer(self, event=None): """Timer event handler Parameters ---------- event : instance of Event The timer event. """ # Smoothly u...
Data can be numpy array or the size of data to allocate. def glBufferData(target, data, usage): """ Data can be numpy array or the size of data to allocate. """ if isinstance(data, int): size = data data = ctypes.c_voidp(0) else: if not data.flags['C_CONTIGUOUS'] or not data.fla...
Return next power of 2 greater than or equal to n def next_power_of_2(n): """ Return next power of 2 greater than or equal to n """ n -= 1 # greater than OR EQUAL TO n shift = 1 while (n + 1) & n: # n+1 is not a power of 2 yet n |= n >> shift shift *= 2 return max(4, n + 1)
Parameters ---------- vertices : numpy array An array whose dtype is compatible with self.vdtype uniforms: numpy array An array whose dtype is compatible with self.utype indices : numpy array An array whose dtype is compatible with self.idtype ...
Compute uniform texture shape def _compute_texture_shape(self, size=1): """ Compute uniform texture shape """ # We should use this line but we may not have a GL context yet # linesize = gl.glGetInteger(gl.GL_MAX_TEXTURE_SIZE) linesize = 1024 count = self._uniforms_float_count ...
Update vertex buffers & texture def _update(self): """ Update vertex buffers & texture """ if self._vertices_buffer is not None: self._vertices_buffer.delete() self._vertices_buffer = VertexBuffer(self._vertices_list.data) if self.itype is not None: if self._in...
Retrieve a graph layout Some graph layouts accept extra options. Please refer to their documentation for more information. Parameters ---------- name : string The name of the layout. The variable `AVAILABLE_LAYOUTS` contains all available layouts. *args Positional argum...
Given viewer session information, make sure the session information is compatible with the current version of the viewers, and if not, update the session information in-place. def update_viewer_state(rec, context): """ Given viewer session information, make sure the session information is compatibl...
Remove C-style comment from GLSL code string. def remove_comments(code): """Remove C-style comment from GLSL code string.""" pattern = r"(\".*?\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*\n)" # first group captures quoted strings (double or single) # second group captures comments (//single-line or /* multi-line...
Merge all includes recursively. def merge_includes(code): """Merge all includes recursively.""" pattern = '\#\s*include\s*"(?P<filename>[a-zA-Z0-9\_\-\.\/]+)"' regex = re.compile(pattern) includes = [] def replace(match): filename = match.group("filename") if filename not in incl...
Add a new widget to this grid. This will cause other widgets in the grid to be resized to make room for the new widget. Can be used to replace a widget as well Parameters ---------- widget : Widget | None The Widget to add. New widget is constructed if widget is None...
Remove a widget from this grid Parameters ---------- widget : Widget The Widget to remove def remove_widget(self, widget): """Remove a widget from this grid Parameters ---------- widget : Widget The Widget to remove """ ...
Resize a widget in the grid to new dimensions. Parameters ---------- widget : Widget The widget to resize row_span : int The number of rows to be occupied by this widget. col_span : int The number of columns to be occupied by this widget. def...
Create a new Grid and add it as a child widget. Parameters ---------- row : int The row in which to add the widget (0 is the topmost row) col : int The column in which to add the widget (0 is the leftmost column) row_span : int The number of r...
Create a new ViewBox and add it as a child widget. Parameters ---------- row : int The row in which to add the widget (0 is the topmost row) col : int The column in which to add the widget (0 is the leftmost column) row_span : int The number o...
Find font def find_font(face, bold, italic): """Find font""" bold = FC_WEIGHT_BOLD if bold else FC_WEIGHT_REGULAR italic = FC_SLANT_ITALIC if italic else FC_SLANT_ROMAN face = face.encode('utf8') fontconfig.FcInit() pattern = fontconfig.FcPatternCreate() fontconfig.FcPatternAddInteger(patte...
List system fonts def _list_fonts(): """List system fonts""" stdout_, stderr = run_subprocess(['fc-list', ':scalable=true', 'family']) vals = [v.split(',')[0] for v in stdout_.strip().splitlines(False)] return vals
Helper to get vispy calling function from the stack def _get_vispy_caller(): """Helper to get vispy calling function from the stack""" records = inspect.stack() # first few records are vispy-based logging calls for record in records[5:]: module = record[0].f_globals['__name__'] if modul...
Convenience function for setting the logging level Parameters ---------- verbose : bool, str, int, or None The verbosity of messages to print. If a str, it can be either DEBUG, INFO, WARNING, ERROR, or CRITICAL. Note that these are for convenience and are equivalent to passing in lo...
Send an exception and traceback to the logger. This function is used in cases where an exception is handled safely but nevertheless should generate a descriptive error message. An extra line is inserted into the stack trace indicating where the exception was caught. Parameters ---------- ...
Helper for prining errors in callbacks See EventEmitter._invoke_callback for a use example. def _handle_exception(ignore_callback_errors, print_callback_errors, obj, cb_event=None, node=None): """Helper for prining errors in callbacks See EventEmitter._invoke_callback for a use exam...
Serialize a NumPy array. def _serialize_buffer(buffer, array_serialization=None): """Serialize a NumPy array.""" if array_serialization == 'binary': # WARNING: in NumPy 1.9, tostring() has been renamed to tobytes() # but tostring() is still here for now for backward compatibility. retur...
Log message emitter that optionally matches and/or records def _vispy_emit_match_andor_record(self, record): """Log message emitter that optionally matches and/or records""" test = record.getMessage() match = self._vispy_match if (match is None or re.search(match, test) or ...
Convert *obj* to a new ShaderObject. If the output is a Variable with no name, then set its name using *ref*. def create(self, obj, ref=None): """ Convert *obj* to a new ShaderObject. If the output is a Variable with no name, then set its name using *ref*. """ if isinstance(ref...
Return all dependencies required to use this object. The last item in the list is *self*. def dependencies(self, sort=False): """ Return all dependencies required to use this object. The last item in the list is *self*. """ alldeps = [] if sort: def key(obj...
Increment the reference count for *dep*. If this is a new dependency, then connect to its *changed* event. def _add_dep(self, dep): """ Increment the reference count for *dep*. If this is a new dependency, then connect to its *changed* event. """ if dep in self._deps: ...
Decrement the reference count for *dep*. If the reference count reaches 0, then the dependency is removed and its *changed* event is disconnected. def _remove_dep(self, dep): """ Decrement the reference count for *dep*. If the reference count reaches 0, then the dependency is removed ...
Called when a dependency's expression has changed. def _dep_changed(self, dep, code_changed=False, value_changed=False): """ Called when a dependency's expression has changed. """ self.changed(code_changed, value_changed)
Inform dependents that this shaderobject has changed. def changed(self, code_changed=False, value_changed=False): """Inform dependents that this shaderobject has changed. """ for d in self._dependents: d._dep_changed(self, code_changed=code_changed, value_...
The great missing equivalence function: Guaranteed evaluation to a single bool value. def eq(a, b): """ The great missing equivalence function: Guaranteed evaluation to a single bool value. """ if a is b: return True if a is None or b is None: return True if a is None and b is N...
Zoom in (or out) at the given center Parameters ---------- factor : float or tuple Fraction by which the scene should be zoomed (e.g. a factor of 2 causes the scene to appear twice as large). center : tuple of 2-4 elements The center of the view. If n...
Pan the view. Parameters ---------- *pan : length-2 sequence The distance to pan the view, in the coordinate system of the scene. def pan(self, *pan): """Pan the view. Parameters ---------- *pan : length-2 sequence The distan...
The SubScene received a mouse event; update transform accordingly. Parameters ---------- event : instance of Event The event. def viewbox_mouse_event(self, event): """ The SubScene received a mouse event; update transform accordingly. Parame...
Set the volume data. Parameters ---------- vol : ndarray The 3D volume. clim : tuple | None Colormap limits to use. None will use the min and max values. def set_data(self, vol, clim=None): """ Set the volume data. Parameters ---------...
Create and set positions and texture coords from the given shape We have six faces with 1 quad (2 triangles) each, resulting in 6*2*3 = 36 vertices in total. def _create_vertex_data(self): """ Create and set positions and texture coords from the given shape We have six...
Set the data Parameters ---------- pos : list, tuple or numpy array Bounds of the region along the axis. len(pos) must be >=2. color : list, tuple, or array The color to use when drawing the line. It must have a shape of (1, 4) for a single color regi...
This method is called immediately before each draw. The *view* argument indicates which view is about to be drawn. def _prepare_draw(self, view=None): """This method is called immediately before each draw. The *view* argument indicates which view is about to be drawn. """ if ...
Repopulate cache def refresh_cache(self, cat_id): ''' Repopulate cache ''' self.cache[cat_id] = most_recent_25_posts_by_category(cat_id) self.last_refresh[cat_id] = datetime.now() print ('Cache refresh at...', str(self.last_refresh[cat_id]))
Merge overlapping intervals. This method is called only once in the constructor. def _merge_intervals(self, min_depth): """ Merge overlapping intervals. This method is called only once in the constructor. """ def add_interval(ret, start, stop): if min_depth...
Return the union between self and ``another_is``. Parameters ---------- another_is : `IntervalSet` an IntervalSet object. Returns ------- interval : `IntervalSet` the union of self with ``another_is``. def union(self, another_is): """ ...
Convert an IntervalSet using the NESTED numbering scheme to an IntervalSet containing UNIQ numbers for HEALPix cells. Parameters ---------- nested_is : `IntervalSet` IntervalSet object storing HEALPix cells as [ipix*4^(29-order), (ipix+1)*4^(29-order)[ intervals. Re...
Convert an IntervalSet containing NUNIQ intervals to an IntervalSet representing HEALPix cells following the NESTED numbering scheme. Parameters ---------- nuniq_is : `IntervalSet` IntervalSet object storing HEALPix cells as [ipix + 4*4^(order), ipix+1 + 4*4^(order)[ interva...
Merge two lists of intervals according to the boolean function op ``a_intervals`` and ``b_intervals`` need to be sorted and consistent (no overlapping intervals). This operation keeps the resulting interval set consistent. Parameters ---------- a_intervals : `~numpy.ndarray` ...
Delete the object from GPU memory. Note that the GPU object will also be deleted when this gloo object is about to be deleted. However, sometimes you want to explicitly delete the GPU object explicitly. def delete(self): """ Delete the object from GPU memory. Note that the G...
Set the data Parameters ---------- image : array-like The image data. def set_data(self, image): """Set the data Parameters ---------- image : array-like The image data. """ data = np.asarray(image) if self._data ...
Rebuild the _data_lookup_fn using different interpolations within the shader def _build_interpolation(self): """Rebuild the _data_lookup_fn using different interpolations within the shader """ interpolation = self._interpolation self._data_lookup_fn = self._interpolation...
Rebuild the vertex buffers used for rendering the image when using the subdivide method. def _build_vertex_data(self): """Rebuild the vertex buffers used for rendering the image when using the subdivide method. """ grid = self._grid w = 1.0 / grid[1] h = 1.0 / gr...
Decide which method to use for *view* and configure it accordingly. def _update_method(self, view): """Decide which method to use for *view* and configure it accordingly. """ method = self._method if method == 'auto': if view.transforms.get_transform().Linear: ...
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 ---------- P : np.array Vertices positions of the path(s) to be added closed: bool Whether path(s...
Given a path P, return the baked vertices as they should be copied in the collection if the path has already been appended. Example: -------- paths.append(P) P *= 2 paths['prev'][0] = bake(P,'prev') paths['curr'][0] = bake(P,'curr') paths['next'][0] = ba...
Draw collection def draw(self, mode="triangle_strip"): """ Draw collection """ gl.glDepthMask(gl.GL_FALSE) Collection.draw(self, mode) gl.glDepthMask(gl.GL_TRUE)
Stop all timers in a canvas. def _stop_timers(canvas): """Stop all timers in a canvas.""" for attr in dir(canvas): try: attr_obj = getattr(canvas, attr) except NotImplementedError: # This try/except is needed because canvas.position raises # an error (it is n...
Print stack trace from call that didn't originate from here def _last_stack_str(): """Print stack trace from call that didn't originate from here""" stack = extract_stack() for s in stack[::-1]: if op.join('vispy', 'gloo', 'buffer.py') not in __file__: break return format_list([s])[...
Set a sub-region of the buffer (deferred operation). Parameters ---------- data : ndarray Data to be uploaded offset: int Offset in buffer where to start copying data (in bytes) copy: bool Since the operation is deferred, data may change befo...
Set data in the buffer (deferred operation). This completely resets the size and contents of the buffer. Parameters ---------- data : ndarray Data to be uploaded copy: bool Since the operation is deferred, data may change before data is actua...
Resize this buffer (deferred operation). Parameters ---------- size : int New buffer size in bytes. def resize_bytes(self, size): """ Resize this buffer (deferred operation). Parameters ---------- size : int New buffer ...
Set a sub-region of the buffer (deferred operation). Parameters ---------- data : ndarray Data to be uploaded offset: int Offset in buffer where to start copying data (in bytes) copy: bool Since the operation is deferred, data may change befo...
Set data (deferred operation) Parameters ---------- data : ndarray Data to be uploaded copy: bool Since the operation is deferred, data may change before data is actually uploaded to GPU memory. Asking explicitly for a copy will prevent th...
GLSL declaration strings required for a variable to hold this data. def glsl_type(self): """ GLSL declaration strings required for a variable to hold this data. """ if self.dtype is None: return None dtshape = self.dtype[0].shape n = dtshape[0] if dtshape else 1 ...
Resize the buffer (in-place, deferred operation) Parameters ---------- size : integer New buffer size in bytes Notes ----- This clears any pending operations. def resize_bytes(self, size): """ Resize the buffer (in-place, deferred operation) ...
Compile all code and return a dict {name: code} where the keys are determined by the keyword arguments passed to __init__(). Parameters ---------- pretty : bool If True, use a slower method to mangle object names. This produces GLSL that is more readable. ...
Rename all objects quickly to guaranteed-unique names using the id() of each object. This produces mostly unreadable GLSL, but is about 10x faster to compile. def _rename_objects_fast(self): """ Rename all objects quickly to guaranteed-unique names using the id() of each object...