repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/shaders/compiler.py
Compiler._rename_objects_pretty
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. # # {name: obj} mapping for finding unique names # 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_deps.items(): for dep in deps: # Add static names to namespace for name in dep.static_names(): self._global_ns[name] = None obj_shaders.setdefault(dep, []).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) + 1 name_index[name] = index ext = '_%d' % index new_name = name[:32-len(ext)] + ext if self._name_available(obj, new_name, shaders): self._assign_name(obj, new_name, shaders) break
python
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. # # {name: obj} mapping for finding unique names # 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_deps.items(): for dep in deps: # Add static names to namespace for name in dep.static_names(): self._global_ns[name] = None obj_shaders.setdefault(dep, []).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) + 1 name_index[name] = index ext = '_%d' % index new_name = name[:32-len(ext)] + ext if self._name_available(obj, new_name, shaders): self._assign_name(obj, new_name, shaders) break
[ "def", "_rename_objects_pretty", "(", "self", ")", ":", "#", "# 1. For each object, add its static names to the global namespace", "# and make a list of the shaders used by the object.", "#", "# {name: obj} mapping for finding unique names", "# 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_deps", ".", "items", "(", ")", ":", "for", "dep", "in", "deps", ":", "# Add static names to namespace", "for", "name", "in", "dep", ".", "static_names", "(", ")", ":", "self", ".", "_global_ns", "[", "name", "]", "=", "None", "obj_shaders", ".", "setdefault", "(", "dep", ",", "[", "]", ")", ".", "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", ")", "+", "1", "name_index", "[", "name", "]", "=", "index", "ext", "=", "'_%d'", "%", "index", "new_name", "=", "name", "[", ":", "32", "-", "len", "(", "ext", ")", "]", "+", "ext", "if", "self", ".", "_name_available", "(", "obj", ",", "new_name", ",", "shaders", ")", ":", "self", ".", "_assign_name", "(", "obj", ",", "new_name", ",", "shaders", ")", "break" ]
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.
[ "Rename", "all", "objects", "like", "name_1", "to", "avoid", "conflicts", ".", "Objects", "are", "only", "renamed", "if", "necessary", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/shaders/compiler.py#L135-L181
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/shaders/compiler.py
Compiler._name_available
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
python
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", "_name_available", "(", "self", ",", "obj", ",", "name", ",", "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" ]
Return True if *name* is available for *obj* in *shaders*.
[ "Return", "True", "if", "*", "name", "*", "is", "available", "for", "*", "obj", "*", "in", "*", "shaders", "*", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/shaders/compiler.py#L196-L205
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/shaders/compiler.py
Compiler._assign_name
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
python
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", "_assign_name", "(", "self", ",", "obj", ",", "name", ",", "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" ]
Assign *name* to *obj* in *shaders*.
[ "Assign", "*", "name", "*", "to", "*", "obj", "*", "in", "*", "shaders", "*", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/shaders/compiler.py#L207-L218
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/colorbar.py
_CoreColorBarVisual._update
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: raise ValueError("half-height must be positive and non-zero" ", not %s" % 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, )) else: # orientation == left or orientation == right if halfw > halfh: raise ValueError("half-width(%s) > half-height(%s) for" "%s orientation," " 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) self.shared_program['a_position'] = vertices
python
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: raise ValueError("half-height must be positive and non-zero" ", not %s" % 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, )) else: # orientation == left or orientation == right if halfw > halfh: raise ValueError("half-width(%s) > half-height(%s) for" "%s orientation," " 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) self.shared_program['a_position'] = vertices
[ "def", "_update", "(", "self", ")", ":", "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", ":", "raise", "ValueError", "(", "\"half-height must be positive and non-zero\"", "\", not %s\"", "%", "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", ",", ")", ")", "else", ":", "# orientation == left or orientation == right", "if", "halfw", ">", "halfh", ":", "raise", "ValueError", "(", "\"half-width(%s) > half-height(%s) for\"", "\"%s orientation,\"", "\" 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", ")", "self", ".", "shared_program", "[", "'a_position'", "]", "=", "vertices" ]
Rebuilds the shaders, and repositions the objects that are used internally by the ColorBarVisual
[ "Rebuilds", "the", "shaders", "and", "repositions", "the", "objects", "that", "are", "used", "internally", "by", "the", "ColorBarVisual" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/colorbar.py#L117-L158
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/colorbar.py
ColorBarVisual._update
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._update_positions() self._colorbar._update() self._border._update()
python
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._update_positions() self._colorbar._update() self._border._update()
[ "def", "_update", "(", "self", ")", ":", "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", ".", "_update_positions", "(", ")", "self", ".", "_colorbar", ".", "_update", "(", ")", "self", ".", "_border", ".", "_update", "(", ")" ]
Rebuilds the shaders, and repositions the objects that are used internally by the ColorBarVisual
[ "Rebuilds", "the", "shaders", "and", "repositions", "the", "objects", "that", "are", "used", "internally", "by", "the", "ColorBarVisual" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/colorbar.py#L319-L333
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/colorbar.py
ColorBarVisual._update_positions
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._get_label_anchors(center=self._pos, halfdim=self._halfdim, orientation=self._orientation, transforms=self.label.transforms) self._label.anchors = label_anchors ticks_anchors = \ ColorBarVisual._get_ticks_anchors(center=self._pos, halfdim=self._halfdim, orientation=self._orientation, transforms=self.label.transforms) self._ticks[0].anchors = ticks_anchors self._ticks[1].anchors = ticks_anchors (label_pos, ticks_pos) = \ 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]
python
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._get_label_anchors(center=self._pos, halfdim=self._halfdim, orientation=self._orientation, transforms=self.label.transforms) self._label.anchors = label_anchors ticks_anchors = \ ColorBarVisual._get_ticks_anchors(center=self._pos, halfdim=self._halfdim, orientation=self._orientation, transforms=self.label.transforms) self._ticks[0].anchors = ticks_anchors self._ticks[1].anchors = ticks_anchors (label_pos, ticks_pos) = \ 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", "_update_positions", "(", "self", ")", ":", "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", ".", "_get_label_anchors", "(", "center", "=", "self", ".", "_pos", ",", "halfdim", "=", "self", ".", "_halfdim", ",", "orientation", "=", "self", ".", "_orientation", ",", "transforms", "=", "self", ".", "label", ".", "transforms", ")", "self", ".", "_label", ".", "anchors", "=", "label_anchors", "ticks_anchors", "=", "ColorBarVisual", ".", "_get_ticks_anchors", "(", "center", "=", "self", ".", "_pos", ",", "halfdim", "=", "self", ".", "_halfdim", ",", "orientation", "=", "self", ".", "_orientation", ",", "transforms", "=", "self", ".", "label", ".", "transforms", ")", "self", ".", "_ticks", "[", "0", "]", ".", "anchors", "=", "ticks_anchors", "self", ".", "_ticks", "[", "1", "]", ".", "anchors", "=", "ticks_anchors", "(", "label_pos", ",", "ticks_pos", ")", "=", "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", "]" ]
updates the positions of the colorbars and labels
[ "updates", "the", "positions", "of", "the", "colorbars", "and", "labels" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/colorbar.py#L335-L374
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/colorbar.py
ColorBarVisual._calc_positions
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 transforms Parameters ---------- center: tuple (x, y) Center of the ColorBar halfdim: tuple (halfw, halfh) Half of the dimensions measured 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('visual', 'document') doc_to_visual = transforms.get_transform('document', 'visual') # doc_widths = visual_to_doc.map(np.array([halfw, halfh, 0, 0], # dtype=np.float32)) doc_x = 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 orientation == "bottom": doc_perp_vector = doc_y elif orientation == "left": doc_perp_vector = -doc_x if orientation == "right": doc_perp_vector = doc_x perp_len = np.linalg.norm(doc_perp_vector) doc_perp_vector /= perp_len perp_len += border_width perp_len += 5 # pixels perp_len *= ColorBarVisual.text_padding_factor doc_perp_vector *= perp_len doc_center = visual_to_doc.map(np.array([x, y, 0, 0], dtype=np.float32)) doc_label_pos = doc_center + doc_perp_vector visual_label_pos = doc_to_visual.map(doc_label_pos)[:3] # next, calculate tick positions if orientation in ["top", "bottom"]: doc_ticks_pos = [doc_label_pos - doc_x, doc_label_pos + doc_x] else: doc_ticks_pos = [doc_label_pos + doc_y, doc_label_pos - doc_y] visual_ticks_pos = [] visual_ticks_pos.append(doc_to_visual.map(doc_ticks_pos[0])[:3]) visual_ticks_pos.append(doc_to_visual.map(doc_ticks_pos[1])[:3]) return (visual_label_pos, visual_ticks_pos)
python
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 transforms Parameters ---------- center: tuple (x, y) Center of the ColorBar halfdim: tuple (halfw, halfh) Half of the dimensions measured 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('visual', 'document') doc_to_visual = transforms.get_transform('document', 'visual') # doc_widths = visual_to_doc.map(np.array([halfw, halfh, 0, 0], # dtype=np.float32)) doc_x = 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 orientation == "bottom": doc_perp_vector = doc_y elif orientation == "left": doc_perp_vector = -doc_x if orientation == "right": doc_perp_vector = doc_x perp_len = np.linalg.norm(doc_perp_vector) doc_perp_vector /= perp_len perp_len += border_width perp_len += 5 # pixels perp_len *= ColorBarVisual.text_padding_factor doc_perp_vector *= perp_len doc_center = visual_to_doc.map(np.array([x, y, 0, 0], dtype=np.float32)) doc_label_pos = doc_center + doc_perp_vector visual_label_pos = doc_to_visual.map(doc_label_pos)[:3] # next, calculate tick positions if orientation in ["top", "bottom"]: doc_ticks_pos = [doc_label_pos - doc_x, doc_label_pos + doc_x] else: doc_ticks_pos = [doc_label_pos + doc_y, doc_label_pos - doc_y] visual_ticks_pos = [] visual_ticks_pos.append(doc_to_visual.map(doc_ticks_pos[0])[:3]) visual_ticks_pos.append(doc_to_visual.map(doc_ticks_pos[1])[:3]) return (visual_label_pos, visual_ticks_pos)
[ "def", "_calc_positions", "(", "center", ",", "halfdim", ",", "border_width", ",", "orientation", ",", "transforms", ")", ":", "(", "x", ",", "y", ")", "=", "center", "(", "halfw", ",", "halfh", ")", "=", "halfdim", "visual_to_doc", "=", "transforms", ".", "get_transform", "(", "'visual'", ",", "'document'", ")", "doc_to_visual", "=", "transforms", ".", "get_transform", "(", "'document'", ",", "'visual'", ")", "# doc_widths = visual_to_doc.map(np.array([halfw, halfh, 0, 0],", "# dtype=np.float32))", "doc_x", "=", "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", "orientation", "==", "\"bottom\"", ":", "doc_perp_vector", "=", "doc_y", "elif", "orientation", "==", "\"left\"", ":", "doc_perp_vector", "=", "-", "doc_x", "if", "orientation", "==", "\"right\"", ":", "doc_perp_vector", "=", "doc_x", "perp_len", "=", "np", ".", "linalg", ".", "norm", "(", "doc_perp_vector", ")", "doc_perp_vector", "/=", "perp_len", "perp_len", "+=", "border_width", "perp_len", "+=", "5", "# pixels", "perp_len", "*=", "ColorBarVisual", ".", "text_padding_factor", "doc_perp_vector", "*=", "perp_len", "doc_center", "=", "visual_to_doc", ".", "map", "(", "np", ".", "array", "(", "[", "x", ",", "y", ",", "0", ",", "0", "]", ",", "dtype", "=", "np", ".", "float32", ")", ")", "doc_label_pos", "=", "doc_center", "+", "doc_perp_vector", "visual_label_pos", "=", "doc_to_visual", ".", "map", "(", "doc_label_pos", ")", "[", ":", "3", "]", "# next, calculate tick positions", "if", "orientation", "in", "[", "\"top\"", ",", "\"bottom\"", "]", ":", "doc_ticks_pos", "=", "[", "doc_label_pos", "-", "doc_x", ",", "doc_label_pos", "+", "doc_x", "]", "else", ":", "doc_ticks_pos", "=", "[", "doc_label_pos", "+", "doc_y", ",", "doc_label_pos", "-", "doc_y", "]", "visual_ticks_pos", "=", "[", "]", "visual_ticks_pos", ".", "append", "(", "doc_to_visual", ".", "map", "(", "doc_ticks_pos", "[", "0", "]", ")", "[", ":", "3", "]", ")", "visual_ticks_pos", ".", "append", "(", "doc_to_visual", ".", "map", "(", "doc_ticks_pos", "[", "1", "]", ")", "[", ":", "3", "]", ")", "return", "(", "visual_label_pos", ",", "visual_ticks_pos", ")" ]
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 transforms Parameters ---------- center: tuple (x, y) Center of the ColorBar halfdim: tuple (halfw, halfh) Half of the dimensions measured 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
[ "Calculate", "the", "text", "centeritions", "given", "the", "ColorBar", "parameters", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/colorbar.py#L471-L551
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/colorbar.py
ColorBarVisual.size
def size(self): """ The size of the ColorBar Returns ------- size: (major_axis_length, minor_axis_length) major and minor axis are defined by the orientation of the ColorBar """ (halfw, halfh) = self._halfdim if self.orientation in ["top", "bottom"]: return (halfw * 2., halfh * 2.) else: return (halfh * 2., halfw * 2.)
python
def size(self): """ The size of the ColorBar Returns ------- size: (major_axis_length, minor_axis_length) major and minor axis are defined by the orientation of the ColorBar """ (halfw, halfh) = self._halfdim if self.orientation in ["top", "bottom"]: return (halfw * 2., halfh * 2.) else: return (halfh * 2., halfw * 2.)
[ "def", "size", "(", "self", ")", ":", "(", "halfw", ",", "halfh", ")", "=", "self", ".", "_halfdim", "if", "self", ".", "orientation", "in", "[", "\"top\"", ",", "\"bottom\"", "]", ":", "return", "(", "halfw", "*", "2.", ",", "halfh", "*", "2.", ")", "else", ":", "return", "(", "halfh", "*", "2.", ",", "halfw", "*", "2.", ")" ]
The size of the ColorBar Returns ------- size: (major_axis_length, minor_axis_length) major and minor axis are defined by the orientation of the ColorBar
[ "The", "size", "of", "the", "ColorBar" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/colorbar.py#L645-L658
train
rbarrois/mpdlcd
mpdlcd/lcdrunner.py
MpdRunner.add_pseudo_fields
def add_pseudo_fields(self): """Add 'pseudo' fields (e.g non-displayed fields) to the display.""" fields = [] if self.backlight_on != enums.BACKLIGHT_ON_NEVER: fields.append( display_fields.BacklightPseudoField(ref='0', backlight_rule=self.backlight_on) ) fields.append( display_fields.PriorityPseudoField( ref='0', priority_playing=self.priority_playing, priority_not_playing=self.priority_not_playing, ) ) self.pattern.add_pseudo_fields(fields, self.screen)
python
def add_pseudo_fields(self): """Add 'pseudo' fields (e.g non-displayed fields) to the display.""" fields = [] if self.backlight_on != enums.BACKLIGHT_ON_NEVER: fields.append( display_fields.BacklightPseudoField(ref='0', backlight_rule=self.backlight_on) ) fields.append( display_fields.PriorityPseudoField( ref='0', priority_playing=self.priority_playing, priority_not_playing=self.priority_not_playing, ) ) self.pattern.add_pseudo_fields(fields, self.screen)
[ "def", "add_pseudo_fields", "(", "self", ")", ":", "fields", "=", "[", "]", "if", "self", ".", "backlight_on", "!=", "enums", ".", "BACKLIGHT_ON_NEVER", ":", "fields", ".", "append", "(", "display_fields", ".", "BacklightPseudoField", "(", "ref", "=", "'0'", ",", "backlight_rule", "=", "self", ".", "backlight_on", ")", ")", "fields", ".", "append", "(", "display_fields", ".", "PriorityPseudoField", "(", "ref", "=", "'0'", ",", "priority_playing", "=", "self", ".", "priority_playing", ",", "priority_not_playing", "=", "self", ".", "priority_not_playing", ",", ")", ")", "self", ".", "pattern", ".", "add_pseudo_fields", "(", "fields", ",", "self", ".", "screen", ")" ]
Add 'pseudo' fields (e.g non-displayed fields) to the display.
[ "Add", "pseudo", "fields", "(", "e", ".", "g", "non", "-", "displayed", "fields", ")", "to", "the", "display", "." ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/lcdrunner.py#L63-L79
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/rect.py
Rect.padded
def padded(self, padding): """Return a new Rect padded (smaller) by padding on all sides Parameters ---------- padding : float The padding. Returns ------- rect : instance of Rect The padded rectangle. """ return Rect(pos=(self.pos[0]+padding, self.pos[1]+padding), size=(self.size[0]-2*padding, self.size[1]-2*padding))
python
def padded(self, padding): """Return a new Rect padded (smaller) by padding on all sides Parameters ---------- padding : float The padding. Returns ------- rect : instance of Rect The padded rectangle. """ return Rect(pos=(self.pos[0]+padding, self.pos[1]+padding), size=(self.size[0]-2*padding, self.size[1]-2*padding))
[ "def", "padded", "(", "self", ",", "padding", ")", ":", "return", "Rect", "(", "pos", "=", "(", "self", ".", "pos", "[", "0", "]", "+", "padding", ",", "self", ".", "pos", "[", "1", "]", "+", "padding", ")", ",", "size", "=", "(", "self", ".", "size", "[", "0", "]", "-", "2", "*", "padding", ",", "self", ".", "size", "[", "1", "]", "-", "2", "*", "padding", ")", ")" ]
Return a new Rect padded (smaller) by padding on all sides Parameters ---------- padding : float The padding. Returns ------- rect : instance of Rect The padded rectangle.
[ "Return", "a", "new", "Rect", "padded", "(", "smaller", ")", "by", "padding", "on", "all", "sides" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/rect.py#L115-L129
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/rect.py
Rect.normalized
def normalized(self): """Return a Rect covering the same area, but with height and width guaranteed to be positive.""" return Rect(pos=(min(self.left, self.right), min(self.top, self.bottom)), size=(abs(self.width), abs(self.height)))
python
def normalized(self): """Return a Rect covering the same area, but with height and width guaranteed to be positive.""" return Rect(pos=(min(self.left, self.right), min(self.top, self.bottom)), size=(abs(self.width), abs(self.height)))
[ "def", "normalized", "(", "self", ")", ":", "return", "Rect", "(", "pos", "=", "(", "min", "(", "self", ".", "left", ",", "self", ".", "right", ")", ",", "min", "(", "self", ".", "top", ",", "self", ".", "bottom", ")", ")", ",", "size", "=", "(", "abs", "(", "self", ".", "width", ")", ",", "abs", "(", "self", ".", "height", ")", ")", ")" ]
Return a Rect covering the same area, but with height and width guaranteed to be positive.
[ "Return", "a", "Rect", "covering", "the", "same", "area", "but", "with", "height", "and", "width", "guaranteed", "to", "be", "positive", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/rect.py#L131-L136
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/rect.py
Rect.flipped
def flipped(self, x=False, y=True): """Return a Rect with the same bounds but with axes inverted Parameters ---------- x : bool Flip the X axis. y : bool Flip the Y axis. Returns ------- rect : instance of Rect The flipped rectangle. """ pos = list(self.pos) size = list(self.size) for i, flip in enumerate((x, y)): if flip: pos[i] += size[i] size[i] *= -1 return Rect(pos, size)
python
def flipped(self, x=False, y=True): """Return a Rect with the same bounds but with axes inverted Parameters ---------- x : bool Flip the X axis. y : bool Flip the Y axis. Returns ------- rect : instance of Rect The flipped rectangle. """ pos = list(self.pos) size = list(self.size) for i, flip in enumerate((x, y)): if flip: pos[i] += size[i] size[i] *= -1 return Rect(pos, size)
[ "def", "flipped", "(", "self", ",", "x", "=", "False", ",", "y", "=", "True", ")", ":", "pos", "=", "list", "(", "self", ".", "pos", ")", "size", "=", "list", "(", "self", ".", "size", ")", "for", "i", ",", "flip", "in", "enumerate", "(", "(", "x", ",", "y", ")", ")", ":", "if", "flip", ":", "pos", "[", "i", "]", "+=", "size", "[", "i", "]", "size", "[", "i", "]", "*=", "-", "1", "return", "Rect", "(", "pos", ",", "size", ")" ]
Return a Rect with the same bounds but with axes inverted Parameters ---------- x : bool Flip the X axis. y : bool Flip the Y axis. Returns ------- rect : instance of Rect The flipped rectangle.
[ "Return", "a", "Rect", "with", "the", "same", "bounds", "but", "with", "axes", "inverted" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/rect.py#L138-L159
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/rect.py
Rect._transform_in
def _transform_in(self): """Return array of coordinates that can be mapped by Transform classes.""" return np.array([ [self.left, self.bottom, 0, 1], [self.right, self.top, 0, 1]])
python
def _transform_in(self): """Return array of coordinates that can be mapped by Transform classes.""" return np.array([ [self.left, self.bottom, 0, 1], [self.right, self.top, 0, 1]])
[ "def", "_transform_in", "(", "self", ")", ":", "return", "np", ".", "array", "(", "[", "[", "self", ".", "left", ",", "self", ".", "bottom", ",", "0", ",", "1", "]", ",", "[", "self", ".", "right", ",", "self", ".", "top", ",", "0", ",", "1", "]", "]", ")" ]
Return array of coordinates that can be mapped by Transform classes.
[ "Return", "array", "of", "coordinates", "that", "can", "be", "mapped", "by", "Transform", "classes", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/rect.py#L193-L198
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/transform_system.py
TransformSystem.configure
def configure(self, viewport=None, fbo_size=None, fbo_rect=None, canvas=None): """Automatically configure the TransformSystem: * canvas_transform maps from the Canvas logical pixel coordinate system to the framebuffer coordinate system, taking into account the logical/physical pixel scale factor, current FBO position, and y-axis inversion. * framebuffer_transform maps from the current GL viewport on the framebuffer coordinate system to clip coordinates (-1 to 1). Parameters ========== viewport : tuple or None The GL viewport rectangle (x, y, w, h). If None, then it is assumed to cover the entire canvas. fbo_size : tuple or None The size of the active FBO. If None, then it is assumed to have the same size as the canvas's framebuffer. fbo_rect : tuple or None The position and size (x, y, w, h) of the FBO in the coordinate system of the canvas's framebuffer. If None, then the bounds are assumed to cover the entire active framebuffer. canvas : Canvas instance Optionally set the canvas for this TransformSystem. See the `canvas` property. """ # TODO: check that d2f and f2r transforms still contain a single # STTransform (if the user has modified these, then auto-config should # either fail or replace the transforms) if canvas is not None: self.canvas = canvas canvas = self._canvas if canvas is None: raise RuntimeError("No canvas assigned to this TransformSystem.") # By default, this should invert the y axis--canvas origin is in top # left, whereas framebuffer origin is in bottom left. map_from = [(0, 0), canvas.size] map_to = [(0, canvas.physical_size[1]), (canvas.physical_size[0], 0)] self._canvas_transform.transforms[1].set_mapping(map_from, map_to) if fbo_rect is None: self._canvas_transform.transforms[0].scale = (1, 1, 1) self._canvas_transform.transforms[0].translate = (0, 0, 0) else: # Map into FBO coordinates map_from = [(fbo_rect[0], fbo_rect[1]), (fbo_rect[0] + fbo_rect[2], fbo_rect[1] + fbo_rect[3])] map_to = [(0, 0), fbo_size] self._canvas_transform.transforms[0].set_mapping(map_from, map_to) if viewport is None: if fbo_size is None: # viewport covers entire canvas map_from = [(0, 0), canvas.physical_size] else: # viewport covers entire FBO map_from = [(0, 0), fbo_size] else: map_from = [viewport[:2], (viewport[0] + viewport[2], viewport[1] + viewport[3])] map_to = [(-1, -1), (1, 1)] self._framebuffer_transform.transforms[0].set_mapping(map_from, map_to)
python
def configure(self, viewport=None, fbo_size=None, fbo_rect=None, canvas=None): """Automatically configure the TransformSystem: * canvas_transform maps from the Canvas logical pixel coordinate system to the framebuffer coordinate system, taking into account the logical/physical pixel scale factor, current FBO position, and y-axis inversion. * framebuffer_transform maps from the current GL viewport on the framebuffer coordinate system to clip coordinates (-1 to 1). Parameters ========== viewport : tuple or None The GL viewport rectangle (x, y, w, h). If None, then it is assumed to cover the entire canvas. fbo_size : tuple or None The size of the active FBO. If None, then it is assumed to have the same size as the canvas's framebuffer. fbo_rect : tuple or None The position and size (x, y, w, h) of the FBO in the coordinate system of the canvas's framebuffer. If None, then the bounds are assumed to cover the entire active framebuffer. canvas : Canvas instance Optionally set the canvas for this TransformSystem. See the `canvas` property. """ # TODO: check that d2f and f2r transforms still contain a single # STTransform (if the user has modified these, then auto-config should # either fail or replace the transforms) if canvas is not None: self.canvas = canvas canvas = self._canvas if canvas is None: raise RuntimeError("No canvas assigned to this TransformSystem.") # By default, this should invert the y axis--canvas origin is in top # left, whereas framebuffer origin is in bottom left. map_from = [(0, 0), canvas.size] map_to = [(0, canvas.physical_size[1]), (canvas.physical_size[0], 0)] self._canvas_transform.transforms[1].set_mapping(map_from, map_to) if fbo_rect is None: self._canvas_transform.transforms[0].scale = (1, 1, 1) self._canvas_transform.transforms[0].translate = (0, 0, 0) else: # Map into FBO coordinates map_from = [(fbo_rect[0], fbo_rect[1]), (fbo_rect[0] + fbo_rect[2], fbo_rect[1] + fbo_rect[3])] map_to = [(0, 0), fbo_size] self._canvas_transform.transforms[0].set_mapping(map_from, map_to) if viewport is None: if fbo_size is None: # viewport covers entire canvas map_from = [(0, 0), canvas.physical_size] else: # viewport covers entire FBO map_from = [(0, 0), fbo_size] else: map_from = [viewport[:2], (viewport[0] + viewport[2], viewport[1] + viewport[3])] map_to = [(-1, -1), (1, 1)] self._framebuffer_transform.transforms[0].set_mapping(map_from, map_to)
[ "def", "configure", "(", "self", ",", "viewport", "=", "None", ",", "fbo_size", "=", "None", ",", "fbo_rect", "=", "None", ",", "canvas", "=", "None", ")", ":", "# TODO: check that d2f and f2r transforms still contain a single", "# STTransform (if the user has modified these, then auto-config should", "# either fail or replace the transforms)", "if", "canvas", "is", "not", "None", ":", "self", ".", "canvas", "=", "canvas", "canvas", "=", "self", ".", "_canvas", "if", "canvas", "is", "None", ":", "raise", "RuntimeError", "(", "\"No canvas assigned to this TransformSystem.\"", ")", "# By default, this should invert the y axis--canvas origin is in top", "# left, whereas framebuffer origin is in bottom left.", "map_from", "=", "[", "(", "0", ",", "0", ")", ",", "canvas", ".", "size", "]", "map_to", "=", "[", "(", "0", ",", "canvas", ".", "physical_size", "[", "1", "]", ")", ",", "(", "canvas", ".", "physical_size", "[", "0", "]", ",", "0", ")", "]", "self", ".", "_canvas_transform", ".", "transforms", "[", "1", "]", ".", "set_mapping", "(", "map_from", ",", "map_to", ")", "if", "fbo_rect", "is", "None", ":", "self", ".", "_canvas_transform", ".", "transforms", "[", "0", "]", ".", "scale", "=", "(", "1", ",", "1", ",", "1", ")", "self", ".", "_canvas_transform", ".", "transforms", "[", "0", "]", ".", "translate", "=", "(", "0", ",", "0", ",", "0", ")", "else", ":", "# Map into FBO coordinates", "map_from", "=", "[", "(", "fbo_rect", "[", "0", "]", ",", "fbo_rect", "[", "1", "]", ")", ",", "(", "fbo_rect", "[", "0", "]", "+", "fbo_rect", "[", "2", "]", ",", "fbo_rect", "[", "1", "]", "+", "fbo_rect", "[", "3", "]", ")", "]", "map_to", "=", "[", "(", "0", ",", "0", ")", ",", "fbo_size", "]", "self", ".", "_canvas_transform", ".", "transforms", "[", "0", "]", ".", "set_mapping", "(", "map_from", ",", "map_to", ")", "if", "viewport", "is", "None", ":", "if", "fbo_size", "is", "None", ":", "# viewport covers entire canvas", "map_from", "=", "[", "(", "0", ",", "0", ")", ",", "canvas", ".", "physical_size", "]", "else", ":", "# viewport covers entire FBO", "map_from", "=", "[", "(", "0", ",", "0", ")", ",", "fbo_size", "]", "else", ":", "map_from", "=", "[", "viewport", "[", ":", "2", "]", ",", "(", "viewport", "[", "0", "]", "+", "viewport", "[", "2", "]", ",", "viewport", "[", "1", "]", "+", "viewport", "[", "3", "]", ")", "]", "map_to", "=", "[", "(", "-", "1", ",", "-", "1", ")", ",", "(", "1", ",", "1", ")", "]", "self", ".", "_framebuffer_transform", ".", "transforms", "[", "0", "]", ".", "set_mapping", "(", "map_from", ",", "map_to", ")" ]
Automatically configure the TransformSystem: * canvas_transform maps from the Canvas logical pixel coordinate system to the framebuffer coordinate system, taking into account the logical/physical pixel scale factor, current FBO position, and y-axis inversion. * framebuffer_transform maps from the current GL viewport on the framebuffer coordinate system to clip coordinates (-1 to 1). Parameters ========== viewport : tuple or None The GL viewport rectangle (x, y, w, h). If None, then it is assumed to cover the entire canvas. fbo_size : tuple or None The size of the active FBO. If None, then it is assumed to have the same size as the canvas's framebuffer. fbo_rect : tuple or None The position and size (x, y, w, h) of the FBO in the coordinate system of the canvas's framebuffer. If None, then the bounds are assumed to cover the entire active framebuffer. canvas : Canvas instance Optionally set the canvas for this TransformSystem. See the `canvas` property.
[ "Automatically", "configure", "the", "TransformSystem", ":" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/transform_system.py#L164-L228
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/transform_system.py
TransformSystem.dpi
def dpi(self): """ Physical resolution of the document coordinate system (dots per inch). """ if self._dpi is None: if self._canvas is None: return None else: return self.canvas.dpi else: return self._dpi
python
def dpi(self): """ Physical resolution of the document coordinate system (dots per inch). """ if self._dpi is None: if self._canvas is None: return None else: return self.canvas.dpi else: return self._dpi
[ "def", "dpi", "(", "self", ")", ":", "if", "self", ".", "_dpi", "is", "None", ":", "if", "self", ".", "_canvas", "is", "None", ":", "return", "None", "else", ":", "return", "self", ".", "canvas", ".", "dpi", "else", ":", "return", "self", ".", "_dpi" ]
Physical resolution of the document coordinate system (dots per inch).
[ "Physical", "resolution", "of", "the", "document", "coordinate", "system", "(", "dots", "per", "inch", ")", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/transform_system.py#L241-L251
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/transform_system.py
TransformSystem.get_transform
def get_transform(self, map_from='visual', map_to='render'): """Return a transform mapping between any two coordinate systems. Parameters ---------- map_from : str The starting coordinate system to map from. Must be one of: visual, scene, document, canvas, framebuffer, or render. map_to : str The ending coordinate system to map to. Must be one of: visual, scene, document, canvas, framebuffer, or render. """ tr = ['visual', 'scene', 'document', 'canvas', 'framebuffer', 'render'] ifrom = tr.index(map_from) ito = tr.index(map_to) if ifrom < ito: trs = [getattr(self, '_' + t + '_transform') for t in tr[ifrom:ito]][::-1] else: trs = [getattr(self, '_' + t + '_transform').inverse for t in tr[ito:ifrom]] return self._cache.get(trs)
python
def get_transform(self, map_from='visual', map_to='render'): """Return a transform mapping between any two coordinate systems. Parameters ---------- map_from : str The starting coordinate system to map from. Must be one of: visual, scene, document, canvas, framebuffer, or render. map_to : str The ending coordinate system to map to. Must be one of: visual, scene, document, canvas, framebuffer, or render. """ tr = ['visual', 'scene', 'document', 'canvas', 'framebuffer', 'render'] ifrom = tr.index(map_from) ito = tr.index(map_to) if ifrom < ito: trs = [getattr(self, '_' + t + '_transform') for t in tr[ifrom:ito]][::-1] else: trs = [getattr(self, '_' + t + '_transform').inverse for t in tr[ito:ifrom]] return self._cache.get(trs)
[ "def", "get_transform", "(", "self", ",", "map_from", "=", "'visual'", ",", "map_to", "=", "'render'", ")", ":", "tr", "=", "[", "'visual'", ",", "'scene'", ",", "'document'", ",", "'canvas'", ",", "'framebuffer'", ",", "'render'", "]", "ifrom", "=", "tr", ".", "index", "(", "map_from", ")", "ito", "=", "tr", ".", "index", "(", "map_to", ")", "if", "ifrom", "<", "ito", ":", "trs", "=", "[", "getattr", "(", "self", ",", "'_'", "+", "t", "+", "'_transform'", ")", "for", "t", "in", "tr", "[", "ifrom", ":", "ito", "]", "]", "[", ":", ":", "-", "1", "]", "else", ":", "trs", "=", "[", "getattr", "(", "self", ",", "'_'", "+", "t", "+", "'_transform'", ")", ".", "inverse", "for", "t", "in", "tr", "[", "ito", ":", "ifrom", "]", "]", "return", "self", ".", "_cache", ".", "get", "(", "trs", ")" ]
Return a transform mapping between any two coordinate systems. Parameters ---------- map_from : str The starting coordinate system to map from. Must be one of: visual, scene, document, canvas, framebuffer, or render. map_to : str The ending coordinate system to map to. Must be one of: visual, scene, document, canvas, framebuffer, or render.
[ "Return", "a", "transform", "mapping", "between", "any", "two", "coordinate", "systems", ".", "Parameters", "----------", "map_from", ":", "str", "The", "starting", "coordinate", "system", "to", "map", "from", ".", "Must", "be", "one", "of", ":", "visual", "scene", "document", "canvas", "framebuffer", "or", "render", ".", "map_to", ":", "str", "The", "ending", "coordinate", "system", "to", "map", "to", ".", "Must", "be", "one", "of", ":", "visual", "scene", "document", "canvas", "framebuffer", "or", "render", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/transform_system.py#L313-L335
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/graphs/layouts/force_directed.py
_calculate_delta_pos
def _calculate_delta_pos(adjacency_arr, pos, t, optimal): """Helper to calculate the delta position""" # XXX eventually this should be refactored for the sparse case to only # do the necessary pairwise distances delta = pos[:, np.newaxis, :] - pos # Distance between points distance2 = (delta*delta).sum(axis=-1) # Enforce minimum distance of 0.01 distance2 = np.where(distance2 < 0.0001, 0.0001, distance2) distance = np.sqrt(distance2) # Displacement "force" displacement = np.zeros((len(delta), 2)) for ii in range(2): displacement[:, ii] = ( delta[:, :, ii] * ((optimal * optimal) / (distance*distance) - (adjacency_arr * distance) / optimal)).sum(axis=1) length = np.sqrt((displacement**2).sum(axis=1)) length = np.where(length < 0.01, 0.1, length) delta_pos = displacement * t / length[:, np.newaxis] return delta_pos
python
def _calculate_delta_pos(adjacency_arr, pos, t, optimal): """Helper to calculate the delta position""" # XXX eventually this should be refactored for the sparse case to only # do the necessary pairwise distances delta = pos[:, np.newaxis, :] - pos # Distance between points distance2 = (delta*delta).sum(axis=-1) # Enforce minimum distance of 0.01 distance2 = np.where(distance2 < 0.0001, 0.0001, distance2) distance = np.sqrt(distance2) # Displacement "force" displacement = np.zeros((len(delta), 2)) for ii in range(2): displacement[:, ii] = ( delta[:, :, ii] * ((optimal * optimal) / (distance*distance) - (adjacency_arr * distance) / optimal)).sum(axis=1) length = np.sqrt((displacement**2).sum(axis=1)) length = np.where(length < 0.01, 0.1, length) delta_pos = displacement * t / length[:, np.newaxis] return delta_pos
[ "def", "_calculate_delta_pos", "(", "adjacency_arr", ",", "pos", ",", "t", ",", "optimal", ")", ":", "# XXX eventually this should be refactored for the sparse case to only", "# do the necessary pairwise distances", "delta", "=", "pos", "[", ":", ",", "np", ".", "newaxis", ",", ":", "]", "-", "pos", "# Distance between points", "distance2", "=", "(", "delta", "*", "delta", ")", ".", "sum", "(", "axis", "=", "-", "1", ")", "# Enforce minimum distance of 0.01", "distance2", "=", "np", ".", "where", "(", "distance2", "<", "0.0001", ",", "0.0001", ",", "distance2", ")", "distance", "=", "np", ".", "sqrt", "(", "distance2", ")", "# Displacement \"force\"", "displacement", "=", "np", ".", "zeros", "(", "(", "len", "(", "delta", ")", ",", "2", ")", ")", "for", "ii", "in", "range", "(", "2", ")", ":", "displacement", "[", ":", ",", "ii", "]", "=", "(", "delta", "[", ":", ",", ":", ",", "ii", "]", "*", "(", "(", "optimal", "*", "optimal", ")", "/", "(", "distance", "*", "distance", ")", "-", "(", "adjacency_arr", "*", "distance", ")", "/", "optimal", ")", ")", ".", "sum", "(", "axis", "=", "1", ")", "length", "=", "np", ".", "sqrt", "(", "(", "displacement", "**", "2", ")", ".", "sum", "(", "axis", "=", "1", ")", ")", "length", "=", "np", ".", "where", "(", "length", "<", "0.01", ",", "0.1", ",", "length", ")", "delta_pos", "=", "displacement", "*", "t", "/", "length", "[", ":", ",", "np", ".", "newaxis", "]", "return", "delta_pos" ]
Helper to calculate the delta position
[ "Helper", "to", "calculate", "the", "delta", "position" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/graphs/layouts/force_directed.py#L190-L212
train
anjishnu/ask-alexa-pykit
lambda_function.py
get_recipe_intent_handler
def get_recipe_intent_handler(request): """ You can insert arbitrary business logic code here """ # Get variables like userId, slots, intent name etc from the 'Request' object ingredient = request.slots["Ingredient"] # Gets an Ingredient Slot from the Request object. if ingredient == None: return alexa.create_response("Could not find an ingredient!") # All manipulations to the request's session object are automatically reflected in the request returned to Amazon. # For e.g. This statement adds a new session attribute (automatically returned with the response) storing the # Last seen ingredient value in the 'last_ingredient' key. request.session['last_ingredient'] = ingredient # Automatically returned as a sessionAttribute # Modifying state like this saves us from explicitly having to return Session objects after every response # alexa can also build cards which can be sent as part of the response card = alexa.create_card(title="GetRecipeIntent activated", subtitle=None, content="asked alexa to find a recipe using {}".format(ingredient)) return alexa.create_response("Finding a recipe with the ingredient {}".format(ingredient), end_session=False, card_obj=card)
python
def get_recipe_intent_handler(request): """ You can insert arbitrary business logic code here """ # Get variables like userId, slots, intent name etc from the 'Request' object ingredient = request.slots["Ingredient"] # Gets an Ingredient Slot from the Request object. if ingredient == None: return alexa.create_response("Could not find an ingredient!") # All manipulations to the request's session object are automatically reflected in the request returned to Amazon. # For e.g. This statement adds a new session attribute (automatically returned with the response) storing the # Last seen ingredient value in the 'last_ingredient' key. request.session['last_ingredient'] = ingredient # Automatically returned as a sessionAttribute # Modifying state like this saves us from explicitly having to return Session objects after every response # alexa can also build cards which can be sent as part of the response card = alexa.create_card(title="GetRecipeIntent activated", subtitle=None, content="asked alexa to find a recipe using {}".format(ingredient)) return alexa.create_response("Finding a recipe with the ingredient {}".format(ingredient), end_session=False, card_obj=card)
[ "def", "get_recipe_intent_handler", "(", "request", ")", ":", "# Get variables like userId, slots, intent name etc from the 'Request' object", "ingredient", "=", "request", ".", "slots", "[", "\"Ingredient\"", "]", "# Gets an Ingredient Slot from the Request object.", "if", "ingredient", "==", "None", ":", "return", "alexa", ".", "create_response", "(", "\"Could not find an ingredient!\"", ")", "# All manipulations to the request's session object are automatically reflected in the request returned to Amazon.", "# For e.g. This statement adds a new session attribute (automatically returned with the response) storing the", "# Last seen ingredient value in the 'last_ingredient' key. ", "request", ".", "session", "[", "'last_ingredient'", "]", "=", "ingredient", "# Automatically returned as a sessionAttribute", "# Modifying state like this saves us from explicitly having to return Session objects after every response", "# alexa can also build cards which can be sent as part of the response", "card", "=", "alexa", ".", "create_card", "(", "title", "=", "\"GetRecipeIntent activated\"", ",", "subtitle", "=", "None", ",", "content", "=", "\"asked alexa to find a recipe using {}\"", ".", "format", "(", "ingredient", ")", ")", "return", "alexa", ".", "create_response", "(", "\"Finding a recipe with the ingredient {}\"", ".", "format", "(", "ingredient", ")", ",", "end_session", "=", "False", ",", "card_obj", "=", "card", ")" ]
You can insert arbitrary business logic code here
[ "You", "can", "insert", "arbitrary", "business", "logic", "code", "here" ]
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/lambda_function.py#L47-L71
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/wrappers.py
use
def use(app=None, gl=None): """ Set the usage options for vispy Specify what app backend and GL backend to use. Parameters ---------- app : str The app backend to use (case insensitive). Standard backends: * 'PyQt4': use Qt widget toolkit via PyQt4. * 'PyQt5': use Qt widget toolkit via PyQt5. * 'PySide': use Qt widget toolkit via PySide. * 'PyGlet': use Pyglet backend. * 'Glfw': use Glfw backend (successor of Glut). Widely available on Linux. * 'SDL2': use SDL v2 backend. * 'osmesa': Use OSMesa backend Additional backends: * 'ipynb_vnc': render in the IPython notebook via a VNC approach (experimental) gl : str The gl backend to use (case insensitive). Options are: * 'gl2': use Vispy's desktop OpenGL API. * 'pyopengl2': use PyOpenGL's desktop OpenGL API. Mostly for testing. * 'es2': (TO COME) use real OpenGL ES 2.0 on Windows via Angle. Availability of ES 2.0 is larger for Windows, since it relies on DirectX. * 'gl+': use the full OpenGL functionality available on your system (via PyOpenGL). Notes ----- If the app option is given, ``vispy.app.use_app()`` is called. If the gl option is given, ``vispy.gloo.use_gl()`` is called. If an app backend name is provided, and that backend could not be loaded, an error is raised. If no backend name is provided, Vispy will first check if the GUI toolkit corresponding to each backend is already imported, and try that backend first. If this is unsuccessful, it will try the 'default_backend' provided in the vispy config. If still not succesful, it will try each backend in a predetermined order. See Also -------- vispy.app.use_app vispy.gloo.gl.use_gl """ if app is None and gl is None: raise TypeError('Must specify at least one of "app" or "gl".') # Example for future. This wont work (yet). if app == 'ipynb_webgl': app = 'headless' gl = 'webgl' if app == 'osmesa': from ..util.osmesa_gl import fix_osmesa_gl_lib fix_osmesa_gl_lib() if gl is not None: raise ValueError("Do not specify gl when using osmesa") # Apply now if gl: from .. import gloo, config config['gl_backend'] = gl gloo.gl.use_gl(gl) if app: from ..app import use_app use_app(app)
python
def use(app=None, gl=None): """ Set the usage options for vispy Specify what app backend and GL backend to use. Parameters ---------- app : str The app backend to use (case insensitive). Standard backends: * 'PyQt4': use Qt widget toolkit via PyQt4. * 'PyQt5': use Qt widget toolkit via PyQt5. * 'PySide': use Qt widget toolkit via PySide. * 'PyGlet': use Pyglet backend. * 'Glfw': use Glfw backend (successor of Glut). Widely available on Linux. * 'SDL2': use SDL v2 backend. * 'osmesa': Use OSMesa backend Additional backends: * 'ipynb_vnc': render in the IPython notebook via a VNC approach (experimental) gl : str The gl backend to use (case insensitive). Options are: * 'gl2': use Vispy's desktop OpenGL API. * 'pyopengl2': use PyOpenGL's desktop OpenGL API. Mostly for testing. * 'es2': (TO COME) use real OpenGL ES 2.0 on Windows via Angle. Availability of ES 2.0 is larger for Windows, since it relies on DirectX. * 'gl+': use the full OpenGL functionality available on your system (via PyOpenGL). Notes ----- If the app option is given, ``vispy.app.use_app()`` is called. If the gl option is given, ``vispy.gloo.use_gl()`` is called. If an app backend name is provided, and that backend could not be loaded, an error is raised. If no backend name is provided, Vispy will first check if the GUI toolkit corresponding to each backend is already imported, and try that backend first. If this is unsuccessful, it will try the 'default_backend' provided in the vispy config. If still not succesful, it will try each backend in a predetermined order. See Also -------- vispy.app.use_app vispy.gloo.gl.use_gl """ if app is None and gl is None: raise TypeError('Must specify at least one of "app" or "gl".') # Example for future. This wont work (yet). if app == 'ipynb_webgl': app = 'headless' gl = 'webgl' if app == 'osmesa': from ..util.osmesa_gl import fix_osmesa_gl_lib fix_osmesa_gl_lib() if gl is not None: raise ValueError("Do not specify gl when using osmesa") # Apply now if gl: from .. import gloo, config config['gl_backend'] = gl gloo.gl.use_gl(gl) if app: from ..app import use_app use_app(app)
[ "def", "use", "(", "app", "=", "None", ",", "gl", "=", "None", ")", ":", "if", "app", "is", "None", "and", "gl", "is", "None", ":", "raise", "TypeError", "(", "'Must specify at least one of \"app\" or \"gl\".'", ")", "# Example for future. This wont work (yet).", "if", "app", "==", "'ipynb_webgl'", ":", "app", "=", "'headless'", "gl", "=", "'webgl'", "if", "app", "==", "'osmesa'", ":", "from", ".", ".", "util", ".", "osmesa_gl", "import", "fix_osmesa_gl_lib", "fix_osmesa_gl_lib", "(", ")", "if", "gl", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Do not specify gl when using osmesa\"", ")", "# Apply now", "if", "gl", ":", "from", ".", ".", "import", "gloo", ",", "config", "config", "[", "'gl_backend'", "]", "=", "gl", "gloo", ".", "gl", ".", "use_gl", "(", "gl", ")", "if", "app", ":", "from", ".", ".", "app", "import", "use_app", "use_app", "(", "app", ")" ]
Set the usage options for vispy Specify what app backend and GL backend to use. Parameters ---------- app : str The app backend to use (case insensitive). Standard backends: * 'PyQt4': use Qt widget toolkit via PyQt4. * 'PyQt5': use Qt widget toolkit via PyQt5. * 'PySide': use Qt widget toolkit via PySide. * 'PyGlet': use Pyglet backend. * 'Glfw': use Glfw backend (successor of Glut). Widely available on Linux. * 'SDL2': use SDL v2 backend. * 'osmesa': Use OSMesa backend Additional backends: * 'ipynb_vnc': render in the IPython notebook via a VNC approach (experimental) gl : str The gl backend to use (case insensitive). Options are: * 'gl2': use Vispy's desktop OpenGL API. * 'pyopengl2': use PyOpenGL's desktop OpenGL API. Mostly for testing. * 'es2': (TO COME) use real OpenGL ES 2.0 on Windows via Angle. Availability of ES 2.0 is larger for Windows, since it relies on DirectX. * 'gl+': use the full OpenGL functionality available on your system (via PyOpenGL). Notes ----- If the app option is given, ``vispy.app.use_app()`` is called. If the gl option is given, ``vispy.gloo.use_gl()`` is called. If an app backend name is provided, and that backend could not be loaded, an error is raised. If no backend name is provided, Vispy will first check if the GUI toolkit corresponding to each backend is already imported, and try that backend first. If this is unsuccessful, it will try the 'default_backend' provided in the vispy config. If still not succesful, it will try each backend in a predetermined order. See Also -------- vispy.app.use_app vispy.gloo.gl.use_gl
[ "Set", "the", "usage", "options", "for", "vispy" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/wrappers.py#L23-L94
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/wrappers.py
run_subprocess
def run_subprocess(command, return_code=False, **kwargs): """Run command using subprocess.Popen Run command and wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. By default, this will also add stdout= and stderr=subproces.PIPE to the call to Popen to suppress printing to the terminal. Parameters ---------- command : list of str Command to run as subprocess (see subprocess.Popen documentation). return_code : bool If True, the returncode will be returned, and no error checking will be performed (so this function should always return without error). **kwargs : dict Additional kwargs to pass to ``subprocess.Popen``. Returns ------- stdout : str Stdout returned by the process. stderr : str Stderr returned by the process. code : int The command exit code. Only returned if ``return_code`` is True. """ # code adapted with permission from mne-python use_kwargs = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) use_kwargs.update(kwargs) p = subprocess.Popen(command, **use_kwargs) output = p.communicate() # communicate() may return bytes, str, or None depending on the kwargs # passed to Popen(). Convert all to unicode str: output = ['' if s is None else s for s in output] output = [s.decode('utf-8') if isinstance(s, bytes) else s for s in output] output = tuple(output) if not return_code and p.returncode: print(output[0]) print(output[1]) err_fun = subprocess.CalledProcessError.__init__ if 'output' in inspect.getargspec(err_fun).args: raise subprocess.CalledProcessError(p.returncode, command, output) else: raise subprocess.CalledProcessError(p.returncode, command) if return_code: output = output + (p.returncode,) return output
python
def run_subprocess(command, return_code=False, **kwargs): """Run command using subprocess.Popen Run command and wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. By default, this will also add stdout= and stderr=subproces.PIPE to the call to Popen to suppress printing to the terminal. Parameters ---------- command : list of str Command to run as subprocess (see subprocess.Popen documentation). return_code : bool If True, the returncode will be returned, and no error checking will be performed (so this function should always return without error). **kwargs : dict Additional kwargs to pass to ``subprocess.Popen``. Returns ------- stdout : str Stdout returned by the process. stderr : str Stderr returned by the process. code : int The command exit code. Only returned if ``return_code`` is True. """ # code adapted with permission from mne-python use_kwargs = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) use_kwargs.update(kwargs) p = subprocess.Popen(command, **use_kwargs) output = p.communicate() # communicate() may return bytes, str, or None depending on the kwargs # passed to Popen(). Convert all to unicode str: output = ['' if s is None else s for s in output] output = [s.decode('utf-8') if isinstance(s, bytes) else s for s in output] output = tuple(output) if not return_code and p.returncode: print(output[0]) print(output[1]) err_fun = subprocess.CalledProcessError.__init__ if 'output' in inspect.getargspec(err_fun).args: raise subprocess.CalledProcessError(p.returncode, command, output) else: raise subprocess.CalledProcessError(p.returncode, command) if return_code: output = output + (p.returncode,) return output
[ "def", "run_subprocess", "(", "command", ",", "return_code", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# code adapted with permission from mne-python", "use_kwargs", "=", "dict", "(", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "use_kwargs", ".", "update", "(", "kwargs", ")", "p", "=", "subprocess", ".", "Popen", "(", "command", ",", "*", "*", "use_kwargs", ")", "output", "=", "p", ".", "communicate", "(", ")", "# communicate() may return bytes, str, or None depending on the kwargs", "# passed to Popen(). Convert all to unicode str:", "output", "=", "[", "''", "if", "s", "is", "None", "else", "s", "for", "s", "in", "output", "]", "output", "=", "[", "s", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "s", ",", "bytes", ")", "else", "s", "for", "s", "in", "output", "]", "output", "=", "tuple", "(", "output", ")", "if", "not", "return_code", "and", "p", ".", "returncode", ":", "print", "(", "output", "[", "0", "]", ")", "print", "(", "output", "[", "1", "]", ")", "err_fun", "=", "subprocess", ".", "CalledProcessError", ".", "__init__", "if", "'output'", "in", "inspect", ".", "getargspec", "(", "err_fun", ")", ".", "args", ":", "raise", "subprocess", ".", "CalledProcessError", "(", "p", ".", "returncode", ",", "command", ",", "output", ")", "else", ":", "raise", "subprocess", ".", "CalledProcessError", "(", "p", ".", "returncode", ",", "command", ")", "if", "return_code", ":", "output", "=", "output", "+", "(", "p", ".", "returncode", ",", ")", "return", "output" ]
Run command using subprocess.Popen Run command and wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. By default, this will also add stdout= and stderr=subproces.PIPE to the call to Popen to suppress printing to the terminal. Parameters ---------- command : list of str Command to run as subprocess (see subprocess.Popen documentation). return_code : bool If True, the returncode will be returned, and no error checking will be performed (so this function should always return without error). **kwargs : dict Additional kwargs to pass to ``subprocess.Popen``. Returns ------- stdout : str Stdout returned by the process. stderr : str Stderr returned by the process. code : int The command exit code. Only returned if ``return_code`` is True.
[ "Run", "command", "using", "subprocess", ".", "Popen" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/wrappers.py#L97-L148
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/app/timer.py
Timer.start
def start(self, interval=None, iterations=None): """Start the timer. A timeout event will be generated every *interval* seconds. If *interval* is None, then self.interval will be used. If *iterations* is specified, the timer will stop after emitting that number of events. If unspecified, then the previous value of self.iterations will be used. If the value is negative, then the timer will continue running until stop() is called. If the timer is already running when this function is called, nothing happens (timer continues running as it did previously, without changing the interval, number of iterations, or emitting a timer start event). """ if self.running: return # don't do anything if already running self.iter_count = 0 if interval is not None: self.interval = interval if iterations is not None: self.max_iterations = iterations self._backend._vispy_start(self.interval) self._running = True self._first_emit_time = precision_time() self._last_emit_time = precision_time() self.events.start(type='timer_start')
python
def start(self, interval=None, iterations=None): """Start the timer. A timeout event will be generated every *interval* seconds. If *interval* is None, then self.interval will be used. If *iterations* is specified, the timer will stop after emitting that number of events. If unspecified, then the previous value of self.iterations will be used. If the value is negative, then the timer will continue running until stop() is called. If the timer is already running when this function is called, nothing happens (timer continues running as it did previously, without changing the interval, number of iterations, or emitting a timer start event). """ if self.running: return # don't do anything if already running self.iter_count = 0 if interval is not None: self.interval = interval if iterations is not None: self.max_iterations = iterations self._backend._vispy_start(self.interval) self._running = True self._first_emit_time = precision_time() self._last_emit_time = precision_time() self.events.start(type='timer_start')
[ "def", "start", "(", "self", ",", "interval", "=", "None", ",", "iterations", "=", "None", ")", ":", "if", "self", ".", "running", ":", "return", "# don't do anything if already running", "self", ".", "iter_count", "=", "0", "if", "interval", "is", "not", "None", ":", "self", ".", "interval", "=", "interval", "if", "iterations", "is", "not", "None", ":", "self", ".", "max_iterations", "=", "iterations", "self", ".", "_backend", ".", "_vispy_start", "(", "self", ".", "interval", ")", "self", ".", "_running", "=", "True", "self", ".", "_first_emit_time", "=", "precision_time", "(", ")", "self", ".", "_last_emit_time", "=", "precision_time", "(", ")", "self", ".", "events", ".", "start", "(", "type", "=", "'timer_start'", ")" ]
Start the timer. A timeout event will be generated every *interval* seconds. If *interval* is None, then self.interval will be used. If *iterations* is specified, the timer will stop after emitting that number of events. If unspecified, then the previous value of self.iterations will be used. If the value is negative, then the timer will continue running until stop() is called. If the timer is already running when this function is called, nothing happens (timer continues running as it did previously, without changing the interval, number of iterations, or emitting a timer start event).
[ "Start", "the", "timer", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/app/timer.py#L97-L124
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/app/timer.py
Timer.stop
def stop(self): """Stop the timer.""" self._backend._vispy_stop() self._running = False self.events.stop(type='timer_stop')
python
def stop(self): """Stop the timer.""" self._backend._vispy_stop() self._running = False self.events.stop(type='timer_stop')
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_backend", ".", "_vispy_stop", "(", ")", "self", ".", "_running", "=", "False", "self", ".", "events", ".", "stop", "(", "type", "=", "'timer_stop'", ")" ]
Stop the timer.
[ "Stop", "the", "timer", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/app/timer.py#L126-L130
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC._best_res_pixels
def _best_res_pixels(self): """ Returns a numpy array of all the HEALPix indexes contained in the MOC at its max order. Returns ------- result : `~numpy.ndarray` The array of HEALPix at ``max_order`` """ factor = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order) pix_l = [] for iv in self._interval_set._intervals: for val in range(iv[0] >> factor, iv[1] >> factor): pix_l.append(val) return np.asarray(pix_l)
python
def _best_res_pixels(self): """ Returns a numpy array of all the HEALPix indexes contained in the MOC at its max order. Returns ------- result : `~numpy.ndarray` The array of HEALPix at ``max_order`` """ factor = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order) pix_l = [] for iv in self._interval_set._intervals: for val in range(iv[0] >> factor, iv[1] >> factor): pix_l.append(val) return np.asarray(pix_l)
[ "def", "_best_res_pixels", "(", "self", ")", ":", "factor", "=", "2", "*", "(", "AbstractMOC", ".", "HPY_MAX_NORDER", "-", "self", ".", "max_order", ")", "pix_l", "=", "[", "]", "for", "iv", "in", "self", ".", "_interval_set", ".", "_intervals", ":", "for", "val", "in", "range", "(", "iv", "[", "0", "]", ">>", "factor", ",", "iv", "[", "1", "]", ">>", "factor", ")", ":", "pix_l", ".", "append", "(", "val", ")", "return", "np", ".", "asarray", "(", "pix_l", ")" ]
Returns a numpy array of all the HEALPix indexes contained in the MOC at its max order. Returns ------- result : `~numpy.ndarray` The array of HEALPix at ``max_order``
[ "Returns", "a", "numpy", "array", "of", "all", "the", "HEALPix", "indexes", "contained", "in", "the", "MOC", "at", "its", "max", "order", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L71-L86
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.contains
def contains(self, ra, dec, keep_inside=True): """ Returns a boolean mask array of the positions lying inside (or outside) the MOC instance. Parameters ---------- ra : `astropy.units.Quantity` Right ascension array dec : `astropy.units.Quantity` Declination array keep_inside : bool, optional True by default. If so the mask describes coordinates lying inside the MOC. If ``keep_inside`` is false, contains will return the mask of the coordinates lying outside the MOC. Returns ------- array : `~np.ndarray` A mask boolean array """ depth = self.max_order m = np.zeros(nside2npix(1 << depth), dtype=bool) pix_id = self._best_res_pixels() m[pix_id] = True if not keep_inside: m = np.logical_not(m) hp = HEALPix(nside=(1 << depth), order='nested') pix = hp.lonlat_to_healpix(ra, dec) return m[pix]
python
def contains(self, ra, dec, keep_inside=True): """ Returns a boolean mask array of the positions lying inside (or outside) the MOC instance. Parameters ---------- ra : `astropy.units.Quantity` Right ascension array dec : `astropy.units.Quantity` Declination array keep_inside : bool, optional True by default. If so the mask describes coordinates lying inside the MOC. If ``keep_inside`` is false, contains will return the mask of the coordinates lying outside the MOC. Returns ------- array : `~np.ndarray` A mask boolean array """ depth = self.max_order m = np.zeros(nside2npix(1 << depth), dtype=bool) pix_id = self._best_res_pixels() m[pix_id] = True if not keep_inside: m = np.logical_not(m) hp = HEALPix(nside=(1 << depth), order='nested') pix = hp.lonlat_to_healpix(ra, dec) return m[pix]
[ "def", "contains", "(", "self", ",", "ra", ",", "dec", ",", "keep_inside", "=", "True", ")", ":", "depth", "=", "self", ".", "max_order", "m", "=", "np", ".", "zeros", "(", "nside2npix", "(", "1", "<<", "depth", ")", ",", "dtype", "=", "bool", ")", "pix_id", "=", "self", ".", "_best_res_pixels", "(", ")", "m", "[", "pix_id", "]", "=", "True", "if", "not", "keep_inside", ":", "m", "=", "np", ".", "logical_not", "(", "m", ")", "hp", "=", "HEALPix", "(", "nside", "=", "(", "1", "<<", "depth", ")", ",", "order", "=", "'nested'", ")", "pix", "=", "hp", ".", "lonlat_to_healpix", "(", "ra", ",", "dec", ")", "return", "m", "[", "pix", "]" ]
Returns a boolean mask array of the positions lying inside (or outside) the MOC instance. Parameters ---------- ra : `astropy.units.Quantity` Right ascension array dec : `astropy.units.Quantity` Declination array keep_inside : bool, optional True by default. If so the mask describes coordinates lying inside the MOC. If ``keep_inside`` is false, contains will return the mask of the coordinates lying outside the MOC. Returns ------- array : `~np.ndarray` A mask boolean array
[ "Returns", "a", "boolean", "mask", "array", "of", "the", "positions", "lying", "inside", "(", "or", "outside", ")", "the", "MOC", "instance", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L88-L119
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.add_neighbours
def add_neighbours(self): """ Extends the MOC instance so that it includes the HEALPix cells touching its border. The depth of the HEALPix cells added at the border is equal to the maximum depth of the MOC instance. Returns ------- moc : `~mocpy.moc.MOC` self extended by one degree of neighbours. """ # Get the pixels array of the MOC at the its max order. ipix = self._best_res_pixels() hp = HEALPix(nside=(1 << self.max_order), order='nested') # Get the HEALPix array containing the neighbors of ``ipix``. # This array "extends" ``ipix`` by one degree of neighbors. extend_ipix = AbstractMOC._neighbour_pixels(hp, ipix) # Compute the difference between ``extend_ipix`` and ``ipix`` to get only the neighboring pixels # located at the border of the MOC. neigh_ipix = np.setdiff1d(extend_ipix, ipix) shift = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order) neigh_itv = np.vstack((neigh_ipix << shift, (neigh_ipix + 1) << shift)).T # This array of HEALPix neighbors are added to the MOC to get an ``extended`` MOC at its max order. self._interval_set = self._interval_set.union(IntervalSet(neigh_itv)) return self
python
def add_neighbours(self): """ Extends the MOC instance so that it includes the HEALPix cells touching its border. The depth of the HEALPix cells added at the border is equal to the maximum depth of the MOC instance. Returns ------- moc : `~mocpy.moc.MOC` self extended by one degree of neighbours. """ # Get the pixels array of the MOC at the its max order. ipix = self._best_res_pixels() hp = HEALPix(nside=(1 << self.max_order), order='nested') # Get the HEALPix array containing the neighbors of ``ipix``. # This array "extends" ``ipix`` by one degree of neighbors. extend_ipix = AbstractMOC._neighbour_pixels(hp, ipix) # Compute the difference between ``extend_ipix`` and ``ipix`` to get only the neighboring pixels # located at the border of the MOC. neigh_ipix = np.setdiff1d(extend_ipix, ipix) shift = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order) neigh_itv = np.vstack((neigh_ipix << shift, (neigh_ipix + 1) << shift)).T # This array of HEALPix neighbors are added to the MOC to get an ``extended`` MOC at its max order. self._interval_set = self._interval_set.union(IntervalSet(neigh_itv)) return self
[ "def", "add_neighbours", "(", "self", ")", ":", "# Get the pixels array of the MOC at the its max order.", "ipix", "=", "self", ".", "_best_res_pixels", "(", ")", "hp", "=", "HEALPix", "(", "nside", "=", "(", "1", "<<", "self", ".", "max_order", ")", ",", "order", "=", "'nested'", ")", "# Get the HEALPix array containing the neighbors of ``ipix``.", "# This array \"extends\" ``ipix`` by one degree of neighbors. ", "extend_ipix", "=", "AbstractMOC", ".", "_neighbour_pixels", "(", "hp", ",", "ipix", ")", "# Compute the difference between ``extend_ipix`` and ``ipix`` to get only the neighboring pixels", "# located at the border of the MOC.", "neigh_ipix", "=", "np", ".", "setdiff1d", "(", "extend_ipix", ",", "ipix", ")", "shift", "=", "2", "*", "(", "AbstractMOC", ".", "HPY_MAX_NORDER", "-", "self", ".", "max_order", ")", "neigh_itv", "=", "np", ".", "vstack", "(", "(", "neigh_ipix", "<<", "shift", ",", "(", "neigh_ipix", "+", "1", ")", "<<", "shift", ")", ")", ".", "T", "# This array of HEALPix neighbors are added to the MOC to get an ``extended`` MOC at its max order.", "self", ".", "_interval_set", "=", "self", ".", "_interval_set", ".", "union", "(", "IntervalSet", "(", "neigh_itv", ")", ")", "return", "self" ]
Extends the MOC instance so that it includes the HEALPix cells touching its border. The depth of the HEALPix cells added at the border is equal to the maximum depth of the MOC instance. Returns ------- moc : `~mocpy.moc.MOC` self extended by one degree of neighbours.
[ "Extends", "the", "MOC", "instance", "so", "that", "it", "includes", "the", "HEALPix", "cells", "touching", "its", "border", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L124-L151
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.remove_neighbours
def remove_neighbours(self): """ Removes from the MOC instance the HEALPix cells located at its border. The depth of the HEALPix cells removed is equal to the maximum depth of the MOC instance. Returns ------- moc : `~mocpy.moc.MOC` self minus its HEALPix cells located at its border. """ # Get the HEALPix cells of the MOC at its max depth ipix = self._best_res_pixels() hp = HEALPix(nside=(1 << self.max_order), order='nested') # Extend it to include the max depth neighbor cells. extend_ipix = AbstractMOC._neighbour_pixels(hp, ipix) # Get only the max depth HEALPix cells lying at the border of the MOC neigh_ipix = np.setxor1d(extend_ipix, ipix) # Remove these pixels from ``ipix`` border_ipix = AbstractMOC._neighbour_pixels(hp, neigh_ipix) reduced_ipix = np.setdiff1d(ipix, border_ipix) # Build the reduced MOC, i.e. MOC without its pixels which were located at its border. shift = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order) reduced_itv = np.vstack((reduced_ipix << shift, (reduced_ipix + 1) << shift)).T self._interval_set = IntervalSet(reduced_itv) return self
python
def remove_neighbours(self): """ Removes from the MOC instance the HEALPix cells located at its border. The depth of the HEALPix cells removed is equal to the maximum depth of the MOC instance. Returns ------- moc : `~mocpy.moc.MOC` self minus its HEALPix cells located at its border. """ # Get the HEALPix cells of the MOC at its max depth ipix = self._best_res_pixels() hp = HEALPix(nside=(1 << self.max_order), order='nested') # Extend it to include the max depth neighbor cells. extend_ipix = AbstractMOC._neighbour_pixels(hp, ipix) # Get only the max depth HEALPix cells lying at the border of the MOC neigh_ipix = np.setxor1d(extend_ipix, ipix) # Remove these pixels from ``ipix`` border_ipix = AbstractMOC._neighbour_pixels(hp, neigh_ipix) reduced_ipix = np.setdiff1d(ipix, border_ipix) # Build the reduced MOC, i.e. MOC without its pixels which were located at its border. shift = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order) reduced_itv = np.vstack((reduced_ipix << shift, (reduced_ipix + 1) << shift)).T self._interval_set = IntervalSet(reduced_itv) return self
[ "def", "remove_neighbours", "(", "self", ")", ":", "# Get the HEALPix cells of the MOC at its max depth", "ipix", "=", "self", ".", "_best_res_pixels", "(", ")", "hp", "=", "HEALPix", "(", "nside", "=", "(", "1", "<<", "self", ".", "max_order", ")", ",", "order", "=", "'nested'", ")", "# Extend it to include the max depth neighbor cells.", "extend_ipix", "=", "AbstractMOC", ".", "_neighbour_pixels", "(", "hp", ",", "ipix", ")", "# Get only the max depth HEALPix cells lying at the border of the MOC", "neigh_ipix", "=", "np", ".", "setxor1d", "(", "extend_ipix", ",", "ipix", ")", "# Remove these pixels from ``ipix``", "border_ipix", "=", "AbstractMOC", ".", "_neighbour_pixels", "(", "hp", ",", "neigh_ipix", ")", "reduced_ipix", "=", "np", ".", "setdiff1d", "(", "ipix", ",", "border_ipix", ")", "# Build the reduced MOC, i.e. MOC without its pixels which were located at its border.", "shift", "=", "2", "*", "(", "AbstractMOC", ".", "HPY_MAX_NORDER", "-", "self", ".", "max_order", ")", "reduced_itv", "=", "np", ".", "vstack", "(", "(", "reduced_ipix", "<<", "shift", ",", "(", "reduced_ipix", "+", "1", ")", "<<", "shift", ")", ")", ".", "T", "self", ".", "_interval_set", "=", "IntervalSet", "(", "reduced_itv", ")", "return", "self" ]
Removes from the MOC instance the HEALPix cells located at its border. The depth of the HEALPix cells removed is equal to the maximum depth of the MOC instance. Returns ------- moc : `~mocpy.moc.MOC` self minus its HEALPix cells located at its border.
[ "Removes", "from", "the", "MOC", "instance", "the", "HEALPix", "cells", "located", "at", "its", "border", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L153-L182
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.fill
def fill(self, ax, wcs, **kw_mpl_pathpatch): """ Draws the MOC on a matplotlib axis. This performs the projection of the cells from the world coordinate system to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.patches.PathPatch` (see the `list of valid keywords <https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch>`__). Parameters ---------- ax : `matplotlib.axes.Axes` Matplotlib axis. wcs : `astropy.wcs.WCS` WCS defining the World system <-> Image system projection. kw_mpl_pathpatch Plotting arguments for `matplotlib.patches.PathPatch`. Examples -------- >>> from mocpy import MOC, WCS >>> from astropy.coordinates import Angle, SkyCoord >>> import astropy.units as u >>> # Load a MOC, e.g. the MOC of GALEXGR6-AIS-FUV >>> filename = './../resources/P-GALEXGR6-AIS-FUV.fits' >>> moc = MOC.from_fits(filename) >>> # Plot the MOC using matplotlib >>> import matplotlib.pyplot as plt >>> fig = plt.figure(111, figsize=(15, 15)) >>> # Define a WCS as a context >>> with WCS(fig, ... fov=50 * u.deg, ... center=SkyCoord(0, 20, unit='deg', frame='icrs'), ... coordsys="icrs", ... rotation=Angle(0, u.degree), ... projection="AIT") as wcs: ... ax = fig.add_subplot(1, 1, 1, projection=wcs) ... # Call fill giving the matplotlib axe and the `~astropy.wcs.WCS` object. ... # We will set the matplotlib keyword linewidth to 0 so that it does not plot ... # the border of each HEALPix cell. ... # The color can also be specified along with an alpha value. ... moc.fill(ax=ax, wcs=wcs, linewidth=0, alpha=0.5, fill=True, color="green") >>> plt.xlabel('ra') >>> plt.ylabel('dec') >>> plt.grid(color="black", linestyle="dotted") """ fill.fill(self, ax, wcs, **kw_mpl_pathpatch)
python
def fill(self, ax, wcs, **kw_mpl_pathpatch): """ Draws the MOC on a matplotlib axis. This performs the projection of the cells from the world coordinate system to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.patches.PathPatch` (see the `list of valid keywords <https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch>`__). Parameters ---------- ax : `matplotlib.axes.Axes` Matplotlib axis. wcs : `astropy.wcs.WCS` WCS defining the World system <-> Image system projection. kw_mpl_pathpatch Plotting arguments for `matplotlib.patches.PathPatch`. Examples -------- >>> from mocpy import MOC, WCS >>> from astropy.coordinates import Angle, SkyCoord >>> import astropy.units as u >>> # Load a MOC, e.g. the MOC of GALEXGR6-AIS-FUV >>> filename = './../resources/P-GALEXGR6-AIS-FUV.fits' >>> moc = MOC.from_fits(filename) >>> # Plot the MOC using matplotlib >>> import matplotlib.pyplot as plt >>> fig = plt.figure(111, figsize=(15, 15)) >>> # Define a WCS as a context >>> with WCS(fig, ... fov=50 * u.deg, ... center=SkyCoord(0, 20, unit='deg', frame='icrs'), ... coordsys="icrs", ... rotation=Angle(0, u.degree), ... projection="AIT") as wcs: ... ax = fig.add_subplot(1, 1, 1, projection=wcs) ... # Call fill giving the matplotlib axe and the `~astropy.wcs.WCS` object. ... # We will set the matplotlib keyword linewidth to 0 so that it does not plot ... # the border of each HEALPix cell. ... # The color can also be specified along with an alpha value. ... moc.fill(ax=ax, wcs=wcs, linewidth=0, alpha=0.5, fill=True, color="green") >>> plt.xlabel('ra') >>> plt.ylabel('dec') >>> plt.grid(color="black", linestyle="dotted") """ fill.fill(self, ax, wcs, **kw_mpl_pathpatch)
[ "def", "fill", "(", "self", ",", "ax", ",", "wcs", ",", "*", "*", "kw_mpl_pathpatch", ")", ":", "fill", ".", "fill", "(", "self", ",", "ax", ",", "wcs", ",", "*", "*", "kw_mpl_pathpatch", ")" ]
Draws the MOC on a matplotlib axis. This performs the projection of the cells from the world coordinate system to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.patches.PathPatch` (see the `list of valid keywords <https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch>`__). Parameters ---------- ax : `matplotlib.axes.Axes` Matplotlib axis. wcs : `astropy.wcs.WCS` WCS defining the World system <-> Image system projection. kw_mpl_pathpatch Plotting arguments for `matplotlib.patches.PathPatch`. Examples -------- >>> from mocpy import MOC, WCS >>> from astropy.coordinates import Angle, SkyCoord >>> import astropy.units as u >>> # Load a MOC, e.g. the MOC of GALEXGR6-AIS-FUV >>> filename = './../resources/P-GALEXGR6-AIS-FUV.fits' >>> moc = MOC.from_fits(filename) >>> # Plot the MOC using matplotlib >>> import matplotlib.pyplot as plt >>> fig = plt.figure(111, figsize=(15, 15)) >>> # Define a WCS as a context >>> with WCS(fig, ... fov=50 * u.deg, ... center=SkyCoord(0, 20, unit='deg', frame='icrs'), ... coordsys="icrs", ... rotation=Angle(0, u.degree), ... projection="AIT") as wcs: ... ax = fig.add_subplot(1, 1, 1, projection=wcs) ... # Call fill giving the matplotlib axe and the `~astropy.wcs.WCS` object. ... # We will set the matplotlib keyword linewidth to 0 so that it does not plot ... # the border of each HEALPix cell. ... # The color can also be specified along with an alpha value. ... moc.fill(ax=ax, wcs=wcs, linewidth=0, alpha=0.5, fill=True, color="green") >>> plt.xlabel('ra') >>> plt.ylabel('dec') >>> plt.grid(color="black", linestyle="dotted")
[ "Draws", "the", "MOC", "on", "a", "matplotlib", "axis", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L184-L229
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.border
def border(self, ax, wcs, **kw_mpl_pathpatch): """ Draws the MOC border(s) on a matplotlib axis. This performs the projection of the sky coordinates defining the perimeter of the MOC to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.patches.PathPatch` (see the `list of valid keywords <https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch>`__). Parameters ---------- ax : `matplotlib.axes.Axes` Matplotlib axis. wcs : `astropy.wcs.WCS` WCS defining the World system <-> Image system projection. kw_mpl_pathpatch Plotting arguments for `matplotlib.patches.PathPatch` Examples -------- >>> from mocpy import MOC, WCS >>> from astropy.coordinates import Angle, SkyCoord >>> import astropy.units as u >>> # Load a MOC, e.g. the MOC of GALEXGR6-AIS-FUV >>> filename = './../resources/P-GALEXGR6-AIS-FUV.fits' >>> moc = MOC.from_fits(filename) >>> # Plot the MOC using matplotlib >>> import matplotlib.pyplot as plt >>> fig = plt.figure(111, figsize=(15, 15)) >>> # Define a WCS as a context >>> with WCS(fig, ... fov=50 * u.deg, ... center=SkyCoord(0, 20, unit='deg', frame='icrs'), ... coordsys="icrs", ... rotation=Angle(0, u.degree), ... projection="AIT") as wcs: ... ax = fig.add_subplot(1, 1, 1, projection=wcs) ... # Call border giving the matplotlib axe and the `~astropy.wcs.WCS` object. ... moc.border(ax=ax, wcs=wcs, alpha=0.5, color="red") >>> plt.xlabel('ra') >>> plt.ylabel('dec') >>> plt.grid(color="black", linestyle="dotted") """ border.border(self, ax, wcs, **kw_mpl_pathpatch)
python
def border(self, ax, wcs, **kw_mpl_pathpatch): """ Draws the MOC border(s) on a matplotlib axis. This performs the projection of the sky coordinates defining the perimeter of the MOC to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.patches.PathPatch` (see the `list of valid keywords <https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch>`__). Parameters ---------- ax : `matplotlib.axes.Axes` Matplotlib axis. wcs : `astropy.wcs.WCS` WCS defining the World system <-> Image system projection. kw_mpl_pathpatch Plotting arguments for `matplotlib.patches.PathPatch` Examples -------- >>> from mocpy import MOC, WCS >>> from astropy.coordinates import Angle, SkyCoord >>> import astropy.units as u >>> # Load a MOC, e.g. the MOC of GALEXGR6-AIS-FUV >>> filename = './../resources/P-GALEXGR6-AIS-FUV.fits' >>> moc = MOC.from_fits(filename) >>> # Plot the MOC using matplotlib >>> import matplotlib.pyplot as plt >>> fig = plt.figure(111, figsize=(15, 15)) >>> # Define a WCS as a context >>> with WCS(fig, ... fov=50 * u.deg, ... center=SkyCoord(0, 20, unit='deg', frame='icrs'), ... coordsys="icrs", ... rotation=Angle(0, u.degree), ... projection="AIT") as wcs: ... ax = fig.add_subplot(1, 1, 1, projection=wcs) ... # Call border giving the matplotlib axe and the `~astropy.wcs.WCS` object. ... moc.border(ax=ax, wcs=wcs, alpha=0.5, color="red") >>> plt.xlabel('ra') >>> plt.ylabel('dec') >>> plt.grid(color="black", linestyle="dotted") """ border.border(self, ax, wcs, **kw_mpl_pathpatch)
[ "def", "border", "(", "self", ",", "ax", ",", "wcs", ",", "*", "*", "kw_mpl_pathpatch", ")", ":", "border", ".", "border", "(", "self", ",", "ax", ",", "wcs", ",", "*", "*", "kw_mpl_pathpatch", ")" ]
Draws the MOC border(s) on a matplotlib axis. This performs the projection of the sky coordinates defining the perimeter of the MOC to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.patches.PathPatch` (see the `list of valid keywords <https://matplotlib.org/api/_as_gen/matplotlib.patches.PathPatch.html#matplotlib.patches.PathPatch>`__). Parameters ---------- ax : `matplotlib.axes.Axes` Matplotlib axis. wcs : `astropy.wcs.WCS` WCS defining the World system <-> Image system projection. kw_mpl_pathpatch Plotting arguments for `matplotlib.patches.PathPatch` Examples -------- >>> from mocpy import MOC, WCS >>> from astropy.coordinates import Angle, SkyCoord >>> import astropy.units as u >>> # Load a MOC, e.g. the MOC of GALEXGR6-AIS-FUV >>> filename = './../resources/P-GALEXGR6-AIS-FUV.fits' >>> moc = MOC.from_fits(filename) >>> # Plot the MOC using matplotlib >>> import matplotlib.pyplot as plt >>> fig = plt.figure(111, figsize=(15, 15)) >>> # Define a WCS as a context >>> with WCS(fig, ... fov=50 * u.deg, ... center=SkyCoord(0, 20, unit='deg', frame='icrs'), ... coordsys="icrs", ... rotation=Angle(0, u.degree), ... projection="AIT") as wcs: ... ax = fig.add_subplot(1, 1, 1, projection=wcs) ... # Call border giving the matplotlib axe and the `~astropy.wcs.WCS` object. ... moc.border(ax=ax, wcs=wcs, alpha=0.5, color="red") >>> plt.xlabel('ra') >>> plt.ylabel('dec') >>> plt.grid(color="black", linestyle="dotted")
[ "Draws", "the", "MOC", "border", "(", "s", ")", "on", "a", "matplotlib", "axis", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L231-L273
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.from_image
def from_image(cls, header, max_norder, mask=None): """ Creates a `~mocpy.moc.MOC` from an image stored as a FITS file. Parameters ---------- header : `astropy.io.fits.Header` FITS header containing all the info of where the image is located (position, size, etc...) max_norder : int The moc resolution. mask : `numpy.ndarray`, optional A boolean array of the same size of the image where pixels having the value 1 are part of the final MOC and pixels having the value 0 are not. Returns ------- moc : `~mocpy.moc.MOC` The resulting MOC. """ # load the image data height = header['NAXIS2'] width = header['NAXIS1'] # use wcs from astropy to locate the image in the world coordinates w = wcs.WCS(header) if mask is not None: # We have an array of pixels that are part of of survey y, x = np.where(mask) pix_crd = np.dstack((x, y))[0] else: # If we do not have a mask array we create the moc of all the image # step_pix = 1 """ Coords returned by wcs_pix2world method correspond to pixel centers. We want to retrieve the moc pix crossing the borders of the image so we have to add 1/2 to the pixels coords before computing the lonlat. The step between two pix_crd is set to `step_pix` but can be diminished to have a better precision at the borders so that all the image is covered (a too big step does not retrieve all the moc pix crossing the borders of the image). """ x, y = np.mgrid[0.5:(width + 0.5 + step_pix):step_pix, 0.5:(height + 0.5 + step_pix):step_pix] pix_crd = np.dstack((x.ravel(), y.ravel()))[0] frame = wcs.utils.wcs_to_celestial_frame(w) world_pix_crd = SkyCoord(w.wcs_pix2world(pix_crd, 1), unit='deg', frame=frame) hp = HEALPix(nside=(1 << max_norder), order='nested', frame=ICRS()) ipix = hp.skycoord_to_healpix(world_pix_crd) # remove doubles ipix = np.unique(ipix) shift = 2 * (AbstractMOC.HPY_MAX_NORDER - max_norder) intervals_arr = np.vstack((ipix << shift, (ipix + 1) << shift)).T # This MOC will be consistent when one will do operations on the moc (union, inter, ...) or # simply write it to a fits or json file interval_set = IntervalSet(intervals_arr) return cls(interval_set=interval_set)
python
def from_image(cls, header, max_norder, mask=None): """ Creates a `~mocpy.moc.MOC` from an image stored as a FITS file. Parameters ---------- header : `astropy.io.fits.Header` FITS header containing all the info of where the image is located (position, size, etc...) max_norder : int The moc resolution. mask : `numpy.ndarray`, optional A boolean array of the same size of the image where pixels having the value 1 are part of the final MOC and pixels having the value 0 are not. Returns ------- moc : `~mocpy.moc.MOC` The resulting MOC. """ # load the image data height = header['NAXIS2'] width = header['NAXIS1'] # use wcs from astropy to locate the image in the world coordinates w = wcs.WCS(header) if mask is not None: # We have an array of pixels that are part of of survey y, x = np.where(mask) pix_crd = np.dstack((x, y))[0] else: # If we do not have a mask array we create the moc of all the image # step_pix = 1 """ Coords returned by wcs_pix2world method correspond to pixel centers. We want to retrieve the moc pix crossing the borders of the image so we have to add 1/2 to the pixels coords before computing the lonlat. The step between two pix_crd is set to `step_pix` but can be diminished to have a better precision at the borders so that all the image is covered (a too big step does not retrieve all the moc pix crossing the borders of the image). """ x, y = np.mgrid[0.5:(width + 0.5 + step_pix):step_pix, 0.5:(height + 0.5 + step_pix):step_pix] pix_crd = np.dstack((x.ravel(), y.ravel()))[0] frame = wcs.utils.wcs_to_celestial_frame(w) world_pix_crd = SkyCoord(w.wcs_pix2world(pix_crd, 1), unit='deg', frame=frame) hp = HEALPix(nside=(1 << max_norder), order='nested', frame=ICRS()) ipix = hp.skycoord_to_healpix(world_pix_crd) # remove doubles ipix = np.unique(ipix) shift = 2 * (AbstractMOC.HPY_MAX_NORDER - max_norder) intervals_arr = np.vstack((ipix << shift, (ipix + 1) << shift)).T # This MOC will be consistent when one will do operations on the moc (union, inter, ...) or # simply write it to a fits or json file interval_set = IntervalSet(intervals_arr) return cls(interval_set=interval_set)
[ "def", "from_image", "(", "cls", ",", "header", ",", "max_norder", ",", "mask", "=", "None", ")", ":", "# load the image data", "height", "=", "header", "[", "'NAXIS2'", "]", "width", "=", "header", "[", "'NAXIS1'", "]", "# use wcs from astropy to locate the image in the world coordinates", "w", "=", "wcs", ".", "WCS", "(", "header", ")", "if", "mask", "is", "not", "None", ":", "# We have an array of pixels that are part of of survey", "y", ",", "x", "=", "np", ".", "where", "(", "mask", ")", "pix_crd", "=", "np", ".", "dstack", "(", "(", "x", ",", "y", ")", ")", "[", "0", "]", "else", ":", "# If we do not have a mask array we create the moc of all the image", "#", "step_pix", "=", "1", "\"\"\"\n Coords returned by wcs_pix2world method correspond to pixel centers. We want to retrieve the moc pix\n crossing the borders of the image so we have to add 1/2 to the pixels coords before computing the lonlat.\n \n The step between two pix_crd is set to `step_pix` but can be diminished to have a better precision at the \n borders so that all the image is covered (a too big step does not retrieve all\n the moc pix crossing the borders of the image).\n \"\"\"", "x", ",", "y", "=", "np", ".", "mgrid", "[", "0.5", ":", "(", "width", "+", "0.5", "+", "step_pix", ")", ":", "step_pix", ",", "0.5", ":", "(", "height", "+", "0.5", "+", "step_pix", ")", ":", "step_pix", "]", "pix_crd", "=", "np", ".", "dstack", "(", "(", "x", ".", "ravel", "(", ")", ",", "y", ".", "ravel", "(", ")", ")", ")", "[", "0", "]", "frame", "=", "wcs", ".", "utils", ".", "wcs_to_celestial_frame", "(", "w", ")", "world_pix_crd", "=", "SkyCoord", "(", "w", ".", "wcs_pix2world", "(", "pix_crd", ",", "1", ")", ",", "unit", "=", "'deg'", ",", "frame", "=", "frame", ")", "hp", "=", "HEALPix", "(", "nside", "=", "(", "1", "<<", "max_norder", ")", ",", "order", "=", "'nested'", ",", "frame", "=", "ICRS", "(", ")", ")", "ipix", "=", "hp", ".", "skycoord_to_healpix", "(", "world_pix_crd", ")", "# remove doubles", "ipix", "=", "np", ".", "unique", "(", "ipix", ")", "shift", "=", "2", "*", "(", "AbstractMOC", ".", "HPY_MAX_NORDER", "-", "max_norder", ")", "intervals_arr", "=", "np", ".", "vstack", "(", "(", "ipix", "<<", "shift", ",", "(", "ipix", "+", "1", ")", "<<", "shift", ")", ")", ".", "T", "# This MOC will be consistent when one will do operations on the moc (union, inter, ...) or", "# simply write it to a fits or json file", "interval_set", "=", "IntervalSet", "(", "intervals_arr", ")", "return", "cls", "(", "interval_set", "=", "interval_set", ")" ]
Creates a `~mocpy.moc.MOC` from an image stored as a FITS file. Parameters ---------- header : `astropy.io.fits.Header` FITS header containing all the info of where the image is located (position, size, etc...) max_norder : int The moc resolution. mask : `numpy.ndarray`, optional A boolean array of the same size of the image where pixels having the value 1 are part of the final MOC and pixels having the value 0 are not. Returns ------- moc : `~mocpy.moc.MOC` The resulting MOC.
[ "Creates", "a", "~mocpy", ".", "moc", ".", "MOC", "from", "an", "image", "stored", "as", "a", "FITS", "file", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L299-L359
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.from_fits_images
def from_fits_images(cls, path_l, max_norder): """ Loads a MOC from a set of FITS file images. Parameters ---------- path_l : [str] A list of path where the fits image are located. max_norder : int The MOC resolution. Returns ------- moc : `~mocpy.moc.MOC` The union of all the MOCs created from the paths found in ``path_l``. """ moc = MOC() for path in path_l: header = fits.getheader(path) current_moc = MOC.from_image(header=header, max_norder=max_norder) moc = moc.union(current_moc) return moc
python
def from_fits_images(cls, path_l, max_norder): """ Loads a MOC from a set of FITS file images. Parameters ---------- path_l : [str] A list of path where the fits image are located. max_norder : int The MOC resolution. Returns ------- moc : `~mocpy.moc.MOC` The union of all the MOCs created from the paths found in ``path_l``. """ moc = MOC() for path in path_l: header = fits.getheader(path) current_moc = MOC.from_image(header=header, max_norder=max_norder) moc = moc.union(current_moc) return moc
[ "def", "from_fits_images", "(", "cls", ",", "path_l", ",", "max_norder", ")", ":", "moc", "=", "MOC", "(", ")", "for", "path", "in", "path_l", ":", "header", "=", "fits", ".", "getheader", "(", "path", ")", "current_moc", "=", "MOC", ".", "from_image", "(", "header", "=", "header", ",", "max_norder", "=", "max_norder", ")", "moc", "=", "moc", ".", "union", "(", "current_moc", ")", "return", "moc" ]
Loads a MOC from a set of FITS file images. Parameters ---------- path_l : [str] A list of path where the fits image are located. max_norder : int The MOC resolution. Returns ------- moc : `~mocpy.moc.MOC` The union of all the MOCs created from the paths found in ``path_l``.
[ "Loads", "a", "MOC", "from", "a", "set", "of", "FITS", "file", "images", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L362-L384
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.from_vizier_table
def from_vizier_table(cls, table_id, nside=256): """ Creates a `~mocpy.moc.MOC` object from a VizieR table. **Info**: This method is already implemented in `astroquery.cds <https://astroquery.readthedocs.io/en/latest/cds/cds.html>`__. You can ask to get a `mocpy.moc.MOC` object from a vizier catalog ID. Parameters ---------- table_id : str table index nside : int, optional 256 by default Returns ------- result : `~mocpy.moc.MOC` The resulting MOC. """ nside_possible_values = (8, 16, 32, 64, 128, 256, 512) if nside not in nside_possible_values: raise ValueError('Bad value for nside. Must be in {0}'.format(nside_possible_values)) result = cls.from_ivorn('ivo://CDS/' + table_id, nside) return result
python
def from_vizier_table(cls, table_id, nside=256): """ Creates a `~mocpy.moc.MOC` object from a VizieR table. **Info**: This method is already implemented in `astroquery.cds <https://astroquery.readthedocs.io/en/latest/cds/cds.html>`__. You can ask to get a `mocpy.moc.MOC` object from a vizier catalog ID. Parameters ---------- table_id : str table index nside : int, optional 256 by default Returns ------- result : `~mocpy.moc.MOC` The resulting MOC. """ nside_possible_values = (8, 16, 32, 64, 128, 256, 512) if nside not in nside_possible_values: raise ValueError('Bad value for nside. Must be in {0}'.format(nside_possible_values)) result = cls.from_ivorn('ivo://CDS/' + table_id, nside) return result
[ "def", "from_vizier_table", "(", "cls", ",", "table_id", ",", "nside", "=", "256", ")", ":", "nside_possible_values", "=", "(", "8", ",", "16", ",", "32", ",", "64", ",", "128", ",", "256", ",", "512", ")", "if", "nside", "not", "in", "nside_possible_values", ":", "raise", "ValueError", "(", "'Bad value for nside. Must be in {0}'", ".", "format", "(", "nside_possible_values", ")", ")", "result", "=", "cls", ".", "from_ivorn", "(", "'ivo://CDS/'", "+", "table_id", ",", "nside", ")", "return", "result" ]
Creates a `~mocpy.moc.MOC` object from a VizieR table. **Info**: This method is already implemented in `astroquery.cds <https://astroquery.readthedocs.io/en/latest/cds/cds.html>`__. You can ask to get a `mocpy.moc.MOC` object from a vizier catalog ID. Parameters ---------- table_id : str table index nside : int, optional 256 by default Returns ------- result : `~mocpy.moc.MOC` The resulting MOC.
[ "Creates", "a", "~mocpy", ".", "moc", ".", "MOC", "object", "from", "a", "VizieR", "table", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L387-L411
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.from_ivorn
def from_ivorn(cls, ivorn, nside=256): """ Creates a `~mocpy.moc.MOC` object from a given ivorn. Parameters ---------- ivorn : str nside : int, optional 256 by default Returns ------- result : `~mocpy.moc.MOC` The resulting MOC. """ return cls.from_url('%s?%s' % (MOC.MOC_SERVER_ROOT_URL, urlencode({ 'ivorn': ivorn, 'get': 'moc', 'order': int(np.log2(nside)) })))
python
def from_ivorn(cls, ivorn, nside=256): """ Creates a `~mocpy.moc.MOC` object from a given ivorn. Parameters ---------- ivorn : str nside : int, optional 256 by default Returns ------- result : `~mocpy.moc.MOC` The resulting MOC. """ return cls.from_url('%s?%s' % (MOC.MOC_SERVER_ROOT_URL, urlencode({ 'ivorn': ivorn, 'get': 'moc', 'order': int(np.log2(nside)) })))
[ "def", "from_ivorn", "(", "cls", ",", "ivorn", ",", "nside", "=", "256", ")", ":", "return", "cls", ".", "from_url", "(", "'%s?%s'", "%", "(", "MOC", ".", "MOC_SERVER_ROOT_URL", ",", "urlencode", "(", "{", "'ivorn'", ":", "ivorn", ",", "'get'", ":", "'moc'", ",", "'order'", ":", "int", "(", "np", ".", "log2", "(", "nside", ")", ")", "}", ")", ")", ")" ]
Creates a `~mocpy.moc.MOC` object from a given ivorn. Parameters ---------- ivorn : str nside : int, optional 256 by default Returns ------- result : `~mocpy.moc.MOC` The resulting MOC.
[ "Creates", "a", "~mocpy", ".", "moc", ".", "MOC", "object", "from", "a", "given", "ivorn", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L416-L436
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.from_url
def from_url(cls, url): """ Creates a `~mocpy.moc.MOC` object from a given url. Parameters ---------- url : str The url of a FITS file storing a MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC. """ path = download_file(url, show_progress=False, timeout=60) return cls.from_fits(path)
python
def from_url(cls, url): """ Creates a `~mocpy.moc.MOC` object from a given url. Parameters ---------- url : str The url of a FITS file storing a MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC. """ path = download_file(url, show_progress=False, timeout=60) return cls.from_fits(path)
[ "def", "from_url", "(", "cls", ",", "url", ")", ":", "path", "=", "download_file", "(", "url", ",", "show_progress", "=", "False", ",", "timeout", "=", "60", ")", "return", "cls", ".", "from_fits", "(", "path", ")" ]
Creates a `~mocpy.moc.MOC` object from a given url. Parameters ---------- url : str The url of a FITS file storing a MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC.
[ "Creates", "a", "~mocpy", ".", "moc", ".", "MOC", "object", "from", "a", "given", "url", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L439-L454
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.from_skycoords
def from_skycoords(cls, skycoords, max_norder): """ Creates a MOC from an `astropy.coordinates.SkyCoord`. Parameters ---------- skycoords : `astropy.coordinates.SkyCoord` The sky coordinates that will belong to the MOC. max_norder : int The depth of the smallest HEALPix cells contained in the MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC """ hp = HEALPix(nside=(1 << max_norder), order='nested') ipix = hp.lonlat_to_healpix(skycoords.icrs.ra, skycoords.icrs.dec) shift = 2 * (AbstractMOC.HPY_MAX_NORDER - max_norder) intervals = np.vstack((ipix << shift, (ipix + 1) << shift)).T interval_set = IntervalSet(intervals) return cls(interval_set)
python
def from_skycoords(cls, skycoords, max_norder): """ Creates a MOC from an `astropy.coordinates.SkyCoord`. Parameters ---------- skycoords : `astropy.coordinates.SkyCoord` The sky coordinates that will belong to the MOC. max_norder : int The depth of the smallest HEALPix cells contained in the MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC """ hp = HEALPix(nside=(1 << max_norder), order='nested') ipix = hp.lonlat_to_healpix(skycoords.icrs.ra, skycoords.icrs.dec) shift = 2 * (AbstractMOC.HPY_MAX_NORDER - max_norder) intervals = np.vstack((ipix << shift, (ipix + 1) << shift)).T interval_set = IntervalSet(intervals) return cls(interval_set)
[ "def", "from_skycoords", "(", "cls", ",", "skycoords", ",", "max_norder", ")", ":", "hp", "=", "HEALPix", "(", "nside", "=", "(", "1", "<<", "max_norder", ")", ",", "order", "=", "'nested'", ")", "ipix", "=", "hp", ".", "lonlat_to_healpix", "(", "skycoords", ".", "icrs", ".", "ra", ",", "skycoords", ".", "icrs", ".", "dec", ")", "shift", "=", "2", "*", "(", "AbstractMOC", ".", "HPY_MAX_NORDER", "-", "max_norder", ")", "intervals", "=", "np", ".", "vstack", "(", "(", "ipix", "<<", "shift", ",", "(", "ipix", "+", "1", ")", "<<", "shift", ")", ")", ".", "T", "interval_set", "=", "IntervalSet", "(", "intervals", ")", "return", "cls", "(", "interval_set", ")" ]
Creates a MOC from an `astropy.coordinates.SkyCoord`. Parameters ---------- skycoords : `astropy.coordinates.SkyCoord` The sky coordinates that will belong to the MOC. max_norder : int The depth of the smallest HEALPix cells contained in the MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC
[ "Creates", "a", "MOC", "from", "an", "astropy", ".", "coordinates", ".", "SkyCoord", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L457-L480
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.from_lonlat
def from_lonlat(cls, lon, lat, max_norder): """ Creates a MOC from astropy lon, lat `astropy.units.Quantity`. Parameters ---------- lon : `astropy.units.Quantity` The longitudes of the sky coordinates belonging to the MOC. lat : `astropy.units.Quantity` The latitudes of the sky coordinates belonging to the MOC. max_norder : int The depth of the smallest HEALPix cells contained in the MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC """ hp = HEALPix(nside=(1 << max_norder), order='nested') ipix = hp.lonlat_to_healpix(lon, lat) shift = 2 * (AbstractMOC.HPY_MAX_NORDER - max_norder) intervals = np.vstack((ipix << shift, (ipix + 1) << shift)).T interval_set = IntervalSet(intervals) return cls(interval_set)
python
def from_lonlat(cls, lon, lat, max_norder): """ Creates a MOC from astropy lon, lat `astropy.units.Quantity`. Parameters ---------- lon : `astropy.units.Quantity` The longitudes of the sky coordinates belonging to the MOC. lat : `astropy.units.Quantity` The latitudes of the sky coordinates belonging to the MOC. max_norder : int The depth of the smallest HEALPix cells contained in the MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC """ hp = HEALPix(nside=(1 << max_norder), order='nested') ipix = hp.lonlat_to_healpix(lon, lat) shift = 2 * (AbstractMOC.HPY_MAX_NORDER - max_norder) intervals = np.vstack((ipix << shift, (ipix + 1) << shift)).T interval_set = IntervalSet(intervals) return cls(interval_set)
[ "def", "from_lonlat", "(", "cls", ",", "lon", ",", "lat", ",", "max_norder", ")", ":", "hp", "=", "HEALPix", "(", "nside", "=", "(", "1", "<<", "max_norder", ")", ",", "order", "=", "'nested'", ")", "ipix", "=", "hp", ".", "lonlat_to_healpix", "(", "lon", ",", "lat", ")", "shift", "=", "2", "*", "(", "AbstractMOC", ".", "HPY_MAX_NORDER", "-", "max_norder", ")", "intervals", "=", "np", ".", "vstack", "(", "(", "ipix", "<<", "shift", ",", "(", "ipix", "+", "1", ")", "<<", "shift", ")", ")", ".", "T", "interval_set", "=", "IntervalSet", "(", "intervals", ")", "return", "cls", "(", "interval_set", ")" ]
Creates a MOC from astropy lon, lat `astropy.units.Quantity`. Parameters ---------- lon : `astropy.units.Quantity` The longitudes of the sky coordinates belonging to the MOC. lat : `astropy.units.Quantity` The latitudes of the sky coordinates belonging to the MOC. max_norder : int The depth of the smallest HEALPix cells contained in the MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC
[ "Creates", "a", "MOC", "from", "astropy", "lon", "lat", "astropy", ".", "units", ".", "Quantity", ".", "Parameters", "----------", "lon", ":", "astropy", ".", "units", ".", "Quantity", "The", "longitudes", "of", "the", "sky", "coordinates", "belonging", "to", "the", "MOC", ".", "lat", ":", "astropy", ".", "units", ".", "Quantity", "The", "latitudes", "of", "the", "sky", "coordinates", "belonging", "to", "the", "MOC", ".", "max_norder", ":", "int", "The", "depth", "of", "the", "smallest", "HEALPix", "cells", "contained", "in", "the", "MOC", ".", "Returns", "-------", "result", ":", "~mocpy", ".", "moc", ".", "MOC", "The", "resulting", "MOC" ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L483-L508
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.from_polygon_skycoord
def from_polygon_skycoord(cls, skycoord, inside=None, max_depth=10): """ Creates a MOC from a polygon. The polygon is given as an `astropy.coordinates.SkyCoord` that contains the vertices of the polygon. Concave and convex polygons are accepted but self-intersecting ones are currently not properly handled. Parameters ---------- skycoord : `astropy.coordinates.SkyCoord` The sky coordinates defining the vertices of a polygon. It can describe a convex or concave polygon but not a self-intersecting one. inside : `astropy.coordinates.SkyCoord`, optional A point that will be inside the MOC is needed as it is not possible to determine the inside area of a polygon on the unit sphere (there is no infinite area that can be considered as the outside because on the sphere, a closed polygon delimits two finite areas). Possible improvement: take the inside area as the one covering the smallest region on the sphere. If inside=None (default behavior), the mean of all the vertices is taken as lying inside the polygon. That approach may not work for concave polygons. max_depth : int, optional The resolution of the MOC. Set to 10 by default. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC """ return MOC.from_polygon(lon=skycoord.icrs.ra, lat=skycoord.icrs.dec, inside=inside, max_depth=max_depth)
python
def from_polygon_skycoord(cls, skycoord, inside=None, max_depth=10): """ Creates a MOC from a polygon. The polygon is given as an `astropy.coordinates.SkyCoord` that contains the vertices of the polygon. Concave and convex polygons are accepted but self-intersecting ones are currently not properly handled. Parameters ---------- skycoord : `astropy.coordinates.SkyCoord` The sky coordinates defining the vertices of a polygon. It can describe a convex or concave polygon but not a self-intersecting one. inside : `astropy.coordinates.SkyCoord`, optional A point that will be inside the MOC is needed as it is not possible to determine the inside area of a polygon on the unit sphere (there is no infinite area that can be considered as the outside because on the sphere, a closed polygon delimits two finite areas). Possible improvement: take the inside area as the one covering the smallest region on the sphere. If inside=None (default behavior), the mean of all the vertices is taken as lying inside the polygon. That approach may not work for concave polygons. max_depth : int, optional The resolution of the MOC. Set to 10 by default. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC """ return MOC.from_polygon(lon=skycoord.icrs.ra, lat=skycoord.icrs.dec, inside=inside, max_depth=max_depth)
[ "def", "from_polygon_skycoord", "(", "cls", ",", "skycoord", ",", "inside", "=", "None", ",", "max_depth", "=", "10", ")", ":", "return", "MOC", ".", "from_polygon", "(", "lon", "=", "skycoord", ".", "icrs", ".", "ra", ",", "lat", "=", "skycoord", ".", "icrs", ".", "dec", ",", "inside", "=", "inside", ",", "max_depth", "=", "max_depth", ")" ]
Creates a MOC from a polygon. The polygon is given as an `astropy.coordinates.SkyCoord` that contains the vertices of the polygon. Concave and convex polygons are accepted but self-intersecting ones are currently not properly handled. Parameters ---------- skycoord : `astropy.coordinates.SkyCoord` The sky coordinates defining the vertices of a polygon. It can describe a convex or concave polygon but not a self-intersecting one. inside : `astropy.coordinates.SkyCoord`, optional A point that will be inside the MOC is needed as it is not possible to determine the inside area of a polygon on the unit sphere (there is no infinite area that can be considered as the outside because on the sphere, a closed polygon delimits two finite areas). Possible improvement: take the inside area as the one covering the smallest region on the sphere. If inside=None (default behavior), the mean of all the vertices is taken as lying inside the polygon. That approach may not work for concave polygons. max_depth : int, optional The resolution of the MOC. Set to 10 by default. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC
[ "Creates", "a", "MOC", "from", "a", "polygon", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L511-L541
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.from_polygon
def from_polygon(cls, lon, lat, inside=None, max_depth=10): """ Creates a MOC from a polygon The polygon is given as lon and lat `astropy.units.Quantity` that define the vertices of the polygon. Concave and convex polygons are accepted but self-intersecting ones are currently not properly handled. Parameters ---------- lon : `astropy.units.Quantity` The longitudes defining the polygon. Can describe convex and concave polygons but not self-intersecting ones. lat : `astropy.units.Quantity` The latitudes defining the polygon. Can describe convex and concave polygons but not self-intersecting ones. inside : `astropy.coordinates.SkyCoord`, optional A point that will be inside the MOC is needed as it is not possible to determine the inside area of a polygon on the unit sphere (there is no infinite area that can be considered as the outside because on the sphere, a closed polygon delimits two finite areas). Possible improvement: take the inside area as the one covering the smallest region on the sphere. If inside=None (default behavior), the mean of all the vertices is taken as lying inside the polygon. That approach may not work for concave polygons. max_depth : int, optional The resolution of the MOC. Set to 10 by default. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC """ from .polygon import PolygonComputer polygon_computer = PolygonComputer(lon, lat, inside, max_depth) # Create the moc from the python dictionary moc = MOC.from_json(polygon_computer.ipix) # We degrade it to the user-requested order if polygon_computer.degrade_to_max_depth: moc = moc.degrade_to_order(max_depth) return moc
python
def from_polygon(cls, lon, lat, inside=None, max_depth=10): """ Creates a MOC from a polygon The polygon is given as lon and lat `astropy.units.Quantity` that define the vertices of the polygon. Concave and convex polygons are accepted but self-intersecting ones are currently not properly handled. Parameters ---------- lon : `astropy.units.Quantity` The longitudes defining the polygon. Can describe convex and concave polygons but not self-intersecting ones. lat : `astropy.units.Quantity` The latitudes defining the polygon. Can describe convex and concave polygons but not self-intersecting ones. inside : `astropy.coordinates.SkyCoord`, optional A point that will be inside the MOC is needed as it is not possible to determine the inside area of a polygon on the unit sphere (there is no infinite area that can be considered as the outside because on the sphere, a closed polygon delimits two finite areas). Possible improvement: take the inside area as the one covering the smallest region on the sphere. If inside=None (default behavior), the mean of all the vertices is taken as lying inside the polygon. That approach may not work for concave polygons. max_depth : int, optional The resolution of the MOC. Set to 10 by default. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC """ from .polygon import PolygonComputer polygon_computer = PolygonComputer(lon, lat, inside, max_depth) # Create the moc from the python dictionary moc = MOC.from_json(polygon_computer.ipix) # We degrade it to the user-requested order if polygon_computer.degrade_to_max_depth: moc = moc.degrade_to_order(max_depth) return moc
[ "def", "from_polygon", "(", "cls", ",", "lon", ",", "lat", ",", "inside", "=", "None", ",", "max_depth", "=", "10", ")", ":", "from", ".", "polygon", "import", "PolygonComputer", "polygon_computer", "=", "PolygonComputer", "(", "lon", ",", "lat", ",", "inside", ",", "max_depth", ")", "# Create the moc from the python dictionary", "moc", "=", "MOC", ".", "from_json", "(", "polygon_computer", ".", "ipix", ")", "# We degrade it to the user-requested order", "if", "polygon_computer", ".", "degrade_to_max_depth", ":", "moc", "=", "moc", ".", "degrade_to_order", "(", "max_depth", ")", "return", "moc" ]
Creates a MOC from a polygon The polygon is given as lon and lat `astropy.units.Quantity` that define the vertices of the polygon. Concave and convex polygons are accepted but self-intersecting ones are currently not properly handled. Parameters ---------- lon : `astropy.units.Quantity` The longitudes defining the polygon. Can describe convex and concave polygons but not self-intersecting ones. lat : `astropy.units.Quantity` The latitudes defining the polygon. Can describe convex and concave polygons but not self-intersecting ones. inside : `astropy.coordinates.SkyCoord`, optional A point that will be inside the MOC is needed as it is not possible to determine the inside area of a polygon on the unit sphere (there is no infinite area that can be considered as the outside because on the sphere, a closed polygon delimits two finite areas). Possible improvement: take the inside area as the one covering the smallest region on the sphere. If inside=None (default behavior), the mean of all the vertices is taken as lying inside the polygon. That approach may not work for concave polygons. max_depth : int, optional The resolution of the MOC. Set to 10 by default. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC
[ "Creates", "a", "MOC", "from", "a", "polygon" ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L544-L586
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.sky_fraction
def sky_fraction(self): """ Sky fraction covered by the MOC """ pix_id = self._best_res_pixels() nb_pix_filled = pix_id.size return nb_pix_filled / float(3 << (2*(self.max_order + 1)))
python
def sky_fraction(self): """ Sky fraction covered by the MOC """ pix_id = self._best_res_pixels() nb_pix_filled = pix_id.size return nb_pix_filled / float(3 << (2*(self.max_order + 1)))
[ "def", "sky_fraction", "(", "self", ")", ":", "pix_id", "=", "self", ".", "_best_res_pixels", "(", ")", "nb_pix_filled", "=", "pix_id", ".", "size", "return", "nb_pix_filled", "/", "float", "(", "3", "<<", "(", "2", "*", "(", "self", ".", "max_order", "+", "1", ")", ")", ")" ]
Sky fraction covered by the MOC
[ "Sky", "fraction", "covered", "by", "the", "MOC" ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L589-L595
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC._query
def _query(self, resource_id, max_rows): """ Internal method to query Simbad or a VizieR table for sources in the coverage of the MOC instance """ from astropy.io.votable import parse_single_table if max_rows is not None and max_rows >= 0: max_rows_str = str(max_rows) else: max_rows_str = str(9999999999) tmp_moc = tempfile.NamedTemporaryFile(delete=False) self.write(tmp_moc.name) r = requests.post('http://cdsxmatch.u-strasbg.fr/QueryCat/QueryCat', data={'mode': 'mocfile', 'catName': resource_id, 'format': 'votable', 'limit': max_rows_str}, files={'moc': open(tmp_moc.name, 'rb')}, headers={'User-Agent': 'MOCPy'}, stream=True) tmp_vot = BytesIO() tmp_vot.write(r.content) table = parse_single_table(tmp_vot).to_table() # finally delete temp files os.unlink(tmp_moc.name) return table
python
def _query(self, resource_id, max_rows): """ Internal method to query Simbad or a VizieR table for sources in the coverage of the MOC instance """ from astropy.io.votable import parse_single_table if max_rows is not None and max_rows >= 0: max_rows_str = str(max_rows) else: max_rows_str = str(9999999999) tmp_moc = tempfile.NamedTemporaryFile(delete=False) self.write(tmp_moc.name) r = requests.post('http://cdsxmatch.u-strasbg.fr/QueryCat/QueryCat', data={'mode': 'mocfile', 'catName': resource_id, 'format': 'votable', 'limit': max_rows_str}, files={'moc': open(tmp_moc.name, 'rb')}, headers={'User-Agent': 'MOCPy'}, stream=True) tmp_vot = BytesIO() tmp_vot.write(r.content) table = parse_single_table(tmp_vot).to_table() # finally delete temp files os.unlink(tmp_moc.name) return table
[ "def", "_query", "(", "self", ",", "resource_id", ",", "max_rows", ")", ":", "from", "astropy", ".", "io", ".", "votable", "import", "parse_single_table", "if", "max_rows", "is", "not", "None", "and", "max_rows", ">=", "0", ":", "max_rows_str", "=", "str", "(", "max_rows", ")", "else", ":", "max_rows_str", "=", "str", "(", "9999999999", ")", "tmp_moc", "=", "tempfile", ".", "NamedTemporaryFile", "(", "delete", "=", "False", ")", "self", ".", "write", "(", "tmp_moc", ".", "name", ")", "r", "=", "requests", ".", "post", "(", "'http://cdsxmatch.u-strasbg.fr/QueryCat/QueryCat'", ",", "data", "=", "{", "'mode'", ":", "'mocfile'", ",", "'catName'", ":", "resource_id", ",", "'format'", ":", "'votable'", ",", "'limit'", ":", "max_rows_str", "}", ",", "files", "=", "{", "'moc'", ":", "open", "(", "tmp_moc", ".", "name", ",", "'rb'", ")", "}", ",", "headers", "=", "{", "'User-Agent'", ":", "'MOCPy'", "}", ",", "stream", "=", "True", ")", "tmp_vot", "=", "BytesIO", "(", ")", "tmp_vot", ".", "write", "(", "r", ".", "content", ")", "table", "=", "parse_single_table", "(", "tmp_vot", ")", ".", "to_table", "(", ")", "# finally delete temp files", "os", ".", "unlink", "(", "tmp_moc", ".", "name", ")", "return", "table" ]
Internal method to query Simbad or a VizieR table for sources in the coverage of the MOC instance
[ "Internal", "method", "to", "query", "Simbad", "or", "a", "VizieR", "table", "for", "sources", "in", "the", "coverage", "of", "the", "MOC", "instance" ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L612-L644
train
cds-astro/mocpy
mocpy/moc/moc.py
MOC.plot
def plot(self, title='MOC', frame=None): """ Plot the MOC object using a mollweide projection. **Deprecated**: New `fill` and `border` methods produce more reliable results and allow you to specify additional matplotlib style parameters. Parameters ---------- title : str The title of the plot frame : `astropy.coordinates.BaseCoordinateFrame`, optional Describes the coordinate system the plot will be (ICRS, Galactic are the only coordinate systems supported). """ frame = ICRS() if frame is None else frame from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt plot_order = 8 if self.max_order > plot_order: plotted_moc = self.degrade_to_order(plot_order) else: plotted_moc = self num_pixels_map = 1024 delta = 2. * np.pi / num_pixels_map x = np.arange(-np.pi, np.pi, delta) y = np.arange(-np.pi/2, np.pi/2, delta) lon_rad, lat_rad = np.meshgrid(x, y) hp = HEALPix(nside=(1 << plotted_moc.max_order), order='nested') if frame and not isinstance(frame, BaseCoordinateFrame): raise ValueError("Only Galactic/ICRS coordinate systems are supported." "Please set `coord` to either 'C' or 'G'.") pix_map = hp.lonlat_to_healpix(lon_rad * u.rad, lat_rad * u.rad) m = np.zeros(nside2npix(1 << plotted_moc.max_order)) pix_id = plotted_moc._best_res_pixels() # change the HEALPix cells if the frame of the MOC is not the same as the one associated with the plot method. if isinstance(frame, Galactic): lon, lat = hp.boundaries_lonlat(pix_id, step=2) sky_crd = SkyCoord(lon, lat, unit='deg') pix_id = hp.lonlat_to_healpix(sky_crd.galactic.l, sky_crd.galactic.b) m[pix_id] = 1 z = np.flip(m[pix_map], axis=1) plt.figure(figsize=(10, 10)) ax = plt.subplot(111, projection="mollweide") ax.set_xticklabels(['150°', '120°', '90°', '60°', '30°', '0°', '330°', '300°', '270°', '240°', '210°', '180°']) color_map = LinearSegmentedColormap.from_list('w2r', ['#eeeeee', '#aa0000']) color_map.set_under('w') color_map.set_bad('gray') ax.pcolormesh(x, y, z, cmap=color_map, vmin=0, vmax=1) ax.tick_params(labelsize=14, labelcolor='#000000') plt.title(title) plt.grid(True, linestyle='--', linewidth=1, color='#555555') plt.show()
python
def plot(self, title='MOC', frame=None): """ Plot the MOC object using a mollweide projection. **Deprecated**: New `fill` and `border` methods produce more reliable results and allow you to specify additional matplotlib style parameters. Parameters ---------- title : str The title of the plot frame : `astropy.coordinates.BaseCoordinateFrame`, optional Describes the coordinate system the plot will be (ICRS, Galactic are the only coordinate systems supported). """ frame = ICRS() if frame is None else frame from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt plot_order = 8 if self.max_order > plot_order: plotted_moc = self.degrade_to_order(plot_order) else: plotted_moc = self num_pixels_map = 1024 delta = 2. * np.pi / num_pixels_map x = np.arange(-np.pi, np.pi, delta) y = np.arange(-np.pi/2, np.pi/2, delta) lon_rad, lat_rad = np.meshgrid(x, y) hp = HEALPix(nside=(1 << plotted_moc.max_order), order='nested') if frame and not isinstance(frame, BaseCoordinateFrame): raise ValueError("Only Galactic/ICRS coordinate systems are supported." "Please set `coord` to either 'C' or 'G'.") pix_map = hp.lonlat_to_healpix(lon_rad * u.rad, lat_rad * u.rad) m = np.zeros(nside2npix(1 << plotted_moc.max_order)) pix_id = plotted_moc._best_res_pixels() # change the HEALPix cells if the frame of the MOC is not the same as the one associated with the plot method. if isinstance(frame, Galactic): lon, lat = hp.boundaries_lonlat(pix_id, step=2) sky_crd = SkyCoord(lon, lat, unit='deg') pix_id = hp.lonlat_to_healpix(sky_crd.galactic.l, sky_crd.galactic.b) m[pix_id] = 1 z = np.flip(m[pix_map], axis=1) plt.figure(figsize=(10, 10)) ax = plt.subplot(111, projection="mollweide") ax.set_xticklabels(['150°', '120°', '90°', '60°', '30°', '0°', '330°', '300°', '270°', '240°', '210°', '180°']) color_map = LinearSegmentedColormap.from_list('w2r', ['#eeeeee', '#aa0000']) color_map.set_under('w') color_map.set_bad('gray') ax.pcolormesh(x, y, z, cmap=color_map, vmin=0, vmax=1) ax.tick_params(labelsize=14, labelcolor='#000000') plt.title(title) plt.grid(True, linestyle='--', linewidth=1, color='#555555') plt.show()
[ "def", "plot", "(", "self", ",", "title", "=", "'MOC'", ",", "frame", "=", "None", ")", ":", "frame", "=", "ICRS", "(", ")", "if", "frame", "is", "None", "else", "frame", "from", "matplotlib", ".", "colors", "import", "LinearSegmentedColormap", "import", "matplotlib", ".", "pyplot", "as", "plt", "plot_order", "=", "8", "if", "self", ".", "max_order", ">", "plot_order", ":", "plotted_moc", "=", "self", ".", "degrade_to_order", "(", "plot_order", ")", "else", ":", "plotted_moc", "=", "self", "num_pixels_map", "=", "1024", "delta", "=", "2.", "*", "np", ".", "pi", "/", "num_pixels_map", "x", "=", "np", ".", "arange", "(", "-", "np", ".", "pi", ",", "np", ".", "pi", ",", "delta", ")", "y", "=", "np", ".", "arange", "(", "-", "np", ".", "pi", "/", "2", ",", "np", ".", "pi", "/", "2", ",", "delta", ")", "lon_rad", ",", "lat_rad", "=", "np", ".", "meshgrid", "(", "x", ",", "y", ")", "hp", "=", "HEALPix", "(", "nside", "=", "(", "1", "<<", "plotted_moc", ".", "max_order", ")", ",", "order", "=", "'nested'", ")", "if", "frame", "and", "not", "isinstance", "(", "frame", ",", "BaseCoordinateFrame", ")", ":", "raise", "ValueError", "(", "\"Only Galactic/ICRS coordinate systems are supported.\"", "\"Please set `coord` to either 'C' or 'G'.\"", ")", "pix_map", "=", "hp", ".", "lonlat_to_healpix", "(", "lon_rad", "*", "u", ".", "rad", ",", "lat_rad", "*", "u", ".", "rad", ")", "m", "=", "np", ".", "zeros", "(", "nside2npix", "(", "1", "<<", "plotted_moc", ".", "max_order", ")", ")", "pix_id", "=", "plotted_moc", ".", "_best_res_pixels", "(", ")", "# change the HEALPix cells if the frame of the MOC is not the same as the one associated with the plot method.", "if", "isinstance", "(", "frame", ",", "Galactic", ")", ":", "lon", ",", "lat", "=", "hp", ".", "boundaries_lonlat", "(", "pix_id", ",", "step", "=", "2", ")", "sky_crd", "=", "SkyCoord", "(", "lon", ",", "lat", ",", "unit", "=", "'deg'", ")", "pix_id", "=", "hp", ".", "lonlat_to_healpix", "(", "sky_crd", ".", "galactic", ".", "l", ",", "sky_crd", ".", "galactic", ".", "b", ")", "m", "[", "pix_id", "]", "=", "1", "z", "=", "np", ".", "flip", "(", "m", "[", "pix_map", "]", ",", "axis", "=", "1", ")", "plt", ".", "figure", "(", "figsize", "=", "(", "10", ",", "10", ")", ")", "ax", "=", "plt", ".", "subplot", "(", "111", ",", "projection", "=", "\"mollweide\"", ")", "ax", ".", "set_xticklabels", "(", "[", "'150°',", " ", "120°', ", "'", "0°', '", "6", "°', '3", "0", "', '0°", "'", " '330", "°", ", '300°", "'", " '270°'", ",", "'240°',", " ", "210°', ", "'", "80°'])", "", "", "", "", "color_map", "=", "LinearSegmentedColormap", ".", "from_list", "(", "'w2r'", ",", "[", "'#eeeeee'", ",", "'#aa0000'", "]", ")", "color_map", ".", "set_under", "(", "'w'", ")", "color_map", ".", "set_bad", "(", "'gray'", ")", "ax", ".", "pcolormesh", "(", "x", ",", "y", ",", "z", ",", "cmap", "=", "color_map", ",", "vmin", "=", "0", ",", "vmax", "=", "1", ")", "ax", ".", "tick_params", "(", "labelsize", "=", "14", ",", "labelcolor", "=", "'#000000'", ")", "plt", ".", "title", "(", "title", ")", "plt", ".", "grid", "(", "True", ",", "linestyle", "=", "'--'", ",", "linewidth", "=", "1", ",", "color", "=", "'#555555'", ")", "plt", ".", "show", "(", ")" ]
Plot the MOC object using a mollweide projection. **Deprecated**: New `fill` and `border` methods produce more reliable results and allow you to specify additional matplotlib style parameters. Parameters ---------- title : str The title of the plot frame : `astropy.coordinates.BaseCoordinateFrame`, optional Describes the coordinate system the plot will be (ICRS, Galactic are the only coordinate systems supported).
[ "Plot", "the", "MOC", "object", "using", "a", "mollweide", "projection", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/moc/moc.py#L646-L712
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/base_transform.py
BaseTransform.inverse
def inverse(self): """ The inverse of this transform. """ if self._inverse is None: self._inverse = InverseTransform(self) return self._inverse
python
def inverse(self): """ The inverse of this transform. """ if self._inverse is None: self._inverse = InverseTransform(self) return self._inverse
[ "def", "inverse", "(", "self", ")", ":", "if", "self", ".", "_inverse", "is", "None", ":", "self", ".", "_inverse", "=", "InverseTransform", "(", "self", ")", "return", "self", ".", "_inverse" ]
The inverse of this transform.
[ "The", "inverse", "of", "this", "transform", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/base_transform.py#L99-L104
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/axis.py
Ticker._tile_ticks
def _tile_ticks(self, frac, tickvec): """Tiles tick marks along the axis.""" origins = np.tile(self.axis._vec, (len(frac), 1)) origins = self.axis.pos[0].T + (origins.T*frac).T endpoints = tickvec + origins return origins, endpoints
python
def _tile_ticks(self, frac, tickvec): """Tiles tick marks along the axis.""" origins = np.tile(self.axis._vec, (len(frac), 1)) origins = self.axis.pos[0].T + (origins.T*frac).T endpoints = tickvec + origins return origins, endpoints
[ "def", "_tile_ticks", "(", "self", ",", "frac", ",", "tickvec", ")", ":", "origins", "=", "np", ".", "tile", "(", "self", ".", "axis", ".", "_vec", ",", "(", "len", "(", "frac", ")", ",", "1", ")", ")", "origins", "=", "self", ".", "axis", ".", "pos", "[", "0", "]", ".", "T", "+", "(", "origins", ".", "T", "*", "frac", ")", ".", "T", "endpoints", "=", "tickvec", "+", "origins", "return", "origins", ",", "endpoints" ]
Tiles tick marks along the axis.
[ "Tiles", "tick", "marks", "along", "the", "axis", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/axis.py#L345-L350
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/axis.py
Ticker._get_tick_frac_labels
def _get_tick_frac_labels(self): """Get the major ticks, minor ticks, and major labels""" minor_num = 4 # number of minor ticks per major division if (self.axis.scale_type == 'linear'): domain = self.axis.domain if domain[1] < domain[0]: flip = True domain = domain[::-1] else: flip = False offset = domain[0] scale = domain[1] - domain[0] transforms = self.axis.transforms length = self.axis.pos[1] - self.axis.pos[0] # in logical coords n_inches = np.sqrt(np.sum(length ** 2)) / transforms.dpi # major = np.linspace(domain[0], domain[1], num=11) # major = MaxNLocator(10).tick_values(*domain) major = _get_ticks_talbot(domain[0], domain[1], n_inches, 2) labels = ['%g' % x for x in major] majstep = major[1] - major[0] minor = [] minstep = majstep / (minor_num + 1) minstart = 0 if self.axis._stop_at_major[0] else -1 minstop = -1 if self.axis._stop_at_major[1] else 0 for i in range(minstart, len(major) + minstop): maj = major[0] + i * majstep minor.extend(np.linspace(maj + minstep, maj + majstep - minstep, minor_num)) major_frac = (major - offset) / scale minor_frac = (np.array(minor) - offset) / scale major_frac = major_frac[::-1] if flip else major_frac use_mask = (major_frac > -0.0001) & (major_frac < 1.0001) major_frac = major_frac[use_mask] labels = [l for li, l in enumerate(labels) if use_mask[li]] minor_frac = minor_frac[(minor_frac > -0.0001) & (minor_frac < 1.0001)] elif self.axis.scale_type == 'logarithmic': return NotImplementedError elif self.axis.scale_type == 'power': return NotImplementedError return major_frac, minor_frac, labels
python
def _get_tick_frac_labels(self): """Get the major ticks, minor ticks, and major labels""" minor_num = 4 # number of minor ticks per major division if (self.axis.scale_type == 'linear'): domain = self.axis.domain if domain[1] < domain[0]: flip = True domain = domain[::-1] else: flip = False offset = domain[0] scale = domain[1] - domain[0] transforms = self.axis.transforms length = self.axis.pos[1] - self.axis.pos[0] # in logical coords n_inches = np.sqrt(np.sum(length ** 2)) / transforms.dpi # major = np.linspace(domain[0], domain[1], num=11) # major = MaxNLocator(10).tick_values(*domain) major = _get_ticks_talbot(domain[0], domain[1], n_inches, 2) labels = ['%g' % x for x in major] majstep = major[1] - major[0] minor = [] minstep = majstep / (minor_num + 1) minstart = 0 if self.axis._stop_at_major[0] else -1 minstop = -1 if self.axis._stop_at_major[1] else 0 for i in range(minstart, len(major) + minstop): maj = major[0] + i * majstep minor.extend(np.linspace(maj + minstep, maj + majstep - minstep, minor_num)) major_frac = (major - offset) / scale minor_frac = (np.array(minor) - offset) / scale major_frac = major_frac[::-1] if flip else major_frac use_mask = (major_frac > -0.0001) & (major_frac < 1.0001) major_frac = major_frac[use_mask] labels = [l for li, l in enumerate(labels) if use_mask[li]] minor_frac = minor_frac[(minor_frac > -0.0001) & (minor_frac < 1.0001)] elif self.axis.scale_type == 'logarithmic': return NotImplementedError elif self.axis.scale_type == 'power': return NotImplementedError return major_frac, minor_frac, labels
[ "def", "_get_tick_frac_labels", "(", "self", ")", ":", "minor_num", "=", "4", "# number of minor ticks per major division", "if", "(", "self", ".", "axis", ".", "scale_type", "==", "'linear'", ")", ":", "domain", "=", "self", ".", "axis", ".", "domain", "if", "domain", "[", "1", "]", "<", "domain", "[", "0", "]", ":", "flip", "=", "True", "domain", "=", "domain", "[", ":", ":", "-", "1", "]", "else", ":", "flip", "=", "False", "offset", "=", "domain", "[", "0", "]", "scale", "=", "domain", "[", "1", "]", "-", "domain", "[", "0", "]", "transforms", "=", "self", ".", "axis", ".", "transforms", "length", "=", "self", ".", "axis", ".", "pos", "[", "1", "]", "-", "self", ".", "axis", ".", "pos", "[", "0", "]", "# in logical coords", "n_inches", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "length", "**", "2", ")", ")", "/", "transforms", ".", "dpi", "# major = np.linspace(domain[0], domain[1], num=11)", "# major = MaxNLocator(10).tick_values(*domain)", "major", "=", "_get_ticks_talbot", "(", "domain", "[", "0", "]", ",", "domain", "[", "1", "]", ",", "n_inches", ",", "2", ")", "labels", "=", "[", "'%g'", "%", "x", "for", "x", "in", "major", "]", "majstep", "=", "major", "[", "1", "]", "-", "major", "[", "0", "]", "minor", "=", "[", "]", "minstep", "=", "majstep", "/", "(", "minor_num", "+", "1", ")", "minstart", "=", "0", "if", "self", ".", "axis", ".", "_stop_at_major", "[", "0", "]", "else", "-", "1", "minstop", "=", "-", "1", "if", "self", ".", "axis", ".", "_stop_at_major", "[", "1", "]", "else", "0", "for", "i", "in", "range", "(", "minstart", ",", "len", "(", "major", ")", "+", "minstop", ")", ":", "maj", "=", "major", "[", "0", "]", "+", "i", "*", "majstep", "minor", ".", "extend", "(", "np", ".", "linspace", "(", "maj", "+", "minstep", ",", "maj", "+", "majstep", "-", "minstep", ",", "minor_num", ")", ")", "major_frac", "=", "(", "major", "-", "offset", ")", "/", "scale", "minor_frac", "=", "(", "np", ".", "array", "(", "minor", ")", "-", "offset", ")", "/", "scale", "major_frac", "=", "major_frac", "[", ":", ":", "-", "1", "]", "if", "flip", "else", "major_frac", "use_mask", "=", "(", "major_frac", ">", "-", "0.0001", ")", "&", "(", "major_frac", "<", "1.0001", ")", "major_frac", "=", "major_frac", "[", "use_mask", "]", "labels", "=", "[", "l", "for", "li", ",", "l", "in", "enumerate", "(", "labels", ")", "if", "use_mask", "[", "li", "]", "]", "minor_frac", "=", "minor_frac", "[", "(", "minor_frac", ">", "-", "0.0001", ")", "&", "(", "minor_frac", "<", "1.0001", ")", "]", "elif", "self", ".", "axis", ".", "scale_type", "==", "'logarithmic'", ":", "return", "NotImplementedError", "elif", "self", ".", "axis", ".", "scale_type", "==", "'power'", ":", "return", "NotImplementedError", "return", "major_frac", ",", "minor_frac", ",", "labels" ]
Get the major ticks, minor ticks, and major labels
[ "Get", "the", "major", "ticks", "minor", "ticks", "and", "major", "labels" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/axis.py#L352-L396
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
interleave_planes
def interleave_planes(ipixels, apixels, ipsize, apsize): """ Interleave (colour) planes, e.g. RGB + A = RGBA. Return an array of pixels consisting of the `ipsize` elements of data from each pixel in `ipixels` followed by the `apsize` elements of data from each pixel in `apixels`. Conventionally `ipixels` and `apixels` are byte arrays so the sizes are bytes, but it actually works with any arrays of the same type. The returned array is the same type as the input arrays which should be the same type as each other. """ itotal = len(ipixels) atotal = len(apixels) newtotal = itotal + atotal newpsize = ipsize + apsize # Set up the output buffer # See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356 out = array(ipixels.typecode) # It's annoying that there is no cheap way to set the array size :-( out.extend(ipixels) out.extend(apixels) # Interleave in the pixel data for i in range(ipsize): out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize] for i in range(apsize): out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize] return out
python
def interleave_planes(ipixels, apixels, ipsize, apsize): """ Interleave (colour) planes, e.g. RGB + A = RGBA. Return an array of pixels consisting of the `ipsize` elements of data from each pixel in `ipixels` followed by the `apsize` elements of data from each pixel in `apixels`. Conventionally `ipixels` and `apixels` are byte arrays so the sizes are bytes, but it actually works with any arrays of the same type. The returned array is the same type as the input arrays which should be the same type as each other. """ itotal = len(ipixels) atotal = len(apixels) newtotal = itotal + atotal newpsize = ipsize + apsize # Set up the output buffer # See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356 out = array(ipixels.typecode) # It's annoying that there is no cheap way to set the array size :-( out.extend(ipixels) out.extend(apixels) # Interleave in the pixel data for i in range(ipsize): out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize] for i in range(apsize): out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize] return out
[ "def", "interleave_planes", "(", "ipixels", ",", "apixels", ",", "ipsize", ",", "apsize", ")", ":", "itotal", "=", "len", "(", "ipixels", ")", "atotal", "=", "len", "(", "apixels", ")", "newtotal", "=", "itotal", "+", "atotal", "newpsize", "=", "ipsize", "+", "apsize", "# Set up the output buffer", "# See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356", "out", "=", "array", "(", "ipixels", ".", "typecode", ")", "# It's annoying that there is no cheap way to set the array size :-(", "out", ".", "extend", "(", "ipixels", ")", "out", ".", "extend", "(", "apixels", ")", "# Interleave in the pixel data", "for", "i", "in", "range", "(", "ipsize", ")", ":", "out", "[", "i", ":", "newtotal", ":", "newpsize", "]", "=", "ipixels", "[", "i", ":", "itotal", ":", "ipsize", "]", "for", "i", "in", "range", "(", "apsize", ")", ":", "out", "[", "i", "+", "ipsize", ":", "newtotal", ":", "newpsize", "]", "=", "apixels", "[", "i", ":", "atotal", ":", "apsize", "]", "return", "out" ]
Interleave (colour) planes, e.g. RGB + A = RGBA. Return an array of pixels consisting of the `ipsize` elements of data from each pixel in `ipixels` followed by the `apsize` elements of data from each pixel in `apixels`. Conventionally `ipixels` and `apixels` are byte arrays so the sizes are bytes, but it actually works with any arrays of the same type. The returned array is the same type as the input arrays which should be the same type as each other.
[ "Interleave", "(", "colour", ")", "planes", "e", ".", "g", ".", "RGB", "+", "A", "=", "RGBA", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L101-L129
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
write_chunks
def write_chunks(out, chunks): """Create a PNG file by writing out the chunks.""" out.write(_signature) for chunk in chunks: write_chunk(out, *chunk)
python
def write_chunks(out, chunks): """Create a PNG file by writing out the chunks.""" out.write(_signature) for chunk in chunks: write_chunk(out, *chunk)
[ "def", "write_chunks", "(", "out", ",", "chunks", ")", ":", "out", ".", "write", "(", "_signature", ")", "for", "chunk", "in", "chunks", ":", "write_chunk", "(", "out", ",", "*", "chunk", ")" ]
Create a PNG file by writing out the chunks.
[ "Create", "a", "PNG", "file", "by", "writing", "out", "the", "chunks", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L838-L843
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
filter_scanline
def filter_scanline(type, line, fo, prev=None): """Apply a scanline filter to a scanline. `type` specifies the filter type (0 to 4); `line` specifies the current (unfiltered) scanline as a sequence of bytes; `prev` specifies the previous (unfiltered) scanline as a sequence of bytes. `fo` specifies the filter offset; normally this is size of a pixel in bytes (the number of bytes per sample times the number of channels), but when this is < 1 (for bit depths < 8) then the filter offset is 1. """ assert 0 <= type < 5 # The output array. Which, pathetically, we extend one-byte at a # time (fortunately this is linear). out = array('B', [type]) def sub(): ai = -fo for x in line: if ai >= 0: x = (x - line[ai]) & 0xff out.append(x) ai += 1 def up(): for i,x in enumerate(line): x = (x - prev[i]) & 0xff out.append(x) def average(): ai = -fo for i,x in enumerate(line): if ai >= 0: x = (x - ((line[ai] + prev[i]) >> 1)) & 0xff else: x = (x - (prev[i] >> 1)) & 0xff out.append(x) ai += 1 def paeth(): # http://www.w3.org/TR/PNG/#9Filter-type-4-Paeth ai = -fo # also used for ci for i,x in enumerate(line): a = 0 b = prev[i] c = 0 if ai >= 0: a = line[ai] c = prev[ai] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: Pr = a elif pb <= pc: Pr = b else: Pr = c x = (x - Pr) & 0xff out.append(x) ai += 1 if not prev: # We're on the first line. Some of the filters can be reduced # to simpler cases which makes handling the line "off the top" # of the image simpler. "up" becomes "none"; "paeth" becomes # "left" (non-trivial, but true). "average" needs to be handled # specially. if type == 2: # "up" type = 0 elif type == 3: prev = [0]*len(line) elif type == 4: # "paeth" type = 1 if type == 0: out.extend(line) elif type == 1: sub() elif type == 2: up() elif type == 3: average() else: # type == 4 paeth() return out
python
def filter_scanline(type, line, fo, prev=None): """Apply a scanline filter to a scanline. `type` specifies the filter type (0 to 4); `line` specifies the current (unfiltered) scanline as a sequence of bytes; `prev` specifies the previous (unfiltered) scanline as a sequence of bytes. `fo` specifies the filter offset; normally this is size of a pixel in bytes (the number of bytes per sample times the number of channels), but when this is < 1 (for bit depths < 8) then the filter offset is 1. """ assert 0 <= type < 5 # The output array. Which, pathetically, we extend one-byte at a # time (fortunately this is linear). out = array('B', [type]) def sub(): ai = -fo for x in line: if ai >= 0: x = (x - line[ai]) & 0xff out.append(x) ai += 1 def up(): for i,x in enumerate(line): x = (x - prev[i]) & 0xff out.append(x) def average(): ai = -fo for i,x in enumerate(line): if ai >= 0: x = (x - ((line[ai] + prev[i]) >> 1)) & 0xff else: x = (x - (prev[i] >> 1)) & 0xff out.append(x) ai += 1 def paeth(): # http://www.w3.org/TR/PNG/#9Filter-type-4-Paeth ai = -fo # also used for ci for i,x in enumerate(line): a = 0 b = prev[i] c = 0 if ai >= 0: a = line[ai] c = prev[ai] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: Pr = a elif pb <= pc: Pr = b else: Pr = c x = (x - Pr) & 0xff out.append(x) ai += 1 if not prev: # We're on the first line. Some of the filters can be reduced # to simpler cases which makes handling the line "off the top" # of the image simpler. "up" becomes "none"; "paeth" becomes # "left" (non-trivial, but true). "average" needs to be handled # specially. if type == 2: # "up" type = 0 elif type == 3: prev = [0]*len(line) elif type == 4: # "paeth" type = 1 if type == 0: out.extend(line) elif type == 1: sub() elif type == 2: up() elif type == 3: average() else: # type == 4 paeth() return out
[ "def", "filter_scanline", "(", "type", ",", "line", ",", "fo", ",", "prev", "=", "None", ")", ":", "assert", "0", "<=", "type", "<", "5", "# The output array. Which, pathetically, we extend one-byte at a", "# time (fortunately this is linear).", "out", "=", "array", "(", "'B'", ",", "[", "type", "]", ")", "def", "sub", "(", ")", ":", "ai", "=", "-", "fo", "for", "x", "in", "line", ":", "if", "ai", ">=", "0", ":", "x", "=", "(", "x", "-", "line", "[", "ai", "]", ")", "&", "0xff", "out", ".", "append", "(", "x", ")", "ai", "+=", "1", "def", "up", "(", ")", ":", "for", "i", ",", "x", "in", "enumerate", "(", "line", ")", ":", "x", "=", "(", "x", "-", "prev", "[", "i", "]", ")", "&", "0xff", "out", ".", "append", "(", "x", ")", "def", "average", "(", ")", ":", "ai", "=", "-", "fo", "for", "i", ",", "x", "in", "enumerate", "(", "line", ")", ":", "if", "ai", ">=", "0", ":", "x", "=", "(", "x", "-", "(", "(", "line", "[", "ai", "]", "+", "prev", "[", "i", "]", ")", ">>", "1", ")", ")", "&", "0xff", "else", ":", "x", "=", "(", "x", "-", "(", "prev", "[", "i", "]", ">>", "1", ")", ")", "&", "0xff", "out", ".", "append", "(", "x", ")", "ai", "+=", "1", "def", "paeth", "(", ")", ":", "# http://www.w3.org/TR/PNG/#9Filter-type-4-Paeth", "ai", "=", "-", "fo", "# also used for ci", "for", "i", ",", "x", "in", "enumerate", "(", "line", ")", ":", "a", "=", "0", "b", "=", "prev", "[", "i", "]", "c", "=", "0", "if", "ai", ">=", "0", ":", "a", "=", "line", "[", "ai", "]", "c", "=", "prev", "[", "ai", "]", "p", "=", "a", "+", "b", "-", "c", "pa", "=", "abs", "(", "p", "-", "a", ")", "pb", "=", "abs", "(", "p", "-", "b", ")", "pc", "=", "abs", "(", "p", "-", "c", ")", "if", "pa", "<=", "pb", "and", "pa", "<=", "pc", ":", "Pr", "=", "a", "elif", "pb", "<=", "pc", ":", "Pr", "=", "b", "else", ":", "Pr", "=", "c", "x", "=", "(", "x", "-", "Pr", ")", "&", "0xff", "out", ".", "append", "(", "x", ")", "ai", "+=", "1", "if", "not", "prev", ":", "# We're on the first line. Some of the filters can be reduced", "# to simpler cases which makes handling the line \"off the top\"", "# of the image simpler. \"up\" becomes \"none\"; \"paeth\" becomes", "# \"left\" (non-trivial, but true). \"average\" needs to be handled", "# specially.", "if", "type", "==", "2", ":", "# \"up\"", "type", "=", "0", "elif", "type", "==", "3", ":", "prev", "=", "[", "0", "]", "*", "len", "(", "line", ")", "elif", "type", "==", "4", ":", "# \"paeth\"", "type", "=", "1", "if", "type", "==", "0", ":", "out", ".", "extend", "(", "line", ")", "elif", "type", "==", "1", ":", "sub", "(", ")", "elif", "type", "==", "2", ":", "up", "(", ")", "elif", "type", "==", "3", ":", "average", "(", ")", "else", ":", "# type == 4", "paeth", "(", ")", "return", "out" ]
Apply a scanline filter to a scanline. `type` specifies the filter type (0 to 4); `line` specifies the current (unfiltered) scanline as a sequence of bytes; `prev` specifies the previous (unfiltered) scanline as a sequence of bytes. `fo` specifies the filter offset; normally this is size of a pixel in bytes (the number of bytes per sample times the number of channels), but when this is < 1 (for bit depths < 8) then the filter offset is 1.
[ "Apply", "a", "scanline", "filter", "to", "a", "scanline", ".", "type", "specifies", "the", "filter", "type", "(", "0", "to", "4", ")", ";", "line", "specifies", "the", "current", "(", "unfiltered", ")", "scanline", "as", "a", "sequence", "of", "bytes", ";", "prev", "specifies", "the", "previous", "(", "unfiltered", ")", "scanline", "as", "a", "sequence", "of", "bytes", ".", "fo", "specifies", "the", "filter", "offset", ";", "normally", "this", "is", "size", "of", "a", "pixel", "in", "bytes", "(", "the", "number", "of", "bytes", "per", "sample", "times", "the", "number", "of", "channels", ")", "but", "when", "this", "is", "<", "1", "(", "for", "bit", "depths", "<", "8", ")", "then", "the", "filter", "offset", "is", "1", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L845-L929
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
from_array
def from_array(a, mode=None, info={}): """Create a PNG :class:`Image` object from a 2- or 3-dimensional array. One application of this function is easy PIL-style saving: ``png.from_array(pixels, 'L').save('foo.png')``. .. note : The use of the term *3-dimensional* is for marketing purposes only. It doesn't actually work. Please bear with us. Meanwhile enjoy the complimentary snacks (on request) and please use a 2-dimensional array. Unless they are specified using the *info* parameter, the PNG's height and width are taken from the array size. For a 3 dimensional array the first axis is the height; the second axis is the width; and the third axis is the channel number. Thus an RGB image that is 16 pixels high and 8 wide will use an array that is 16x8x3. For 2 dimensional arrays the first axis is the height, but the second axis is ``width*channels``, so an RGB image that is 16 pixels high and 8 wide will use a 2-dimensional array that is 16x24 (each row will be 8*3==24 sample values). *mode* is a string that specifies the image colour format in a PIL-style mode. It can be: ``'L'`` greyscale (1 channel) ``'LA'`` greyscale with alpha (2 channel) ``'RGB'`` colour image (3 channel) ``'RGBA'`` colour image with alpha (4 channel) The mode string can also specify the bit depth (overriding how this function normally derives the bit depth, see below). Appending ``';16'`` to the mode will cause the PNG to be 16 bits per channel; any decimal from 1 to 16 can be used to specify the bit depth. When a 2-dimensional array is used *mode* determines how many channels the image has, and so allows the width to be derived from the second array dimension. The array is expected to be a ``numpy`` array, but it can be any suitable Python sequence. For example, a list of lists can be used: ``png.from_array([[0, 255, 0], [255, 0, 255]], 'L')``. The exact rules are: ``len(a)`` gives the first dimension, height; ``len(a[0])`` gives the second dimension; ``len(a[0][0])`` gives the third dimension, unless an exception is raised in which case a 2-dimensional array is assumed. It's slightly more complicated than that because an iterator of rows can be used, and it all still works. Using an iterator allows data to be streamed efficiently. The bit depth of the PNG is normally taken from the array element's datatype (but if *mode* specifies a bitdepth then that is used instead). The array element's datatype is determined in a way which is supposed to work both for ``numpy`` arrays and for Python ``array.array`` objects. A 1 byte datatype will give a bit depth of 8, a 2 byte datatype will give a bit depth of 16. If the datatype does not have an implicit size, for example it is a plain Python list of lists, as above, then a default of 8 is used. The *info* parameter is a dictionary that can be used to specify metadata (in the same style as the arguments to the :class:``png.Writer`` class). For this function the keys that are useful are: height overrides the height derived from the array dimensions and allows *a* to be an iterable. width overrides the width derived from the array dimensions. bitdepth overrides the bit depth derived from the element datatype (but must match *mode* if that also specifies a bit depth). Generally anything specified in the *info* dictionary will override any implicit choices that this function would otherwise make, but must match any explicit ones. For example, if the *info* dictionary has a ``greyscale`` key then this must be true when mode is ``'L'`` or ``'LA'`` and false when mode is ``'RGB'`` or ``'RGBA'``. """ # We abuse the *info* parameter by modifying it. Take a copy here. # (Also typechecks *info* to some extent). info = dict(info) # Syntax check mode string. bitdepth = None try: # Assign the 'L' or 'RGBA' part to `gotmode`. if mode.startswith('L'): gotmode = 'L' mode = mode[1:] elif mode.startswith('RGB'): gotmode = 'RGB' mode = mode[3:] else: raise Error() if mode.startswith('A'): gotmode += 'A' mode = mode[1:] # Skip any optional ';' while mode.startswith(';'): mode = mode[1:] # Parse optional bitdepth if mode: try: bitdepth = int(mode) except (TypeError, ValueError): raise Error() except Error: raise Error("mode string should be 'RGB' or 'L;16' or similar.") mode = gotmode # Get bitdepth from *mode* if possible. if bitdepth: if info.get('bitdepth') and bitdepth != info['bitdepth']: raise Error("mode bitdepth (%d) should match info bitdepth (%d)." % (bitdepth, info['bitdepth'])) info['bitdepth'] = bitdepth # Fill in and/or check entries in *info*. # Dimensions. if 'size' in info: # Check width, height, size all match where used. for dimension,axis in [('width', 0), ('height', 1)]: if dimension in info: if info[dimension] != info['size'][axis]: raise Error( "info[%r] should match info['size'][%r]." % (dimension, axis)) info['width'],info['height'] = info['size'] if 'height' not in info: try: l = len(a) except TypeError: raise Error( "len(a) does not work, supply info['height'] instead.") info['height'] = l # Colour format. if 'greyscale' in info: if bool(info['greyscale']) != ('L' in mode): raise Error("info['greyscale'] should match mode.") info['greyscale'] = 'L' in mode if 'alpha' in info: if bool(info['alpha']) != ('A' in mode): raise Error("info['alpha'] should match mode.") info['alpha'] = 'A' in mode planes = len(mode) if 'planes' in info: if info['planes'] != planes: raise Error("info['planes'] should match mode.") # In order to work out whether we the array is 2D or 3D we need its # first row, which requires that we take a copy of its iterator. # We may also need the first row to derive width and bitdepth. a,t = itertools.tee(a) row = t.next() del t try: row[0][0] threed = True testelement = row[0] except (IndexError, TypeError): threed = False testelement = row if 'width' not in info: if threed: width = len(row) else: width = len(row) // planes info['width'] = width # Not implemented yet assert not threed if 'bitdepth' not in info: try: dtype = testelement.dtype # goto the "else:" clause. Sorry. except AttributeError: try: # Try a Python array.array. bitdepth = 8 * testelement.itemsize except AttributeError: # We can't determine it from the array element's # datatype, use a default of 8. bitdepth = 8 else: # If we got here without exception, we now assume that # the array is a numpy array. if dtype.kind == 'b': bitdepth = 1 else: bitdepth = 8 * dtype.itemsize info['bitdepth'] = bitdepth for thing in 'width height bitdepth greyscale alpha'.split(): assert thing in info return Image(a, info)
python
def from_array(a, mode=None, info={}): """Create a PNG :class:`Image` object from a 2- or 3-dimensional array. One application of this function is easy PIL-style saving: ``png.from_array(pixels, 'L').save('foo.png')``. .. note : The use of the term *3-dimensional* is for marketing purposes only. It doesn't actually work. Please bear with us. Meanwhile enjoy the complimentary snacks (on request) and please use a 2-dimensional array. Unless they are specified using the *info* parameter, the PNG's height and width are taken from the array size. For a 3 dimensional array the first axis is the height; the second axis is the width; and the third axis is the channel number. Thus an RGB image that is 16 pixels high and 8 wide will use an array that is 16x8x3. For 2 dimensional arrays the first axis is the height, but the second axis is ``width*channels``, so an RGB image that is 16 pixels high and 8 wide will use a 2-dimensional array that is 16x24 (each row will be 8*3==24 sample values). *mode* is a string that specifies the image colour format in a PIL-style mode. It can be: ``'L'`` greyscale (1 channel) ``'LA'`` greyscale with alpha (2 channel) ``'RGB'`` colour image (3 channel) ``'RGBA'`` colour image with alpha (4 channel) The mode string can also specify the bit depth (overriding how this function normally derives the bit depth, see below). Appending ``';16'`` to the mode will cause the PNG to be 16 bits per channel; any decimal from 1 to 16 can be used to specify the bit depth. When a 2-dimensional array is used *mode* determines how many channels the image has, and so allows the width to be derived from the second array dimension. The array is expected to be a ``numpy`` array, but it can be any suitable Python sequence. For example, a list of lists can be used: ``png.from_array([[0, 255, 0], [255, 0, 255]], 'L')``. The exact rules are: ``len(a)`` gives the first dimension, height; ``len(a[0])`` gives the second dimension; ``len(a[0][0])`` gives the third dimension, unless an exception is raised in which case a 2-dimensional array is assumed. It's slightly more complicated than that because an iterator of rows can be used, and it all still works. Using an iterator allows data to be streamed efficiently. The bit depth of the PNG is normally taken from the array element's datatype (but if *mode* specifies a bitdepth then that is used instead). The array element's datatype is determined in a way which is supposed to work both for ``numpy`` arrays and for Python ``array.array`` objects. A 1 byte datatype will give a bit depth of 8, a 2 byte datatype will give a bit depth of 16. If the datatype does not have an implicit size, for example it is a plain Python list of lists, as above, then a default of 8 is used. The *info* parameter is a dictionary that can be used to specify metadata (in the same style as the arguments to the :class:``png.Writer`` class). For this function the keys that are useful are: height overrides the height derived from the array dimensions and allows *a* to be an iterable. width overrides the width derived from the array dimensions. bitdepth overrides the bit depth derived from the element datatype (but must match *mode* if that also specifies a bit depth). Generally anything specified in the *info* dictionary will override any implicit choices that this function would otherwise make, but must match any explicit ones. For example, if the *info* dictionary has a ``greyscale`` key then this must be true when mode is ``'L'`` or ``'LA'`` and false when mode is ``'RGB'`` or ``'RGBA'``. """ # We abuse the *info* parameter by modifying it. Take a copy here. # (Also typechecks *info* to some extent). info = dict(info) # Syntax check mode string. bitdepth = None try: # Assign the 'L' or 'RGBA' part to `gotmode`. if mode.startswith('L'): gotmode = 'L' mode = mode[1:] elif mode.startswith('RGB'): gotmode = 'RGB' mode = mode[3:] else: raise Error() if mode.startswith('A'): gotmode += 'A' mode = mode[1:] # Skip any optional ';' while mode.startswith(';'): mode = mode[1:] # Parse optional bitdepth if mode: try: bitdepth = int(mode) except (TypeError, ValueError): raise Error() except Error: raise Error("mode string should be 'RGB' or 'L;16' or similar.") mode = gotmode # Get bitdepth from *mode* if possible. if bitdepth: if info.get('bitdepth') and bitdepth != info['bitdepth']: raise Error("mode bitdepth (%d) should match info bitdepth (%d)." % (bitdepth, info['bitdepth'])) info['bitdepth'] = bitdepth # Fill in and/or check entries in *info*. # Dimensions. if 'size' in info: # Check width, height, size all match where used. for dimension,axis in [('width', 0), ('height', 1)]: if dimension in info: if info[dimension] != info['size'][axis]: raise Error( "info[%r] should match info['size'][%r]." % (dimension, axis)) info['width'],info['height'] = info['size'] if 'height' not in info: try: l = len(a) except TypeError: raise Error( "len(a) does not work, supply info['height'] instead.") info['height'] = l # Colour format. if 'greyscale' in info: if bool(info['greyscale']) != ('L' in mode): raise Error("info['greyscale'] should match mode.") info['greyscale'] = 'L' in mode if 'alpha' in info: if bool(info['alpha']) != ('A' in mode): raise Error("info['alpha'] should match mode.") info['alpha'] = 'A' in mode planes = len(mode) if 'planes' in info: if info['planes'] != planes: raise Error("info['planes'] should match mode.") # In order to work out whether we the array is 2D or 3D we need its # first row, which requires that we take a copy of its iterator. # We may also need the first row to derive width and bitdepth. a,t = itertools.tee(a) row = t.next() del t try: row[0][0] threed = True testelement = row[0] except (IndexError, TypeError): threed = False testelement = row if 'width' not in info: if threed: width = len(row) else: width = len(row) // planes info['width'] = width # Not implemented yet assert not threed if 'bitdepth' not in info: try: dtype = testelement.dtype # goto the "else:" clause. Sorry. except AttributeError: try: # Try a Python array.array. bitdepth = 8 * testelement.itemsize except AttributeError: # We can't determine it from the array element's # datatype, use a default of 8. bitdepth = 8 else: # If we got here without exception, we now assume that # the array is a numpy array. if dtype.kind == 'b': bitdepth = 1 else: bitdepth = 8 * dtype.itemsize info['bitdepth'] = bitdepth for thing in 'width height bitdepth greyscale alpha'.split(): assert thing in info return Image(a, info)
[ "def", "from_array", "(", "a", ",", "mode", "=", "None", ",", "info", "=", "{", "}", ")", ":", "# We abuse the *info* parameter by modifying it. Take a copy here.", "# (Also typechecks *info* to some extent).", "info", "=", "dict", "(", "info", ")", "# Syntax check mode string.", "bitdepth", "=", "None", "try", ":", "# Assign the 'L' or 'RGBA' part to `gotmode`.", "if", "mode", ".", "startswith", "(", "'L'", ")", ":", "gotmode", "=", "'L'", "mode", "=", "mode", "[", "1", ":", "]", "elif", "mode", ".", "startswith", "(", "'RGB'", ")", ":", "gotmode", "=", "'RGB'", "mode", "=", "mode", "[", "3", ":", "]", "else", ":", "raise", "Error", "(", ")", "if", "mode", ".", "startswith", "(", "'A'", ")", ":", "gotmode", "+=", "'A'", "mode", "=", "mode", "[", "1", ":", "]", "# Skip any optional ';'", "while", "mode", ".", "startswith", "(", "';'", ")", ":", "mode", "=", "mode", "[", "1", ":", "]", "# Parse optional bitdepth", "if", "mode", ":", "try", ":", "bitdepth", "=", "int", "(", "mode", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "Error", "(", ")", "except", "Error", ":", "raise", "Error", "(", "\"mode string should be 'RGB' or 'L;16' or similar.\"", ")", "mode", "=", "gotmode", "# Get bitdepth from *mode* if possible.", "if", "bitdepth", ":", "if", "info", ".", "get", "(", "'bitdepth'", ")", "and", "bitdepth", "!=", "info", "[", "'bitdepth'", "]", ":", "raise", "Error", "(", "\"mode bitdepth (%d) should match info bitdepth (%d).\"", "%", "(", "bitdepth", ",", "info", "[", "'bitdepth'", "]", ")", ")", "info", "[", "'bitdepth'", "]", "=", "bitdepth", "# Fill in and/or check entries in *info*.", "# Dimensions.", "if", "'size'", "in", "info", ":", "# Check width, height, size all match where used.", "for", "dimension", ",", "axis", "in", "[", "(", "'width'", ",", "0", ")", ",", "(", "'height'", ",", "1", ")", "]", ":", "if", "dimension", "in", "info", ":", "if", "info", "[", "dimension", "]", "!=", "info", "[", "'size'", "]", "[", "axis", "]", ":", "raise", "Error", "(", "\"info[%r] should match info['size'][%r].\"", "%", "(", "dimension", ",", "axis", ")", ")", "info", "[", "'width'", "]", ",", "info", "[", "'height'", "]", "=", "info", "[", "'size'", "]", "if", "'height'", "not", "in", "info", ":", "try", ":", "l", "=", "len", "(", "a", ")", "except", "TypeError", ":", "raise", "Error", "(", "\"len(a) does not work, supply info['height'] instead.\"", ")", "info", "[", "'height'", "]", "=", "l", "# Colour format.", "if", "'greyscale'", "in", "info", ":", "if", "bool", "(", "info", "[", "'greyscale'", "]", ")", "!=", "(", "'L'", "in", "mode", ")", ":", "raise", "Error", "(", "\"info['greyscale'] should match mode.\"", ")", "info", "[", "'greyscale'", "]", "=", "'L'", "in", "mode", "if", "'alpha'", "in", "info", ":", "if", "bool", "(", "info", "[", "'alpha'", "]", ")", "!=", "(", "'A'", "in", "mode", ")", ":", "raise", "Error", "(", "\"info['alpha'] should match mode.\"", ")", "info", "[", "'alpha'", "]", "=", "'A'", "in", "mode", "planes", "=", "len", "(", "mode", ")", "if", "'planes'", "in", "info", ":", "if", "info", "[", "'planes'", "]", "!=", "planes", ":", "raise", "Error", "(", "\"info['planes'] should match mode.\"", ")", "# In order to work out whether we the array is 2D or 3D we need its", "# first row, which requires that we take a copy of its iterator.", "# We may also need the first row to derive width and bitdepth.", "a", ",", "t", "=", "itertools", ".", "tee", "(", "a", ")", "row", "=", "t", ".", "next", "(", ")", "del", "t", "try", ":", "row", "[", "0", "]", "[", "0", "]", "threed", "=", "True", "testelement", "=", "row", "[", "0", "]", "except", "(", "IndexError", ",", "TypeError", ")", ":", "threed", "=", "False", "testelement", "=", "row", "if", "'width'", "not", "in", "info", ":", "if", "threed", ":", "width", "=", "len", "(", "row", ")", "else", ":", "width", "=", "len", "(", "row", ")", "//", "planes", "info", "[", "'width'", "]", "=", "width", "# Not implemented yet", "assert", "not", "threed", "if", "'bitdepth'", "not", "in", "info", ":", "try", ":", "dtype", "=", "testelement", ".", "dtype", "# goto the \"else:\" clause. Sorry.", "except", "AttributeError", ":", "try", ":", "# Try a Python array.array.", "bitdepth", "=", "8", "*", "testelement", ".", "itemsize", "except", "AttributeError", ":", "# We can't determine it from the array element's", "# datatype, use a default of 8.", "bitdepth", "=", "8", "else", ":", "# If we got here without exception, we now assume that", "# the array is a numpy array.", "if", "dtype", ".", "kind", "==", "'b'", ":", "bitdepth", "=", "1", "else", ":", "bitdepth", "=", "8", "*", "dtype", ".", "itemsize", "info", "[", "'bitdepth'", "]", "=", "bitdepth", "for", "thing", "in", "'width height bitdepth greyscale alpha'", ".", "split", "(", ")", ":", "assert", "thing", "in", "info", "return", "Image", "(", "a", ",", "info", ")" ]
Create a PNG :class:`Image` object from a 2- or 3-dimensional array. One application of this function is easy PIL-style saving: ``png.from_array(pixels, 'L').save('foo.png')``. .. note : The use of the term *3-dimensional* is for marketing purposes only. It doesn't actually work. Please bear with us. Meanwhile enjoy the complimentary snacks (on request) and please use a 2-dimensional array. Unless they are specified using the *info* parameter, the PNG's height and width are taken from the array size. For a 3 dimensional array the first axis is the height; the second axis is the width; and the third axis is the channel number. Thus an RGB image that is 16 pixels high and 8 wide will use an array that is 16x8x3. For 2 dimensional arrays the first axis is the height, but the second axis is ``width*channels``, so an RGB image that is 16 pixels high and 8 wide will use a 2-dimensional array that is 16x24 (each row will be 8*3==24 sample values). *mode* is a string that specifies the image colour format in a PIL-style mode. It can be: ``'L'`` greyscale (1 channel) ``'LA'`` greyscale with alpha (2 channel) ``'RGB'`` colour image (3 channel) ``'RGBA'`` colour image with alpha (4 channel) The mode string can also specify the bit depth (overriding how this function normally derives the bit depth, see below). Appending ``';16'`` to the mode will cause the PNG to be 16 bits per channel; any decimal from 1 to 16 can be used to specify the bit depth. When a 2-dimensional array is used *mode* determines how many channels the image has, and so allows the width to be derived from the second array dimension. The array is expected to be a ``numpy`` array, but it can be any suitable Python sequence. For example, a list of lists can be used: ``png.from_array([[0, 255, 0], [255, 0, 255]], 'L')``. The exact rules are: ``len(a)`` gives the first dimension, height; ``len(a[0])`` gives the second dimension; ``len(a[0][0])`` gives the third dimension, unless an exception is raised in which case a 2-dimensional array is assumed. It's slightly more complicated than that because an iterator of rows can be used, and it all still works. Using an iterator allows data to be streamed efficiently. The bit depth of the PNG is normally taken from the array element's datatype (but if *mode* specifies a bitdepth then that is used instead). The array element's datatype is determined in a way which is supposed to work both for ``numpy`` arrays and for Python ``array.array`` objects. A 1 byte datatype will give a bit depth of 8, a 2 byte datatype will give a bit depth of 16. If the datatype does not have an implicit size, for example it is a plain Python list of lists, as above, then a default of 8 is used. The *info* parameter is a dictionary that can be used to specify metadata (in the same style as the arguments to the :class:``png.Writer`` class). For this function the keys that are useful are: height overrides the height derived from the array dimensions and allows *a* to be an iterable. width overrides the width derived from the array dimensions. bitdepth overrides the bit depth derived from the element datatype (but must match *mode* if that also specifies a bit depth). Generally anything specified in the *info* dictionary will override any implicit choices that this function would otherwise make, but must match any explicit ones. For example, if the *info* dictionary has a ``greyscale`` key then this must be true when mode is ``'L'`` or ``'LA'`` and false when mode is ``'RGB'`` or ``'RGBA'``.
[ "Create", "a", "PNG", ":", "class", ":", "Image", "object", "from", "a", "2", "-", "or", "3", "-", "dimensional", "array", ".", "One", "application", "of", "this", "function", "is", "easy", "PIL", "-", "style", "saving", ":", "png", ".", "from_array", "(", "pixels", "L", ")", ".", "save", "(", "foo", ".", "png", ")", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L932-L1136
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Writer.make_palette
def make_palette(self): """Create the byte sequences for a ``PLTE`` and if necessary a ``tRNS`` chunk. Returned as a pair (*p*, *t*). *t* will be ``None`` if no ``tRNS`` chunk is necessary. """ p = array('B') t = array('B') for x in self.palette: p.extend(x[0:3]) if len(x) > 3: t.append(x[3]) p = tostring(p) t = tostring(t) if t: return p,t return p,None
python
def make_palette(self): """Create the byte sequences for a ``PLTE`` and if necessary a ``tRNS`` chunk. Returned as a pair (*p*, *t*). *t* will be ``None`` if no ``tRNS`` chunk is necessary. """ p = array('B') t = array('B') for x in self.palette: p.extend(x[0:3]) if len(x) > 3: t.append(x[3]) p = tostring(p) t = tostring(t) if t: return p,t return p,None
[ "def", "make_palette", "(", "self", ")", ":", "p", "=", "array", "(", "'B'", ")", "t", "=", "array", "(", "'B'", ")", "for", "x", "in", "self", ".", "palette", ":", "p", ".", "extend", "(", "x", "[", "0", ":", "3", "]", ")", "if", "len", "(", "x", ")", ">", "3", ":", "t", ".", "append", "(", "x", "[", "3", "]", ")", "p", "=", "tostring", "(", "p", ")", "t", "=", "tostring", "(", "t", ")", "if", "t", ":", "return", "p", ",", "t", "return", "p", ",", "None" ]
Create the byte sequences for a ``PLTE`` and if necessary a ``tRNS`` chunk. Returned as a pair (*p*, *t*). *t* will be ``None`` if no ``tRNS`` chunk is necessary.
[ "Create", "the", "byte", "sequences", "for", "a", "PLTE", "and", "if", "necessary", "a", "tRNS", "chunk", ".", "Returned", "as", "a", "pair", "(", "*", "p", "*", "*", "t", "*", ")", ".", "*", "t", "*", "will", "be", "None", "if", "no", "tRNS", "chunk", "is", "necessary", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L464-L481
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Writer.write
def write(self, outfile, rows): """Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` values. If `interlace` is specified (when creating the instance), then an interlaced PNG file will be written. Supply the rows in the normal image order; the interlacing is carried out internally. .. note :: Interlacing will require the entire image to be in working memory. """ if self.interlace: fmt = 'BH'[self.bitdepth > 8] a = array(fmt, itertools.chain(*rows)) return self.write_array(outfile, a) nrows = self.write_passes(outfile, rows) if nrows != self.height: raise ValueError( "rows supplied (%d) does not match height (%d)" % (nrows, self.height))
python
def write(self, outfile, rows): """Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` values. If `interlace` is specified (when creating the instance), then an interlaced PNG file will be written. Supply the rows in the normal image order; the interlacing is carried out internally. .. note :: Interlacing will require the entire image to be in working memory. """ if self.interlace: fmt = 'BH'[self.bitdepth > 8] a = array(fmt, itertools.chain(*rows)) return self.write_array(outfile, a) nrows = self.write_passes(outfile, rows) if nrows != self.height: raise ValueError( "rows supplied (%d) does not match height (%d)" % (nrows, self.height))
[ "def", "write", "(", "self", ",", "outfile", ",", "rows", ")", ":", "if", "self", ".", "interlace", ":", "fmt", "=", "'BH'", "[", "self", ".", "bitdepth", ">", "8", "]", "a", "=", "array", "(", "fmt", ",", "itertools", ".", "chain", "(", "*", "rows", ")", ")", "return", "self", ".", "write_array", "(", "outfile", ",", "a", ")", "nrows", "=", "self", ".", "write_passes", "(", "outfile", ",", "rows", ")", "if", "nrows", "!=", "self", ".", "height", ":", "raise", "ValueError", "(", "\"rows supplied (%d) does not match height (%d)\"", "%", "(", "nrows", ",", "self", ".", "height", ")", ")" ]
Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` values. If `interlace` is specified (when creating the instance), then an interlaced PNG file will be written. Supply the rows in the normal image order; the interlacing is carried out internally. .. note :: Interlacing will require the entire image to be in working memory.
[ "Write", "a", "PNG", "image", "to", "the", "output", "file", ".", "rows", "should", "be", "an", "iterable", "that", "yields", "each", "row", "in", "boxed", "row", "flat", "pixel", "format", ".", "The", "rows", "should", "be", "the", "rows", "of", "the", "original", "image", "so", "there", "should", "be", "self", ".", "height", "rows", "of", "self", ".", "width", "*", "self", ".", "planes", "values", ".", "If", "interlace", "is", "specified", "(", "when", "creating", "the", "instance", ")", "then", "an", "interlaced", "PNG", "file", "will", "be", "written", ".", "Supply", "the", "rows", "in", "the", "normal", "image", "order", ";", "the", "interlacing", "is", "carried", "out", "internally", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L483-L508
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Writer.write_passes
def write_passes(self, outfile, rows, packed=False): """ Write a PNG image to the output file. Most users are expected to find the :meth:`write` or :meth:`write_array` method more convenient. The rows should be given to this method in the order that they appear in the output file. For straightlaced images, this is the usual top to bottom ordering, but for interlaced images the rows should have already been interlaced before passing them to this function. `rows` should be an iterable that yields each row. When `packed` is ``False`` the rows should be in boxed row flat pixel format; when `packed` is ``True`` each row should be a packed sequence of bytes. """ # http://www.w3.org/TR/PNG/#5PNG-file-signature outfile.write(_signature) # http://www.w3.org/TR/PNG/#11IHDR write_chunk(outfile, 'IHDR', struct.pack("!2I5B", self.width, self.height, self.bitdepth, self.color_type, 0, 0, self.interlace)) # See :chunk:order # http://www.w3.org/TR/PNG/#11gAMA if self.gamma is not None: write_chunk(outfile, 'gAMA', struct.pack("!L", int(round(self.gamma*1e5)))) # See :chunk:order # http://www.w3.org/TR/PNG/#11sBIT if self.rescale: write_chunk(outfile, 'sBIT', struct.pack('%dB' % self.planes, *[self.rescale[0]]*self.planes)) # :chunk:order: Without a palette (PLTE chunk), ordering is # relatively relaxed. With one, gAMA chunk must precede PLTE # chunk which must precede tRNS and bKGD. # See http://www.w3.org/TR/PNG/#5ChunkOrdering if self.palette: p,t = self.make_palette() write_chunk(outfile, 'PLTE', p) if t: # tRNS chunk is optional. Only needed if palette entries # have alpha. write_chunk(outfile, 'tRNS', t) # http://www.w3.org/TR/PNG/#11tRNS if self.transparent is not None: if self.greyscale: write_chunk(outfile, 'tRNS', struct.pack("!1H", *self.transparent)) else: write_chunk(outfile, 'tRNS', struct.pack("!3H", *self.transparent)) # http://www.w3.org/TR/PNG/#11bKGD if self.background is not None: if self.greyscale: write_chunk(outfile, 'bKGD', struct.pack("!1H", *self.background)) else: write_chunk(outfile, 'bKGD', struct.pack("!3H", *self.background)) # http://www.w3.org/TR/PNG/#11IDAT if self.compression is not None: compressor = zlib.compressobj(self.compression) else: compressor = zlib.compressobj() # Choose an extend function based on the bitdepth. The extend # function packs/decomposes the pixel values into bytes and # stuffs them onto the data array. data = array('B') if self.bitdepth == 8 or packed: extend = data.extend elif self.bitdepth == 16: # Decompose into bytes def extend(sl): fmt = '!%dH' % len(sl) data.extend(array('B', struct.pack(fmt, *sl))) else: # Pack into bytes assert self.bitdepth < 8 # samples per byte spb = int(8/self.bitdepth) def extend(sl): a = array('B', sl) # Adding padding bytes so we can group into a whole # number of spb-tuples. l = float(len(a)) extra = math.ceil(l / float(spb))*spb - l a.extend([0]*int(extra)) # Pack into bytes l = group(a, spb) l = map(lambda e: reduce(lambda x,y: (x << self.bitdepth) + y, e), l) data.extend(l) if self.rescale: oldextend = extend factor = \ float(2**self.rescale[1]-1) / float(2**self.rescale[0]-1) def extend(sl): oldextend(map(lambda x: int(round(factor*x)), sl)) # Build the first row, testing mostly to see if we need to # changed the extend function to cope with NumPy integer types # (they cause our ordinary definition of extend to fail, so we # wrap it). See # http://code.google.com/p/pypng/issues/detail?id=44 enumrows = enumerate(rows) del rows # First row's filter type. data.append(0) # :todo: Certain exceptions in the call to ``.next()`` or the # following try would indicate no row data supplied. # Should catch. i,row = enumrows.next() try: # If this fails... extend(row) except: # ... try a version that converts the values to int first. # Not only does this work for the (slightly broken) NumPy # types, there are probably lots of other, unknown, "nearly" # int types it works for. def wrapmapint(f): return lambda sl: f(map(int, sl)) extend = wrapmapint(extend) del wrapmapint extend(row) for i,row in enumrows: # Add "None" filter type. Currently, it's essential that # this filter type be used for every scanline as we do not # mark the first row of a reduced pass image; that means we # could accidentally compute the wrong filtered scanline if # we used "up", "average", or "paeth" on such a line. data.append(0) extend(row) if len(data) > self.chunk_limit: compressed = compressor.compress(tostring(data)) if len(compressed): write_chunk(outfile, 'IDAT', compressed) # Because of our very witty definition of ``extend``, # above, we must re-use the same ``data`` object. Hence # we use ``del`` to empty this one, rather than create a # fresh one (which would be my natural FP instinct). del data[:] if len(data): compressed = compressor.compress(tostring(data)) else: compressed = strtobytes('') flushed = compressor.flush() if len(compressed) or len(flushed): write_chunk(outfile, 'IDAT', compressed + flushed) # http://www.w3.org/TR/PNG/#11IEND write_chunk(outfile, 'IEND') return i+1
python
def write_passes(self, outfile, rows, packed=False): """ Write a PNG image to the output file. Most users are expected to find the :meth:`write` or :meth:`write_array` method more convenient. The rows should be given to this method in the order that they appear in the output file. For straightlaced images, this is the usual top to bottom ordering, but for interlaced images the rows should have already been interlaced before passing them to this function. `rows` should be an iterable that yields each row. When `packed` is ``False`` the rows should be in boxed row flat pixel format; when `packed` is ``True`` each row should be a packed sequence of bytes. """ # http://www.w3.org/TR/PNG/#5PNG-file-signature outfile.write(_signature) # http://www.w3.org/TR/PNG/#11IHDR write_chunk(outfile, 'IHDR', struct.pack("!2I5B", self.width, self.height, self.bitdepth, self.color_type, 0, 0, self.interlace)) # See :chunk:order # http://www.w3.org/TR/PNG/#11gAMA if self.gamma is not None: write_chunk(outfile, 'gAMA', struct.pack("!L", int(round(self.gamma*1e5)))) # See :chunk:order # http://www.w3.org/TR/PNG/#11sBIT if self.rescale: write_chunk(outfile, 'sBIT', struct.pack('%dB' % self.planes, *[self.rescale[0]]*self.planes)) # :chunk:order: Without a palette (PLTE chunk), ordering is # relatively relaxed. With one, gAMA chunk must precede PLTE # chunk which must precede tRNS and bKGD. # See http://www.w3.org/TR/PNG/#5ChunkOrdering if self.palette: p,t = self.make_palette() write_chunk(outfile, 'PLTE', p) if t: # tRNS chunk is optional. Only needed if palette entries # have alpha. write_chunk(outfile, 'tRNS', t) # http://www.w3.org/TR/PNG/#11tRNS if self.transparent is not None: if self.greyscale: write_chunk(outfile, 'tRNS', struct.pack("!1H", *self.transparent)) else: write_chunk(outfile, 'tRNS', struct.pack("!3H", *self.transparent)) # http://www.w3.org/TR/PNG/#11bKGD if self.background is not None: if self.greyscale: write_chunk(outfile, 'bKGD', struct.pack("!1H", *self.background)) else: write_chunk(outfile, 'bKGD', struct.pack("!3H", *self.background)) # http://www.w3.org/TR/PNG/#11IDAT if self.compression is not None: compressor = zlib.compressobj(self.compression) else: compressor = zlib.compressobj() # Choose an extend function based on the bitdepth. The extend # function packs/decomposes the pixel values into bytes and # stuffs them onto the data array. data = array('B') if self.bitdepth == 8 or packed: extend = data.extend elif self.bitdepth == 16: # Decompose into bytes def extend(sl): fmt = '!%dH' % len(sl) data.extend(array('B', struct.pack(fmt, *sl))) else: # Pack into bytes assert self.bitdepth < 8 # samples per byte spb = int(8/self.bitdepth) def extend(sl): a = array('B', sl) # Adding padding bytes so we can group into a whole # number of spb-tuples. l = float(len(a)) extra = math.ceil(l / float(spb))*spb - l a.extend([0]*int(extra)) # Pack into bytes l = group(a, spb) l = map(lambda e: reduce(lambda x,y: (x << self.bitdepth) + y, e), l) data.extend(l) if self.rescale: oldextend = extend factor = \ float(2**self.rescale[1]-1) / float(2**self.rescale[0]-1) def extend(sl): oldextend(map(lambda x: int(round(factor*x)), sl)) # Build the first row, testing mostly to see if we need to # changed the extend function to cope with NumPy integer types # (they cause our ordinary definition of extend to fail, so we # wrap it). See # http://code.google.com/p/pypng/issues/detail?id=44 enumrows = enumerate(rows) del rows # First row's filter type. data.append(0) # :todo: Certain exceptions in the call to ``.next()`` or the # following try would indicate no row data supplied. # Should catch. i,row = enumrows.next() try: # If this fails... extend(row) except: # ... try a version that converts the values to int first. # Not only does this work for the (slightly broken) NumPy # types, there are probably lots of other, unknown, "nearly" # int types it works for. def wrapmapint(f): return lambda sl: f(map(int, sl)) extend = wrapmapint(extend) del wrapmapint extend(row) for i,row in enumrows: # Add "None" filter type. Currently, it's essential that # this filter type be used for every scanline as we do not # mark the first row of a reduced pass image; that means we # could accidentally compute the wrong filtered scanline if # we used "up", "average", or "paeth" on such a line. data.append(0) extend(row) if len(data) > self.chunk_limit: compressed = compressor.compress(tostring(data)) if len(compressed): write_chunk(outfile, 'IDAT', compressed) # Because of our very witty definition of ``extend``, # above, we must re-use the same ``data`` object. Hence # we use ``del`` to empty this one, rather than create a # fresh one (which would be my natural FP instinct). del data[:] if len(data): compressed = compressor.compress(tostring(data)) else: compressed = strtobytes('') flushed = compressor.flush() if len(compressed) or len(flushed): write_chunk(outfile, 'IDAT', compressed + flushed) # http://www.w3.org/TR/PNG/#11IEND write_chunk(outfile, 'IEND') return i+1
[ "def", "write_passes", "(", "self", ",", "outfile", ",", "rows", ",", "packed", "=", "False", ")", ":", "# http://www.w3.org/TR/PNG/#5PNG-file-signature", "outfile", ".", "write", "(", "_signature", ")", "# http://www.w3.org/TR/PNG/#11IHDR", "write_chunk", "(", "outfile", ",", "'IHDR'", ",", "struct", ".", "pack", "(", "\"!2I5B\"", ",", "self", ".", "width", ",", "self", ".", "height", ",", "self", ".", "bitdepth", ",", "self", ".", "color_type", ",", "0", ",", "0", ",", "self", ".", "interlace", ")", ")", "# See :chunk:order", "# http://www.w3.org/TR/PNG/#11gAMA", "if", "self", ".", "gamma", "is", "not", "None", ":", "write_chunk", "(", "outfile", ",", "'gAMA'", ",", "struct", ".", "pack", "(", "\"!L\"", ",", "int", "(", "round", "(", "self", ".", "gamma", "*", "1e5", ")", ")", ")", ")", "# See :chunk:order", "# http://www.w3.org/TR/PNG/#11sBIT", "if", "self", ".", "rescale", ":", "write_chunk", "(", "outfile", ",", "'sBIT'", ",", "struct", ".", "pack", "(", "'%dB'", "%", "self", ".", "planes", ",", "*", "[", "self", ".", "rescale", "[", "0", "]", "]", "*", "self", ".", "planes", ")", ")", "# :chunk:order: Without a palette (PLTE chunk), ordering is", "# relatively relaxed. With one, gAMA chunk must precede PLTE", "# chunk which must precede tRNS and bKGD.", "# See http://www.w3.org/TR/PNG/#5ChunkOrdering", "if", "self", ".", "palette", ":", "p", ",", "t", "=", "self", ".", "make_palette", "(", ")", "write_chunk", "(", "outfile", ",", "'PLTE'", ",", "p", ")", "if", "t", ":", "# tRNS chunk is optional. Only needed if palette entries", "# have alpha.", "write_chunk", "(", "outfile", ",", "'tRNS'", ",", "t", ")", "# http://www.w3.org/TR/PNG/#11tRNS", "if", "self", ".", "transparent", "is", "not", "None", ":", "if", "self", ".", "greyscale", ":", "write_chunk", "(", "outfile", ",", "'tRNS'", ",", "struct", ".", "pack", "(", "\"!1H\"", ",", "*", "self", ".", "transparent", ")", ")", "else", ":", "write_chunk", "(", "outfile", ",", "'tRNS'", ",", "struct", ".", "pack", "(", "\"!3H\"", ",", "*", "self", ".", "transparent", ")", ")", "# http://www.w3.org/TR/PNG/#11bKGD", "if", "self", ".", "background", "is", "not", "None", ":", "if", "self", ".", "greyscale", ":", "write_chunk", "(", "outfile", ",", "'bKGD'", ",", "struct", ".", "pack", "(", "\"!1H\"", ",", "*", "self", ".", "background", ")", ")", "else", ":", "write_chunk", "(", "outfile", ",", "'bKGD'", ",", "struct", ".", "pack", "(", "\"!3H\"", ",", "*", "self", ".", "background", ")", ")", "# http://www.w3.org/TR/PNG/#11IDAT", "if", "self", ".", "compression", "is", "not", "None", ":", "compressor", "=", "zlib", ".", "compressobj", "(", "self", ".", "compression", ")", "else", ":", "compressor", "=", "zlib", ".", "compressobj", "(", ")", "# Choose an extend function based on the bitdepth. The extend", "# function packs/decomposes the pixel values into bytes and", "# stuffs them onto the data array.", "data", "=", "array", "(", "'B'", ")", "if", "self", ".", "bitdepth", "==", "8", "or", "packed", ":", "extend", "=", "data", ".", "extend", "elif", "self", ".", "bitdepth", "==", "16", ":", "# Decompose into bytes", "def", "extend", "(", "sl", ")", ":", "fmt", "=", "'!%dH'", "%", "len", "(", "sl", ")", "data", ".", "extend", "(", "array", "(", "'B'", ",", "struct", ".", "pack", "(", "fmt", ",", "*", "sl", ")", ")", ")", "else", ":", "# Pack into bytes", "assert", "self", ".", "bitdepth", "<", "8", "# samples per byte", "spb", "=", "int", "(", "8", "/", "self", ".", "bitdepth", ")", "def", "extend", "(", "sl", ")", ":", "a", "=", "array", "(", "'B'", ",", "sl", ")", "# Adding padding bytes so we can group into a whole", "# number of spb-tuples.", "l", "=", "float", "(", "len", "(", "a", ")", ")", "extra", "=", "math", ".", "ceil", "(", "l", "/", "float", "(", "spb", ")", ")", "*", "spb", "-", "l", "a", ".", "extend", "(", "[", "0", "]", "*", "int", "(", "extra", ")", ")", "# Pack into bytes", "l", "=", "group", "(", "a", ",", "spb", ")", "l", "=", "map", "(", "lambda", "e", ":", "reduce", "(", "lambda", "x", ",", "y", ":", "(", "x", "<<", "self", ".", "bitdepth", ")", "+", "y", ",", "e", ")", ",", "l", ")", "data", ".", "extend", "(", "l", ")", "if", "self", ".", "rescale", ":", "oldextend", "=", "extend", "factor", "=", "float", "(", "2", "**", "self", ".", "rescale", "[", "1", "]", "-", "1", ")", "/", "float", "(", "2", "**", "self", ".", "rescale", "[", "0", "]", "-", "1", ")", "def", "extend", "(", "sl", ")", ":", "oldextend", "(", "map", "(", "lambda", "x", ":", "int", "(", "round", "(", "factor", "*", "x", ")", ")", ",", "sl", ")", ")", "# Build the first row, testing mostly to see if we need to", "# changed the extend function to cope with NumPy integer types", "# (they cause our ordinary definition of extend to fail, so we", "# wrap it). See", "# http://code.google.com/p/pypng/issues/detail?id=44", "enumrows", "=", "enumerate", "(", "rows", ")", "del", "rows", "# First row's filter type.", "data", ".", "append", "(", "0", ")", "# :todo: Certain exceptions in the call to ``.next()`` or the", "# following try would indicate no row data supplied.", "# Should catch.", "i", ",", "row", "=", "enumrows", ".", "next", "(", ")", "try", ":", "# If this fails...", "extend", "(", "row", ")", "except", ":", "# ... try a version that converts the values to int first.", "# Not only does this work for the (slightly broken) NumPy", "# types, there are probably lots of other, unknown, \"nearly\"", "# int types it works for.", "def", "wrapmapint", "(", "f", ")", ":", "return", "lambda", "sl", ":", "f", "(", "map", "(", "int", ",", "sl", ")", ")", "extend", "=", "wrapmapint", "(", "extend", ")", "del", "wrapmapint", "extend", "(", "row", ")", "for", "i", ",", "row", "in", "enumrows", ":", "# Add \"None\" filter type. Currently, it's essential that", "# this filter type be used for every scanline as we do not", "# mark the first row of a reduced pass image; that means we", "# could accidentally compute the wrong filtered scanline if", "# we used \"up\", \"average\", or \"paeth\" on such a line.", "data", ".", "append", "(", "0", ")", "extend", "(", "row", ")", "if", "len", "(", "data", ")", ">", "self", ".", "chunk_limit", ":", "compressed", "=", "compressor", ".", "compress", "(", "tostring", "(", "data", ")", ")", "if", "len", "(", "compressed", ")", ":", "write_chunk", "(", "outfile", ",", "'IDAT'", ",", "compressed", ")", "# Because of our very witty definition of ``extend``,", "# above, we must re-use the same ``data`` object. Hence", "# we use ``del`` to empty this one, rather than create a", "# fresh one (which would be my natural FP instinct).", "del", "data", "[", ":", "]", "if", "len", "(", "data", ")", ":", "compressed", "=", "compressor", ".", "compress", "(", "tostring", "(", "data", ")", ")", "else", ":", "compressed", "=", "strtobytes", "(", "''", ")", "flushed", "=", "compressor", ".", "flush", "(", ")", "if", "len", "(", "compressed", ")", "or", "len", "(", "flushed", ")", ":", "write_chunk", "(", "outfile", ",", "'IDAT'", ",", "compressed", "+", "flushed", ")", "# http://www.w3.org/TR/PNG/#11IEND", "write_chunk", "(", "outfile", ",", "'IEND'", ")", "return", "i", "+", "1" ]
Write a PNG image to the output file. Most users are expected to find the :meth:`write` or :meth:`write_array` method more convenient. The rows should be given to this method in the order that they appear in the output file. For straightlaced images, this is the usual top to bottom ordering, but for interlaced images the rows should have already been interlaced before passing them to this function. `rows` should be an iterable that yields each row. When `packed` is ``False`` the rows should be in boxed row flat pixel format; when `packed` is ``True`` each row should be a packed sequence of bytes.
[ "Write", "a", "PNG", "image", "to", "the", "output", "file", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L510-L676
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Writer.write_packed
def write_packed(self, outfile, rows): """ Write PNG file to `outfile`. The pixel data comes from `rows` which should be in boxed row packed format. Each row should be a sequence of packed bytes. Technically, this method does work for interlaced images but it is best avoided. For interlaced images, the rows should be presented in the order that they appear in the file. This method should not be used when the source image bit depth is not one naturally supported by PNG; the bit depth should be 1, 2, 4, 8, or 16. """ if self.rescale: raise Error("write_packed method not suitable for bit depth %d" % self.rescale[0]) return self.write_passes(outfile, rows, packed=True)
python
def write_packed(self, outfile, rows): """ Write PNG file to `outfile`. The pixel data comes from `rows` which should be in boxed row packed format. Each row should be a sequence of packed bytes. Technically, this method does work for interlaced images but it is best avoided. For interlaced images, the rows should be presented in the order that they appear in the file. This method should not be used when the source image bit depth is not one naturally supported by PNG; the bit depth should be 1, 2, 4, 8, or 16. """ if self.rescale: raise Error("write_packed method not suitable for bit depth %d" % self.rescale[0]) return self.write_passes(outfile, rows, packed=True)
[ "def", "write_packed", "(", "self", ",", "outfile", ",", "rows", ")", ":", "if", "self", ".", "rescale", ":", "raise", "Error", "(", "\"write_packed method not suitable for bit depth %d\"", "%", "self", ".", "rescale", "[", "0", "]", ")", "return", "self", ".", "write_passes", "(", "outfile", ",", "rows", ",", "packed", "=", "True", ")" ]
Write PNG file to `outfile`. The pixel data comes from `rows` which should be in boxed row packed format. Each row should be a sequence of packed bytes. Technically, this method does work for interlaced images but it is best avoided. For interlaced images, the rows should be presented in the order that they appear in the file. This method should not be used when the source image bit depth is not one naturally supported by PNG; the bit depth should be 1, 2, 4, 8, or 16.
[ "Write", "PNG", "file", "to", "outfile", ".", "The", "pixel", "data", "comes", "from", "rows", "which", "should", "be", "in", "boxed", "row", "packed", "format", ".", "Each", "row", "should", "be", "a", "sequence", "of", "packed", "bytes", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L689-L707
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Writer.convert_pnm
def convert_pnm(self, infile, outfile): """ Convert a PNM file containing raw pixel data into a PNG file with the parameters set in the writer object. Works for (binary) PGM, PPM, and PAM formats. """ if self.interlace: pixels = array('B') pixels.fromfile(infile, (self.bitdepth/8) * self.color_planes * self.width * self.height) self.write_passes(outfile, self.array_scanlines_interlace(pixels)) else: self.write_passes(outfile, self.file_scanlines(infile))
python
def convert_pnm(self, infile, outfile): """ Convert a PNM file containing raw pixel data into a PNG file with the parameters set in the writer object. Works for (binary) PGM, PPM, and PAM formats. """ if self.interlace: pixels = array('B') pixels.fromfile(infile, (self.bitdepth/8) * self.color_planes * self.width * self.height) self.write_passes(outfile, self.array_scanlines_interlace(pixels)) else: self.write_passes(outfile, self.file_scanlines(infile))
[ "def", "convert_pnm", "(", "self", ",", "infile", ",", "outfile", ")", ":", "if", "self", ".", "interlace", ":", "pixels", "=", "array", "(", "'B'", ")", "pixels", ".", "fromfile", "(", "infile", ",", "(", "self", ".", "bitdepth", "/", "8", ")", "*", "self", ".", "color_planes", "*", "self", ".", "width", "*", "self", ".", "height", ")", "self", ".", "write_passes", "(", "outfile", ",", "self", ".", "array_scanlines_interlace", "(", "pixels", ")", ")", "else", ":", "self", ".", "write_passes", "(", "outfile", ",", "self", ".", "file_scanlines", "(", "infile", ")", ")" ]
Convert a PNM file containing raw pixel data into a PNG file with the parameters set in the writer object. Works for (binary) PGM, PPM, and PAM formats.
[ "Convert", "a", "PNM", "file", "containing", "raw", "pixel", "data", "into", "a", "PNG", "file", "with", "the", "parameters", "set", "in", "the", "writer", "object", ".", "Works", "for", "(", "binary", ")", "PGM", "PPM", "and", "PAM", "formats", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L709-L723
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Writer.convert_ppm_and_pgm
def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile): """ Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object. """ pixels = array('B') pixels.fromfile(ppmfile, (self.bitdepth/8) * self.color_planes * self.width * self.height) apixels = array('B') apixels.fromfile(pgmfile, (self.bitdepth/8) * self.width * self.height) pixels = interleave_planes(pixels, apixels, (self.bitdepth/8) * self.color_planes, (self.bitdepth/8)) if self.interlace: self.write_passes(outfile, self.array_scanlines_interlace(pixels)) else: self.write_passes(outfile, self.array_scanlines(pixels))
python
def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile): """ Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object. """ pixels = array('B') pixels.fromfile(ppmfile, (self.bitdepth/8) * self.color_planes * self.width * self.height) apixels = array('B') apixels.fromfile(pgmfile, (self.bitdepth/8) * self.width * self.height) pixels = interleave_planes(pixels, apixels, (self.bitdepth/8) * self.color_planes, (self.bitdepth/8)) if self.interlace: self.write_passes(outfile, self.array_scanlines_interlace(pixels)) else: self.write_passes(outfile, self.array_scanlines(pixels))
[ "def", "convert_ppm_and_pgm", "(", "self", ",", "ppmfile", ",", "pgmfile", ",", "outfile", ")", ":", "pixels", "=", "array", "(", "'B'", ")", "pixels", ".", "fromfile", "(", "ppmfile", ",", "(", "self", ".", "bitdepth", "/", "8", ")", "*", "self", ".", "color_planes", "*", "self", ".", "width", "*", "self", ".", "height", ")", "apixels", "=", "array", "(", "'B'", ")", "apixels", ".", "fromfile", "(", "pgmfile", ",", "(", "self", ".", "bitdepth", "/", "8", ")", "*", "self", ".", "width", "*", "self", ".", "height", ")", "pixels", "=", "interleave_planes", "(", "pixels", ",", "apixels", ",", "(", "self", ".", "bitdepth", "/", "8", ")", "*", "self", ".", "color_planes", ",", "(", "self", ".", "bitdepth", "/", "8", ")", ")", "if", "self", ".", "interlace", ":", "self", ".", "write_passes", "(", "outfile", ",", "self", ".", "array_scanlines_interlace", "(", "pixels", ")", ")", "else", ":", "self", ".", "write_passes", "(", "outfile", ",", "self", ".", "array_scanlines", "(", "pixels", ")", ")" ]
Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object.
[ "Convert", "a", "PPM", "and", "PGM", "file", "containing", "raw", "pixel", "data", "into", "a", "PNG", "outfile", "with", "the", "parameters", "set", "in", "the", "writer", "object", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L725-L744
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Writer.file_scanlines
def file_scanlines(self, infile): """ Generates boxed rows in flat pixel format, from the input file `infile`. It assumes that the input file is in a "Netpbm-like" binary format, and is positioned at the beginning of the first pixel. The number of pixels to read is taken from the image dimensions (`width`, `height`, `planes`) and the number of bytes per value is implied by the image `bitdepth`. """ # Values per row vpr = self.width * self.planes row_bytes = vpr if self.bitdepth > 8: assert self.bitdepth == 16 row_bytes *= 2 fmt = '>%dH' % vpr def line(): return array('H', struct.unpack(fmt, infile.read(row_bytes))) else: def line(): scanline = array('B', infile.read(row_bytes)) return scanline for y in range(self.height): yield line()
python
def file_scanlines(self, infile): """ Generates boxed rows in flat pixel format, from the input file `infile`. It assumes that the input file is in a "Netpbm-like" binary format, and is positioned at the beginning of the first pixel. The number of pixels to read is taken from the image dimensions (`width`, `height`, `planes`) and the number of bytes per value is implied by the image `bitdepth`. """ # Values per row vpr = self.width * self.planes row_bytes = vpr if self.bitdepth > 8: assert self.bitdepth == 16 row_bytes *= 2 fmt = '>%dH' % vpr def line(): return array('H', struct.unpack(fmt, infile.read(row_bytes))) else: def line(): scanline = array('B', infile.read(row_bytes)) return scanline for y in range(self.height): yield line()
[ "def", "file_scanlines", "(", "self", ",", "infile", ")", ":", "# Values per row", "vpr", "=", "self", ".", "width", "*", "self", ".", "planes", "row_bytes", "=", "vpr", "if", "self", ".", "bitdepth", ">", "8", ":", "assert", "self", ".", "bitdepth", "==", "16", "row_bytes", "*=", "2", "fmt", "=", "'>%dH'", "%", "vpr", "def", "line", "(", ")", ":", "return", "array", "(", "'H'", ",", "struct", ".", "unpack", "(", "fmt", ",", "infile", ".", "read", "(", "row_bytes", ")", ")", ")", "else", ":", "def", "line", "(", ")", ":", "scanline", "=", "array", "(", "'B'", ",", "infile", ".", "read", "(", "row_bytes", ")", ")", "return", "scanline", "for", "y", "in", "range", "(", "self", ".", "height", ")", ":", "yield", "line", "(", ")" ]
Generates boxed rows in flat pixel format, from the input file `infile`. It assumes that the input file is in a "Netpbm-like" binary format, and is positioned at the beginning of the first pixel. The number of pixels to read is taken from the image dimensions (`width`, `height`, `planes`) and the number of bytes per value is implied by the image `bitdepth`.
[ "Generates", "boxed", "rows", "in", "flat", "pixel", "format", "from", "the", "input", "file", "infile", ".", "It", "assumes", "that", "the", "input", "file", "is", "in", "a", "Netpbm", "-", "like", "binary", "format", "and", "is", "positioned", "at", "the", "beginning", "of", "the", "first", "pixel", ".", "The", "number", "of", "pixels", "to", "read", "is", "taken", "from", "the", "image", "dimensions", "(", "width", "height", "planes", ")", "and", "the", "number", "of", "bytes", "per", "value", "is", "implied", "by", "the", "image", "bitdepth", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L746-L770
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Writer.array_scanlines_interlace
def array_scanlines_interlace(self, pixels): """ Generator for interlaced scanlines from an array. `pixels` is the full source image in flat row flat pixel format. The generator yields each scanline of the reduced passes in turn, in boxed row flat pixel format. """ # http://www.w3.org/TR/PNG/#8InterlaceMethods # Array type. fmt = 'BH'[self.bitdepth > 8] # Value per row vpr = self.width * self.planes for xstart, ystart, xstep, ystep in _adam7: if xstart >= self.width: continue # Pixels per row (of reduced image) ppr = int(math.ceil((self.width-xstart)/float(xstep))) # number of values in reduced image row. row_len = ppr*self.planes for y in range(ystart, self.height, ystep): if xstep == 1: offset = y * vpr yield pixels[offset:offset+vpr] else: row = array(fmt) # There's no easier way to set the length of an array row.extend(pixels[0:row_len]) offset = y * vpr + xstart * self.planes end_offset = (y+1) * vpr skip = self.planes * xstep for i in range(self.planes): row[i::self.planes] = \ pixels[offset+i:end_offset:skip] yield row
python
def array_scanlines_interlace(self, pixels): """ Generator for interlaced scanlines from an array. `pixels` is the full source image in flat row flat pixel format. The generator yields each scanline of the reduced passes in turn, in boxed row flat pixel format. """ # http://www.w3.org/TR/PNG/#8InterlaceMethods # Array type. fmt = 'BH'[self.bitdepth > 8] # Value per row vpr = self.width * self.planes for xstart, ystart, xstep, ystep in _adam7: if xstart >= self.width: continue # Pixels per row (of reduced image) ppr = int(math.ceil((self.width-xstart)/float(xstep))) # number of values in reduced image row. row_len = ppr*self.planes for y in range(ystart, self.height, ystep): if xstep == 1: offset = y * vpr yield pixels[offset:offset+vpr] else: row = array(fmt) # There's no easier way to set the length of an array row.extend(pixels[0:row_len]) offset = y * vpr + xstart * self.planes end_offset = (y+1) * vpr skip = self.planes * xstep for i in range(self.planes): row[i::self.planes] = \ pixels[offset+i:end_offset:skip] yield row
[ "def", "array_scanlines_interlace", "(", "self", ",", "pixels", ")", ":", "# http://www.w3.org/TR/PNG/#8InterlaceMethods", "# Array type.", "fmt", "=", "'BH'", "[", "self", ".", "bitdepth", ">", "8", "]", "# Value per row", "vpr", "=", "self", ".", "width", "*", "self", ".", "planes", "for", "xstart", ",", "ystart", ",", "xstep", ",", "ystep", "in", "_adam7", ":", "if", "xstart", ">=", "self", ".", "width", ":", "continue", "# Pixels per row (of reduced image)", "ppr", "=", "int", "(", "math", ".", "ceil", "(", "(", "self", ".", "width", "-", "xstart", ")", "/", "float", "(", "xstep", ")", ")", ")", "# number of values in reduced image row.", "row_len", "=", "ppr", "*", "self", ".", "planes", "for", "y", "in", "range", "(", "ystart", ",", "self", ".", "height", ",", "ystep", ")", ":", "if", "xstep", "==", "1", ":", "offset", "=", "y", "*", "vpr", "yield", "pixels", "[", "offset", ":", "offset", "+", "vpr", "]", "else", ":", "row", "=", "array", "(", "fmt", ")", "# There's no easier way to set the length of an array", "row", ".", "extend", "(", "pixels", "[", "0", ":", "row_len", "]", ")", "offset", "=", "y", "*", "vpr", "+", "xstart", "*", "self", ".", "planes", "end_offset", "=", "(", "y", "+", "1", ")", "*", "vpr", "skip", "=", "self", ".", "planes", "*", "xstep", "for", "i", "in", "range", "(", "self", ".", "planes", ")", ":", "row", "[", "i", ":", ":", "self", ".", "planes", "]", "=", "pixels", "[", "offset", "+", "i", ":", "end_offset", ":", "skip", "]", "yield", "row" ]
Generator for interlaced scanlines from an array. `pixels` is the full source image in flat row flat pixel format. The generator yields each scanline of the reduced passes in turn, in boxed row flat pixel format.
[ "Generator", "for", "interlaced", "scanlines", "from", "an", "array", ".", "pixels", "is", "the", "full", "source", "image", "in", "flat", "row", "flat", "pixel", "format", ".", "The", "generator", "yields", "each", "scanline", "of", "the", "reduced", "passes", "in", "turn", "in", "boxed", "row", "flat", "pixel", "format", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L786-L820
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.undo_filter
def undo_filter(self, filter_type, scanline, previous): """Undo the filter for a scanline. `scanline` is a sequence of bytes that does not include the initial filter type byte. `previous` is decoded previous scanline (for straightlaced images this is the previous pixel row, but for interlaced images, it is the previous scanline in the reduced image, which in general is not the previous pixel row in the final image). When there is no previous scanline (the first row of a straightlaced image, or the first row in one of the passes in an interlaced image), then this argument should be ``None``. The scanline will have the effects of filtering removed, and the result will be returned as a fresh sequence of bytes. """ # :todo: Would it be better to update scanline in place? # Yes, with the Cython extension making the undo_filter fast, # updating scanline inplace makes the code 3 times faster # (reading 50 images of 800x800 went from 40s to 16s) result = scanline if filter_type == 0: return result if filter_type not in (1,2,3,4): raise FormatError('Invalid PNG Filter Type.' ' See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .') # Filter unit. The stride from one pixel to the corresponding # byte from the previous pixel. Normally this is the pixel # size in bytes, but when this is smaller than 1, the previous # byte is used instead. fu = max(1, self.psize) # For the first line of a pass, synthesize a dummy previous # line. An alternative approach would be to observe that on the # first line 'up' is the same as 'null', 'paeth' is the same # as 'sub', with only 'average' requiring any special case. if not previous: previous = array('B', [0]*len(scanline)) def sub(): """Undo sub filter.""" ai = 0 # Loop starts at index fu. Observe that the initial part # of the result is already filled in correctly with # scanline. for i in range(fu, len(result)): x = scanline[i] a = result[ai] result[i] = (x + a) & 0xff ai += 1 def up(): """Undo up filter.""" for i in range(len(result)): x = scanline[i] b = previous[i] result[i] = (x + b) & 0xff def average(): """Undo average filter.""" ai = -fu for i in range(len(result)): x = scanline[i] if ai < 0: a = 0 else: a = result[ai] b = previous[i] result[i] = (x + ((a + b) >> 1)) & 0xff ai += 1 def paeth(): """Undo Paeth filter.""" # Also used for ci. ai = -fu for i in range(len(result)): x = scanline[i] if ai < 0: a = c = 0 else: a = result[ai] c = previous[ai] b = previous[i] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: pr = a elif pb <= pc: pr = b else: pr = c result[i] = (x + pr) & 0xff ai += 1 # Call appropriate filter algorithm. Note that 0 has already # been dealt with. (None, pngfilters.undo_filter_sub, pngfilters.undo_filter_up, pngfilters.undo_filter_average, pngfilters.undo_filter_paeth)[filter_type](fu, scanline, previous, result) return result
python
def undo_filter(self, filter_type, scanline, previous): """Undo the filter for a scanline. `scanline` is a sequence of bytes that does not include the initial filter type byte. `previous` is decoded previous scanline (for straightlaced images this is the previous pixel row, but for interlaced images, it is the previous scanline in the reduced image, which in general is not the previous pixel row in the final image). When there is no previous scanline (the first row of a straightlaced image, or the first row in one of the passes in an interlaced image), then this argument should be ``None``. The scanline will have the effects of filtering removed, and the result will be returned as a fresh sequence of bytes. """ # :todo: Would it be better to update scanline in place? # Yes, with the Cython extension making the undo_filter fast, # updating scanline inplace makes the code 3 times faster # (reading 50 images of 800x800 went from 40s to 16s) result = scanline if filter_type == 0: return result if filter_type not in (1,2,3,4): raise FormatError('Invalid PNG Filter Type.' ' See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .') # Filter unit. The stride from one pixel to the corresponding # byte from the previous pixel. Normally this is the pixel # size in bytes, but when this is smaller than 1, the previous # byte is used instead. fu = max(1, self.psize) # For the first line of a pass, synthesize a dummy previous # line. An alternative approach would be to observe that on the # first line 'up' is the same as 'null', 'paeth' is the same # as 'sub', with only 'average' requiring any special case. if not previous: previous = array('B', [0]*len(scanline)) def sub(): """Undo sub filter.""" ai = 0 # Loop starts at index fu. Observe that the initial part # of the result is already filled in correctly with # scanline. for i in range(fu, len(result)): x = scanline[i] a = result[ai] result[i] = (x + a) & 0xff ai += 1 def up(): """Undo up filter.""" for i in range(len(result)): x = scanline[i] b = previous[i] result[i] = (x + b) & 0xff def average(): """Undo average filter.""" ai = -fu for i in range(len(result)): x = scanline[i] if ai < 0: a = 0 else: a = result[ai] b = previous[i] result[i] = (x + ((a + b) >> 1)) & 0xff ai += 1 def paeth(): """Undo Paeth filter.""" # Also used for ci. ai = -fu for i in range(len(result)): x = scanline[i] if ai < 0: a = c = 0 else: a = result[ai] c = previous[ai] b = previous[i] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: pr = a elif pb <= pc: pr = b else: pr = c result[i] = (x + pr) & 0xff ai += 1 # Call appropriate filter algorithm. Note that 0 has already # been dealt with. (None, pngfilters.undo_filter_sub, pngfilters.undo_filter_up, pngfilters.undo_filter_average, pngfilters.undo_filter_paeth)[filter_type](fu, scanline, previous, result) return result
[ "def", "undo_filter", "(", "self", ",", "filter_type", ",", "scanline", ",", "previous", ")", ":", "# :todo: Would it be better to update scanline in place?", "# Yes, with the Cython extension making the undo_filter fast,", "# updating scanline inplace makes the code 3 times faster", "# (reading 50 images of 800x800 went from 40s to 16s)", "result", "=", "scanline", "if", "filter_type", "==", "0", ":", "return", "result", "if", "filter_type", "not", "in", "(", "1", ",", "2", ",", "3", ",", "4", ")", ":", "raise", "FormatError", "(", "'Invalid PNG Filter Type.'", "' See http://www.w3.org/TR/2003/REC-PNG-20031110/#9Filters .'", ")", "# Filter unit. The stride from one pixel to the corresponding", "# byte from the previous pixel. Normally this is the pixel", "# size in bytes, but when this is smaller than 1, the previous", "# byte is used instead.", "fu", "=", "max", "(", "1", ",", "self", ".", "psize", ")", "# For the first line of a pass, synthesize a dummy previous", "# line. An alternative approach would be to observe that on the", "# first line 'up' is the same as 'null', 'paeth' is the same", "# as 'sub', with only 'average' requiring any special case.", "if", "not", "previous", ":", "previous", "=", "array", "(", "'B'", ",", "[", "0", "]", "*", "len", "(", "scanline", ")", ")", "def", "sub", "(", ")", ":", "\"\"\"Undo sub filter.\"\"\"", "ai", "=", "0", "# Loop starts at index fu. Observe that the initial part", "# of the result is already filled in correctly with", "# scanline.", "for", "i", "in", "range", "(", "fu", ",", "len", "(", "result", ")", ")", ":", "x", "=", "scanline", "[", "i", "]", "a", "=", "result", "[", "ai", "]", "result", "[", "i", "]", "=", "(", "x", "+", "a", ")", "&", "0xff", "ai", "+=", "1", "def", "up", "(", ")", ":", "\"\"\"Undo up filter.\"\"\"", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "x", "=", "scanline", "[", "i", "]", "b", "=", "previous", "[", "i", "]", "result", "[", "i", "]", "=", "(", "x", "+", "b", ")", "&", "0xff", "def", "average", "(", ")", ":", "\"\"\"Undo average filter.\"\"\"", "ai", "=", "-", "fu", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "x", "=", "scanline", "[", "i", "]", "if", "ai", "<", "0", ":", "a", "=", "0", "else", ":", "a", "=", "result", "[", "ai", "]", "b", "=", "previous", "[", "i", "]", "result", "[", "i", "]", "=", "(", "x", "+", "(", "(", "a", "+", "b", ")", ">>", "1", ")", ")", "&", "0xff", "ai", "+=", "1", "def", "paeth", "(", ")", ":", "\"\"\"Undo Paeth filter.\"\"\"", "# Also used for ci.", "ai", "=", "-", "fu", "for", "i", "in", "range", "(", "len", "(", "result", ")", ")", ":", "x", "=", "scanline", "[", "i", "]", "if", "ai", "<", "0", ":", "a", "=", "c", "=", "0", "else", ":", "a", "=", "result", "[", "ai", "]", "c", "=", "previous", "[", "ai", "]", "b", "=", "previous", "[", "i", "]", "p", "=", "a", "+", "b", "-", "c", "pa", "=", "abs", "(", "p", "-", "a", ")", "pb", "=", "abs", "(", "p", "-", "b", ")", "pc", "=", "abs", "(", "p", "-", "c", ")", "if", "pa", "<=", "pb", "and", "pa", "<=", "pc", ":", "pr", "=", "a", "elif", "pb", "<=", "pc", ":", "pr", "=", "b", "else", ":", "pr", "=", "c", "result", "[", "i", "]", "=", "(", "x", "+", "pr", ")", "&", "0xff", "ai", "+=", "1", "# Call appropriate filter algorithm. Note that 0 has already", "# been dealt with.", "(", "None", ",", "pngfilters", ".", "undo_filter_sub", ",", "pngfilters", ".", "undo_filter_up", ",", "pngfilters", ".", "undo_filter_average", ",", "pngfilters", ".", "undo_filter_paeth", ")", "[", "filter_type", "]", "(", "fu", ",", "scanline", ",", "previous", ",", "result", ")", "return", "result" ]
Undo the filter for a scanline. `scanline` is a sequence of bytes that does not include the initial filter type byte. `previous` is decoded previous scanline (for straightlaced images this is the previous pixel row, but for interlaced images, it is the previous scanline in the reduced image, which in general is not the previous pixel row in the final image). When there is no previous scanline (the first row of a straightlaced image, or the first row in one of the passes in an interlaced image), then this argument should be ``None``. The scanline will have the effects of filtering removed, and the result will be returned as a fresh sequence of bytes.
[ "Undo", "the", "filter", "for", "a", "scanline", ".", "scanline", "is", "a", "sequence", "of", "bytes", "that", "does", "not", "include", "the", "initial", "filter", "type", "byte", ".", "previous", "is", "decoded", "previous", "scanline", "(", "for", "straightlaced", "images", "this", "is", "the", "previous", "pixel", "row", "but", "for", "interlaced", "images", "it", "is", "the", "previous", "scanline", "in", "the", "reduced", "image", "which", "in", "general", "is", "not", "the", "previous", "pixel", "row", "in", "the", "final", "image", ")", ".", "When", "there", "is", "no", "previous", "scanline", "(", "the", "first", "row", "of", "a", "straightlaced", "image", "or", "the", "first", "row", "in", "one", "of", "the", "passes", "in", "an", "interlaced", "image", ")", "then", "this", "argument", "should", "be", "None", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1315-L1424
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.deinterlace
def deinterlace(self, raw): """ Read raw pixel data, undo filters, deinterlace, and flatten. Return in flat row flat pixel format. """ # Values per row (of the target image) vpr = self.width * self.planes # Make a result array, and make it big enough. Interleaving # writes to the output array randomly (well, not quite), so the # entire output array must be in memory. fmt = 'BH'[self.bitdepth > 8] a = array(fmt, [0]*vpr*self.height) source_offset = 0 for xstart, ystart, xstep, ystep in _adam7: if xstart >= self.width: continue # The previous (reconstructed) scanline. None at the # beginning of a pass to indicate that there is no previous # line. recon = None # Pixels per row (reduced pass image) ppr = int(math.ceil((self.width-xstart)/float(xstep))) # Row size in bytes for this pass. row_size = int(math.ceil(self.psize * ppr)) for y in range(ystart, self.height, ystep): filter_type = raw[source_offset] source_offset += 1 scanline = raw[source_offset:source_offset+row_size] source_offset += row_size recon = self.undo_filter(filter_type, scanline, recon) # Convert so that there is one element per pixel value flat = self.serialtoflat(recon, ppr) if xstep == 1: assert xstart == 0 offset = y * vpr a[offset:offset+vpr] = flat else: offset = y * vpr + xstart * self.planes end_offset = (y+1) * vpr skip = self.planes * xstep for i in range(self.planes): a[offset+i:end_offset:skip] = \ flat[i::self.planes] return a
python
def deinterlace(self, raw): """ Read raw pixel data, undo filters, deinterlace, and flatten. Return in flat row flat pixel format. """ # Values per row (of the target image) vpr = self.width * self.planes # Make a result array, and make it big enough. Interleaving # writes to the output array randomly (well, not quite), so the # entire output array must be in memory. fmt = 'BH'[self.bitdepth > 8] a = array(fmt, [0]*vpr*self.height) source_offset = 0 for xstart, ystart, xstep, ystep in _adam7: if xstart >= self.width: continue # The previous (reconstructed) scanline. None at the # beginning of a pass to indicate that there is no previous # line. recon = None # Pixels per row (reduced pass image) ppr = int(math.ceil((self.width-xstart)/float(xstep))) # Row size in bytes for this pass. row_size = int(math.ceil(self.psize * ppr)) for y in range(ystart, self.height, ystep): filter_type = raw[source_offset] source_offset += 1 scanline = raw[source_offset:source_offset+row_size] source_offset += row_size recon = self.undo_filter(filter_type, scanline, recon) # Convert so that there is one element per pixel value flat = self.serialtoflat(recon, ppr) if xstep == 1: assert xstart == 0 offset = y * vpr a[offset:offset+vpr] = flat else: offset = y * vpr + xstart * self.planes end_offset = (y+1) * vpr skip = self.planes * xstep for i in range(self.planes): a[offset+i:end_offset:skip] = \ flat[i::self.planes] return a
[ "def", "deinterlace", "(", "self", ",", "raw", ")", ":", "# Values per row (of the target image)", "vpr", "=", "self", ".", "width", "*", "self", ".", "planes", "# Make a result array, and make it big enough. Interleaving", "# writes to the output array randomly (well, not quite), so the", "# entire output array must be in memory.", "fmt", "=", "'BH'", "[", "self", ".", "bitdepth", ">", "8", "]", "a", "=", "array", "(", "fmt", ",", "[", "0", "]", "*", "vpr", "*", "self", ".", "height", ")", "source_offset", "=", "0", "for", "xstart", ",", "ystart", ",", "xstep", ",", "ystep", "in", "_adam7", ":", "if", "xstart", ">=", "self", ".", "width", ":", "continue", "# The previous (reconstructed) scanline. None at the", "# beginning of a pass to indicate that there is no previous", "# line.", "recon", "=", "None", "# Pixels per row (reduced pass image)", "ppr", "=", "int", "(", "math", ".", "ceil", "(", "(", "self", ".", "width", "-", "xstart", ")", "/", "float", "(", "xstep", ")", ")", ")", "# Row size in bytes for this pass.", "row_size", "=", "int", "(", "math", ".", "ceil", "(", "self", ".", "psize", "*", "ppr", ")", ")", "for", "y", "in", "range", "(", "ystart", ",", "self", ".", "height", ",", "ystep", ")", ":", "filter_type", "=", "raw", "[", "source_offset", "]", "source_offset", "+=", "1", "scanline", "=", "raw", "[", "source_offset", ":", "source_offset", "+", "row_size", "]", "source_offset", "+=", "row_size", "recon", "=", "self", ".", "undo_filter", "(", "filter_type", ",", "scanline", ",", "recon", ")", "# Convert so that there is one element per pixel value", "flat", "=", "self", ".", "serialtoflat", "(", "recon", ",", "ppr", ")", "if", "xstep", "==", "1", ":", "assert", "xstart", "==", "0", "offset", "=", "y", "*", "vpr", "a", "[", "offset", ":", "offset", "+", "vpr", "]", "=", "flat", "else", ":", "offset", "=", "y", "*", "vpr", "+", "xstart", "*", "self", ".", "planes", "end_offset", "=", "(", "y", "+", "1", ")", "*", "vpr", "skip", "=", "self", ".", "planes", "*", "xstep", "for", "i", "in", "range", "(", "self", ".", "planes", ")", ":", "a", "[", "offset", "+", "i", ":", "end_offset", ":", "skip", "]", "=", "flat", "[", "i", ":", ":", "self", ".", "planes", "]", "return", "a" ]
Read raw pixel data, undo filters, deinterlace, and flatten. Return in flat row flat pixel format.
[ "Read", "raw", "pixel", "data", "undo", "filters", "deinterlace", "and", "flatten", ".", "Return", "in", "flat", "row", "flat", "pixel", "format", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1426-L1472
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.iterboxed
def iterboxed(self, rows): """Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row in turn. """ def asvalues(raw): """Convert a row of raw bytes into a flat row. Result will be a freshly allocated object, not shared with argument. """ if self.bitdepth == 8: return array('B', raw) if self.bitdepth == 16: raw = tostring(raw) return array('H', struct.unpack('!%dH' % (len(raw)//2), raw)) assert self.bitdepth < 8 width = self.width # Samples per byte spb = 8//self.bitdepth out = array('B') mask = 2**self.bitdepth - 1 shifts = map(self.bitdepth.__mul__, reversed(range(spb))) for o in raw: out.extend(map(lambda i: mask&(o>>i), shifts)) return out[:width] return imap(asvalues, rows)
python
def iterboxed(self, rows): """Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row in turn. """ def asvalues(raw): """Convert a row of raw bytes into a flat row. Result will be a freshly allocated object, not shared with argument. """ if self.bitdepth == 8: return array('B', raw) if self.bitdepth == 16: raw = tostring(raw) return array('H', struct.unpack('!%dH' % (len(raw)//2), raw)) assert self.bitdepth < 8 width = self.width # Samples per byte spb = 8//self.bitdepth out = array('B') mask = 2**self.bitdepth - 1 shifts = map(self.bitdepth.__mul__, reversed(range(spb))) for o in raw: out.extend(map(lambda i: mask&(o>>i), shifts)) return out[:width] return imap(asvalues, rows)
[ "def", "iterboxed", "(", "self", ",", "rows", ")", ":", "def", "asvalues", "(", "raw", ")", ":", "\"\"\"Convert a row of raw bytes into a flat row. Result will\n be a freshly allocated object, not shared with\n argument.\n \"\"\"", "if", "self", ".", "bitdepth", "==", "8", ":", "return", "array", "(", "'B'", ",", "raw", ")", "if", "self", ".", "bitdepth", "==", "16", ":", "raw", "=", "tostring", "(", "raw", ")", "return", "array", "(", "'H'", ",", "struct", ".", "unpack", "(", "'!%dH'", "%", "(", "len", "(", "raw", ")", "//", "2", ")", ",", "raw", ")", ")", "assert", "self", ".", "bitdepth", "<", "8", "width", "=", "self", ".", "width", "# Samples per byte", "spb", "=", "8", "//", "self", ".", "bitdepth", "out", "=", "array", "(", "'B'", ")", "mask", "=", "2", "**", "self", ".", "bitdepth", "-", "1", "shifts", "=", "map", "(", "self", ".", "bitdepth", ".", "__mul__", ",", "reversed", "(", "range", "(", "spb", ")", ")", ")", "for", "o", "in", "raw", ":", "out", ".", "extend", "(", "map", "(", "lambda", "i", ":", "mask", "&", "(", "o", ">>", "i", ")", ",", "shifts", ")", ")", "return", "out", "[", ":", "width", "]", "return", "imap", "(", "asvalues", ",", "rows", ")" ]
Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row in turn.
[ "Iterator", "that", "yields", "each", "scanline", "in", "boxed", "row", "flat", "pixel", "format", ".", "rows", "should", "be", "an", "iterator", "that", "yields", "the", "bytes", "of", "each", "row", "in", "turn", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1474-L1502
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.serialtoflat
def serialtoflat(self, bytes, width=None): """Convert serial format (byte stream) pixel data to flat row flat pixel. """ if self.bitdepth == 8: return bytes if self.bitdepth == 16: bytes = tostring(bytes) return array('H', struct.unpack('!%dH' % (len(bytes)//2), bytes)) assert self.bitdepth < 8 if width is None: width = self.width # Samples per byte spb = 8//self.bitdepth out = array('B') mask = 2**self.bitdepth - 1 shifts = map(self.bitdepth.__mul__, reversed(range(spb))) l = width for o in bytes: out.extend([(mask&(o>>s)) for s in shifts][:l]) l -= spb if l <= 0: l = width return out
python
def serialtoflat(self, bytes, width=None): """Convert serial format (byte stream) pixel data to flat row flat pixel. """ if self.bitdepth == 8: return bytes if self.bitdepth == 16: bytes = tostring(bytes) return array('H', struct.unpack('!%dH' % (len(bytes)//2), bytes)) assert self.bitdepth < 8 if width is None: width = self.width # Samples per byte spb = 8//self.bitdepth out = array('B') mask = 2**self.bitdepth - 1 shifts = map(self.bitdepth.__mul__, reversed(range(spb))) l = width for o in bytes: out.extend([(mask&(o>>s)) for s in shifts][:l]) l -= spb if l <= 0: l = width return out
[ "def", "serialtoflat", "(", "self", ",", "bytes", ",", "width", "=", "None", ")", ":", "if", "self", ".", "bitdepth", "==", "8", ":", "return", "bytes", "if", "self", ".", "bitdepth", "==", "16", ":", "bytes", "=", "tostring", "(", "bytes", ")", "return", "array", "(", "'H'", ",", "struct", ".", "unpack", "(", "'!%dH'", "%", "(", "len", "(", "bytes", ")", "//", "2", ")", ",", "bytes", ")", ")", "assert", "self", ".", "bitdepth", "<", "8", "if", "width", "is", "None", ":", "width", "=", "self", ".", "width", "# Samples per byte", "spb", "=", "8", "//", "self", ".", "bitdepth", "out", "=", "array", "(", "'B'", ")", "mask", "=", "2", "**", "self", ".", "bitdepth", "-", "1", "shifts", "=", "map", "(", "self", ".", "bitdepth", ".", "__mul__", ",", "reversed", "(", "range", "(", "spb", ")", ")", ")", "l", "=", "width", "for", "o", "in", "bytes", ":", "out", ".", "extend", "(", "[", "(", "mask", "&", "(", "o", ">>", "s", ")", ")", "for", "s", "in", "shifts", "]", "[", ":", "l", "]", ")", "l", "-=", "spb", "if", "l", "<=", "0", ":", "l", "=", "width", "return", "out" ]
Convert serial format (byte stream) pixel data to flat row flat pixel.
[ "Convert", "serial", "format", "(", "byte", "stream", ")", "pixel", "data", "to", "flat", "row", "flat", "pixel", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1504-L1529
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.iterstraight
def iterstraight(self, raw): """Iterator that undoes the effect of filtering, and yields each row in serialised format (as a sequence of bytes). Assumes input is straightlaced. `raw` should be an iterable that yields the raw bytes in chunks of arbitrary size. """ # length of row, in bytes rb = self.row_bytes a = array('B') # The previous (reconstructed) scanline. None indicates first # line of image. recon = None for some in raw: a.extend(some) while len(a) >= rb + 1: filter_type = a[0] scanline = a[1:rb+1] del a[:rb+1] recon = self.undo_filter(filter_type, scanline, recon) yield recon if len(a) != 0: # :file:format We get here with a file format error: # when the available bytes (after decompressing) do not # pack into exact rows. raise FormatError( 'Wrong size for decompressed IDAT chunk.') assert len(a) == 0
python
def iterstraight(self, raw): """Iterator that undoes the effect of filtering, and yields each row in serialised format (as a sequence of bytes). Assumes input is straightlaced. `raw` should be an iterable that yields the raw bytes in chunks of arbitrary size. """ # length of row, in bytes rb = self.row_bytes a = array('B') # The previous (reconstructed) scanline. None indicates first # line of image. recon = None for some in raw: a.extend(some) while len(a) >= rb + 1: filter_type = a[0] scanline = a[1:rb+1] del a[:rb+1] recon = self.undo_filter(filter_type, scanline, recon) yield recon if len(a) != 0: # :file:format We get here with a file format error: # when the available bytes (after decompressing) do not # pack into exact rows. raise FormatError( 'Wrong size for decompressed IDAT chunk.') assert len(a) == 0
[ "def", "iterstraight", "(", "self", ",", "raw", ")", ":", "# length of row, in bytes", "rb", "=", "self", ".", "row_bytes", "a", "=", "array", "(", "'B'", ")", "# The previous (reconstructed) scanline. None indicates first", "# line of image.", "recon", "=", "None", "for", "some", "in", "raw", ":", "a", ".", "extend", "(", "some", ")", "while", "len", "(", "a", ")", ">=", "rb", "+", "1", ":", "filter_type", "=", "a", "[", "0", "]", "scanline", "=", "a", "[", "1", ":", "rb", "+", "1", "]", "del", "a", "[", ":", "rb", "+", "1", "]", "recon", "=", "self", ".", "undo_filter", "(", "filter_type", ",", "scanline", ",", "recon", ")", "yield", "recon", "if", "len", "(", "a", ")", "!=", "0", ":", "# :file:format We get here with a file format error:", "# when the available bytes (after decompressing) do not", "# pack into exact rows.", "raise", "FormatError", "(", "'Wrong size for decompressed IDAT chunk.'", ")", "assert", "len", "(", "a", ")", "==", "0" ]
Iterator that undoes the effect of filtering, and yields each row in serialised format (as a sequence of bytes). Assumes input is straightlaced. `raw` should be an iterable that yields the raw bytes in chunks of arbitrary size.
[ "Iterator", "that", "undoes", "the", "effect", "of", "filtering", "and", "yields", "each", "row", "in", "serialised", "format", "(", "as", "a", "sequence", "of", "bytes", ")", ".", "Assumes", "input", "is", "straightlaced", ".", "raw", "should", "be", "an", "iterable", "that", "yields", "the", "raw", "bytes", "in", "chunks", "of", "arbitrary", "size", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1531-L1558
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.chunklentype
def chunklentype(self): """Reads just enough of the input to determine the next chunk's length and type, returned as a (*length*, *type*) pair where *type* is a string. If there are no more chunks, ``None`` is returned. """ x = self.file.read(8) if not x: return None if len(x) != 8: raise FormatError( 'End of file whilst reading chunk length and type.') length,type = struct.unpack('!I4s', x) type = bytestostr(type) if length > 2**31-1: raise FormatError('Chunk %s is too large: %d.' % (type,length)) return length,type
python
def chunklentype(self): """Reads just enough of the input to determine the next chunk's length and type, returned as a (*length*, *type*) pair where *type* is a string. If there are no more chunks, ``None`` is returned. """ x = self.file.read(8) if not x: return None if len(x) != 8: raise FormatError( 'End of file whilst reading chunk length and type.') length,type = struct.unpack('!I4s', x) type = bytestostr(type) if length > 2**31-1: raise FormatError('Chunk %s is too large: %d.' % (type,length)) return length,type
[ "def", "chunklentype", "(", "self", ")", ":", "x", "=", "self", ".", "file", ".", "read", "(", "8", ")", "if", "not", "x", ":", "return", "None", "if", "len", "(", "x", ")", "!=", "8", ":", "raise", "FormatError", "(", "'End of file whilst reading chunk length and type.'", ")", "length", ",", "type", "=", "struct", ".", "unpack", "(", "'!I4s'", ",", "x", ")", "type", "=", "bytestostr", "(", "type", ")", "if", "length", ">", "2", "**", "31", "-", "1", ":", "raise", "FormatError", "(", "'Chunk %s is too large: %d.'", "%", "(", "type", ",", "length", ")", ")", "return", "length", ",", "type" ]
Reads just enough of the input to determine the next chunk's length and type, returned as a (*length*, *type*) pair where *type* is a string. If there are no more chunks, ``None`` is returned.
[ "Reads", "just", "enough", "of", "the", "input", "to", "determine", "the", "next", "chunk", "s", "length", "and", "type", "returned", "as", "a", "(", "*", "length", "*", "*", "type", "*", ")", "pair", "where", "*", "type", "*", "is", "a", "string", ".", "If", "there", "are", "no", "more", "chunks", "None", "is", "returned", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1594-L1611
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.read
def read(self, lenient=False): """ Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. If the optional `lenient` argument evaluates to True, checksum failures will raise warnings rather than exceptions. """ def iteridat(): """Iterator that yields all the ``IDAT`` chunks as strings.""" while True: try: type, data = self.chunk(lenient=lenient) except ValueError as e: raise ChunkError(e.args[0]) if type == 'IEND': # http://www.w3.org/TR/PNG/#11IEND break if type != 'IDAT': continue # type == 'IDAT' # http://www.w3.org/TR/PNG/#11IDAT if self.colormap and not self.plte: warnings.warn("PLTE chunk is required before IDAT chunk") yield data def iterdecomp(idat): """Iterator that yields decompressed strings. `idat` should be an iterator that yields the ``IDAT`` chunk data. """ # Currently, with no max_length parameter to decompress, # this routine will do one yield per IDAT chunk: Not very # incremental. d = zlib.decompressobj() # Each IDAT chunk is passed to the decompressor, then any # remaining state is decompressed out. for data in idat: # :todo: add a max_length argument here to limit output # size. yield array('B', d.decompress(data)) yield array('B', d.flush()) self.preamble(lenient=lenient) raw = iterdecomp(iteridat()) if self.interlace: raw = array('B', itertools.chain(*raw)) arraycode = 'BH'[self.bitdepth>8] # Like :meth:`group` but producing an array.array object for # each row. pixels = imap(lambda *row: array(arraycode, row), *[iter(self.deinterlace(raw))]*self.width*self.planes) else: pixels = self.iterboxed(self.iterstraight(raw)) meta = dict() for attr in 'greyscale alpha planes bitdepth interlace'.split(): meta[attr] = getattr(self, attr) meta['size'] = (self.width, self.height) for attr in 'gamma transparent background'.split(): a = getattr(self, attr, None) if a is not None: meta[attr] = a if self.plte: meta['palette'] = self.palette() return self.width, self.height, pixels, meta
python
def read(self, lenient=False): """ Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. If the optional `lenient` argument evaluates to True, checksum failures will raise warnings rather than exceptions. """ def iteridat(): """Iterator that yields all the ``IDAT`` chunks as strings.""" while True: try: type, data = self.chunk(lenient=lenient) except ValueError as e: raise ChunkError(e.args[0]) if type == 'IEND': # http://www.w3.org/TR/PNG/#11IEND break if type != 'IDAT': continue # type == 'IDAT' # http://www.w3.org/TR/PNG/#11IDAT if self.colormap and not self.plte: warnings.warn("PLTE chunk is required before IDAT chunk") yield data def iterdecomp(idat): """Iterator that yields decompressed strings. `idat` should be an iterator that yields the ``IDAT`` chunk data. """ # Currently, with no max_length parameter to decompress, # this routine will do one yield per IDAT chunk: Not very # incremental. d = zlib.decompressobj() # Each IDAT chunk is passed to the decompressor, then any # remaining state is decompressed out. for data in idat: # :todo: add a max_length argument here to limit output # size. yield array('B', d.decompress(data)) yield array('B', d.flush()) self.preamble(lenient=lenient) raw = iterdecomp(iteridat()) if self.interlace: raw = array('B', itertools.chain(*raw)) arraycode = 'BH'[self.bitdepth>8] # Like :meth:`group` but producing an array.array object for # each row. pixels = imap(lambda *row: array(arraycode, row), *[iter(self.deinterlace(raw))]*self.width*self.planes) else: pixels = self.iterboxed(self.iterstraight(raw)) meta = dict() for attr in 'greyscale alpha planes bitdepth interlace'.split(): meta[attr] = getattr(self, attr) meta['size'] = (self.width, self.height) for attr in 'gamma transparent background'.split(): a = getattr(self, attr, None) if a is not None: meta[attr] = a if self.plte: meta['palette'] = self.palette() return self.width, self.height, pixels, meta
[ "def", "read", "(", "self", ",", "lenient", "=", "False", ")", ":", "def", "iteridat", "(", ")", ":", "\"\"\"Iterator that yields all the ``IDAT`` chunks as strings.\"\"\"", "while", "True", ":", "try", ":", "type", ",", "data", "=", "self", ".", "chunk", "(", "lenient", "=", "lenient", ")", "except", "ValueError", "as", "e", ":", "raise", "ChunkError", "(", "e", ".", "args", "[", "0", "]", ")", "if", "type", "==", "'IEND'", ":", "# http://www.w3.org/TR/PNG/#11IEND", "break", "if", "type", "!=", "'IDAT'", ":", "continue", "# type == 'IDAT'", "# http://www.w3.org/TR/PNG/#11IDAT", "if", "self", ".", "colormap", "and", "not", "self", ".", "plte", ":", "warnings", ".", "warn", "(", "\"PLTE chunk is required before IDAT chunk\"", ")", "yield", "data", "def", "iterdecomp", "(", "idat", ")", ":", "\"\"\"Iterator that yields decompressed strings. `idat` should\n be an iterator that yields the ``IDAT`` chunk data.\n \"\"\"", "# Currently, with no max_length parameter to decompress,", "# this routine will do one yield per IDAT chunk: Not very", "# incremental.", "d", "=", "zlib", ".", "decompressobj", "(", ")", "# Each IDAT chunk is passed to the decompressor, then any", "# remaining state is decompressed out.", "for", "data", "in", "idat", ":", "# :todo: add a max_length argument here to limit output", "# size.", "yield", "array", "(", "'B'", ",", "d", ".", "decompress", "(", "data", ")", ")", "yield", "array", "(", "'B'", ",", "d", ".", "flush", "(", ")", ")", "self", ".", "preamble", "(", "lenient", "=", "lenient", ")", "raw", "=", "iterdecomp", "(", "iteridat", "(", ")", ")", "if", "self", ".", "interlace", ":", "raw", "=", "array", "(", "'B'", ",", "itertools", ".", "chain", "(", "*", "raw", ")", ")", "arraycode", "=", "'BH'", "[", "self", ".", "bitdepth", ">", "8", "]", "# Like :meth:`group` but producing an array.array object for", "# each row.", "pixels", "=", "imap", "(", "lambda", "*", "row", ":", "array", "(", "arraycode", ",", "row", ")", ",", "*", "[", "iter", "(", "self", ".", "deinterlace", "(", "raw", ")", ")", "]", "*", "self", ".", "width", "*", "self", ".", "planes", ")", "else", ":", "pixels", "=", "self", ".", "iterboxed", "(", "self", ".", "iterstraight", "(", "raw", ")", ")", "meta", "=", "dict", "(", ")", "for", "attr", "in", "'greyscale alpha planes bitdepth interlace'", ".", "split", "(", ")", ":", "meta", "[", "attr", "]", "=", "getattr", "(", "self", ",", "attr", ")", "meta", "[", "'size'", "]", "=", "(", "self", ".", "width", ",", "self", ".", "height", ")", "for", "attr", "in", "'gamma transparent background'", ".", "split", "(", ")", ":", "a", "=", "getattr", "(", "self", ",", "attr", ",", "None", ")", "if", "a", "is", "not", "None", ":", "meta", "[", "attr", "]", "=", "a", "if", "self", ".", "plte", ":", "meta", "[", "'palette'", "]", "=", "self", ".", "palette", "(", ")", "return", "self", ".", "width", ",", "self", ".", "height", ",", "pixels", ",", "meta" ]
Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. If the optional `lenient` argument evaluates to True, checksum failures will raise warnings rather than exceptions.
[ "Read", "the", "PNG", "file", "and", "decode", "it", ".", "Returns", "(", "width", "height", "pixels", "metadata", ")", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1735-L1805
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.palette
def palette(self, alpha='natural'): """Returns a palette that is a sequence of 3-tuples or 4-tuples, synthesizing it from the ``PLTE`` and ``tRNS`` chunks. These chunks should have already been processed (for example, by calling the :meth:`preamble` method). All the tuples are the same size: 3-tuples if there is no ``tRNS`` chunk, 4-tuples when there is a ``tRNS`` chunk. Assumes that the image is colour type 3 and therefore a ``PLTE`` chunk is required. If the `alpha` argument is ``'force'`` then an alpha channel is always added, forcing the result to be a sequence of 4-tuples. """ if not self.plte: raise FormatError( "Required PLTE chunk is missing in colour type 3 image.") plte = group(array('B', self.plte), 3) if self.trns or alpha == 'force': trns = array('B', self.trns or '') trns.extend([255]*(len(plte)-len(trns))) plte = map(operator.add, plte, group(trns, 1)) return plte
python
def palette(self, alpha='natural'): """Returns a palette that is a sequence of 3-tuples or 4-tuples, synthesizing it from the ``PLTE`` and ``tRNS`` chunks. These chunks should have already been processed (for example, by calling the :meth:`preamble` method). All the tuples are the same size: 3-tuples if there is no ``tRNS`` chunk, 4-tuples when there is a ``tRNS`` chunk. Assumes that the image is colour type 3 and therefore a ``PLTE`` chunk is required. If the `alpha` argument is ``'force'`` then an alpha channel is always added, forcing the result to be a sequence of 4-tuples. """ if not self.plte: raise FormatError( "Required PLTE chunk is missing in colour type 3 image.") plte = group(array('B', self.plte), 3) if self.trns or alpha == 'force': trns = array('B', self.trns or '') trns.extend([255]*(len(plte)-len(trns))) plte = map(operator.add, plte, group(trns, 1)) return plte
[ "def", "palette", "(", "self", ",", "alpha", "=", "'natural'", ")", ":", "if", "not", "self", ".", "plte", ":", "raise", "FormatError", "(", "\"Required PLTE chunk is missing in colour type 3 image.\"", ")", "plte", "=", "group", "(", "array", "(", "'B'", ",", "self", ".", "plte", ")", ",", "3", ")", "if", "self", ".", "trns", "or", "alpha", "==", "'force'", ":", "trns", "=", "array", "(", "'B'", ",", "self", ".", "trns", "or", "''", ")", "trns", ".", "extend", "(", "[", "255", "]", "*", "(", "len", "(", "plte", ")", "-", "len", "(", "trns", ")", ")", ")", "plte", "=", "map", "(", "operator", ".", "add", ",", "plte", ",", "group", "(", "trns", ",", "1", ")", ")", "return", "plte" ]
Returns a palette that is a sequence of 3-tuples or 4-tuples, synthesizing it from the ``PLTE`` and ``tRNS`` chunks. These chunks should have already been processed (for example, by calling the :meth:`preamble` method). All the tuples are the same size: 3-tuples if there is no ``tRNS`` chunk, 4-tuples when there is a ``tRNS`` chunk. Assumes that the image is colour type 3 and therefore a ``PLTE`` chunk is required. If the `alpha` argument is ``'force'`` then an alpha channel is always added, forcing the result to be a sequence of 4-tuples.
[ "Returns", "a", "palette", "that", "is", "a", "sequence", "of", "3", "-", "tuples", "or", "4", "-", "tuples", "synthesizing", "it", "from", "the", "PLTE", "and", "tRNS", "chunks", ".", "These", "chunks", "should", "have", "already", "been", "processed", "(", "for", "example", "by", "calling", "the", ":", "meth", ":", "preamble", "method", ")", ".", "All", "the", "tuples", "are", "the", "same", "size", ":", "3", "-", "tuples", "if", "there", "is", "no", "tRNS", "chunk", "4", "-", "tuples", "when", "there", "is", "a", "tRNS", "chunk", ".", "Assumes", "that", "the", "image", "is", "colour", "type", "3", "and", "therefore", "a", "PLTE", "chunk", "is", "required", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1826-L1847
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.asDirect
def asDirect(self): """Returns the image data as a direct representation of an ``x * y * planes`` array. This method is intended to remove the need for callers to deal with palettes and transparency themselves. Images with a palette (colour type 3) are converted to RGB or RGBA; images with transparency (a ``tRNS`` chunk) are converted to LA or RGBA as appropriate. When returned in this format the pixel values represent the colour value directly without needing to refer to palettes or transparency information. Like the :meth:`read` method this method returns a 4-tuple: (*width*, *height*, *pixels*, *meta*) This method normally returns pixel values with the bit depth they have in the source image, but when the source PNG has an ``sBIT`` chunk it is inspected and can reduce the bit depth of the result pixels; pixel values will be reduced according to the bit depth specified in the ``sBIT`` chunk (PNG nerds should note a single result bit depth is used for all channels; the maximum of the ones specified in the ``sBIT`` chunk. An RGB565 image will be rescaled to 6-bit RGB666). The *meta* dictionary that is returned reflects the `direct` format and not the original source image. For example, an RGB source image with a ``tRNS`` chunk to represent a transparent colour, will have ``planes=3`` and ``alpha=False`` for the source image, but the *meta* dictionary returned by this method will have ``planes=4`` and ``alpha=True`` because an alpha channel is synthesized and added. *pixels* is the pixel data in boxed row flat pixel format (just like the :meth:`read` method). All the other aspects of the image data are not changed. """ self.preamble() # Simple case, no conversion necessary. if not self.colormap and not self.trns and not self.sbit: return self.read() x,y,pixels,meta = self.read() if self.colormap: meta['colormap'] = False meta['alpha'] = bool(self.trns) meta['bitdepth'] = 8 meta['planes'] = 3 + bool(self.trns) plte = self.palette() def iterpal(pixels): for row in pixels: row = map(plte.__getitem__, row) yield array('B', itertools.chain(*row)) pixels = iterpal(pixels) elif self.trns: # It would be nice if there was some reasonable way # of doing this without generating a whole load of # intermediate tuples. But tuples does seem like the # easiest way, with no other way clearly much simpler or # much faster. (Actually, the L to LA conversion could # perhaps go faster (all those 1-tuples!), but I still # wonder whether the code proliferation is worth it) it = self.transparent maxval = 2**meta['bitdepth']-1 planes = meta['planes'] meta['alpha'] = True meta['planes'] += 1 typecode = 'BH'[meta['bitdepth']>8] def itertrns(pixels): for row in pixels: # For each row we group it into pixels, then form a # characterisation vector that says whether each # pixel is opaque or not. Then we convert # True/False to 0/maxval (by multiplication), # and add it as the extra channel. row = group(row, planes) opa = map(it.__ne__, row) opa = map(maxval.__mul__, opa) opa = zip(opa) # convert to 1-tuples yield array(typecode, itertools.chain(*map(operator.add, row, opa))) pixels = itertrns(pixels) targetbitdepth = None if self.sbit: sbit = struct.unpack('%dB' % len(self.sbit), self.sbit) targetbitdepth = max(sbit) if targetbitdepth > meta['bitdepth']: raise Error('sBIT chunk %r exceeds bitdepth %d' % (sbit,self.bitdepth)) if min(sbit) <= 0: raise Error('sBIT chunk %r has a 0-entry' % sbit) if targetbitdepth == meta['bitdepth']: targetbitdepth = None if targetbitdepth: shift = meta['bitdepth'] - targetbitdepth meta['bitdepth'] = targetbitdepth def itershift(pixels): for row in pixels: yield map(shift.__rrshift__, row) pixels = itershift(pixels) return x,y,pixels,meta
python
def asDirect(self): """Returns the image data as a direct representation of an ``x * y * planes`` array. This method is intended to remove the need for callers to deal with palettes and transparency themselves. Images with a palette (colour type 3) are converted to RGB or RGBA; images with transparency (a ``tRNS`` chunk) are converted to LA or RGBA as appropriate. When returned in this format the pixel values represent the colour value directly without needing to refer to palettes or transparency information. Like the :meth:`read` method this method returns a 4-tuple: (*width*, *height*, *pixels*, *meta*) This method normally returns pixel values with the bit depth they have in the source image, but when the source PNG has an ``sBIT`` chunk it is inspected and can reduce the bit depth of the result pixels; pixel values will be reduced according to the bit depth specified in the ``sBIT`` chunk (PNG nerds should note a single result bit depth is used for all channels; the maximum of the ones specified in the ``sBIT`` chunk. An RGB565 image will be rescaled to 6-bit RGB666). The *meta* dictionary that is returned reflects the `direct` format and not the original source image. For example, an RGB source image with a ``tRNS`` chunk to represent a transparent colour, will have ``planes=3`` and ``alpha=False`` for the source image, but the *meta* dictionary returned by this method will have ``planes=4`` and ``alpha=True`` because an alpha channel is synthesized and added. *pixels* is the pixel data in boxed row flat pixel format (just like the :meth:`read` method). All the other aspects of the image data are not changed. """ self.preamble() # Simple case, no conversion necessary. if not self.colormap and not self.trns and not self.sbit: return self.read() x,y,pixels,meta = self.read() if self.colormap: meta['colormap'] = False meta['alpha'] = bool(self.trns) meta['bitdepth'] = 8 meta['planes'] = 3 + bool(self.trns) plte = self.palette() def iterpal(pixels): for row in pixels: row = map(plte.__getitem__, row) yield array('B', itertools.chain(*row)) pixels = iterpal(pixels) elif self.trns: # It would be nice if there was some reasonable way # of doing this without generating a whole load of # intermediate tuples. But tuples does seem like the # easiest way, with no other way clearly much simpler or # much faster. (Actually, the L to LA conversion could # perhaps go faster (all those 1-tuples!), but I still # wonder whether the code proliferation is worth it) it = self.transparent maxval = 2**meta['bitdepth']-1 planes = meta['planes'] meta['alpha'] = True meta['planes'] += 1 typecode = 'BH'[meta['bitdepth']>8] def itertrns(pixels): for row in pixels: # For each row we group it into pixels, then form a # characterisation vector that says whether each # pixel is opaque or not. Then we convert # True/False to 0/maxval (by multiplication), # and add it as the extra channel. row = group(row, planes) opa = map(it.__ne__, row) opa = map(maxval.__mul__, opa) opa = zip(opa) # convert to 1-tuples yield array(typecode, itertools.chain(*map(operator.add, row, opa))) pixels = itertrns(pixels) targetbitdepth = None if self.sbit: sbit = struct.unpack('%dB' % len(self.sbit), self.sbit) targetbitdepth = max(sbit) if targetbitdepth > meta['bitdepth']: raise Error('sBIT chunk %r exceeds bitdepth %d' % (sbit,self.bitdepth)) if min(sbit) <= 0: raise Error('sBIT chunk %r has a 0-entry' % sbit) if targetbitdepth == meta['bitdepth']: targetbitdepth = None if targetbitdepth: shift = meta['bitdepth'] - targetbitdepth meta['bitdepth'] = targetbitdepth def itershift(pixels): for row in pixels: yield map(shift.__rrshift__, row) pixels = itershift(pixels) return x,y,pixels,meta
[ "def", "asDirect", "(", "self", ")", ":", "self", ".", "preamble", "(", ")", "# Simple case, no conversion necessary.", "if", "not", "self", ".", "colormap", "and", "not", "self", ".", "trns", "and", "not", "self", ".", "sbit", ":", "return", "self", ".", "read", "(", ")", "x", ",", "y", ",", "pixels", ",", "meta", "=", "self", ".", "read", "(", ")", "if", "self", ".", "colormap", ":", "meta", "[", "'colormap'", "]", "=", "False", "meta", "[", "'alpha'", "]", "=", "bool", "(", "self", ".", "trns", ")", "meta", "[", "'bitdepth'", "]", "=", "8", "meta", "[", "'planes'", "]", "=", "3", "+", "bool", "(", "self", ".", "trns", ")", "plte", "=", "self", ".", "palette", "(", ")", "def", "iterpal", "(", "pixels", ")", ":", "for", "row", "in", "pixels", ":", "row", "=", "map", "(", "plte", ".", "__getitem__", ",", "row", ")", "yield", "array", "(", "'B'", ",", "itertools", ".", "chain", "(", "*", "row", ")", ")", "pixels", "=", "iterpal", "(", "pixels", ")", "elif", "self", ".", "trns", ":", "# It would be nice if there was some reasonable way", "# of doing this without generating a whole load of", "# intermediate tuples. But tuples does seem like the", "# easiest way, with no other way clearly much simpler or", "# much faster. (Actually, the L to LA conversion could", "# perhaps go faster (all those 1-tuples!), but I still", "# wonder whether the code proliferation is worth it)", "it", "=", "self", ".", "transparent", "maxval", "=", "2", "**", "meta", "[", "'bitdepth'", "]", "-", "1", "planes", "=", "meta", "[", "'planes'", "]", "meta", "[", "'alpha'", "]", "=", "True", "meta", "[", "'planes'", "]", "+=", "1", "typecode", "=", "'BH'", "[", "meta", "[", "'bitdepth'", "]", ">", "8", "]", "def", "itertrns", "(", "pixels", ")", ":", "for", "row", "in", "pixels", ":", "# For each row we group it into pixels, then form a", "# characterisation vector that says whether each", "# pixel is opaque or not. Then we convert", "# True/False to 0/maxval (by multiplication),", "# and add it as the extra channel.", "row", "=", "group", "(", "row", ",", "planes", ")", "opa", "=", "map", "(", "it", ".", "__ne__", ",", "row", ")", "opa", "=", "map", "(", "maxval", ".", "__mul__", ",", "opa", ")", "opa", "=", "zip", "(", "opa", ")", "# convert to 1-tuples", "yield", "array", "(", "typecode", ",", "itertools", ".", "chain", "(", "*", "map", "(", "operator", ".", "add", ",", "row", ",", "opa", ")", ")", ")", "pixels", "=", "itertrns", "(", "pixels", ")", "targetbitdepth", "=", "None", "if", "self", ".", "sbit", ":", "sbit", "=", "struct", ".", "unpack", "(", "'%dB'", "%", "len", "(", "self", ".", "sbit", ")", ",", "self", ".", "sbit", ")", "targetbitdepth", "=", "max", "(", "sbit", ")", "if", "targetbitdepth", ">", "meta", "[", "'bitdepth'", "]", ":", "raise", "Error", "(", "'sBIT chunk %r exceeds bitdepth %d'", "%", "(", "sbit", ",", "self", ".", "bitdepth", ")", ")", "if", "min", "(", "sbit", ")", "<=", "0", ":", "raise", "Error", "(", "'sBIT chunk %r has a 0-entry'", "%", "sbit", ")", "if", "targetbitdepth", "==", "meta", "[", "'bitdepth'", "]", ":", "targetbitdepth", "=", "None", "if", "targetbitdepth", ":", "shift", "=", "meta", "[", "'bitdepth'", "]", "-", "targetbitdepth", "meta", "[", "'bitdepth'", "]", "=", "targetbitdepth", "def", "itershift", "(", "pixels", ")", ":", "for", "row", "in", "pixels", ":", "yield", "map", "(", "shift", ".", "__rrshift__", ",", "row", ")", "pixels", "=", "itershift", "(", "pixels", ")", "return", "x", ",", "y", ",", "pixels", ",", "meta" ]
Returns the image data as a direct representation of an ``x * y * planes`` array. This method is intended to remove the need for callers to deal with palettes and transparency themselves. Images with a palette (colour type 3) are converted to RGB or RGBA; images with transparency (a ``tRNS`` chunk) are converted to LA or RGBA as appropriate. When returned in this format the pixel values represent the colour value directly without needing to refer to palettes or transparency information. Like the :meth:`read` method this method returns a 4-tuple: (*width*, *height*, *pixels*, *meta*) This method normally returns pixel values with the bit depth they have in the source image, but when the source PNG has an ``sBIT`` chunk it is inspected and can reduce the bit depth of the result pixels; pixel values will be reduced according to the bit depth specified in the ``sBIT`` chunk (PNG nerds should note a single result bit depth is used for all channels; the maximum of the ones specified in the ``sBIT`` chunk. An RGB565 image will be rescaled to 6-bit RGB666). The *meta* dictionary that is returned reflects the `direct` format and not the original source image. For example, an RGB source image with a ``tRNS`` chunk to represent a transparent colour, will have ``planes=3`` and ``alpha=False`` for the source image, but the *meta* dictionary returned by this method will have ``planes=4`` and ``alpha=True`` because an alpha channel is synthesized and added. *pixels* is the pixel data in boxed row flat pixel format (just like the :meth:`read` method). All the other aspects of the image data are not changed.
[ "Returns", "the", "image", "data", "as", "a", "direct", "representation", "of", "an", "x", "*", "y", "*", "planes", "array", ".", "This", "method", "is", "intended", "to", "remove", "the", "need", "for", "callers", "to", "deal", "with", "palettes", "and", "transparency", "themselves", ".", "Images", "with", "a", "palette", "(", "colour", "type", "3", ")", "are", "converted", "to", "RGB", "or", "RGBA", ";", "images", "with", "transparency", "(", "a", "tRNS", "chunk", ")", "are", "converted", "to", "LA", "or", "RGBA", "as", "appropriate", ".", "When", "returned", "in", "this", "format", "the", "pixel", "values", "represent", "the", "colour", "value", "directly", "without", "needing", "to", "refer", "to", "palettes", "or", "transparency", "information", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1849-L1952
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.asFloat
def asFloat(self, maxval=1.0): """Return image pixels as per :meth:`asDirect` method, but scale all pixel values to be floating point values between 0.0 and *maxval*. """ x,y,pixels,info = self.asDirect() sourcemaxval = 2**info['bitdepth']-1 del info['bitdepth'] info['maxval'] = float(maxval) factor = float(maxval)/float(sourcemaxval) def iterfloat(): for row in pixels: yield map(factor.__mul__, row) return x,y,iterfloat(),info
python
def asFloat(self, maxval=1.0): """Return image pixels as per :meth:`asDirect` method, but scale all pixel values to be floating point values between 0.0 and *maxval*. """ x,y,pixels,info = self.asDirect() sourcemaxval = 2**info['bitdepth']-1 del info['bitdepth'] info['maxval'] = float(maxval) factor = float(maxval)/float(sourcemaxval) def iterfloat(): for row in pixels: yield map(factor.__mul__, row) return x,y,iterfloat(),info
[ "def", "asFloat", "(", "self", ",", "maxval", "=", "1.0", ")", ":", "x", ",", "y", ",", "pixels", ",", "info", "=", "self", ".", "asDirect", "(", ")", "sourcemaxval", "=", "2", "**", "info", "[", "'bitdepth'", "]", "-", "1", "del", "info", "[", "'bitdepth'", "]", "info", "[", "'maxval'", "]", "=", "float", "(", "maxval", ")", "factor", "=", "float", "(", "maxval", ")", "/", "float", "(", "sourcemaxval", ")", "def", "iterfloat", "(", ")", ":", "for", "row", "in", "pixels", ":", "yield", "map", "(", "factor", ".", "__mul__", ",", "row", ")", "return", "x", ",", "y", ",", "iterfloat", "(", ")", ",", "info" ]
Return image pixels as per :meth:`asDirect` method, but scale all pixel values to be floating point values between 0.0 and *maxval*.
[ "Return", "image", "pixels", "as", "per", ":", "meth", ":", "asDirect", "method", "but", "scale", "all", "pixel", "values", "to", "be", "floating", "point", "values", "between", "0", ".", "0", "and", "*", "maxval", "*", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1954-L1968
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader._as_rescale
def _as_rescale(self, get, targetbitdepth): """Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.""" width,height,pixels,meta = get() maxval = 2**meta['bitdepth'] - 1 targetmaxval = 2**targetbitdepth - 1 factor = float(targetmaxval) / float(maxval) meta['bitdepth'] = targetbitdepth def iterscale(): for row in pixels: yield map(lambda x: int(round(x*factor)), row) if maxval == targetmaxval: return width, height, pixels, meta else: return width, height, iterscale(), meta
python
def _as_rescale(self, get, targetbitdepth): """Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.""" width,height,pixels,meta = get() maxval = 2**meta['bitdepth'] - 1 targetmaxval = 2**targetbitdepth - 1 factor = float(targetmaxval) / float(maxval) meta['bitdepth'] = targetbitdepth def iterscale(): for row in pixels: yield map(lambda x: int(round(x*factor)), row) if maxval == targetmaxval: return width, height, pixels, meta else: return width, height, iterscale(), meta
[ "def", "_as_rescale", "(", "self", ",", "get", ",", "targetbitdepth", ")", ":", "width", ",", "height", ",", "pixels", ",", "meta", "=", "get", "(", ")", "maxval", "=", "2", "**", "meta", "[", "'bitdepth'", "]", "-", "1", "targetmaxval", "=", "2", "**", "targetbitdepth", "-", "1", "factor", "=", "float", "(", "targetmaxval", ")", "/", "float", "(", "maxval", ")", "meta", "[", "'bitdepth'", "]", "=", "targetbitdepth", "def", "iterscale", "(", ")", ":", "for", "row", "in", "pixels", ":", "yield", "map", "(", "lambda", "x", ":", "int", "(", "round", "(", "x", "*", "factor", ")", ")", ",", "row", ")", "if", "maxval", "==", "targetmaxval", ":", "return", "width", ",", "height", ",", "pixels", ",", "meta", "else", ":", "return", "width", ",", "height", ",", "iterscale", "(", ")", ",", "meta" ]
Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.
[ "Helper", "used", "by", ":", "meth", ":", "asRGB8", "and", ":", "meth", ":", "asRGBA8", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L1970-L1984
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.asRGB
def asRGB(self): """Return image as RGB pixels. RGB colour images are passed through unchanged; greyscales are expanded into RGB triplets (there is a small speed overhead for doing this). An alpha channel in the source image will raise an exception. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In particular, for this method ``metadata['greyscale']`` will be ``False``. """ width,height,pixels,meta = self.asDirect() if meta['alpha']: raise Error("will not convert image with alpha channel to RGB") if not meta['greyscale']: return width,height,pixels,meta meta['greyscale'] = False typecode = 'BH'[meta['bitdepth'] > 8] def iterrgb(): for row in pixels: a = array(typecode, [0]) * 3 * width for i in range(3): a[i::3] = row yield a return width,height,iterrgb(),meta
python
def asRGB(self): """Return image as RGB pixels. RGB colour images are passed through unchanged; greyscales are expanded into RGB triplets (there is a small speed overhead for doing this). An alpha channel in the source image will raise an exception. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In particular, for this method ``metadata['greyscale']`` will be ``False``. """ width,height,pixels,meta = self.asDirect() if meta['alpha']: raise Error("will not convert image with alpha channel to RGB") if not meta['greyscale']: return width,height,pixels,meta meta['greyscale'] = False typecode = 'BH'[meta['bitdepth'] > 8] def iterrgb(): for row in pixels: a = array(typecode, [0]) * 3 * width for i in range(3): a[i::3] = row yield a return width,height,iterrgb(),meta
[ "def", "asRGB", "(", "self", ")", ":", "width", ",", "height", ",", "pixels", ",", "meta", "=", "self", ".", "asDirect", "(", ")", "if", "meta", "[", "'alpha'", "]", ":", "raise", "Error", "(", "\"will not convert image with alpha channel to RGB\"", ")", "if", "not", "meta", "[", "'greyscale'", "]", ":", "return", "width", ",", "height", ",", "pixels", ",", "meta", "meta", "[", "'greyscale'", "]", "=", "False", "typecode", "=", "'BH'", "[", "meta", "[", "'bitdepth'", "]", ">", "8", "]", "def", "iterrgb", "(", ")", ":", "for", "row", "in", "pixels", ":", "a", "=", "array", "(", "typecode", ",", "[", "0", "]", ")", "*", "3", "*", "width", "for", "i", "in", "range", "(", "3", ")", ":", "a", "[", "i", ":", ":", "3", "]", "=", "row", "yield", "a", "return", "width", ",", "height", ",", "iterrgb", "(", ")", ",", "meta" ]
Return image as RGB pixels. RGB colour images are passed through unchanged; greyscales are expanded into RGB triplets (there is a small speed overhead for doing this). An alpha channel in the source image will raise an exception. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In particular, for this method ``metadata['greyscale']`` will be ``False``.
[ "Return", "image", "as", "RGB", "pixels", ".", "RGB", "colour", "images", "are", "passed", "through", "unchanged", ";", "greyscales", "are", "expanded", "into", "RGB", "triplets", "(", "there", "is", "a", "small", "speed", "overhead", "for", "doing", "this", ")", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L2017-L2044
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/png.py
Reader.asRGBA
def asRGBA(self): """Return image as RGBA pixels. Greyscales are expanded into RGB triplets; an alpha channel is synthesized if necessary. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In particular, for this method ``metadata['greyscale']`` will be ``False``, and ``metadata['alpha']`` will be ``True``. """ width,height,pixels,meta = self.asDirect() if meta['alpha'] and not meta['greyscale']: return width,height,pixels,meta typecode = 'BH'[meta['bitdepth'] > 8] maxval = 2**meta['bitdepth'] - 1 maxbuffer = struct.pack('=' + typecode, maxval) * 4 * width def newarray(): return array(typecode, maxbuffer) if meta['alpha'] and meta['greyscale']: # LA to RGBA def convert(): for row in pixels: # Create a fresh target row, then copy L channel # into first three target channels, and A channel # into fourth channel. a = newarray() pngfilters.convert_la_to_rgba(row, a) yield a elif meta['greyscale']: # L to RGBA def convert(): for row in pixels: a = newarray() pngfilters.convert_l_to_rgba(row, a) yield a else: assert not meta['alpha'] and not meta['greyscale'] # RGB to RGBA def convert(): for row in pixels: a = newarray() pngfilters.convert_rgb_to_rgba(row, a) yield a meta['alpha'] = True meta['greyscale'] = False return width,height,convert(),meta
python
def asRGBA(self): """Return image as RGBA pixels. Greyscales are expanded into RGB triplets; an alpha channel is synthesized if necessary. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In particular, for this method ``metadata['greyscale']`` will be ``False``, and ``metadata['alpha']`` will be ``True``. """ width,height,pixels,meta = self.asDirect() if meta['alpha'] and not meta['greyscale']: return width,height,pixels,meta typecode = 'BH'[meta['bitdepth'] > 8] maxval = 2**meta['bitdepth'] - 1 maxbuffer = struct.pack('=' + typecode, maxval) * 4 * width def newarray(): return array(typecode, maxbuffer) if meta['alpha'] and meta['greyscale']: # LA to RGBA def convert(): for row in pixels: # Create a fresh target row, then copy L channel # into first three target channels, and A channel # into fourth channel. a = newarray() pngfilters.convert_la_to_rgba(row, a) yield a elif meta['greyscale']: # L to RGBA def convert(): for row in pixels: a = newarray() pngfilters.convert_l_to_rgba(row, a) yield a else: assert not meta['alpha'] and not meta['greyscale'] # RGB to RGBA def convert(): for row in pixels: a = newarray() pngfilters.convert_rgb_to_rgba(row, a) yield a meta['alpha'] = True meta['greyscale'] = False return width,height,convert(),meta
[ "def", "asRGBA", "(", "self", ")", ":", "width", ",", "height", ",", "pixels", ",", "meta", "=", "self", ".", "asDirect", "(", ")", "if", "meta", "[", "'alpha'", "]", "and", "not", "meta", "[", "'greyscale'", "]", ":", "return", "width", ",", "height", ",", "pixels", ",", "meta", "typecode", "=", "'BH'", "[", "meta", "[", "'bitdepth'", "]", ">", "8", "]", "maxval", "=", "2", "**", "meta", "[", "'bitdepth'", "]", "-", "1", "maxbuffer", "=", "struct", ".", "pack", "(", "'='", "+", "typecode", ",", "maxval", ")", "*", "4", "*", "width", "def", "newarray", "(", ")", ":", "return", "array", "(", "typecode", ",", "maxbuffer", ")", "if", "meta", "[", "'alpha'", "]", "and", "meta", "[", "'greyscale'", "]", ":", "# LA to RGBA", "def", "convert", "(", ")", ":", "for", "row", "in", "pixels", ":", "# Create a fresh target row, then copy L channel", "# into first three target channels, and A channel", "# into fourth channel.", "a", "=", "newarray", "(", ")", "pngfilters", ".", "convert_la_to_rgba", "(", "row", ",", "a", ")", "yield", "a", "elif", "meta", "[", "'greyscale'", "]", ":", "# L to RGBA", "def", "convert", "(", ")", ":", "for", "row", "in", "pixels", ":", "a", "=", "newarray", "(", ")", "pngfilters", ".", "convert_l_to_rgba", "(", "row", ",", "a", ")", "yield", "a", "else", ":", "assert", "not", "meta", "[", "'alpha'", "]", "and", "not", "meta", "[", "'greyscale'", "]", "# RGB to RGBA", "def", "convert", "(", ")", ":", "for", "row", "in", "pixels", ":", "a", "=", "newarray", "(", ")", "pngfilters", ".", "convert_rgb_to_rgba", "(", "row", ",", "a", ")", "yield", "a", "meta", "[", "'alpha'", "]", "=", "True", "meta", "[", "'greyscale'", "]", "=", "False", "return", "width", ",", "height", ",", "convert", "(", ")", ",", "meta" ]
Return image as RGBA pixels. Greyscales are expanded into RGB triplets; an alpha channel is synthesized if necessary. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In particular, for this method ``metadata['greyscale']`` will be ``False``, and ``metadata['alpha']`` will be ``True``.
[ "Return", "image", "as", "RGBA", "pixels", ".", "Greyscales", "are", "expanded", "into", "RGB", "triplets", ";", "an", "alpha", "channel", "is", "synthesized", "if", "necessary", ".", "The", "return", "values", "are", "as", "for", "the", ":", "meth", ":", "read", "method", "except", "that", "the", "*", "metadata", "*", "reflect", "the", "returned", "pixels", "not", "the", "source", "image", ".", "In", "particular", "for", "this", "method", "metadata", "[", "greyscale", "]", "will", "be", "False", "and", "metadata", "[", "alpha", "]", "will", "be", "True", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/png.py#L2046-L2092
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/fetching.py
load_data_file
def load_data_file(fname, directory=None, force_download=False): """Get a standard vispy demo data file Parameters ---------- fname : str The filename on the remote ``demo-data`` repository to download, e.g. ``'molecular_viewer/micelle.npy'``. These correspond to paths on ``https://github.com/vispy/demo-data/``. directory : str | None Directory to use to save the file. By default, the vispy configuration directory is used. force_download : bool | str If True, the file will be downloaded even if a local copy exists (and this copy will be overwritten). Can also be a YYYY-MM-DD date to ensure a file is up-to-date (modified date of a file on disk, if present, is checked). Returns ------- fname : str The path to the file on the local system. """ _url_root = 'http://github.com/vispy/demo-data/raw/master/' url = _url_root + fname if directory is None: directory = config['data_path'] if directory is None: raise ValueError('config["data_path"] is not defined, ' 'so directory must be supplied') fname = op.join(directory, op.normcase(fname)) # convert to native if op.isfile(fname): if not force_download: # we're done return fname if isinstance(force_download, string_types): ntime = time.strptime(force_download, '%Y-%m-%d') ftime = time.gmtime(op.getctime(fname)) if ftime >= ntime: return fname else: print('File older than %s, updating...' % force_download) if not op.isdir(op.dirname(fname)): os.makedirs(op.abspath(op.dirname(fname))) # let's go get the file _fetch_file(url, fname) return fname
python
def load_data_file(fname, directory=None, force_download=False): """Get a standard vispy demo data file Parameters ---------- fname : str The filename on the remote ``demo-data`` repository to download, e.g. ``'molecular_viewer/micelle.npy'``. These correspond to paths on ``https://github.com/vispy/demo-data/``. directory : str | None Directory to use to save the file. By default, the vispy configuration directory is used. force_download : bool | str If True, the file will be downloaded even if a local copy exists (and this copy will be overwritten). Can also be a YYYY-MM-DD date to ensure a file is up-to-date (modified date of a file on disk, if present, is checked). Returns ------- fname : str The path to the file on the local system. """ _url_root = 'http://github.com/vispy/demo-data/raw/master/' url = _url_root + fname if directory is None: directory = config['data_path'] if directory is None: raise ValueError('config["data_path"] is not defined, ' 'so directory must be supplied') fname = op.join(directory, op.normcase(fname)) # convert to native if op.isfile(fname): if not force_download: # we're done return fname if isinstance(force_download, string_types): ntime = time.strptime(force_download, '%Y-%m-%d') ftime = time.gmtime(op.getctime(fname)) if ftime >= ntime: return fname else: print('File older than %s, updating...' % force_download) if not op.isdir(op.dirname(fname)): os.makedirs(op.abspath(op.dirname(fname))) # let's go get the file _fetch_file(url, fname) return fname
[ "def", "load_data_file", "(", "fname", ",", "directory", "=", "None", ",", "force_download", "=", "False", ")", ":", "_url_root", "=", "'http://github.com/vispy/demo-data/raw/master/'", "url", "=", "_url_root", "+", "fname", "if", "directory", "is", "None", ":", "directory", "=", "config", "[", "'data_path'", "]", "if", "directory", "is", "None", ":", "raise", "ValueError", "(", "'config[\"data_path\"] is not defined, '", "'so directory must be supplied'", ")", "fname", "=", "op", ".", "join", "(", "directory", ",", "op", ".", "normcase", "(", "fname", ")", ")", "# convert to native", "if", "op", ".", "isfile", "(", "fname", ")", ":", "if", "not", "force_download", ":", "# we're done", "return", "fname", "if", "isinstance", "(", "force_download", ",", "string_types", ")", ":", "ntime", "=", "time", ".", "strptime", "(", "force_download", ",", "'%Y-%m-%d'", ")", "ftime", "=", "time", ".", "gmtime", "(", "op", ".", "getctime", "(", "fname", ")", ")", "if", "ftime", ">=", "ntime", ":", "return", "fname", "else", ":", "print", "(", "'File older than %s, updating...'", "%", "force_download", ")", "if", "not", "op", ".", "isdir", "(", "op", ".", "dirname", "(", "fname", ")", ")", ":", "os", ".", "makedirs", "(", "op", ".", "abspath", "(", "op", ".", "dirname", "(", "fname", ")", ")", ")", "# let's go get the file", "_fetch_file", "(", "url", ",", "fname", ")", "return", "fname" ]
Get a standard vispy demo data file Parameters ---------- fname : str The filename on the remote ``demo-data`` repository to download, e.g. ``'molecular_viewer/micelle.npy'``. These correspond to paths on ``https://github.com/vispy/demo-data/``. directory : str | None Directory to use to save the file. By default, the vispy configuration directory is used. force_download : bool | str If True, the file will be downloaded even if a local copy exists (and this copy will be overwritten). Can also be a YYYY-MM-DD date to ensure a file is up-to-date (modified date of a file on disk, if present, is checked). Returns ------- fname : str The path to the file on the local system.
[ "Get", "a", "standard", "vispy", "demo", "data", "file" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/fetching.py#L23-L69
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/fetching.py
_chunk_read
def _chunk_read(response, local_file, chunk_size=65536, initial_size=0): """Download a file chunk by chunk and show advancement Can also be used when resuming downloads over http. Parameters ---------- response: urllib.response.addinfourl Response to the download request in order to get file size. local_file: file Hard disk file where data should be written. chunk_size: integer, optional Size of downloaded chunks. Default: 8192 initial_size: int, optional If resuming, indicate the initial size of the file. """ # Adapted from NISL: # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py bytes_so_far = initial_size # Returns only amount left to download when resuming, not the size of the # entire file total_size = int(response.headers['Content-Length'].strip()) total_size += initial_size progress = ProgressBar(total_size, initial_value=bytes_so_far, max_chars=40, spinner=True, mesg='downloading') while True: chunk = response.read(chunk_size) bytes_so_far += len(chunk) if not chunk: sys.stderr.write('\n') break _chunk_write(chunk, local_file, progress)
python
def _chunk_read(response, local_file, chunk_size=65536, initial_size=0): """Download a file chunk by chunk and show advancement Can also be used when resuming downloads over http. Parameters ---------- response: urllib.response.addinfourl Response to the download request in order to get file size. local_file: file Hard disk file where data should be written. chunk_size: integer, optional Size of downloaded chunks. Default: 8192 initial_size: int, optional If resuming, indicate the initial size of the file. """ # Adapted from NISL: # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py bytes_so_far = initial_size # Returns only amount left to download when resuming, not the size of the # entire file total_size = int(response.headers['Content-Length'].strip()) total_size += initial_size progress = ProgressBar(total_size, initial_value=bytes_so_far, max_chars=40, spinner=True, mesg='downloading') while True: chunk = response.read(chunk_size) bytes_so_far += len(chunk) if not chunk: sys.stderr.write('\n') break _chunk_write(chunk, local_file, progress)
[ "def", "_chunk_read", "(", "response", ",", "local_file", ",", "chunk_size", "=", "65536", ",", "initial_size", "=", "0", ")", ":", "# Adapted from NISL:", "# https://github.com/nisl/tutorial/blob/master/nisl/datasets.py", "bytes_so_far", "=", "initial_size", "# Returns only amount left to download when resuming, not the size of the", "# entire file", "total_size", "=", "int", "(", "response", ".", "headers", "[", "'Content-Length'", "]", ".", "strip", "(", ")", ")", "total_size", "+=", "initial_size", "progress", "=", "ProgressBar", "(", "total_size", ",", "initial_value", "=", "bytes_so_far", ",", "max_chars", "=", "40", ",", "spinner", "=", "True", ",", "mesg", "=", "'downloading'", ")", "while", "True", ":", "chunk", "=", "response", ".", "read", "(", "chunk_size", ")", "bytes_so_far", "+=", "len", "(", "chunk", ")", "if", "not", "chunk", ":", "sys", ".", "stderr", ".", "write", "(", "'\\n'", ")", "break", "_chunk_write", "(", "chunk", ",", "local_file", ",", "progress", ")" ]
Download a file chunk by chunk and show advancement Can also be used when resuming downloads over http. Parameters ---------- response: urllib.response.addinfourl Response to the download request in order to get file size. local_file: file Hard disk file where data should be written. chunk_size: integer, optional Size of downloaded chunks. Default: 8192 initial_size: int, optional If resuming, indicate the initial size of the file.
[ "Download", "a", "file", "chunk", "by", "chunk", "and", "show", "advancement" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/fetching.py#L174-L207
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/fetching.py
_chunk_write
def _chunk_write(chunk, local_file, progress): """Write a chunk to file and update the progress bar""" local_file.write(chunk) progress.update_with_increment_value(len(chunk))
python
def _chunk_write(chunk, local_file, progress): """Write a chunk to file and update the progress bar""" local_file.write(chunk) progress.update_with_increment_value(len(chunk))
[ "def", "_chunk_write", "(", "chunk", ",", "local_file", ",", "progress", ")", ":", "local_file", ".", "write", "(", "chunk", ")", "progress", ".", "update_with_increment_value", "(", "len", "(", "chunk", ")", ")" ]
Write a chunk to file and update the progress bar
[ "Write", "a", "chunk", "to", "file", "and", "update", "the", "progress", "bar" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/fetching.py#L210-L213
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/fetching.py
_fetch_file
def _fetch_file(url, file_name, print_destination=True): """Load requested file, downloading it if needed or requested Parameters ---------- url: string The url of file to be downloaded. file_name: string Name, along with the path, of where downloaded file will be saved. print_destination: bool, optional If true, destination of where file was saved will be printed after download finishes. """ # Adapted from NISL: # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py temp_file_name = file_name + ".part" local_file = None initial_size = 0 # Checking file size and displaying it alongside the download url n_try = 3 for ii in range(n_try): try: data = urllib.request.urlopen(url, timeout=15.) except Exception as e: if ii == n_try - 1: raise RuntimeError('Error while fetching file %s.\n' 'Dataset fetching aborted (%s)' % (url, e)) try: file_size = int(data.headers['Content-Length'].strip()) print('Downloading data from %s (%s)' % (url, sizeof_fmt(file_size))) local_file = open(temp_file_name, "wb") _chunk_read(data, local_file, initial_size=initial_size) # temp file must be closed prior to the move if not local_file.closed: local_file.close() shutil.move(temp_file_name, file_name) if print_destination is True: sys.stdout.write('File saved as %s.\n' % file_name) except Exception as e: raise RuntimeError('Error while fetching file %s.\n' 'Dataset fetching aborted (%s)' % (url, e)) finally: if local_file is not None: if not local_file.closed: local_file.close()
python
def _fetch_file(url, file_name, print_destination=True): """Load requested file, downloading it if needed or requested Parameters ---------- url: string The url of file to be downloaded. file_name: string Name, along with the path, of where downloaded file will be saved. print_destination: bool, optional If true, destination of where file was saved will be printed after download finishes. """ # Adapted from NISL: # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py temp_file_name = file_name + ".part" local_file = None initial_size = 0 # Checking file size and displaying it alongside the download url n_try = 3 for ii in range(n_try): try: data = urllib.request.urlopen(url, timeout=15.) except Exception as e: if ii == n_try - 1: raise RuntimeError('Error while fetching file %s.\n' 'Dataset fetching aborted (%s)' % (url, e)) try: file_size = int(data.headers['Content-Length'].strip()) print('Downloading data from %s (%s)' % (url, sizeof_fmt(file_size))) local_file = open(temp_file_name, "wb") _chunk_read(data, local_file, initial_size=initial_size) # temp file must be closed prior to the move if not local_file.closed: local_file.close() shutil.move(temp_file_name, file_name) if print_destination is True: sys.stdout.write('File saved as %s.\n' % file_name) except Exception as e: raise RuntimeError('Error while fetching file %s.\n' 'Dataset fetching aborted (%s)' % (url, e)) finally: if local_file is not None: if not local_file.closed: local_file.close()
[ "def", "_fetch_file", "(", "url", ",", "file_name", ",", "print_destination", "=", "True", ")", ":", "# Adapted from NISL:", "# https://github.com/nisl/tutorial/blob/master/nisl/datasets.py", "temp_file_name", "=", "file_name", "+", "\".part\"", "local_file", "=", "None", "initial_size", "=", "0", "# Checking file size and displaying it alongside the download url", "n_try", "=", "3", "for", "ii", "in", "range", "(", "n_try", ")", ":", "try", ":", "data", "=", "urllib", ".", "request", ".", "urlopen", "(", "url", ",", "timeout", "=", "15.", ")", "except", "Exception", "as", "e", ":", "if", "ii", "==", "n_try", "-", "1", ":", "raise", "RuntimeError", "(", "'Error while fetching file %s.\\n'", "'Dataset fetching aborted (%s)'", "%", "(", "url", ",", "e", ")", ")", "try", ":", "file_size", "=", "int", "(", "data", ".", "headers", "[", "'Content-Length'", "]", ".", "strip", "(", ")", ")", "print", "(", "'Downloading data from %s (%s)'", "%", "(", "url", ",", "sizeof_fmt", "(", "file_size", ")", ")", ")", "local_file", "=", "open", "(", "temp_file_name", ",", "\"wb\"", ")", "_chunk_read", "(", "data", ",", "local_file", ",", "initial_size", "=", "initial_size", ")", "# temp file must be closed prior to the move", "if", "not", "local_file", ".", "closed", ":", "local_file", ".", "close", "(", ")", "shutil", ".", "move", "(", "temp_file_name", ",", "file_name", ")", "if", "print_destination", "is", "True", ":", "sys", ".", "stdout", ".", "write", "(", "'File saved as %s.\\n'", "%", "file_name", ")", "except", "Exception", "as", "e", ":", "raise", "RuntimeError", "(", "'Error while fetching file %s.\\n'", "'Dataset fetching aborted (%s)'", "%", "(", "url", ",", "e", ")", ")", "finally", ":", "if", "local_file", "is", "not", "None", ":", "if", "not", "local_file", ".", "closed", ":", "local_file", ".", "close", "(", ")" ]
Load requested file, downloading it if needed or requested Parameters ---------- url: string The url of file to be downloaded. file_name: string Name, along with the path, of where downloaded file will be saved. print_destination: bool, optional If true, destination of where file was saved will be printed after download finishes.
[ "Load", "requested", "file", "downloading", "it", "if", "needed", "or", "requested" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/fetching.py#L216-L261
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/fetching.py
ProgressBar.update
def update(self, cur_value, mesg=None): """Update progressbar with current value of process Parameters ---------- cur_value : number Current value of process. Should be <= max_value (but this is not enforced). The percent of the progressbar will be computed as (cur_value / max_value) * 100 mesg : str Message to display to the right of the progressbar. If None, the last message provided will be used. To clear the current message, pass a null string, ''. """ # Ensure floating-point division so we can get fractions of a percent # for the progressbar. self.cur_value = cur_value progress = float(self.cur_value) / self.max_value num_chars = int(progress * self.max_chars) num_left = self.max_chars - num_chars # Update the message if mesg is not None: self.mesg = mesg # The \r tells the cursor to return to the beginning of the line rather # than starting a new line. This allows us to have a progressbar-style # display in the console window. bar = self.template.format(self.progress_character * num_chars, ' ' * num_left, progress * 100, self.spinner_symbols[self.spinner_index], self.mesg) sys.stdout.write(bar) # Increament the spinner if self.spinner: self.spinner_index = (self.spinner_index + 1) % self.n_spinner # Force a flush because sometimes when using bash scripts and pipes, # the output is not printed until after the program exits. sys.stdout.flush()
python
def update(self, cur_value, mesg=None): """Update progressbar with current value of process Parameters ---------- cur_value : number Current value of process. Should be <= max_value (but this is not enforced). The percent of the progressbar will be computed as (cur_value / max_value) * 100 mesg : str Message to display to the right of the progressbar. If None, the last message provided will be used. To clear the current message, pass a null string, ''. """ # Ensure floating-point division so we can get fractions of a percent # for the progressbar. self.cur_value = cur_value progress = float(self.cur_value) / self.max_value num_chars = int(progress * self.max_chars) num_left = self.max_chars - num_chars # Update the message if mesg is not None: self.mesg = mesg # The \r tells the cursor to return to the beginning of the line rather # than starting a new line. This allows us to have a progressbar-style # display in the console window. bar = self.template.format(self.progress_character * num_chars, ' ' * num_left, progress * 100, self.spinner_symbols[self.spinner_index], self.mesg) sys.stdout.write(bar) # Increament the spinner if self.spinner: self.spinner_index = (self.spinner_index + 1) % self.n_spinner # Force a flush because sometimes when using bash scripts and pipes, # the output is not printed until after the program exits. sys.stdout.flush()
[ "def", "update", "(", "self", ",", "cur_value", ",", "mesg", "=", "None", ")", ":", "# Ensure floating-point division so we can get fractions of a percent", "# for the progressbar.", "self", ".", "cur_value", "=", "cur_value", "progress", "=", "float", "(", "self", ".", "cur_value", ")", "/", "self", ".", "max_value", "num_chars", "=", "int", "(", "progress", "*", "self", ".", "max_chars", ")", "num_left", "=", "self", ".", "max_chars", "-", "num_chars", "# Update the message", "if", "mesg", "is", "not", "None", ":", "self", ".", "mesg", "=", "mesg", "# The \\r tells the cursor to return to the beginning of the line rather", "# than starting a new line. This allows us to have a progressbar-style", "# display in the console window.", "bar", "=", "self", ".", "template", ".", "format", "(", "self", ".", "progress_character", "*", "num_chars", ",", "' '", "*", "num_left", ",", "progress", "*", "100", ",", "self", ".", "spinner_symbols", "[", "self", ".", "spinner_index", "]", ",", "self", ".", "mesg", ")", "sys", ".", "stdout", ".", "write", "(", "bar", ")", "# Increament the spinner", "if", "self", ".", "spinner", ":", "self", ".", "spinner_index", "=", "(", "self", ".", "spinner_index", "+", "1", ")", "%", "self", ".", "n_spinner", "# Force a flush because sometimes when using bash scripts and pipes,", "# the output is not printed until after the program exits.", "sys", ".", "stdout", ".", "flush", "(", ")" ]
Update progressbar with current value of process Parameters ---------- cur_value : number Current value of process. Should be <= max_value (but this is not enforced). The percent of the progressbar will be computed as (cur_value / max_value) * 100 mesg : str Message to display to the right of the progressbar. If None, the last message provided will be used. To clear the current message, pass a null string, ''.
[ "Update", "progressbar", "with", "current", "value", "of", "process" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/fetching.py#L113-L153
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/fetching.py
ProgressBar.update_with_increment_value
def update_with_increment_value(self, increment_value, mesg=None): """Update progressbar with the value of the increment instead of the current value of process as in update() Parameters ---------- increment_value : int Value of the increment of process. The percent of the progressbar will be computed as (self.cur_value + increment_value / max_value) * 100 mesg : str Message to display to the right of the progressbar. If None, the last message provided will be used. To clear the current message, pass a null string, ''. """ self.cur_value += increment_value self.update(self.cur_value, mesg)
python
def update_with_increment_value(self, increment_value, mesg=None): """Update progressbar with the value of the increment instead of the current value of process as in update() Parameters ---------- increment_value : int Value of the increment of process. The percent of the progressbar will be computed as (self.cur_value + increment_value / max_value) * 100 mesg : str Message to display to the right of the progressbar. If None, the last message provided will be used. To clear the current message, pass a null string, ''. """ self.cur_value += increment_value self.update(self.cur_value, mesg)
[ "def", "update_with_increment_value", "(", "self", ",", "increment_value", ",", "mesg", "=", "None", ")", ":", "self", ".", "cur_value", "+=", "increment_value", "self", ".", "update", "(", "self", ".", "cur_value", ",", "mesg", ")" ]
Update progressbar with the value of the increment instead of the current value of process as in update() Parameters ---------- increment_value : int Value of the increment of process. The percent of the progressbar will be computed as (self.cur_value + increment_value / max_value) * 100 mesg : str Message to display to the right of the progressbar. If None, the last message provided will be used. To clear the current message, pass a null string, ''.
[ "Update", "progressbar", "with", "the", "value", "of", "the", "increment", "instead", "of", "the", "current", "value", "of", "process", "as", "in", "update", "()" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/fetching.py#L155-L171
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.central_widget
def central_widget(self): """ Returns the default widget that occupies the entire area of the canvas. """ if self._central_widget is None: self._central_widget = Widget(size=self.size, parent=self.scene) return self._central_widget
python
def central_widget(self): """ Returns the default widget that occupies the entire area of the canvas. """ if self._central_widget is None: self._central_widget = Widget(size=self.size, parent=self.scene) return self._central_widget
[ "def", "central_widget", "(", "self", ")", ":", "if", "self", ".", "_central_widget", "is", "None", ":", "self", ".", "_central_widget", "=", "Widget", "(", "size", "=", "self", ".", "size", ",", "parent", "=", "self", ".", "scene", ")", "return", "self", ".", "_central_widget" ]
Returns the default widget that occupies the entire area of the canvas.
[ "Returns", "the", "default", "widget", "that", "occupies", "the", "entire", "area", "of", "the", "canvas", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L164-L170
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.render
def render(self, region=None, size=None, bgcolor=None): """Render the scene to an offscreen buffer and return the image array. Parameters ---------- region : tuple | None Specifies the region of the canvas to render. Format is (x, y, w, h). By default, the entire canvas is rendered. size : tuple | None Specifies the size of the image array to return. If no size is given, then the size of the *region* is used, multiplied by the pixel scaling factor of the canvas (see `pixel_scale`). This argument allows the scene to be rendered at resolutions different from the native canvas resolution. bgcolor : instance of Color | None The background color to use. 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. """ self.set_current() # Set up a framebuffer to render to offset = (0, 0) if region is None else region[:2] csize = self.size if region is None else region[2:] s = self.pixel_scale size = tuple([x * s for x in csize]) if size is None else size fbo = gloo.FrameBuffer(color=gloo.RenderBuffer(size[::-1]), depth=gloo.RenderBuffer(size[::-1])) self.push_fbo(fbo, offset, csize) try: self._draw_scene(bgcolor=bgcolor) return fbo.read() finally: self.pop_fbo()
python
def render(self, region=None, size=None, bgcolor=None): """Render the scene to an offscreen buffer and return the image array. Parameters ---------- region : tuple | None Specifies the region of the canvas to render. Format is (x, y, w, h). By default, the entire canvas is rendered. size : tuple | None Specifies the size of the image array to return. If no size is given, then the size of the *region* is used, multiplied by the pixel scaling factor of the canvas (see `pixel_scale`). This argument allows the scene to be rendered at resolutions different from the native canvas resolution. bgcolor : instance of Color | None The background color to use. 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. """ self.set_current() # Set up a framebuffer to render to offset = (0, 0) if region is None else region[:2] csize = self.size if region is None else region[2:] s = self.pixel_scale size = tuple([x * s for x in csize]) if size is None else size fbo = gloo.FrameBuffer(color=gloo.RenderBuffer(size[::-1]), depth=gloo.RenderBuffer(size[::-1])) self.push_fbo(fbo, offset, csize) try: self._draw_scene(bgcolor=bgcolor) return fbo.read() finally: self.pop_fbo()
[ "def", "render", "(", "self", ",", "region", "=", "None", ",", "size", "=", "None", ",", "bgcolor", "=", "None", ")", ":", "self", ".", "set_current", "(", ")", "# Set up a framebuffer to render to", "offset", "=", "(", "0", ",", "0", ")", "if", "region", "is", "None", "else", "region", "[", ":", "2", "]", "csize", "=", "self", ".", "size", "if", "region", "is", "None", "else", "region", "[", "2", ":", "]", "s", "=", "self", ".", "pixel_scale", "size", "=", "tuple", "(", "[", "x", "*", "s", "for", "x", "in", "csize", "]", ")", "if", "size", "is", "None", "else", "size", "fbo", "=", "gloo", ".", "FrameBuffer", "(", "color", "=", "gloo", ".", "RenderBuffer", "(", "size", "[", ":", ":", "-", "1", "]", ")", ",", "depth", "=", "gloo", ".", "RenderBuffer", "(", "size", "[", ":", ":", "-", "1", "]", ")", ")", "self", ".", "push_fbo", "(", "fbo", ",", "offset", ",", "csize", ")", "try", ":", "self", ".", "_draw_scene", "(", "bgcolor", "=", "bgcolor", ")", "return", "fbo", ".", "read", "(", ")", "finally", ":", "self", ".", "pop_fbo", "(", ")" ]
Render the scene to an offscreen buffer and return the image array. Parameters ---------- region : tuple | None Specifies the region of the canvas to render. Format is (x, y, w, h). By default, the entire canvas is rendered. size : tuple | None Specifies the size of the image array to return. If no size is given, then the size of the *region* is used, multiplied by the pixel scaling factor of the canvas (see `pixel_scale`). This argument allows the scene to be rendered at resolutions different from the native canvas resolution. bgcolor : instance of Color | None The background color to use. 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.
[ "Render", "the", "scene", "to", "an", "offscreen", "buffer", "and", "return", "the", "image", "array", ".", "Parameters", "----------", "region", ":", "tuple", "|", "None", "Specifies", "the", "region", "of", "the", "canvas", "to", "render", ".", "Format", "is", "(", "x", "y", "w", "h", ")", ".", "By", "default", "the", "entire", "canvas", "is", "rendered", ".", "size", ":", "tuple", "|", "None", "Specifies", "the", "size", "of", "the", "image", "array", "to", "return", ".", "If", "no", "size", "is", "given", "then", "the", "size", "of", "the", "*", "region", "*", "is", "used", "multiplied", "by", "the", "pixel", "scaling", "factor", "of", "the", "canvas", "(", "see", "pixel_scale", ")", ".", "This", "argument", "allows", "the", "scene", "to", "be", "rendered", "at", "resolutions", "different", "from", "the", "native", "canvas", "resolution", ".", "bgcolor", ":", "instance", "of", "Color", "|", "None", "The", "background", "color", "to", "use", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L209-L247
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.draw_visual
def draw_visual(self, visual, event=None): """ Draw a visual and its children to the canvas or currently active framebuffer. Parameters ---------- visual : Visual The visual to draw event : None or DrawEvent Optionally specifies the original canvas draw event that initiated this draw. """ prof = Profiler() # make sure this canvas's context is active self.set_current() try: self._drawing = True # get order to draw visuals if visual not in self._draw_order: self._draw_order[visual] = self._generate_draw_order() order = self._draw_order[visual] # draw (while avoiding branches with visible=False) stack = [] invisible_node = None for node, start in order: if start: stack.append(node) if invisible_node is None: if not node.visible: # disable drawing until we exit this node's subtree invisible_node = node else: if hasattr(node, 'draw'): node.draw() prof.mark(str(node)) else: if node is invisible_node: invisible_node = None stack.pop() finally: self._drawing = False
python
def draw_visual(self, visual, event=None): """ Draw a visual and its children to the canvas or currently active framebuffer. Parameters ---------- visual : Visual The visual to draw event : None or DrawEvent Optionally specifies the original canvas draw event that initiated this draw. """ prof = Profiler() # make sure this canvas's context is active self.set_current() try: self._drawing = True # get order to draw visuals if visual not in self._draw_order: self._draw_order[visual] = self._generate_draw_order() order = self._draw_order[visual] # draw (while avoiding branches with visible=False) stack = [] invisible_node = None for node, start in order: if start: stack.append(node) if invisible_node is None: if not node.visible: # disable drawing until we exit this node's subtree invisible_node = node else: if hasattr(node, 'draw'): node.draw() prof.mark(str(node)) else: if node is invisible_node: invisible_node = None stack.pop() finally: self._drawing = False
[ "def", "draw_visual", "(", "self", ",", "visual", ",", "event", "=", "None", ")", ":", "prof", "=", "Profiler", "(", ")", "# make sure this canvas's context is active", "self", ".", "set_current", "(", ")", "try", ":", "self", ".", "_drawing", "=", "True", "# get order to draw visuals", "if", "visual", "not", "in", "self", ".", "_draw_order", ":", "self", ".", "_draw_order", "[", "visual", "]", "=", "self", ".", "_generate_draw_order", "(", ")", "order", "=", "self", ".", "_draw_order", "[", "visual", "]", "# draw (while avoiding branches with visible=False)", "stack", "=", "[", "]", "invisible_node", "=", "None", "for", "node", ",", "start", "in", "order", ":", "if", "start", ":", "stack", ".", "append", "(", "node", ")", "if", "invisible_node", "is", "None", ":", "if", "not", "node", ".", "visible", ":", "# disable drawing until we exit this node's subtree", "invisible_node", "=", "node", "else", ":", "if", "hasattr", "(", "node", ",", "'draw'", ")", ":", "node", ".", "draw", "(", ")", "prof", ".", "mark", "(", "str", "(", "node", ")", ")", "else", ":", "if", "node", "is", "invisible_node", ":", "invisible_node", "=", "None", "stack", ".", "pop", "(", ")", "finally", ":", "self", ".", "_drawing", "=", "False" ]
Draw a visual and its children to the canvas or currently active framebuffer. Parameters ---------- visual : Visual The visual to draw event : None or DrawEvent Optionally specifies the original canvas draw event that initiated this draw.
[ "Draw", "a", "visual", "and", "its", "children", "to", "the", "canvas", "or", "currently", "active", "framebuffer", ".", "Parameters", "----------", "visual", ":", "Visual", "The", "visual", "to", "draw", "event", ":", "None", "or", "DrawEvent", "Optionally", "specifies", "the", "original", "canvas", "draw", "event", "that", "initiated", "this", "draw", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L255-L298
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas._generate_draw_order
def _generate_draw_order(self, node=None): """Return a list giving the order to draw visuals. Each node appears twice in the list--(node, True) appears before the node's children are drawn, and (node, False) appears after. """ if node is None: node = self._scene order = [(node, True)] children = node.children children.sort(key=lambda ch: ch.order) for ch in children: order.extend(self._generate_draw_order(ch)) order.append((node, False)) return order
python
def _generate_draw_order(self, node=None): """Return a list giving the order to draw visuals. Each node appears twice in the list--(node, True) appears before the node's children are drawn, and (node, False) appears after. """ if node is None: node = self._scene order = [(node, True)] children = node.children children.sort(key=lambda ch: ch.order) for ch in children: order.extend(self._generate_draw_order(ch)) order.append((node, False)) return order
[ "def", "_generate_draw_order", "(", "self", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "_scene", "order", "=", "[", "(", "node", ",", "True", ")", "]", "children", "=", "node", ".", "children", "children", ".", "sort", "(", "key", "=", "lambda", "ch", ":", "ch", ".", "order", ")", "for", "ch", "in", "children", ":", "order", ".", "extend", "(", "self", ".", "_generate_draw_order", "(", "ch", ")", ")", "order", ".", "append", "(", "(", "node", ",", "False", ")", ")", "return", "order" ]
Return a list giving the order to draw visuals. Each node appears twice in the list--(node, True) appears before the node's children are drawn, and (node, False) appears after.
[ "Return", "a", "list", "giving", "the", "order", "to", "draw", "visuals", ".", "Each", "node", "appears", "twice", "in", "the", "list", "--", "(", "node", "True", ")", "appears", "before", "the", "node", "s", "children", "are", "drawn", "and", "(", "node", "False", ")", "appears", "after", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L300-L314
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.visual_at
def visual_at(self, pos): """Return the visual at a given position Parameters ---------- pos : tuple The position in logical coordinates to query. Returns ------- visual : instance of Visual | None The visual at the position, if it exists. """ tr = self.transforms.get_transform('canvas', 'framebuffer') fbpos = tr.map(pos)[:2] try: id_ = self._render_picking(region=(fbpos[0], fbpos[1], 1, 1)) vis = VisualNode._visual_ids.get(id_[0, 0], None) except RuntimeError: # Don't have read_pixels() support for IPython. Fall back to # bounds checking. return self._visual_bounds_at(pos) return vis
python
def visual_at(self, pos): """Return the visual at a given position Parameters ---------- pos : tuple The position in logical coordinates to query. Returns ------- visual : instance of Visual | None The visual at the position, if it exists. """ tr = self.transforms.get_transform('canvas', 'framebuffer') fbpos = tr.map(pos)[:2] try: id_ = self._render_picking(region=(fbpos[0], fbpos[1], 1, 1)) vis = VisualNode._visual_ids.get(id_[0, 0], None) except RuntimeError: # Don't have read_pixels() support for IPython. Fall back to # bounds checking. return self._visual_bounds_at(pos) return vis
[ "def", "visual_at", "(", "self", ",", "pos", ")", ":", "tr", "=", "self", ".", "transforms", ".", "get_transform", "(", "'canvas'", ",", "'framebuffer'", ")", "fbpos", "=", "tr", ".", "map", "(", "pos", ")", "[", ":", "2", "]", "try", ":", "id_", "=", "self", ".", "_render_picking", "(", "region", "=", "(", "fbpos", "[", "0", "]", ",", "fbpos", "[", "1", "]", ",", "1", ",", "1", ")", ")", "vis", "=", "VisualNode", ".", "_visual_ids", ".", "get", "(", "id_", "[", "0", ",", "0", "]", ",", "None", ")", "except", "RuntimeError", ":", "# Don't have read_pixels() support for IPython. Fall back to", "# bounds checking.", "return", "self", ".", "_visual_bounds_at", "(", "pos", ")", "return", "vis" ]
Return the visual at a given position Parameters ---------- pos : tuple The position in logical coordinates to query. Returns ------- visual : instance of Visual | None The visual at the position, if it exists.
[ "Return", "the", "visual", "at", "a", "given", "position" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L367-L391
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas._visual_bounds_at
def _visual_bounds_at(self, pos, node=None): """Find a visual whose bounding rect encompasses *pos*. """ if node is None: node = self.scene for ch in node.children: hit = self._visual_bounds_at(pos, ch) if hit is not None: return hit if (not isinstance(node, VisualNode) or not node.visible or not node.interactive): return None bounds = [node.bounds(axis=i) for i in range(2)] if None in bounds: return None tr = self.scene.node_transform(node).inverse corners = np.array([ [bounds[0][0], bounds[1][0]], [bounds[0][0], bounds[1][1]], [bounds[0][1], bounds[1][0]], [bounds[0][1], bounds[1][1]]]) bounds = tr.map(corners) xhit = bounds[:, 0].min() < pos[0] < bounds[:, 0].max() yhit = bounds[:, 1].min() < pos[1] < bounds[:, 1].max() if xhit and yhit: return node
python
def _visual_bounds_at(self, pos, node=None): """Find a visual whose bounding rect encompasses *pos*. """ if node is None: node = self.scene for ch in node.children: hit = self._visual_bounds_at(pos, ch) if hit is not None: return hit if (not isinstance(node, VisualNode) or not node.visible or not node.interactive): return None bounds = [node.bounds(axis=i) for i in range(2)] if None in bounds: return None tr = self.scene.node_transform(node).inverse corners = np.array([ [bounds[0][0], bounds[1][0]], [bounds[0][0], bounds[1][1]], [bounds[0][1], bounds[1][0]], [bounds[0][1], bounds[1][1]]]) bounds = tr.map(corners) xhit = bounds[:, 0].min() < pos[0] < bounds[:, 0].max() yhit = bounds[:, 1].min() < pos[1] < bounds[:, 1].max() if xhit and yhit: return node
[ "def", "_visual_bounds_at", "(", "self", ",", "pos", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "scene", "for", "ch", "in", "node", ".", "children", ":", "hit", "=", "self", ".", "_visual_bounds_at", "(", "pos", ",", "ch", ")", "if", "hit", "is", "not", "None", ":", "return", "hit", "if", "(", "not", "isinstance", "(", "node", ",", "VisualNode", ")", "or", "not", "node", ".", "visible", "or", "not", "node", ".", "interactive", ")", ":", "return", "None", "bounds", "=", "[", "node", ".", "bounds", "(", "axis", "=", "i", ")", "for", "i", "in", "range", "(", "2", ")", "]", "if", "None", "in", "bounds", ":", "return", "None", "tr", "=", "self", ".", "scene", ".", "node_transform", "(", "node", ")", ".", "inverse", "corners", "=", "np", ".", "array", "(", "[", "[", "bounds", "[", "0", "]", "[", "0", "]", ",", "bounds", "[", "1", "]", "[", "0", "]", "]", ",", "[", "bounds", "[", "0", "]", "[", "0", "]", ",", "bounds", "[", "1", "]", "[", "1", "]", "]", ",", "[", "bounds", "[", "0", "]", "[", "1", "]", ",", "bounds", "[", "1", "]", "[", "0", "]", "]", ",", "[", "bounds", "[", "0", "]", "[", "1", "]", ",", "bounds", "[", "1", "]", "[", "1", "]", "]", "]", ")", "bounds", "=", "tr", ".", "map", "(", "corners", ")", "xhit", "=", "bounds", "[", ":", ",", "0", "]", ".", "min", "(", ")", "<", "pos", "[", "0", "]", "<", "bounds", "[", ":", ",", "0", "]", ".", "max", "(", ")", "yhit", "=", "bounds", "[", ":", ",", "1", "]", ".", "min", "(", ")", "<", "pos", "[", "1", "]", "<", "bounds", "[", ":", ",", "1", "]", ".", "max", "(", ")", "if", "xhit", "and", "yhit", ":", "return", "node" ]
Find a visual whose bounding rect encompasses *pos*.
[ "Find", "a", "visual", "whose", "bounding", "rect", "encompasses", "*", "pos", "*", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L393-L423
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.visuals_at
def visuals_at(self, pos, radius=10): """Return a list of visuals within *radius* pixels of *pos*. Visuals are sorted by their proximity to *pos*. Parameters ---------- pos : tuple (x, y) position at which to find visuals. radius : int Distance away from *pos* to search for visuals. """ tr = self.transforms.get_transform('canvas', 'framebuffer') pos = tr.map(pos)[:2] id = self._render_picking(region=(pos[0]-radius, pos[1]-radius, radius * 2 + 1, radius * 2 + 1)) ids = [] seen = set() for i in range(radius): subr = id[radius-i:radius+i+1, radius-i:radius+i+1] subr_ids = set(list(np.unique(subr))) ids.extend(list(subr_ids - seen)) seen |= subr_ids visuals = [VisualNode._visual_ids.get(x, None) for x in ids] return [v for v in visuals if v is not None]
python
def visuals_at(self, pos, radius=10): """Return a list of visuals within *radius* pixels of *pos*. Visuals are sorted by their proximity to *pos*. Parameters ---------- pos : tuple (x, y) position at which to find visuals. radius : int Distance away from *pos* to search for visuals. """ tr = self.transforms.get_transform('canvas', 'framebuffer') pos = tr.map(pos)[:2] id = self._render_picking(region=(pos[0]-radius, pos[1]-radius, radius * 2 + 1, radius * 2 + 1)) ids = [] seen = set() for i in range(radius): subr = id[radius-i:radius+i+1, radius-i:radius+i+1] subr_ids = set(list(np.unique(subr))) ids.extend(list(subr_ids - seen)) seen |= subr_ids visuals = [VisualNode._visual_ids.get(x, None) for x in ids] return [v for v in visuals if v is not None]
[ "def", "visuals_at", "(", "self", ",", "pos", ",", "radius", "=", "10", ")", ":", "tr", "=", "self", ".", "transforms", ".", "get_transform", "(", "'canvas'", ",", "'framebuffer'", ")", "pos", "=", "tr", ".", "map", "(", "pos", ")", "[", ":", "2", "]", "id", "=", "self", ".", "_render_picking", "(", "region", "=", "(", "pos", "[", "0", "]", "-", "radius", ",", "pos", "[", "1", "]", "-", "radius", ",", "radius", "*", "2", "+", "1", ",", "radius", "*", "2", "+", "1", ")", ")", "ids", "=", "[", "]", "seen", "=", "set", "(", ")", "for", "i", "in", "range", "(", "radius", ")", ":", "subr", "=", "id", "[", "radius", "-", "i", ":", "radius", "+", "i", "+", "1", ",", "radius", "-", "i", ":", "radius", "+", "i", "+", "1", "]", "subr_ids", "=", "set", "(", "list", "(", "np", ".", "unique", "(", "subr", ")", ")", ")", "ids", ".", "extend", "(", "list", "(", "subr_ids", "-", "seen", ")", ")", "seen", "|=", "subr_ids", "visuals", "=", "[", "VisualNode", ".", "_visual_ids", ".", "get", "(", "x", ",", "None", ")", "for", "x", "in", "ids", "]", "return", "[", "v", "for", "v", "in", "visuals", "if", "v", "is", "not", "None", "]" ]
Return a list of visuals within *radius* pixels of *pos*. Visuals are sorted by their proximity to *pos*. Parameters ---------- pos : tuple (x, y) position at which to find visuals. radius : int Distance away from *pos* to search for visuals.
[ "Return", "a", "list", "of", "visuals", "within", "*", "radius", "*", "pixels", "of", "*", "pos", "*", ".", "Visuals", "are", "sorted", "by", "their", "proximity", "to", "*", "pos", "*", ".", "Parameters", "----------", "pos", ":", "tuple", "(", "x", "y", ")", "position", "at", "which", "to", "find", "visuals", ".", "radius", ":", "int", "Distance", "away", "from", "*", "pos", "*", "to", "search", "for", "visuals", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L425-L450
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas._render_picking
def _render_picking(self, **kwargs): """Render the scene in picking mode, returning a 2D array of visual IDs. """ try: self._scene.picking = True img = self.render(bgcolor=(0, 0, 0, 0), **kwargs) finally: self._scene.picking = False img = img.astype('int32') * [2**0, 2**8, 2**16, 2**24] id_ = img.sum(axis=2).astype('int32') return id_
python
def _render_picking(self, **kwargs): """Render the scene in picking mode, returning a 2D array of visual IDs. """ try: self._scene.picking = True img = self.render(bgcolor=(0, 0, 0, 0), **kwargs) finally: self._scene.picking = False img = img.astype('int32') * [2**0, 2**8, 2**16, 2**24] id_ = img.sum(axis=2).astype('int32') return id_
[ "def", "_render_picking", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "self", ".", "_scene", ".", "picking", "=", "True", "img", "=", "self", ".", "render", "(", "bgcolor", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ",", "*", "*", "kwargs", ")", "finally", ":", "self", ".", "_scene", ".", "picking", "=", "False", "img", "=", "img", ".", "astype", "(", "'int32'", ")", "*", "[", "2", "**", "0", ",", "2", "**", "8", ",", "2", "**", "16", ",", "2", "**", "24", "]", "id_", "=", "img", ".", "sum", "(", "axis", "=", "2", ")", ".", "astype", "(", "'int32'", ")", "return", "id_" ]
Render the scene in picking mode, returning a 2D array of visual IDs.
[ "Render", "the", "scene", "in", "picking", "mode", "returning", "a", "2D", "array", "of", "visual", "IDs", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L452-L463
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.on_resize
def on_resize(self, event): """Resize handler Parameters ---------- event : instance of Event The resize event. """ self._update_transforms() if self._central_widget is not None: self._central_widget.size = self.size if len(self._vp_stack) == 0: self.context.set_viewport(0, 0, *self.physical_size)
python
def on_resize(self, event): """Resize handler Parameters ---------- event : instance of Event The resize event. """ self._update_transforms() if self._central_widget is not None: self._central_widget.size = self.size if len(self._vp_stack) == 0: self.context.set_viewport(0, 0, *self.physical_size)
[ "def", "on_resize", "(", "self", ",", "event", ")", ":", "self", ".", "_update_transforms", "(", ")", "if", "self", ".", "_central_widget", "is", "not", "None", ":", "self", ".", "_central_widget", ".", "size", "=", "self", ".", "size", "if", "len", "(", "self", ".", "_vp_stack", ")", "==", "0", ":", "self", ".", "context", ".", "set_viewport", "(", "0", ",", "0", ",", "*", "self", ".", "physical_size", ")" ]
Resize handler Parameters ---------- event : instance of Event The resize event.
[ "Resize", "handler" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L465-L479
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.on_close
def on_close(self, event): """Close event handler Parameters ---------- event : instance of Event The event. """ self.events.mouse_press.disconnect(self._process_mouse_event) self.events.mouse_move.disconnect(self._process_mouse_event) self.events.mouse_release.disconnect(self._process_mouse_event) self.events.mouse_wheel.disconnect(self._process_mouse_event)
python
def on_close(self, event): """Close event handler Parameters ---------- event : instance of Event The event. """ self.events.mouse_press.disconnect(self._process_mouse_event) self.events.mouse_move.disconnect(self._process_mouse_event) self.events.mouse_release.disconnect(self._process_mouse_event) self.events.mouse_wheel.disconnect(self._process_mouse_event)
[ "def", "on_close", "(", "self", ",", "event", ")", ":", "self", ".", "events", ".", "mouse_press", ".", "disconnect", "(", "self", ".", "_process_mouse_event", ")", "self", ".", "events", ".", "mouse_move", ".", "disconnect", "(", "self", ".", "_process_mouse_event", ")", "self", ".", "events", ".", "mouse_release", ".", "disconnect", "(", "self", ".", "_process_mouse_event", ")", "self", ".", "events", ".", "mouse_wheel", ".", "disconnect", "(", "self", ".", "_process_mouse_event", ")" ]
Close event handler Parameters ---------- event : instance of Event The event.
[ "Close", "event", "handler" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L481-L492
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.push_viewport
def push_viewport(self, viewport): """ Push a viewport (x, y, w, h) on the stack. Values must be integers relative to the active framebuffer. Parameters ---------- viewport : tuple The viewport as (x, y, w, h). """ vp = list(viewport) # Normalize viewport before setting; if vp[2] < 0: vp[0] += vp[2] vp[2] *= -1 if vp[3] < 0: vp[1] += vp[3] vp[3] *= -1 self._vp_stack.append(vp) try: self.context.set_viewport(*vp) except: self._vp_stack.pop() raise self._update_transforms()
python
def push_viewport(self, viewport): """ Push a viewport (x, y, w, h) on the stack. Values must be integers relative to the active framebuffer. Parameters ---------- viewport : tuple The viewport as (x, y, w, h). """ vp = list(viewport) # Normalize viewport before setting; if vp[2] < 0: vp[0] += vp[2] vp[2] *= -1 if vp[3] < 0: vp[1] += vp[3] vp[3] *= -1 self._vp_stack.append(vp) try: self.context.set_viewport(*vp) except: self._vp_stack.pop() raise self._update_transforms()
[ "def", "push_viewport", "(", "self", ",", "viewport", ")", ":", "vp", "=", "list", "(", "viewport", ")", "# Normalize viewport before setting;", "if", "vp", "[", "2", "]", "<", "0", ":", "vp", "[", "0", "]", "+=", "vp", "[", "2", "]", "vp", "[", "2", "]", "*=", "-", "1", "if", "vp", "[", "3", "]", "<", "0", ":", "vp", "[", "1", "]", "+=", "vp", "[", "3", "]", "vp", "[", "3", "]", "*=", "-", "1", "self", ".", "_vp_stack", ".", "append", "(", "vp", ")", "try", ":", "self", ".", "context", ".", "set_viewport", "(", "*", "vp", ")", "except", ":", "self", ".", "_vp_stack", ".", "pop", "(", ")", "raise", "self", ".", "_update_transforms", "(", ")" ]
Push a viewport (x, y, w, h) on the stack. Values must be integers relative to the active framebuffer. Parameters ---------- viewport : tuple The viewport as (x, y, w, h).
[ "Push", "a", "viewport", "(", "x", "y", "w", "h", ")", "on", "the", "stack", ".", "Values", "must", "be", "integers", "relative", "to", "the", "active", "framebuffer", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L495-L520
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.pop_viewport
def pop_viewport(self): """ Pop a viewport from the stack. """ vp = self._vp_stack.pop() # Activate latest if len(self._vp_stack) > 0: self.context.set_viewport(*self._vp_stack[-1]) else: self.context.set_viewport(0, 0, *self.physical_size) self._update_transforms() return vp
python
def pop_viewport(self): """ Pop a viewport from the stack. """ vp = self._vp_stack.pop() # Activate latest if len(self._vp_stack) > 0: self.context.set_viewport(*self._vp_stack[-1]) else: self.context.set_viewport(0, 0, *self.physical_size) self._update_transforms() return vp
[ "def", "pop_viewport", "(", "self", ")", ":", "vp", "=", "self", ".", "_vp_stack", ".", "pop", "(", ")", "# Activate latest", "if", "len", "(", "self", ".", "_vp_stack", ")", ">", "0", ":", "self", ".", "context", ".", "set_viewport", "(", "*", "self", ".", "_vp_stack", "[", "-", "1", "]", ")", "else", ":", "self", ".", "context", ".", "set_viewport", "(", "0", ",", "0", ",", "*", "self", ".", "physical_size", ")", "self", ".", "_update_transforms", "(", ")", "return", "vp" ]
Pop a viewport from the stack.
[ "Pop", "a", "viewport", "from", "the", "stack", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L522-L533
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.push_fbo
def push_fbo(self, fbo, offset, csize): """ Push an FBO on the stack. This activates the framebuffer and causes subsequent rendering to be written to the framebuffer rather than the canvas's back buffer. This will also set the canvas viewport to cover the boundaries of the framebuffer. Parameters ---------- fbo : instance of FrameBuffer The framebuffer object . offset : tuple The location of the fbo origin relative to the canvas's framebuffer origin. csize : tuple The size of the region in the canvas's framebuffer that should be covered by this framebuffer object. """ self._fb_stack.append((fbo, offset, csize)) try: fbo.activate() h, w = fbo.color_buffer.shape[:2] self.push_viewport((0, 0, w, h)) except Exception: self._fb_stack.pop() raise self._update_transforms()
python
def push_fbo(self, fbo, offset, csize): """ Push an FBO on the stack. This activates the framebuffer and causes subsequent rendering to be written to the framebuffer rather than the canvas's back buffer. This will also set the canvas viewport to cover the boundaries of the framebuffer. Parameters ---------- fbo : instance of FrameBuffer The framebuffer object . offset : tuple The location of the fbo origin relative to the canvas's framebuffer origin. csize : tuple The size of the region in the canvas's framebuffer that should be covered by this framebuffer object. """ self._fb_stack.append((fbo, offset, csize)) try: fbo.activate() h, w = fbo.color_buffer.shape[:2] self.push_viewport((0, 0, w, h)) except Exception: self._fb_stack.pop() raise self._update_transforms()
[ "def", "push_fbo", "(", "self", ",", "fbo", ",", "offset", ",", "csize", ")", ":", "self", ".", "_fb_stack", ".", "append", "(", "(", "fbo", ",", "offset", ",", "csize", ")", ")", "try", ":", "fbo", ".", "activate", "(", ")", "h", ",", "w", "=", "fbo", ".", "color_buffer", ".", "shape", "[", ":", "2", "]", "self", ".", "push_viewport", "(", "(", "0", ",", "0", ",", "w", ",", "h", ")", ")", "except", "Exception", ":", "self", ".", "_fb_stack", ".", "pop", "(", ")", "raise", "self", ".", "_update_transforms", "(", ")" ]
Push an FBO on the stack. This activates the framebuffer and causes subsequent rendering to be written to the framebuffer rather than the canvas's back buffer. This will also set the canvas viewport to cover the boundaries of the framebuffer. Parameters ---------- fbo : instance of FrameBuffer The framebuffer object . offset : tuple The location of the fbo origin relative to the canvas's framebuffer origin. csize : tuple The size of the region in the canvas's framebuffer that should be covered by this framebuffer object.
[ "Push", "an", "FBO", "on", "the", "stack", ".", "This", "activates", "the", "framebuffer", "and", "causes", "subsequent", "rendering", "to", "be", "written", "to", "the", "framebuffer", "rather", "than", "the", "canvas", "s", "back", "buffer", ".", "This", "will", "also", "set", "the", "canvas", "viewport", "to", "cover", "the", "boundaries", "of", "the", "framebuffer", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L535-L563
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas.pop_fbo
def pop_fbo(self): """ Pop an FBO from the stack. """ fbo = self._fb_stack.pop() fbo[0].deactivate() self.pop_viewport() if len(self._fb_stack) > 0: old_fbo = self._fb_stack[-1] old_fbo[0].activate() self._update_transforms() return fbo
python
def pop_fbo(self): """ Pop an FBO from the stack. """ fbo = self._fb_stack.pop() fbo[0].deactivate() self.pop_viewport() if len(self._fb_stack) > 0: old_fbo = self._fb_stack[-1] old_fbo[0].activate() self._update_transforms() return fbo
[ "def", "pop_fbo", "(", "self", ")", ":", "fbo", "=", "self", ".", "_fb_stack", ".", "pop", "(", ")", "fbo", "[", "0", "]", ".", "deactivate", "(", ")", "self", ".", "pop_viewport", "(", ")", "if", "len", "(", "self", ".", "_fb_stack", ")", ">", "0", ":", "old_fbo", "=", "self", ".", "_fb_stack", "[", "-", "1", "]", "old_fbo", "[", "0", "]", ".", "activate", "(", ")", "self", ".", "_update_transforms", "(", ")", "return", "fbo" ]
Pop an FBO from the stack.
[ "Pop", "an", "FBO", "from", "the", "stack", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L565-L576
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/canvas.py
SceneCanvas._update_transforms
def _update_transforms(self): """Update the canvas's TransformSystem to correct for the current canvas size, framebuffer, and viewport. """ if len(self._fb_stack) == 0: fb_size = fb_rect = None else: fb, origin, fb_size = self._fb_stack[-1] fb_rect = origin + fb_size if len(self._vp_stack) == 0: viewport = None else: viewport = self._vp_stack[-1] self.transforms.configure(viewport=viewport, fbo_size=fb_size, fbo_rect=fb_rect)
python
def _update_transforms(self): """Update the canvas's TransformSystem to correct for the current canvas size, framebuffer, and viewport. """ if len(self._fb_stack) == 0: fb_size = fb_rect = None else: fb, origin, fb_size = self._fb_stack[-1] fb_rect = origin + fb_size if len(self._vp_stack) == 0: viewport = None else: viewport = self._vp_stack[-1] self.transforms.configure(viewport=viewport, fbo_size=fb_size, fbo_rect=fb_rect)
[ "def", "_update_transforms", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_fb_stack", ")", "==", "0", ":", "fb_size", "=", "fb_rect", "=", "None", "else", ":", "fb", ",", "origin", ",", "fb_size", "=", "self", ".", "_fb_stack", "[", "-", "1", "]", "fb_rect", "=", "origin", "+", "fb_size", "if", "len", "(", "self", ".", "_vp_stack", ")", "==", "0", ":", "viewport", "=", "None", "else", ":", "viewport", "=", "self", ".", "_vp_stack", "[", "-", "1", "]", "self", ".", "transforms", ".", "configure", "(", "viewport", "=", "viewport", ",", "fbo_size", "=", "fb_size", ",", "fbo_rect", "=", "fb_rect", ")" ]
Update the canvas's TransformSystem to correct for the current canvas size, framebuffer, and viewport.
[ "Update", "the", "canvas", "s", "TransformSystem", "to", "correct", "for", "the", "current", "canvas", "size", "framebuffer", "and", "viewport", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/canvas.py#L587-L603
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/texture.py
BaseTexture.wrapping
def wrapping(self): """ Texture wrapping mode """ value = self._wrapping return value[0] if all([v == value[0] for v in value]) else value
python
def wrapping(self): """ Texture wrapping mode """ value = self._wrapping return value[0] if all([v == value[0] for v in value]) else value
[ "def", "wrapping", "(", "self", ")", ":", "value", "=", "self", ".", "_wrapping", "return", "value", "[", "0", "]", "if", "all", "(", "[", "v", "==", "value", "[", "0", "]", "for", "v", "in", "value", "]", ")", "else", "value" ]
Texture wrapping mode
[ "Texture", "wrapping", "mode" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/texture.py#L156-L159
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/texture.py
BaseTexture.resize
def resize(self, shape, format=None, internalformat=None): """Set the texture size and format Parameters ---------- shape : tuple of integers New texture shape in zyx order. Optionally, an extra dimention may be specified to indicate the number of color channels. format : str | enum | None The format of the texture: 'luminance', 'alpha', 'luminance_alpha', 'rgb', or 'rgba'. If not given the format is chosen automatically based on the number of channels. When the data has one channel, 'luminance' is assumed. internalformat : str | enum | None The internal (storage) format of the texture: 'luminance', 'alpha', 'r8', 'r16', 'r16f', 'r32f'; 'luminance_alpha', 'rg8', 'rg16', 'rg16f', 'rg32f'; 'rgb', 'rgb8', 'rgb16', 'rgb16f', 'rgb32f'; 'rgba', 'rgba8', 'rgba16', 'rgba16f', 'rgba32f'. If None, the internalformat is chosen automatically based on the number of channels. This is a hint which may be ignored by the OpenGL implementation. """ return self._resize(shape, format, internalformat)
python
def resize(self, shape, format=None, internalformat=None): """Set the texture size and format Parameters ---------- shape : tuple of integers New texture shape in zyx order. Optionally, an extra dimention may be specified to indicate the number of color channels. format : str | enum | None The format of the texture: 'luminance', 'alpha', 'luminance_alpha', 'rgb', or 'rgba'. If not given the format is chosen automatically based on the number of channels. When the data has one channel, 'luminance' is assumed. internalformat : str | enum | None The internal (storage) format of the texture: 'luminance', 'alpha', 'r8', 'r16', 'r16f', 'r32f'; 'luminance_alpha', 'rg8', 'rg16', 'rg16f', 'rg32f'; 'rgb', 'rgb8', 'rgb16', 'rgb16f', 'rgb32f'; 'rgba', 'rgba8', 'rgba16', 'rgba16f', 'rgba32f'. If None, the internalformat is chosen automatically based on the number of channels. This is a hint which may be ignored by the OpenGL implementation. """ return self._resize(shape, format, internalformat)
[ "def", "resize", "(", "self", ",", "shape", ",", "format", "=", "None", ",", "internalformat", "=", "None", ")", ":", "return", "self", ".", "_resize", "(", "shape", ",", "format", ",", "internalformat", ")" ]
Set the texture size and format Parameters ---------- shape : tuple of integers New texture shape in zyx order. Optionally, an extra dimention may be specified to indicate the number of color channels. format : str | enum | None The format of the texture: 'luminance', 'alpha', 'luminance_alpha', 'rgb', or 'rgba'. If not given the format is chosen automatically based on the number of channels. When the data has one channel, 'luminance' is assumed. internalformat : str | enum | None The internal (storage) format of the texture: 'luminance', 'alpha', 'r8', 'r16', 'r16f', 'r32f'; 'luminance_alpha', 'rg8', 'rg16', 'rg16f', 'rg32f'; 'rgb', 'rgb8', 'rgb16', 'rgb16f', 'rgb32f'; 'rgba', 'rgba8', 'rgba16', 'rgba16f', 'rgba32f'. If None, the internalformat is chosen automatically based on the number of channels. This is a hint which may be ignored by the OpenGL implementation.
[ "Set", "the", "texture", "size", "and", "format" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/texture.py#L202-L224
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/texture.py
BaseTexture._resize
def _resize(self, shape, format=None, internalformat=None): """Internal method for resize. """ shape = self._normalize_shape(shape) # Check if not self._resizable: raise RuntimeError("Texture is not resizable") # Determine format if format is None: format = self._formats[shape[-1]] # Keep current format if channels match if self._format and \ self._inv_formats[self._format] == self._inv_formats[format]: format = self._format else: format = check_enum(format) if internalformat is None: # Keep current internalformat if channels match if self._internalformat and \ self._inv_internalformats[self._internalformat] == shape[-1]: internalformat = self._internalformat else: internalformat = check_enum(internalformat) # Check if format not in self._inv_formats: raise ValueError('Invalid texture format: %r.' % format) elif shape[-1] != self._inv_formats[format]: raise ValueError('Format does not match with given shape. ' '(format expects %d elements, data has %d)' % (self._inv_formats[format], shape[-1])) if internalformat is None: pass elif internalformat not in self._inv_internalformats: raise ValueError( 'Invalid texture internalformat: %r. Allowed formats: %r' % (internalformat, self._inv_internalformats) ) elif shape[-1] != self._inv_internalformats[internalformat]: raise ValueError('Internalformat does not match with given shape.') # Store and send GLIR command self._shape = shape self._format = format self._internalformat = internalformat self._glir.command('SIZE', self._id, self._shape, self._format, self._internalformat)
python
def _resize(self, shape, format=None, internalformat=None): """Internal method for resize. """ shape = self._normalize_shape(shape) # Check if not self._resizable: raise RuntimeError("Texture is not resizable") # Determine format if format is None: format = self._formats[shape[-1]] # Keep current format if channels match if self._format and \ self._inv_formats[self._format] == self._inv_formats[format]: format = self._format else: format = check_enum(format) if internalformat is None: # Keep current internalformat if channels match if self._internalformat and \ self._inv_internalformats[self._internalformat] == shape[-1]: internalformat = self._internalformat else: internalformat = check_enum(internalformat) # Check if format not in self._inv_formats: raise ValueError('Invalid texture format: %r.' % format) elif shape[-1] != self._inv_formats[format]: raise ValueError('Format does not match with given shape. ' '(format expects %d elements, data has %d)' % (self._inv_formats[format], shape[-1])) if internalformat is None: pass elif internalformat not in self._inv_internalformats: raise ValueError( 'Invalid texture internalformat: %r. Allowed formats: %r' % (internalformat, self._inv_internalformats) ) elif shape[-1] != self._inv_internalformats[internalformat]: raise ValueError('Internalformat does not match with given shape.') # Store and send GLIR command self._shape = shape self._format = format self._internalformat = internalformat self._glir.command('SIZE', self._id, self._shape, self._format, self._internalformat)
[ "def", "_resize", "(", "self", ",", "shape", ",", "format", "=", "None", ",", "internalformat", "=", "None", ")", ":", "shape", "=", "self", ".", "_normalize_shape", "(", "shape", ")", "# Check", "if", "not", "self", ".", "_resizable", ":", "raise", "RuntimeError", "(", "\"Texture is not resizable\"", ")", "# Determine format", "if", "format", "is", "None", ":", "format", "=", "self", ".", "_formats", "[", "shape", "[", "-", "1", "]", "]", "# Keep current format if channels match", "if", "self", ".", "_format", "and", "self", ".", "_inv_formats", "[", "self", ".", "_format", "]", "==", "self", ".", "_inv_formats", "[", "format", "]", ":", "format", "=", "self", ".", "_format", "else", ":", "format", "=", "check_enum", "(", "format", ")", "if", "internalformat", "is", "None", ":", "# Keep current internalformat if channels match", "if", "self", ".", "_internalformat", "and", "self", ".", "_inv_internalformats", "[", "self", ".", "_internalformat", "]", "==", "shape", "[", "-", "1", "]", ":", "internalformat", "=", "self", ".", "_internalformat", "else", ":", "internalformat", "=", "check_enum", "(", "internalformat", ")", "# Check", "if", "format", "not", "in", "self", ".", "_inv_formats", ":", "raise", "ValueError", "(", "'Invalid texture format: %r.'", "%", "format", ")", "elif", "shape", "[", "-", "1", "]", "!=", "self", ".", "_inv_formats", "[", "format", "]", ":", "raise", "ValueError", "(", "'Format does not match with given shape. '", "'(format expects %d elements, data has %d)'", "%", "(", "self", ".", "_inv_formats", "[", "format", "]", ",", "shape", "[", "-", "1", "]", ")", ")", "if", "internalformat", "is", "None", ":", "pass", "elif", "internalformat", "not", "in", "self", ".", "_inv_internalformats", ":", "raise", "ValueError", "(", "'Invalid texture internalformat: %r. Allowed formats: %r'", "%", "(", "internalformat", ",", "self", ".", "_inv_internalformats", ")", ")", "elif", "shape", "[", "-", "1", "]", "!=", "self", ".", "_inv_internalformats", "[", "internalformat", "]", ":", "raise", "ValueError", "(", "'Internalformat does not match with given shape.'", ")", "# Store and send GLIR command", "self", ".", "_shape", "=", "shape", "self", ".", "_format", "=", "format", "self", ".", "_internalformat", "=", "internalformat", "self", ".", "_glir", ".", "command", "(", "'SIZE'", ",", "self", ".", "_id", ",", "self", ".", "_shape", ",", "self", ".", "_format", ",", "self", ".", "_internalformat", ")" ]
Internal method for resize.
[ "Internal", "method", "for", "resize", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/texture.py#L226-L277
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/texture.py
BaseTexture.set_data
def set_data(self, data, offset=None, copy=False): """Set texture data Parameters ---------- data : ndarray Data to be uploaded offset: int | tuple of ints Offset in texture where to start copying data 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. Notes ----- This operation implicitely resizes the texture to the shape of the data if given offset is None. """ return self._set_data(data, offset, copy)
python
def set_data(self, data, offset=None, copy=False): """Set texture data Parameters ---------- data : ndarray Data to be uploaded offset: int | tuple of ints Offset in texture where to start copying data 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. Notes ----- This operation implicitely resizes the texture to the shape of the data if given offset is None. """ return self._set_data(data, offset, copy)
[ "def", "set_data", "(", "self", ",", "data", ",", "offset", "=", "None", ",", "copy", "=", "False", ")", ":", "return", "self", ".", "_set_data", "(", "data", ",", "offset", ",", "copy", ")" ]
Set texture data Parameters ---------- data : ndarray Data to be uploaded offset: int | tuple of ints Offset in texture where to start copying data 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. Notes ----- This operation implicitely resizes the texture to the shape of the data if given offset is None.
[ "Set", "texture", "data" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/texture.py#L279-L298
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/texture.py
BaseTexture._set_data
def _set_data(self, data, offset=None, copy=False): """Internal method for set_data. """ # Copy if needed, check/normalize shape data = np.array(data, copy=copy) data = self._normalize_shape(data) # Maybe resize to purge DATA commands? if offset is None: self._resize(data.shape) elif all([i == 0 for i in offset]) and data.shape == self._shape: self._resize(data.shape) # Convert offset to something usable offset = offset or tuple([0 for i in range(self._ndim)]) assert len(offset) == self._ndim # Check if data fits for i in range(len(data.shape)-1): if offset[i] + data.shape[i] > self._shape[i]: raise ValueError("Data is too large") # Send GLIR command self._glir.command('DATA', self._id, offset, data)
python
def _set_data(self, data, offset=None, copy=False): """Internal method for set_data. """ # Copy if needed, check/normalize shape data = np.array(data, copy=copy) data = self._normalize_shape(data) # Maybe resize to purge DATA commands? if offset is None: self._resize(data.shape) elif all([i == 0 for i in offset]) and data.shape == self._shape: self._resize(data.shape) # Convert offset to something usable offset = offset or tuple([0 for i in range(self._ndim)]) assert len(offset) == self._ndim # Check if data fits for i in range(len(data.shape)-1): if offset[i] + data.shape[i] > self._shape[i]: raise ValueError("Data is too large") # Send GLIR command self._glir.command('DATA', self._id, offset, data)
[ "def", "_set_data", "(", "self", ",", "data", ",", "offset", "=", "None", ",", "copy", "=", "False", ")", ":", "# Copy if needed, check/normalize shape", "data", "=", "np", ".", "array", "(", "data", ",", "copy", "=", "copy", ")", "data", "=", "self", ".", "_normalize_shape", "(", "data", ")", "# Maybe resize to purge DATA commands?", "if", "offset", "is", "None", ":", "self", ".", "_resize", "(", "data", ".", "shape", ")", "elif", "all", "(", "[", "i", "==", "0", "for", "i", "in", "offset", "]", ")", "and", "data", ".", "shape", "==", "self", ".", "_shape", ":", "self", ".", "_resize", "(", "data", ".", "shape", ")", "# Convert offset to something usable", "offset", "=", "offset", "or", "tuple", "(", "[", "0", "for", "i", "in", "range", "(", "self", ".", "_ndim", ")", "]", ")", "assert", "len", "(", "offset", ")", "==", "self", ".", "_ndim", "# Check if data fits", "for", "i", "in", "range", "(", "len", "(", "data", ".", "shape", ")", "-", "1", ")", ":", "if", "offset", "[", "i", "]", "+", "data", ".", "shape", "[", "i", "]", ">", "self", ".", "_shape", "[", "i", "]", ":", "raise", "ValueError", "(", "\"Data is too large\"", ")", "# Send GLIR command", "self", ".", "_glir", ".", "command", "(", "'DATA'", ",", "self", ".", "_id", ",", "offset", ",", "data", ")" ]
Internal method for set_data.
[ "Internal", "method", "for", "set_data", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/texture.py#L300-L324
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/texture.py
TextureEmulated3D.set_data
def set_data(self, data, offset=None, copy=False): """Set texture data Parameters ---------- data : ndarray Data to be uploaded offset: int | tuple of ints Offset in texture where to start copying data 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. Notes ----- This operation implicitely resizes the texture to the shape of the data if given offset is None. """ self._set_emulated_shape(data) Texture2D.set_data(self, self._normalize_emulated_shape(data), offset, copy) self._update_variables()
python
def set_data(self, data, offset=None, copy=False): """Set texture data Parameters ---------- data : ndarray Data to be uploaded offset: int | tuple of ints Offset in texture where to start copying data 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. Notes ----- This operation implicitely resizes the texture to the shape of the data if given offset is None. """ self._set_emulated_shape(data) Texture2D.set_data(self, self._normalize_emulated_shape(data), offset, copy) self._update_variables()
[ "def", "set_data", "(", "self", ",", "data", ",", "offset", "=", "None", ",", "copy", "=", "False", ")", ":", "self", ".", "_set_emulated_shape", "(", "data", ")", "Texture2D", ".", "set_data", "(", "self", ",", "self", ".", "_normalize_emulated_shape", "(", "data", ")", ",", "offset", ",", "copy", ")", "self", ".", "_update_variables", "(", ")" ]
Set texture data Parameters ---------- data : ndarray Data to be uploaded offset: int | tuple of ints Offset in texture where to start copying data 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. Notes ----- This operation implicitely resizes the texture to the shape of the data if given offset is None.
[ "Set", "texture", "data" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/texture.py#L726-L748
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/texture.py
TextureEmulated3D.resize
def resize(self, shape, format=None, internalformat=None): """Set the texture size and format Parameters ---------- shape : tuple of integers New texture shape in zyx order. Optionally, an extra dimention may be specified to indicate the number of color channels. format : str | enum | None The format of the texture: 'luminance', 'alpha', 'luminance_alpha', 'rgb', or 'rgba'. If not given the format is chosen automatically based on the number of channels. When the data has one channel, 'luminance' is assumed. internalformat : str | enum | None The internal (storage) format of the texture: 'luminance', 'alpha', 'r8', 'r16', 'r16f', 'r32f'; 'luminance_alpha', 'rg8', 'rg16', 'rg16f', 'rg32f'; 'rgb', 'rgb8', 'rgb16', 'rgb16f', 'rgb32f'; 'rgba', 'rgba8', 'rgba16', 'rgba16f', 'rgba32f'. If None, the internalformat is chosen automatically based on the number of channels. This is a hint which may be ignored by the OpenGL implementation. """ self._set_emulated_shape(shape) Texture2D.resize(self, self._normalize_emulated_shape(shape), format, internalformat) self._update_variables()
python
def resize(self, shape, format=None, internalformat=None): """Set the texture size and format Parameters ---------- shape : tuple of integers New texture shape in zyx order. Optionally, an extra dimention may be specified to indicate the number of color channels. format : str | enum | None The format of the texture: 'luminance', 'alpha', 'luminance_alpha', 'rgb', or 'rgba'. If not given the format is chosen automatically based on the number of channels. When the data has one channel, 'luminance' is assumed. internalformat : str | enum | None The internal (storage) format of the texture: 'luminance', 'alpha', 'r8', 'r16', 'r16f', 'r32f'; 'luminance_alpha', 'rg8', 'rg16', 'rg16f', 'rg32f'; 'rgb', 'rgb8', 'rgb16', 'rgb16f', 'rgb32f'; 'rgba', 'rgba8', 'rgba16', 'rgba16f', 'rgba32f'. If None, the internalformat is chosen automatically based on the number of channels. This is a hint which may be ignored by the OpenGL implementation. """ self._set_emulated_shape(shape) Texture2D.resize(self, self._normalize_emulated_shape(shape), format, internalformat) self._update_variables()
[ "def", "resize", "(", "self", ",", "shape", ",", "format", "=", "None", ",", "internalformat", "=", "None", ")", ":", "self", ".", "_set_emulated_shape", "(", "shape", ")", "Texture2D", ".", "resize", "(", "self", ",", "self", ".", "_normalize_emulated_shape", "(", "shape", ")", ",", "format", ",", "internalformat", ")", "self", ".", "_update_variables", "(", ")" ]
Set the texture size and format Parameters ---------- shape : tuple of integers New texture shape in zyx order. Optionally, an extra dimention may be specified to indicate the number of color channels. format : str | enum | None The format of the texture: 'luminance', 'alpha', 'luminance_alpha', 'rgb', or 'rgba'. If not given the format is chosen automatically based on the number of channels. When the data has one channel, 'luminance' is assumed. internalformat : str | enum | None The internal (storage) format of the texture: 'luminance', 'alpha', 'r8', 'r16', 'r16f', 'r32f'; 'luminance_alpha', 'rg8', 'rg16', 'rg16f', 'rg32f'; 'rgb', 'rgb8', 'rgb16', 'rgb16f', 'rgb32f'; 'rgba', 'rgba8', 'rgba16', 'rgba16f', 'rgba32f'. If None, the internalformat is chosen automatically based on the number of channels. This is a hint which may be ignored by the OpenGL implementation.
[ "Set", "the", "texture", "size", "and", "format" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/texture.py#L750-L775
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/texture.py
TextureAtlas.get_free_region
def get_free_region(self, width, height): """Get a free region of given size and allocate it Parameters ---------- width : int Width of region to allocate height : int Height of region to allocate Returns ------- bounds : tuple | None A newly allocated region as (x, y, w, h) or None (if failed). """ best_height = best_width = np.inf best_index = -1 for i in range(len(self._atlas_nodes)): y = self._fit(i, width, height) if y >= 0: node = self._atlas_nodes[i] if (y+height < best_height or (y+height == best_height and node[2] < best_width)): best_height = y+height best_index = i best_width = node[2] region = node[0], y, width, height if best_index == -1: return None node = region[0], region[1] + height, width self._atlas_nodes.insert(best_index, node) i = best_index+1 while i < len(self._atlas_nodes): node = self._atlas_nodes[i] prev_node = self._atlas_nodes[i-1] if node[0] < prev_node[0]+prev_node[2]: shrink = prev_node[0]+prev_node[2] - node[0] x, y, w = self._atlas_nodes[i] self._atlas_nodes[i] = x+shrink, y, w-shrink if self._atlas_nodes[i][2] <= 0: del self._atlas_nodes[i] i -= 1 else: break else: break i += 1 # Merge nodes i = 0 while i < len(self._atlas_nodes)-1: node = self._atlas_nodes[i] next_node = self._atlas_nodes[i+1] if node[1] == next_node[1]: self._atlas_nodes[i] = node[0], node[1], node[2]+next_node[2] del self._atlas_nodes[i+1] else: i += 1 return region
python
def get_free_region(self, width, height): """Get a free region of given size and allocate it Parameters ---------- width : int Width of region to allocate height : int Height of region to allocate Returns ------- bounds : tuple | None A newly allocated region as (x, y, w, h) or None (if failed). """ best_height = best_width = np.inf best_index = -1 for i in range(len(self._atlas_nodes)): y = self._fit(i, width, height) if y >= 0: node = self._atlas_nodes[i] if (y+height < best_height or (y+height == best_height and node[2] < best_width)): best_height = y+height best_index = i best_width = node[2] region = node[0], y, width, height if best_index == -1: return None node = region[0], region[1] + height, width self._atlas_nodes.insert(best_index, node) i = best_index+1 while i < len(self._atlas_nodes): node = self._atlas_nodes[i] prev_node = self._atlas_nodes[i-1] if node[0] < prev_node[0]+prev_node[2]: shrink = prev_node[0]+prev_node[2] - node[0] x, y, w = self._atlas_nodes[i] self._atlas_nodes[i] = x+shrink, y, w-shrink if self._atlas_nodes[i][2] <= 0: del self._atlas_nodes[i] i -= 1 else: break else: break i += 1 # Merge nodes i = 0 while i < len(self._atlas_nodes)-1: node = self._atlas_nodes[i] next_node = self._atlas_nodes[i+1] if node[1] == next_node[1]: self._atlas_nodes[i] = node[0], node[1], node[2]+next_node[2] del self._atlas_nodes[i+1] else: i += 1 return region
[ "def", "get_free_region", "(", "self", ",", "width", ",", "height", ")", ":", "best_height", "=", "best_width", "=", "np", ".", "inf", "best_index", "=", "-", "1", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_atlas_nodes", ")", ")", ":", "y", "=", "self", ".", "_fit", "(", "i", ",", "width", ",", "height", ")", "if", "y", ">=", "0", ":", "node", "=", "self", ".", "_atlas_nodes", "[", "i", "]", "if", "(", "y", "+", "height", "<", "best_height", "or", "(", "y", "+", "height", "==", "best_height", "and", "node", "[", "2", "]", "<", "best_width", ")", ")", ":", "best_height", "=", "y", "+", "height", "best_index", "=", "i", "best_width", "=", "node", "[", "2", "]", "region", "=", "node", "[", "0", "]", ",", "y", ",", "width", ",", "height", "if", "best_index", "==", "-", "1", ":", "return", "None", "node", "=", "region", "[", "0", "]", ",", "region", "[", "1", "]", "+", "height", ",", "width", "self", ".", "_atlas_nodes", ".", "insert", "(", "best_index", ",", "node", ")", "i", "=", "best_index", "+", "1", "while", "i", "<", "len", "(", "self", ".", "_atlas_nodes", ")", ":", "node", "=", "self", ".", "_atlas_nodes", "[", "i", "]", "prev_node", "=", "self", ".", "_atlas_nodes", "[", "i", "-", "1", "]", "if", "node", "[", "0", "]", "<", "prev_node", "[", "0", "]", "+", "prev_node", "[", "2", "]", ":", "shrink", "=", "prev_node", "[", "0", "]", "+", "prev_node", "[", "2", "]", "-", "node", "[", "0", "]", "x", ",", "y", ",", "w", "=", "self", ".", "_atlas_nodes", "[", "i", "]", "self", ".", "_atlas_nodes", "[", "i", "]", "=", "x", "+", "shrink", ",", "y", ",", "w", "-", "shrink", "if", "self", ".", "_atlas_nodes", "[", "i", "]", "[", "2", "]", "<=", "0", ":", "del", "self", ".", "_atlas_nodes", "[", "i", "]", "i", "-=", "1", "else", ":", "break", "else", ":", "break", "i", "+=", "1", "# Merge nodes", "i", "=", "0", "while", "i", "<", "len", "(", "self", ".", "_atlas_nodes", ")", "-", "1", ":", "node", "=", "self", ".", "_atlas_nodes", "[", "i", "]", "next_node", "=", "self", ".", "_atlas_nodes", "[", "i", "+", "1", "]", "if", "node", "[", "1", "]", "==", "next_node", "[", "1", "]", ":", "self", ".", "_atlas_nodes", "[", "i", "]", "=", "node", "[", "0", "]", ",", "node", "[", "1", "]", ",", "node", "[", "2", "]", "+", "next_node", "[", "2", "]", "del", "self", ".", "_atlas_nodes", "[", "i", "+", "1", "]", "else", ":", "i", "+=", "1", "return", "region" ]
Get a free region of given size and allocate it Parameters ---------- width : int Width of region to allocate height : int Height of region to allocate Returns ------- bounds : tuple | None A newly allocated region as (x, y, w, h) or None (if failed).
[ "Get", "a", "free", "region", "of", "given", "size", "and", "allocate", "it" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/texture.py#L839-L900
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/texture.py
TextureAtlas._fit
def _fit(self, index, width, height): """Test if region (width, height) fit into self._atlas_nodes[index]""" node = self._atlas_nodes[index] x, y = node[0], node[1] width_left = width if x+width > self._shape[1]: return -1 i = index while width_left > 0: node = self._atlas_nodes[i] y = max(y, node[1]) if y+height > self._shape[0]: return -1 width_left -= node[2] i += 1 return y
python
def _fit(self, index, width, height): """Test if region (width, height) fit into self._atlas_nodes[index]""" node = self._atlas_nodes[index] x, y = node[0], node[1] width_left = width if x+width > self._shape[1]: return -1 i = index while width_left > 0: node = self._atlas_nodes[i] y = max(y, node[1]) if y+height > self._shape[0]: return -1 width_left -= node[2] i += 1 return y
[ "def", "_fit", "(", "self", ",", "index", ",", "width", ",", "height", ")", ":", "node", "=", "self", ".", "_atlas_nodes", "[", "index", "]", "x", ",", "y", "=", "node", "[", "0", "]", ",", "node", "[", "1", "]", "width_left", "=", "width", "if", "x", "+", "width", ">", "self", ".", "_shape", "[", "1", "]", ":", "return", "-", "1", "i", "=", "index", "while", "width_left", ">", "0", ":", "node", "=", "self", ".", "_atlas_nodes", "[", "i", "]", "y", "=", "max", "(", "y", ",", "node", "[", "1", "]", ")", "if", "y", "+", "height", ">", "self", ".", "_shape", "[", "0", "]", ":", "return", "-", "1", "width_left", "-=", "node", "[", "2", "]", "i", "+=", "1", "return", "y" ]
Test if region (width, height) fit into self._atlas_nodes[index]
[ "Test", "if", "region", "(", "width", "height", ")", "fit", "into", "self", ".", "_atlas_nodes", "[", "index", "]" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/texture.py#L902-L917
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/color/colormap.py
_vector_or_scalar
def _vector_or_scalar(x, type='row'): """Convert an object to either a scalar or a row or column vector.""" if isinstance(x, (list, tuple)): x = np.array(x) if isinstance(x, np.ndarray): assert x.ndim == 1 if type == 'column': x = x[:, None] return x
python
def _vector_or_scalar(x, type='row'): """Convert an object to either a scalar or a row or column vector.""" if isinstance(x, (list, tuple)): x = np.array(x) if isinstance(x, np.ndarray): assert x.ndim == 1 if type == 'column': x = x[:, None] return x
[ "def", "_vector_or_scalar", "(", "x", ",", "type", "=", "'row'", ")", ":", "if", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "x", "=", "np", ".", "array", "(", "x", ")", "if", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")", ":", "assert", "x", ".", "ndim", "==", "1", "if", "type", "==", "'column'", ":", "x", "=", "x", "[", ":", ",", "None", "]", "return", "x" ]
Convert an object to either a scalar or a row or column vector.
[ "Convert", "an", "object", "to", "either", "a", "scalar", "or", "a", "row", "or", "column", "vector", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/colormap.py#L20-L28
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/color/colormap.py
_vector
def _vector(x, type='row'): """Convert an object to a row or column vector.""" if isinstance(x, (list, tuple)): x = np.array(x, dtype=np.float32) elif not isinstance(x, np.ndarray): x = np.array([x], dtype=np.float32) assert x.ndim == 1 if type == 'column': x = x[:, None] return x
python
def _vector(x, type='row'): """Convert an object to a row or column vector.""" if isinstance(x, (list, tuple)): x = np.array(x, dtype=np.float32) elif not isinstance(x, np.ndarray): x = np.array([x], dtype=np.float32) assert x.ndim == 1 if type == 'column': x = x[:, None] return x
[ "def", "_vector", "(", "x", ",", "type", "=", "'row'", ")", ":", "if", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "x", "=", "np", ".", "array", "(", "x", ",", "dtype", "=", "np", ".", "float32", ")", "elif", "not", "isinstance", "(", "x", ",", "np", ".", "ndarray", ")", ":", "x", "=", "np", ".", "array", "(", "[", "x", "]", ",", "dtype", "=", "np", ".", "float32", ")", "assert", "x", ".", "ndim", "==", "1", "if", "type", "==", "'column'", ":", "x", "=", "x", "[", ":", ",", "None", "]", "return", "x" ]
Convert an object to a row or column vector.
[ "Convert", "an", "object", "to", "a", "row", "or", "column", "vector", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/colormap.py#L31-L40
train