code stringlengths 1 18.2k |
|---|
= tb del tb # Get rid of it in this namespace # Handle if not ignore_callback_errors: raise if print_callback_errors != "never": this_print = 'full' if print_callback_errors in ('first', 'reminders'): # need to check to see if we've hit this yet if exp_type == 'callback': key = repr(cb) + repr(event) else: key = repr(n... |
'first': this_print = None else: # reminders ii = registry[key] # Use logarithmic selection # (1, 2, ..., 10, 20, ..., 100, 200, ...) if ii == (2 ** int(np.log2(ii))): this_print = ii else: this_print = None else: registry[key] = 1 if this_print == 'full': logger.log_exception() if exp_type == 'callback': logger.error(... |
% node) elif this_print is not None: if exp_type == 'callback': logger.error("Invoking %s repeat %s" % (cb, this_print)) else: # == 'node': logger.error("Drawing node %s repeat %s" % (node, this_print)) |
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. return buffer.ravel().tostring() elif array_serialization == 'b... |
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 re.search(match, _get_vispy_caller())): if self._vispy_emit_record: fmt_rec = self._vispy_formatter.forma... |
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, Variable): ref = ref.name elif isinstance(ref, string_types) and ref.startswith('gl_'): # gl_ names not allowed for variables ref = ref[3:].lower() # ... |
magic method: if hasattr(obj, '_shader_object'): obj = obj._shader_object() if isinstance(obj, ShaderObject): if isinstance(obj, Variable) and obj.name is None: obj.name = ref elif isinstance(obj, string_types): obj = TextExpression(obj) else: obj = Variable(ref, obj) # Try prepending the name to indicate attribute, un... |
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): # sort deps such that we get functions, variables, self. if not isinstance(obj, Variable): return (0, 0) else: return (1, obj.vtype) deps = sorted(sel... |
alldeps |
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: self._deps[dep] += 1 else: self._deps[dep] = 1 dep._dependents[self] = None |
def _remove_dep(self, dep): """ Decrement the reference count for *dep*. If the reference count reaches 0, then the dependency is removed and its *changed* event is disconnected. """ refcount = self._deps[dep] if refcount == 1: self._deps.pop(dep) dep._dependents.pop(self) else: self._deps[dep] -= 1 |
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) |
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_changed=value_changed) |
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 None else False try: e = a == b except ValueError: return False except AttributeError: return False except Exception: print("a:"... |
str(b)) raise t = type(e) if t is bool: return e elif t is bool_: return bool(e) elif isinstance(e, ndarray): try: # disaster: if a is empty and b is not, then e.all() is True if a.shape != b.shape: return False except Exception: return False if (hasattr(e, 'implements') and e.implements('MetaArray')): return e.asarray... |
def zoom(self, factor, center=None): """ 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 not given or None, use the cu... |
in (2, 3, 4) # Get scale factor, take scale ratio into account if np.isscalar(factor): scale = [factor, factor] else: if len(factor) != 2: raise TypeError("factor must be scalar or length-2 sequence.") scale = list(factor) if self.aspect is not None: scale[0] = scale[1] # Init some variables center = center if (center ... |
that allocation will # trigger view_changed: rect = Rect(self.rect) # Get space from given center to edges left_space = center[0] - rect.left right_space = rect.right - center[0] bottom_space = center[1] - rect.bottom top_space = rect.top - center[1] # Scale these spaces rect.left = center[0] - left_space * scale[0] re... |
center[1] + top_space * scale[1] self.rect = rect |
def pan(self, *pan): """Pan the view. Parameters ---------- *pan : length-2 sequence The distance to pan the view, in the coordinate system of the scene. """ if len(pan) == 1: pan = pan[0] self.rect = self.rect + pan |
def viewbox_mouse_event(self, event): """ The SubScene received a mouse event; update transform accordingly. Parameters ---------- event : instance of Event The event. """ if event.handled or not self.interactive: return # Scrolling BaseCamera.viewbox_mouse_event(self, event) if event.type == 'mouse_wheel': center = se... |
= event.mouse_event.press_event.pos p2 = event.mouse_event.pos if 1 in event.buttons and not modifiers: # Translate p1 = np.array(event.last_event.pos)[:2] p2 = np.array(event.pos)[:2] p1s = self._transform.imap(p1) p2s = self._transform.imap(p2) self.pan(p1s-p2s) event.handled = True elif 2 in event.buttons and not mo... |
event.handled = False elif event.type == 'mouse_press': # accept the event if it is button 1 or 2. # This is required in order to receive future events event.handled = event.button in [1, 2] else: event.handled = False |
def set_data(self, vol, clim=None): """ 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. """ # Check volume if not isinstance(vol, np.ndarray): raise ValueError('Volume visual needs a numpy array.') if not ((vol.ndi... |
visual needs a 3D image.') # Handle clim if clim is not None: clim = np.array(clim, float) if not (clim.ndim == 1 and clim.size == 2): raise ValueError('clim must be a 2-element array-like') self._clim = tuple(clim) if self._clim is None: self._clim = vol.min(), vol.max() # Apply clim vol = np.array(vol, dtype='float32... |
self._clim[0] else: vol -= self._clim[0] vol /= self._clim[1] - self._clim[0] # Apply to texture self._tex.set_data(vol) # will be efficient if vol is same shape self.shared_program['u_shape'] = (vol.shape[2], vol.shape[1], vol.shape[0]) shape = vol.shape[:3] if self._vol_shape != shape: self._vol_shape = shape self._n... |
def _create_vertex_data(self): """ 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. """ shape = self._vol_shape # Get corner coordinates. The -0.5 offset is to center # pixels/voxels. This works correctly for an... |
-0.5, shape[1] - 0.5 z0, z1 = -0.5, shape[0] - 0.5 pos = np.array([ [x0, y0, z0], [x1, y0, z0], [x0, y1, z0], [x1, y1, z0], [x0, y0, z1], [x1, y0, z1], [x0, y1, z1], [x1, y1, z1], ], dtype=np.float32) """ 6-------7 /| /| 4-------5 | | | | | | 2-----|-3 |/ |/ 0-------1 """ # Order is chosen such that normals face |
outward; front faces will be # culled. indices = np.array([2, 6, 0, 4, 5, 6, 7, 2, 3, 0, 1, 5, 3, 7], dtype=np.uint32) # Apply self._vertices.set_data(pos) self._index_buffer.set_data(indices) |
def set_data(self, pos=None, color=None): """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 region or (len(pos), 4) for ... |
self._pos new_color = self._color if pos is not None: num_elements = len(pos) pos = np.array(pos, dtype=np.float32) if pos.ndim != 1: raise ValueError('Expected 1D array') vertex = np.empty((num_elements * 2, 2), dtype=np.float32) if self._is_vertical: vertex[:, 0] = np.repeat(pos, 2) vertex[:, 1] = np.tile([-1, 1], nu... |
is not None: color = np.array(color, dtype=np.float32) num_elements = new_pos.shape[0] / 2 if color.ndim == 2: if color.shape[0] != num_elements: raise ValueError('Expected a color for each pos') if color.shape[1] != 4: raise ValueError('Each color must be a RGBA array') color = np.repeat(color, 2, axis=0).astype(np.fl... |
axis=0) color = color.astype(np.float32) else: raise ValueError('Expected a numpy array of shape ' '(%d, 4) or (1, 4)' % num_elements) new_color = color self._changed['color'] = True # Ensure pos and color have the same size if new_pos.shape[0] != new_color.shape[0]: raise ValueError('pos and color does must have the s... |
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 self._changed['pos']: self.pos_buf.set_data(self._pos) self._changed['pos'] = False if self._changed['color']: self.color_buf.set_data(self._color) self._progr... |
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])) |
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 is not None: shift = 2 * (29 - min_depth) mask = (int(1) << shift) - 1 if stop - start < mask: ret.append((start, stop)) else: ofs = start & ma... |
- ofs) + (mask + 1) ret.append((start, st)) while st + mask + 1 < stop: ret.append((st, st + mask + 1)) st = st + mask + 1 ret.append((st, stop)) else: ret.append((start, stop)) ret = [] start = stop = None # Use numpy sort method self._intervals.sort(axis=0) for itv in self._intervals: if start is None: start, stop = ... |
intervals if itv[0] > stop: add_interval(ret, start, stop) start, stop = itv else: # merge intervals if itv[1] > stop: stop = itv[1] if start is not None and stop is not None: add_interval(ret, start, stop) self._intervals = np.asarray(ret) |
def union(self, another_is): """ 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``. """ result = IntervalSet() if another_is.empty(): result._intervals = self._intervals... |
def to_nuniq_interval_set(cls, nested_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. Returns -... |
order = 0 while not r2.empty(): shift = int(2 * (IntervalSet.HPY_MAX_ORDER - order)) ofs = (int(1) << shift) - 1 ofs2 = int(1) << (2 * order + 2) r4 = [] for iv in r2._intervals: a = (int(iv[0]) + ofs) >> shift b = int(iv[1]) >> shift c = a << shift d = b << shift if d > c: r4.append((c, d)) |
res.append((a + ofs2, b + ofs2)) if len(r4) > 0: r4_is = IntervalSet(np.asarray(r4)) r2 = r2.difference(r4_is) order += 1 return IntervalSet(np.asarray(res)) |
def from_nuniq_interval_set(cls, nuniq_is): """ 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)[ inte... |
appending a numpy array # For these algorithms we append a list and create the interval set from the finished list rtmp = [] last_order = 0 intervals = nuniq_is._intervals diff_order = IntervalSet.HPY_MAX_ORDER shift_order = 2 * diff_order for interval in intervals: for j in range(interval[0], interval[1]): order, i_pi... |
diff_order = IntervalSet.HPY_MAX_ORDER - order shift_order = 2 * diff_order rtmp.append((i_pix << shift_order, (i_pix + 1) << shift_order)) nested_is = nested_is.union(IntervalSet(np.asarray(rtmp))) return nested_is |
def merge(a_intervals, b_intervals, op): """ 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`... |
represented as a N x 2 numpy array op : `function` Lambda function taking two params and returning the result of the operation between these two params. Exemple : lambda in_a, in_b: in_a and in_b describes the intersection of ``a_intervals`` and ``b_intervals`` whereas lambda in_a, in_b: in_a or in_b describes the unio... |
2 numpy containing intervals resulting from the op between ``a_intervals`` and ``b_intervals``. """ a_endpoints = a_intervals.flatten().tolist() b_endpoints = b_intervals.flatten().tolist() sentinel = max(a_endpoints[-1], b_endpoints[-1]) + 1 a_endpoints += [sentinel] b_endpoints += [sentinel] a_index = 0 b_index = 0 r... |
^ (b_index % 2)) in_res = op(in_a, in_b) if in_res ^ (len(res) % 2): res += [scan] if scan == a_endpoints[a_index]: a_index += 1 if scan == b_endpoints[b_index]: b_index += 1 scan = min(a_endpoints[a_index], b_endpoints[b_index]) return np.asarray(res).reshape((-1, 2)) |
def delete(self): """ 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. """ # We only allow the object from being deleted once, otherwise # we might be deleting anothe... |
our GPU object was deleted. Also note that e.g. # DataBufferView does not have the _glir attribute. if hasattr(self, '_glir'): # Send our final command into the queue self._glir.command('DELETE', self._id) # Tell master glir queue that this queue is no longer being used self._glir._deletable = True # Detach the queue d... |
def set_data(self, image): """Set the data Parameters ---------- image : array-like The image data. """ data = np.asarray(image) if self._data is None or self._data.shape != data.shape: self._need_vertex_update = True self._data = data self._need_texture_upload = True |
def _build_interpolation(self): """Rebuild the _data_lookup_fn using different interpolations within the shader """ interpolation = self._interpolation self._data_lookup_fn = self._interpolation_fun[interpolation] self.shared_program.frag['get_data'] = self._data_lookup_fn # only 'bilinear' uses 'linear' texture interp... |
self._data.shape[:2][::-1] if self._texture.interpolation != texture_interpolation: self._texture.interpolation = texture_interpolation self._data_lookup_fn['texture'] = self._texture self._need_interpolation_update = False |
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 / grid[0] quad = np.array([[0, 0, 0], [w, 0, 0], [w, h, 0], [0, 0, 0], [w, h, 0], [0, h, 0]], dtype=np.float32) quads = np.empty((grid[1], grid[0], 6,... |
0.:grid[0]].transpose(1, 2, 0) mgrid = mgrid[:, :, np.newaxis, :] mgrid[..., 0] *= w mgrid[..., 1] *= h quads[..., :2] += mgrid tex_coords = quads.reshape(grid[1]*grid[0]*6, 3) tex_coords = np.ascontiguousarray(tex_coords[:, :2]) vertices = tex_coords * self.size self._subdiv_position.set_data(vertices.astype('float32'... |
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: method = 'subdivide' else: method = 'impostor' view._method_used = method if method == 'subdivide': view.view_program['method']... |
draw method '%s'" % method) self.shared_program['image_size'] = self.size view._need_method_update = False self._prepare_transforms(view) |
def append(self, P, closed=False, itemsize=None, **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 ---------- P : np.array Vertices positions of the path(s) to be added closed: bool Whether path(s) is/are clo... |
or 2-tuple Path start /end cap color : list, array or 4-tuple Path color linewidth : list, array or float Path linewidth antialias : list, array or float Path antialias area """ itemsize = itemsize or len(P) itemcount = len(P) / itemsize P = P.reshape(itemcount, itemsize, 3) if closed: V = np.empty((itemcount, itemsize... |
in self.vtype.names: if name not in ['collection_index', 'prev', 'curr', 'next']: V[name][1:-2] = kwargs.get(name, self._defaults[name]) V['prev'][:, 2:-1] = P V['prev'][:, 1] = V['prev'][:, -2] V['curr'][:, 1:-2] = P V['curr'][:, -2] = V['curr'][:, 1] V['next'][:, 0:-3] = P V['next'][:, -3] = V['next'][:, 0] V['next']... |
if name not in ['collection_index', 'prev', 'curr', 'next']: V[name][1:-1] = kwargs.get(name, self._defaults[name]) V['prev'][:, 2:] = P V['prev'][:, 1] = V['prev'][:, 2] V['curr'][:, 1:-1] = P V['next'][:, :-2] = P V['next'][:, -2] = V['next'][:, -3] V[:, 0] = V[:, 1] V[:, -1] = V[:, -2] V = V.ravel() V = np.repeat(V,... |
2 * (itemsize + 3)) else: V = V.reshape(itemcount, 2 * (itemsize + 2)) V["id"][:, :2] = 2, -2 V["id"][:, -2:] = 2, -2 V = V.ravel() # Uniforms if self.utype: U = np.zeros(itemcount, dtype=self.utype) for name in self.utype.names: if name not in ["__unused__"]: U[name] = kwargs.get(name, self._defaults[name]) else: U = ... |
def bake(self, P, key='curr', closed=False, itemsize=None): """ 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] = bake... |
= np.arange(n + 3) if key == 'prev': I -= 2 I[0], I[1], I[-1] = n - 1, n - 1, n - 1 elif key == 'next': I[0], I[-3], I[-2], I[-1] = 1, 0, 1, 1 else: I -= 1 I[0], I[-1], I[n + 1] = 0, 0, 0 else: I = np.arange(n + 2) if key == 'prev': I -= 2 I[0], |
I[1], I[-1] = 0, 0, n - 2 elif key == 'next': I[0], I[-1], I[-2] = 1, n - 1, n - 1 else: I -= 1 I[0], I[-1] = 0, n - 1 I = np.repeat(I, 2) return P[I] |
def draw(self, mode="triangle_strip"): """ Draw collection """ gl.glDepthMask(gl.GL_FALSE) Collection.draw(self, mode) gl.glDepthMask(gl.GL_TRUE) |
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 not implemented in this backend). attr_obj = None if isinstance(attr_obj, Timer): attr_obj.... |
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])[0] |
def set_subdata(self, data, offset=0, copy=False): """ 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 before data is actually upl... |
= np.array(data, copy=copy) nbytes = data.nbytes if offset < 0: raise ValueError("Offset must be positive") elif (offset + nbytes) > self._nbytes: raise ValueError("Data does not fit into buffer") # If the whole buffer is to be written, we clear any pending data # (because they will be overwritten anyway) if nbytes == ... |
def set_data(self, data, copy=False): """ 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 actually uploaded to GPU memory. Asking e... |
= data.nbytes if nbytes != self._nbytes: self.resize_bytes(nbytes) else: # Use SIZE to discard any previous data setting self._glir.command('SIZE', self._id, nbytes) if nbytes: # Only set data if there *is* data self._glir.command('DATA', self._id, 0, data) |
def resize_bytes(self, size): """ Resize this buffer (deferred operation). Parameters ---------- size : int New buffer size in bytes. """ self._nbytes = size self._glir.command('SIZE', self._id, size) # Invalidate any view on this buffer for view in self._views: if view() is not None: view()._valid = False self._views ... |
def set_subdata(self, data, offset=0, copy=False, **kwargs): """ 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 before data is ac... |
: dict Additional keyword arguments. """ data = self._prepare_data(data, **kwargs) offset = offset * self.itemsize Buffer.set_subdata(self, data=data, offset=offset, copy=copy) |
def set_data(self, data, copy=False, **kwargs): """ 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 this behavior. **kwargs : dict ... |
self._dtype.itemsize Buffer.set_data(self, data=data, copy=copy) |
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 if n > 1: dtype = 'vec%d' % n else: dtype = 'float' if 'f' in self.dtype[0].base.kind else 'int' return 'attribute', dtype |
def resize_bytes(self, size): """ Resize the buffer (in-place, deferred operation) Parameters ---------- size : integer New buffer size in bytes Notes ----- This clears any pending operations. """ Buffer.resize_bytes(self, size) self._size = size // self.itemsize |
def compile(self, pretty=True): """ 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. If False, then the output is... |
# Authoritative mapping of {obj: name} self._object_names = {} # # 1. collect list of dependencies for each shader # # maps {shader_name: [deps]} self._shader_deps = {} for shader_name, shader in self.shaders.items(): this_shader_deps = [] self._shader_deps[shader_name] = this_shader_deps dep_set = set() for dep in sha... |
this_shader_deps.append(dep) dep_set.add(dep) # # 2. Assign names to all objects. # if pretty: self._rename_objects_pretty() else: self._rename_objects_fast() # # 3. Now we have a complete namespace; concatenate all definitions # together in topological order. # compiled = {} obj_names = self._object_names for shader_n... |
pragma if present; regex = r'#version (\d+)' m = re.search(regex, dep_code) if m is not None: # check requested version if m.group(1) != '120': raise RuntimeError("Currently only GLSL #version " "120 is supported.") dep_code = re.sub(regex, '', dep_code) code.append(dep_code) compiled[shader_name] = '\n'.join(code) sel... |
def _rename_objects_fast(self): """ 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. """ for shader_name, deps in self._shader_deps.items(): for dep in deps: name = dep.name if name != 'main': ext = '_%x' % id(... |
def _rename_objects_pretty(self): """ Rename all objects like "name_1" to avoid conflicts. Objects are only renamed if necessary. This method produces more readable GLSL, but is rather slow. """ # # 1. For each object, add its static names to the global namespace # and make a list of the shaders used by the object. # #... |
initialize with reserved keywords. self._global_ns = dict([(kwd, None) for kwd in gloo.util.KEYWORDS]) # functions are local per-shader self._shader_ns = dict([(shader, {}) for shader in self.shaders]) # for each object, keep a list of shaders the object appears in obj_shaders = {} for shader_name, deps in self._shader... |
[]).append(shader_name) # # 2. Assign new object names # name_index = {} for obj, shaders in obj_shaders.items(): name = obj.name if self._name_available(obj, name, shaders): # hooray, we get to keep this name self._assign_name(obj, name, shaders) else: # boo, find a new name while True: index = name_index.get(name, 0)... |
self._name_available(obj, new_name, shaders): self._assign_name(obj, new_name, shaders) break |
def _name_available(self, obj, name, shaders): """ Return True if *name* is available for *obj* in *shaders*. """ if name in self._global_ns: return False shaders = self.shaders if self._is_global(obj) else shaders for shader in shaders: if name in self._shader_ns[shader]: return False return True |
def _assign_name(self, obj, name, shaders): """ Assign *name* to *obj* in *shaders*. """ if self._is_global(obj): assert name not in self._global_ns self._global_ns[name] = obj else: for shader in shaders: ns = self._shader_ns[shader] assert name not in ns ns[name] = obj self._object_names[obj] = name |
def _update(self): """Rebuilds the shaders, and repositions the objects that are used internally by the ColorBarVisual """ x, y = self._pos halfw, halfh = self._halfdim # test that width and height are non-zero if halfw <= 0: raise ValueError("half-width must be positive and non-zero" ", not %s" % halfw) if halfh <= 0:... |
halfh) # test that the given width and height is consistent # with the orientation if (self._orientation == "bottom" or self._orientation == "top"): if halfw < halfh: raise ValueError("half-width(%s) < half-height(%s) for" "%s orientation," " expected half-width >= half-height" % (halfw, halfh, self._orientation, )) el... |
" expected half-width <= half-height" % (halfw, halfh, self._orientation, )) # Set up the attributes that the shaders require vertices = np.array([[x - halfw, y - halfh], [x + halfw, y - halfh], [x + halfw, y + halfh], # tri 2 [x - halfw, y - halfh], [x + halfw, y + halfh], [x - halfw, y + halfh]], dtype=np.float32) se... |
def _update(self): """Rebuilds the shaders, and repositions the objects that are used internally by the ColorBarVisual """ self._colorbar.halfdim = self._halfdim self._border.halfdim = self._halfdim self._label.text = self._label_str self._ticks[0].text = str(self._clim[0]) self._ticks[1].text = str(self._clim[1]) self... |
def _update_positions(self): """ updates the positions of the colorbars and labels """ self._colorbar.pos = self._pos self._border.pos = self._pos if self._orientation == "right" or self._orientation == "left": self._label.rotation = -90 x, y = self._pos halfw, halfh = self._halfdim label_anchors = \ ColorBarVisual._ge... |
ColorBarVisual._calc_positions(center=self._pos, halfdim=self._halfdim, border_width=self.border_width, orientation=self._orientation, transforms=self.transforms) self._label.pos = label_pos self._ticks[0].pos = ticks_pos[0] self._ticks[1].pos = ticks_pos[1] |
def _calc_positions(center, halfdim, border_width, orientation, transforms): """ Calculate the text centeritions given the ColorBar parameters. Note ---- This is static because in principle, this function does not need access to the state of the ColorBar at all. It's a computation function that computes coordinate tran... |
from the center border_width: float Width of the border of the ColorBar orientation: "top" | "bottom" | "left" | "right" Position of the label with respect to the ColorBar transforms: TransformSystem the transforms of the ColorBar """ (x, y) = center (halfw, halfh) = halfdim visual_to_doc = transforms.get_transform('vi... |
visual_to_doc.map(np.array([halfw, 0, 0, 0], dtype=np.float32)) doc_y = visual_to_doc.map(np.array([0, halfh, 0, 0], dtype=np.float32)) if doc_x[0] < 0: doc_x *= -1 if doc_y[1] < 0: doc_y *= -1 # doc_halfw = np.abs(doc_widths[0]) # doc_halfh = np.abs(doc_widths[1]) if orientation == "top": doc_perp_vector = -doc_y elif... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.