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/util/dpi/_linux.py
_get_dpi_from
def _get_dpi_from(cmd, pattern, func): """Match pattern against the output of func, passing the results as floats to func. If anything fails, return None. """ try: out, _ = run_subprocess([cmd]) except (OSError, CalledProcessError): pass else: match = re.search(pattern, out) if match: return func(*map(float, match.groups()))
python
def _get_dpi_from(cmd, pattern, func): """Match pattern against the output of func, passing the results as floats to func. If anything fails, return None. """ try: out, _ = run_subprocess([cmd]) except (OSError, CalledProcessError): pass else: match = re.search(pattern, out) if match: return func(*map(float, match.groups()))
[ "def", "_get_dpi_from", "(", "cmd", ",", "pattern", ",", "func", ")", ":", "try", ":", "out", ",", "_", "=", "run_subprocess", "(", "[", "cmd", "]", ")", "except", "(", "OSError", ",", "CalledProcessError", ")", ":", "pass", "else", ":", "match", "=", "re", ".", "search", "(", "pattern", ",", "out", ")", "if", "match", ":", "return", "func", "(", "*", "map", "(", "float", ",", "match", ".", "groups", "(", ")", ")", ")" ]
Match pattern against the output of func, passing the results as floats to func. If anything fails, return None.
[ "Match", "pattern", "against", "the", "output", "of", "func", "passing", "the", "results", "as", "floats", "to", "func", ".", "If", "anything", "fails", "return", "None", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/dpi/_linux.py#L15-L26
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/dpi/_linux.py
get_dpi
def get_dpi(raise_error=True): """Get screen DPI from the OS Parameters ---------- raise_error : bool If True, raise an error if DPI could not be determined. Returns ------- dpi : float Dots per inch of the primary screen. """ # If we are running without an X server (e.g. OSMesa), use a fixed DPI if 'DISPLAY' not in os.environ: return 96. from_xdpyinfo = _get_dpi_from( 'xdpyinfo', r'(\d+)x(\d+) dots per inch', lambda x_dpi, y_dpi: (x_dpi + y_dpi) / 2) if from_xdpyinfo is not None: return from_xdpyinfo from_xrandr = _get_dpi_from( 'xrandr', r'(\d+)x(\d+).*?(\d+)mm x (\d+)mm', lambda x_px, y_px, x_mm, y_mm: 25.4 * (x_px / x_mm + y_px / y_mm) / 2) if from_xrandr is not None: return from_xrandr if raise_error: raise RuntimeError('could not determine DPI') else: logger.warning('could not determine DPI') return 96
python
def get_dpi(raise_error=True): """Get screen DPI from the OS Parameters ---------- raise_error : bool If True, raise an error if DPI could not be determined. Returns ------- dpi : float Dots per inch of the primary screen. """ # If we are running without an X server (e.g. OSMesa), use a fixed DPI if 'DISPLAY' not in os.environ: return 96. from_xdpyinfo = _get_dpi_from( 'xdpyinfo', r'(\d+)x(\d+) dots per inch', lambda x_dpi, y_dpi: (x_dpi + y_dpi) / 2) if from_xdpyinfo is not None: return from_xdpyinfo from_xrandr = _get_dpi_from( 'xrandr', r'(\d+)x(\d+).*?(\d+)mm x (\d+)mm', lambda x_px, y_px, x_mm, y_mm: 25.4 * (x_px / x_mm + y_px / y_mm) / 2) if from_xrandr is not None: return from_xrandr if raise_error: raise RuntimeError('could not determine DPI') else: logger.warning('could not determine DPI') return 96
[ "def", "get_dpi", "(", "raise_error", "=", "True", ")", ":", "# If we are running without an X server (e.g. OSMesa), use a fixed DPI", "if", "'DISPLAY'", "not", "in", "os", ".", "environ", ":", "return", "96.", "from_xdpyinfo", "=", "_get_dpi_from", "(", "'xdpyinfo'", ",", "r'(\\d+)x(\\d+) dots per inch'", ",", "lambda", "x_dpi", ",", "y_dpi", ":", "(", "x_dpi", "+", "y_dpi", ")", "/", "2", ")", "if", "from_xdpyinfo", "is", "not", "None", ":", "return", "from_xdpyinfo", "from_xrandr", "=", "_get_dpi_from", "(", "'xrandr'", ",", "r'(\\d+)x(\\d+).*?(\\d+)mm x (\\d+)mm'", ",", "lambda", "x_px", ",", "y_px", ",", "x_mm", ",", "y_mm", ":", "25.4", "*", "(", "x_px", "/", "x_mm", "+", "y_px", "/", "y_mm", ")", "/", "2", ")", "if", "from_xrandr", "is", "not", "None", ":", "return", "from_xrandr", "if", "raise_error", ":", "raise", "RuntimeError", "(", "'could not determine DPI'", ")", "else", ":", "logger", ".", "warning", "(", "'could not determine DPI'", ")", "return", "96" ]
Get screen DPI from the OS Parameters ---------- raise_error : bool If True, raise an error if DPI could not be determined. Returns ------- dpi : float Dots per inch of the primary screen.
[ "Get", "screen", "DPI", "from", "the", "OS" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/dpi/_linux.py#L29-L61
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/graphs/graph.py
GraphVisual.set_data
def set_data(self, adjacency_mat=None, **kwargs): """Set the data Parameters ---------- adjacency_mat : ndarray | None The adjacency matrix. **kwargs : dict Keyword arguments to pass to the arrows. """ if adjacency_mat is not None: if adjacency_mat.shape[0] != adjacency_mat.shape[1]: raise ValueError("Adjacency matrix should be square.") self._adjacency_mat = adjacency_mat for k in self._arrow_attributes: if k in kwargs: translated = (self._arrow_kw_trans[k] if k in self._arrow_kw_trans else k) setattr(self._edges, translated, kwargs.pop(k)) arrow_kwargs = {} for k in self._arrow_kwargs: if k in kwargs: translated = (self._arrow_kw_trans[k] if k in self._arrow_kw_trans else k) arrow_kwargs[translated] = kwargs.pop(k) node_kwargs = {} for k in self._node_kwargs: if k in kwargs: translated = (self._node_kw_trans[k] if k in self._node_kw_trans else k) node_kwargs[translated] = kwargs.pop(k) if len(kwargs) > 0: raise TypeError("%s.set_data() got invalid keyword arguments: %S" % (self.__class__.__name__, list(kwargs.keys()))) # The actual data is set in GraphVisual.animate_layout or # GraphVisual.set_final_layout self._arrow_data = arrow_kwargs self._node_data = node_kwargs if not self._animate: self.set_final_layout()
python
def set_data(self, adjacency_mat=None, **kwargs): """Set the data Parameters ---------- adjacency_mat : ndarray | None The adjacency matrix. **kwargs : dict Keyword arguments to pass to the arrows. """ if adjacency_mat is not None: if adjacency_mat.shape[0] != adjacency_mat.shape[1]: raise ValueError("Adjacency matrix should be square.") self._adjacency_mat = adjacency_mat for k in self._arrow_attributes: if k in kwargs: translated = (self._arrow_kw_trans[k] if k in self._arrow_kw_trans else k) setattr(self._edges, translated, kwargs.pop(k)) arrow_kwargs = {} for k in self._arrow_kwargs: if k in kwargs: translated = (self._arrow_kw_trans[k] if k in self._arrow_kw_trans else k) arrow_kwargs[translated] = kwargs.pop(k) node_kwargs = {} for k in self._node_kwargs: if k in kwargs: translated = (self._node_kw_trans[k] if k in self._node_kw_trans else k) node_kwargs[translated] = kwargs.pop(k) if len(kwargs) > 0: raise TypeError("%s.set_data() got invalid keyword arguments: %S" % (self.__class__.__name__, list(kwargs.keys()))) # The actual data is set in GraphVisual.animate_layout or # GraphVisual.set_final_layout self._arrow_data = arrow_kwargs self._node_data = node_kwargs if not self._animate: self.set_final_layout()
[ "def", "set_data", "(", "self", ",", "adjacency_mat", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "adjacency_mat", "is", "not", "None", ":", "if", "adjacency_mat", ".", "shape", "[", "0", "]", "!=", "adjacency_mat", ".", "shape", "[", "1", "]", ":", "raise", "ValueError", "(", "\"Adjacency matrix should be square.\"", ")", "self", ".", "_adjacency_mat", "=", "adjacency_mat", "for", "k", "in", "self", ".", "_arrow_attributes", ":", "if", "k", "in", "kwargs", ":", "translated", "=", "(", "self", ".", "_arrow_kw_trans", "[", "k", "]", "if", "k", "in", "self", ".", "_arrow_kw_trans", "else", "k", ")", "setattr", "(", "self", ".", "_edges", ",", "translated", ",", "kwargs", ".", "pop", "(", "k", ")", ")", "arrow_kwargs", "=", "{", "}", "for", "k", "in", "self", ".", "_arrow_kwargs", ":", "if", "k", "in", "kwargs", ":", "translated", "=", "(", "self", ".", "_arrow_kw_trans", "[", "k", "]", "if", "k", "in", "self", ".", "_arrow_kw_trans", "else", "k", ")", "arrow_kwargs", "[", "translated", "]", "=", "kwargs", ".", "pop", "(", "k", ")", "node_kwargs", "=", "{", "}", "for", "k", "in", "self", ".", "_node_kwargs", ":", "if", "k", "in", "kwargs", ":", "translated", "=", "(", "self", ".", "_node_kw_trans", "[", "k", "]", "if", "k", "in", "self", ".", "_node_kw_trans", "else", "k", ")", "node_kwargs", "[", "translated", "]", "=", "kwargs", ".", "pop", "(", "k", ")", "if", "len", "(", "kwargs", ")", ">", "0", ":", "raise", "TypeError", "(", "\"%s.set_data() got invalid keyword arguments: %S\"", "%", "(", "self", ".", "__class__", ".", "__name__", ",", "list", "(", "kwargs", ".", "keys", "(", ")", ")", ")", ")", "# The actual data is set in GraphVisual.animate_layout or", "# GraphVisual.set_final_layout", "self", ".", "_arrow_data", "=", "arrow_kwargs", "self", ".", "_node_data", "=", "node_kwargs", "if", "not", "self", ".", "_animate", ":", "self", ".", "set_final_layout", "(", ")" ]
Set the data Parameters ---------- adjacency_mat : ndarray | None The adjacency matrix. **kwargs : dict Keyword arguments to pass to the arrows.
[ "Set", "the", "data" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/graphs/graph.py#L177-L226
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/widgets/colorbar.py
ColorBarWidget.calc_size
def calc_size(rect, orientation): """Calculate a size Parameters ---------- rect : rectangle The rectangle. orientation : str Either "bottom" or "top". """ (total_halfx, total_halfy) = rect.center if orientation in ["bottom", "top"]: (total_major_axis, total_minor_axis) = (total_halfx, total_halfy) else: (total_major_axis, total_minor_axis) = (total_halfy, total_halfx) major_axis = total_major_axis * (1.0 - ColorBarWidget.major_axis_padding) minor_axis = major_axis * ColorBarWidget.minor_axis_ratio # if the minor axis is "leaking" from the padding, then clamp minor_axis = np.minimum(minor_axis, total_minor_axis * (1.0 - ColorBarWidget.minor_axis_padding)) return (major_axis, minor_axis)
python
def calc_size(rect, orientation): """Calculate a size Parameters ---------- rect : rectangle The rectangle. orientation : str Either "bottom" or "top". """ (total_halfx, total_halfy) = rect.center if orientation in ["bottom", "top"]: (total_major_axis, total_minor_axis) = (total_halfx, total_halfy) else: (total_major_axis, total_minor_axis) = (total_halfy, total_halfx) major_axis = total_major_axis * (1.0 - ColorBarWidget.major_axis_padding) minor_axis = major_axis * ColorBarWidget.minor_axis_ratio # if the minor axis is "leaking" from the padding, then clamp minor_axis = np.minimum(minor_axis, total_minor_axis * (1.0 - ColorBarWidget.minor_axis_padding)) return (major_axis, minor_axis)
[ "def", "calc_size", "(", "rect", ",", "orientation", ")", ":", "(", "total_halfx", ",", "total_halfy", ")", "=", "rect", ".", "center", "if", "orientation", "in", "[", "\"bottom\"", ",", "\"top\"", "]", ":", "(", "total_major_axis", ",", "total_minor_axis", ")", "=", "(", "total_halfx", ",", "total_halfy", ")", "else", ":", "(", "total_major_axis", ",", "total_minor_axis", ")", "=", "(", "total_halfy", ",", "total_halfx", ")", "major_axis", "=", "total_major_axis", "*", "(", "1.0", "-", "ColorBarWidget", ".", "major_axis_padding", ")", "minor_axis", "=", "major_axis", "*", "ColorBarWidget", ".", "minor_axis_ratio", "# if the minor axis is \"leaking\" from the padding, then clamp", "minor_axis", "=", "np", ".", "minimum", "(", "minor_axis", ",", "total_minor_axis", "*", "(", "1.0", "-", "ColorBarWidget", ".", "minor_axis_padding", ")", ")", "return", "(", "major_axis", ",", "minor_axis", ")" ]
Calculate a size Parameters ---------- rect : rectangle The rectangle. orientation : str Either "bottom" or "top".
[ "Calculate", "a", "size" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/widgets/colorbar.py#L101-L126
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/collections/util.py
dtype_reduce
def dtype_reduce(dtype, level=0, depth=0): """ Try to reduce dtype up to a given level when it is possible dtype = [ ('vertex', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('normal', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('color', [('r', 'f4'), ('g', 'f4'), ('b', 'f4'), ('a', 'f4')])] level 0: ['color,vertex,normal,', 10, 'float32'] level 1: [['color', 4, 'float32'] ['normal', 3, 'float32'] ['vertex', 3, 'float32']] """ dtype = np.dtype(dtype) fields = dtype.fields # No fields if fields is None: if len(dtype.shape): count = reduce(mul, dtype.shape) else: count = 1 # size = dtype.itemsize / count if dtype.subdtype: name = str(dtype.subdtype[0]) else: name = str(dtype) return ['', count, name] else: items = [] name = '' # Get reduced fields for key, value in fields.items(): l = dtype_reduce(value[0], level, depth + 1) if type(l[0]) is str: items.append([key, l[1], l[2]]) else: items.append(l) name += key + ',' # Check if we can reduce item list ctype = None count = 0 for i, item in enumerate(items): # One item is a list, we cannot reduce if type(item[0]) is not str: return items else: if i == 0: ctype = item[2] count += item[1] else: if item[2] != ctype: return items count += item[1] if depth >= level: return [name, count, ctype] else: return items
python
def dtype_reduce(dtype, level=0, depth=0): """ Try to reduce dtype up to a given level when it is possible dtype = [ ('vertex', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('normal', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('color', [('r', 'f4'), ('g', 'f4'), ('b', 'f4'), ('a', 'f4')])] level 0: ['color,vertex,normal,', 10, 'float32'] level 1: [['color', 4, 'float32'] ['normal', 3, 'float32'] ['vertex', 3, 'float32']] """ dtype = np.dtype(dtype) fields = dtype.fields # No fields if fields is None: if len(dtype.shape): count = reduce(mul, dtype.shape) else: count = 1 # size = dtype.itemsize / count if dtype.subdtype: name = str(dtype.subdtype[0]) else: name = str(dtype) return ['', count, name] else: items = [] name = '' # Get reduced fields for key, value in fields.items(): l = dtype_reduce(value[0], level, depth + 1) if type(l[0]) is str: items.append([key, l[1], l[2]]) else: items.append(l) name += key + ',' # Check if we can reduce item list ctype = None count = 0 for i, item in enumerate(items): # One item is a list, we cannot reduce if type(item[0]) is not str: return items else: if i == 0: ctype = item[2] count += item[1] else: if item[2] != ctype: return items count += item[1] if depth >= level: return [name, count, ctype] else: return items
[ "def", "dtype_reduce", "(", "dtype", ",", "level", "=", "0", ",", "depth", "=", "0", ")", ":", "dtype", "=", "np", ".", "dtype", "(", "dtype", ")", "fields", "=", "dtype", ".", "fields", "# No fields", "if", "fields", "is", "None", ":", "if", "len", "(", "dtype", ".", "shape", ")", ":", "count", "=", "reduce", "(", "mul", ",", "dtype", ".", "shape", ")", "else", ":", "count", "=", "1", "# size = dtype.itemsize / count", "if", "dtype", ".", "subdtype", ":", "name", "=", "str", "(", "dtype", ".", "subdtype", "[", "0", "]", ")", "else", ":", "name", "=", "str", "(", "dtype", ")", "return", "[", "''", ",", "count", ",", "name", "]", "else", ":", "items", "=", "[", "]", "name", "=", "''", "# Get reduced fields", "for", "key", ",", "value", "in", "fields", ".", "items", "(", ")", ":", "l", "=", "dtype_reduce", "(", "value", "[", "0", "]", ",", "level", ",", "depth", "+", "1", ")", "if", "type", "(", "l", "[", "0", "]", ")", "is", "str", ":", "items", ".", "append", "(", "[", "key", ",", "l", "[", "1", "]", ",", "l", "[", "2", "]", "]", ")", "else", ":", "items", ".", "append", "(", "l", ")", "name", "+=", "key", "+", "','", "# Check if we can reduce item list", "ctype", "=", "None", "count", "=", "0", "for", "i", ",", "item", "in", "enumerate", "(", "items", ")", ":", "# One item is a list, we cannot reduce", "if", "type", "(", "item", "[", "0", "]", ")", "is", "not", "str", ":", "return", "items", "else", ":", "if", "i", "==", "0", ":", "ctype", "=", "item", "[", "2", "]", "count", "+=", "item", "[", "1", "]", "else", ":", "if", "item", "[", "2", "]", "!=", "ctype", ":", "return", "items", "count", "+=", "item", "[", "1", "]", "if", "depth", ">=", "level", ":", "return", "[", "name", ",", "count", ",", "ctype", "]", "else", ":", "return", "items" ]
Try to reduce dtype up to a given level when it is possible dtype = [ ('vertex', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('normal', [('x', 'f4'), ('y', 'f4'), ('z', 'f4')]), ('color', [('r', 'f4'), ('g', 'f4'), ('b', 'f4'), ('a', 'f4')])] level 0: ['color,vertex,normal,', 10, 'float32'] level 1: [['color', 4, 'float32'] ['normal', 3, 'float32'] ['vertex', 3, 'float32']]
[ "Try", "to", "reduce", "dtype", "up", "to", "a", "given", "level", "when", "it", "is", "possible" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/collections/util.py#L13-L72
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/collections/util.py
fetchcode
def fetchcode(utype, prefix=""): """ Generate the GLSL code needed to retrieve fake uniform values from a texture. uniforms : sampler2D Texture to fetch uniforms from uniforms_shape: vec3 Size of texture (width,height,count) where count is the number of float to be fetched. collection_index: float Attribute giving the index of the uniforms to be fetched. This index relates to the index in the uniform array from python side. """ utype = np.dtype(utype) _utype = dtype_reduce(utype, level=1) header = """ uniform sampler2D uniforms; uniform vec3 uniforms_shape; attribute float collection_index; """ # Header generation (easy) types = {1: 'float', 2: 'vec2 ', 3: 'vec3 ', 4: 'vec4 ', 9: 'mat3 ', 16: 'mat4 '} for name, count, _ in _utype: if name != '__unused__': header += "varying %s %s%s;\n" % (types[count], prefix, name) # Body generation (not so easy) body = """\nvoid fetch_uniforms() { float rows = uniforms_shape.x; float cols = uniforms_shape.y; float count = uniforms_shape.z; float index = collection_index; int index_x = int(mod(index, (floor(cols/(count/4.0))))) * int(count/4.0); int index_y = int(floor(index / (floor(cols/(count/4.0))))); float size_x = cols - 1.0; float size_y = rows - 1.0; float ty = 0.0; if (size_y > 0.0) ty = float(index_y)/size_y; int i = index_x; vec4 _uniform;\n""" _utype = dict([(name, count) for name, count, _ in _utype]) store = 0 # Be very careful with utype name order (_utype.keys is wrong) for name in utype.names: if name == '__unused__': continue count, shift = _utype[name], 0 size = count while count: if store == 0: body += "\n _uniform = texture2D(uniforms, vec2(float(i++)/size_x,ty));\n" # noqa store = 4 if store == 4: a = "xyzw" elif store == 3: a = "yzw" elif store == 2: a = "zw" elif store == 1: a = "w" if shift == 0: b = "xyzw" elif shift == 1: b = "yzw" elif shift == 2: b = "zw" elif shift == 3: b = "w" i = min(min(len(b), count), len(a)) if size > 1: body += " %s%s.%s = _uniform.%s;\n" % (prefix, name, b[:i], a[:i]) # noqa else: body += " %s%s = _uniform.%s;\n" % (prefix, name, a[:i]) count -= i shift += i store -= i body += """}\n\n""" return header + body
python
def fetchcode(utype, prefix=""): """ Generate the GLSL code needed to retrieve fake uniform values from a texture. uniforms : sampler2D Texture to fetch uniforms from uniforms_shape: vec3 Size of texture (width,height,count) where count is the number of float to be fetched. collection_index: float Attribute giving the index of the uniforms to be fetched. This index relates to the index in the uniform array from python side. """ utype = np.dtype(utype) _utype = dtype_reduce(utype, level=1) header = """ uniform sampler2D uniforms; uniform vec3 uniforms_shape; attribute float collection_index; """ # Header generation (easy) types = {1: 'float', 2: 'vec2 ', 3: 'vec3 ', 4: 'vec4 ', 9: 'mat3 ', 16: 'mat4 '} for name, count, _ in _utype: if name != '__unused__': header += "varying %s %s%s;\n" % (types[count], prefix, name) # Body generation (not so easy) body = """\nvoid fetch_uniforms() { float rows = uniforms_shape.x; float cols = uniforms_shape.y; float count = uniforms_shape.z; float index = collection_index; int index_x = int(mod(index, (floor(cols/(count/4.0))))) * int(count/4.0); int index_y = int(floor(index / (floor(cols/(count/4.0))))); float size_x = cols - 1.0; float size_y = rows - 1.0; float ty = 0.0; if (size_y > 0.0) ty = float(index_y)/size_y; int i = index_x; vec4 _uniform;\n""" _utype = dict([(name, count) for name, count, _ in _utype]) store = 0 # Be very careful with utype name order (_utype.keys is wrong) for name in utype.names: if name == '__unused__': continue count, shift = _utype[name], 0 size = count while count: if store == 0: body += "\n _uniform = texture2D(uniforms, vec2(float(i++)/size_x,ty));\n" # noqa store = 4 if store == 4: a = "xyzw" elif store == 3: a = "yzw" elif store == 2: a = "zw" elif store == 1: a = "w" if shift == 0: b = "xyzw" elif shift == 1: b = "yzw" elif shift == 2: b = "zw" elif shift == 3: b = "w" i = min(min(len(b), count), len(a)) if size > 1: body += " %s%s.%s = _uniform.%s;\n" % (prefix, name, b[:i], a[:i]) # noqa else: body += " %s%s = _uniform.%s;\n" % (prefix, name, a[:i]) count -= i shift += i store -= i body += """}\n\n""" return header + body
[ "def", "fetchcode", "(", "utype", ",", "prefix", "=", "\"\"", ")", ":", "utype", "=", "np", ".", "dtype", "(", "utype", ")", "_utype", "=", "dtype_reduce", "(", "utype", ",", "level", "=", "1", ")", "header", "=", "\"\"\"\nuniform sampler2D uniforms;\nuniform vec3 uniforms_shape;\nattribute float collection_index;\n\n\"\"\"", "# Header generation (easy)", "types", "=", "{", "1", ":", "'float'", ",", "2", ":", "'vec2 '", ",", "3", ":", "'vec3 '", ",", "4", ":", "'vec4 '", ",", "9", ":", "'mat3 '", ",", "16", ":", "'mat4 '", "}", "for", "name", ",", "count", ",", "_", "in", "_utype", ":", "if", "name", "!=", "'__unused__'", ":", "header", "+=", "\"varying %s %s%s;\\n\"", "%", "(", "types", "[", "count", "]", ",", "prefix", ",", "name", ")", "# Body generation (not so easy)", "body", "=", "\"\"\"\\nvoid fetch_uniforms() {\n float rows = uniforms_shape.x;\n float cols = uniforms_shape.y;\n float count = uniforms_shape.z;\n float index = collection_index;\n int index_x = int(mod(index, (floor(cols/(count/4.0))))) * int(count/4.0);\n int index_y = int(floor(index / (floor(cols/(count/4.0)))));\n float size_x = cols - 1.0;\n float size_y = rows - 1.0;\n float ty = 0.0;\n if (size_y > 0.0)\n ty = float(index_y)/size_y;\n int i = index_x;\n vec4 _uniform;\\n\"\"\"", "_utype", "=", "dict", "(", "[", "(", "name", ",", "count", ")", "for", "name", ",", "count", ",", "_", "in", "_utype", "]", ")", "store", "=", "0", "# Be very careful with utype name order (_utype.keys is wrong)", "for", "name", "in", "utype", ".", "names", ":", "if", "name", "==", "'__unused__'", ":", "continue", "count", ",", "shift", "=", "_utype", "[", "name", "]", ",", "0", "size", "=", "count", "while", "count", ":", "if", "store", "==", "0", ":", "body", "+=", "\"\\n _uniform = texture2D(uniforms, vec2(float(i++)/size_x,ty));\\n\"", "# noqa", "store", "=", "4", "if", "store", "==", "4", ":", "a", "=", "\"xyzw\"", "elif", "store", "==", "3", ":", "a", "=", "\"yzw\"", "elif", "store", "==", "2", ":", "a", "=", "\"zw\"", "elif", "store", "==", "1", ":", "a", "=", "\"w\"", "if", "shift", "==", "0", ":", "b", "=", "\"xyzw\"", "elif", "shift", "==", "1", ":", "b", "=", "\"yzw\"", "elif", "shift", "==", "2", ":", "b", "=", "\"zw\"", "elif", "shift", "==", "3", ":", "b", "=", "\"w\"", "i", "=", "min", "(", "min", "(", "len", "(", "b", ")", ",", "count", ")", ",", "len", "(", "a", ")", ")", "if", "size", ">", "1", ":", "body", "+=", "\" %s%s.%s = _uniform.%s;\\n\"", "%", "(", "prefix", ",", "name", ",", "b", "[", ":", "i", "]", ",", "a", "[", ":", "i", "]", ")", "# noqa", "else", ":", "body", "+=", "\" %s%s = _uniform.%s;\\n\"", "%", "(", "prefix", ",", "name", ",", "a", "[", ":", "i", "]", ")", "count", "-=", "i", "shift", "+=", "i", "store", "-=", "i", "body", "+=", "\"\"\"}\\n\\n\"\"\"", "return", "header", "+", "body" ]
Generate the GLSL code needed to retrieve fake uniform values from a texture. uniforms : sampler2D Texture to fetch uniforms from uniforms_shape: vec3 Size of texture (width,height,count) where count is the number of float to be fetched. collection_index: float Attribute giving the index of the uniforms to be fetched. This index relates to the index in the uniform array from python side.
[ "Generate", "the", "GLSL", "code", "needed", "to", "retrieve", "fake", "uniform", "values", "from", "a", "texture", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/collections/util.py#L75-L163
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/generation.py
create_cube
def create_cube(): """ Generate vertices & indices for a filled and outlined cube Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. filled : array Indices to use to produce a filled cube. outline : array Indices to use to produce an outline of the cube. """ vtype = [('position', np.float32, 3), ('texcoord', np.float32, 2), ('normal', np.float32, 3), ('color', np.float32, 4)] itype = np.uint32 # Vertices positions p = np.array([[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1]]) # Face Normals n = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0], [-1, 0, 1], [0, -1, 0], [0, 0, -1]]) # Vertice colors c = np.array([[1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [1, 0, 1, 1], [1, 0, 0, 1], [1, 1, 0, 1], [0, 1, 0, 1], [0, 0, 0, 1]]) # Texture coords t = np.array([[0, 0], [0, 1], [1, 1], [1, 0]]) faces_p = [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5] faces_c = [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5] faces_n = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5] faces_t = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, 3, 0, 1, 2, 3] vertices = np.zeros(24, vtype) vertices['position'] = p[faces_p] vertices['normal'] = n[faces_n] vertices['color'] = c[faces_c] vertices['texcoord'] = t[faces_t] filled = np.resize( np.array([0, 1, 2, 0, 2, 3], dtype=itype), 6 * (2 * 3)) filled += np.repeat(4 * np.arange(6, dtype=itype), 6) filled = filled.reshape((len(filled) // 3, 3)) outline = np.resize( np.array([0, 1, 1, 2, 2, 3, 3, 0], dtype=itype), 6 * (2 * 4)) outline += np.repeat(4 * np.arange(6, dtype=itype), 8) return vertices, filled, outline
python
def create_cube(): """ Generate vertices & indices for a filled and outlined cube Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. filled : array Indices to use to produce a filled cube. outline : array Indices to use to produce an outline of the cube. """ vtype = [('position', np.float32, 3), ('texcoord', np.float32, 2), ('normal', np.float32, 3), ('color', np.float32, 4)] itype = np.uint32 # Vertices positions p = np.array([[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1]]) # Face Normals n = np.array([[0, 0, 1], [1, 0, 0], [0, 1, 0], [-1, 0, 1], [0, -1, 0], [0, 0, -1]]) # Vertice colors c = np.array([[1, 1, 1, 1], [0, 1, 1, 1], [0, 0, 1, 1], [1, 0, 1, 1], [1, 0, 0, 1], [1, 1, 0, 1], [0, 1, 0, 1], [0, 0, 0, 1]]) # Texture coords t = np.array([[0, 0], [0, 1], [1, 1], [1, 0]]) faces_p = [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5] faces_c = [0, 1, 2, 3, 0, 3, 4, 5, 0, 5, 6, 1, 1, 6, 7, 2, 7, 4, 3, 2, 4, 7, 6, 5] faces_n = [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5] faces_t = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 3, 2, 1, 0, 0, 1, 2, 3, 0, 1, 2, 3] vertices = np.zeros(24, vtype) vertices['position'] = p[faces_p] vertices['normal'] = n[faces_n] vertices['color'] = c[faces_c] vertices['texcoord'] = t[faces_t] filled = np.resize( np.array([0, 1, 2, 0, 2, 3], dtype=itype), 6 * (2 * 3)) filled += np.repeat(4 * np.arange(6, dtype=itype), 6) filled = filled.reshape((len(filled) // 3, 3)) outline = np.resize( np.array([0, 1, 1, 2, 2, 3, 3, 0], dtype=itype), 6 * (2 * 4)) outline += np.repeat(4 * np.arange(6, dtype=itype), 8) return vertices, filled, outline
[ "def", "create_cube", "(", ")", ":", "vtype", "=", "[", "(", "'position'", ",", "np", ".", "float32", ",", "3", ")", ",", "(", "'texcoord'", ",", "np", ".", "float32", ",", "2", ")", ",", "(", "'normal'", ",", "np", ".", "float32", ",", "3", ")", ",", "(", "'color'", ",", "np", ".", "float32", ",", "4", ")", "]", "itype", "=", "np", ".", "uint32", "# Vertices positions", "p", "=", "np", ".", "array", "(", "[", "[", "1", ",", "1", ",", "1", "]", ",", "[", "-", "1", ",", "1", ",", "1", "]", ",", "[", "-", "1", ",", "-", "1", ",", "1", "]", ",", "[", "1", ",", "-", "1", ",", "1", "]", ",", "[", "1", ",", "-", "1", ",", "-", "1", "]", ",", "[", "1", ",", "1", ",", "-", "1", "]", ",", "[", "-", "1", ",", "1", ",", "-", "1", "]", ",", "[", "-", "1", ",", "-", "1", ",", "-", "1", "]", "]", ")", "# Face Normals", "n", "=", "np", ".", "array", "(", "[", "[", "0", ",", "0", ",", "1", "]", ",", "[", "1", ",", "0", ",", "0", "]", ",", "[", "0", ",", "1", ",", "0", "]", ",", "[", "-", "1", ",", "0", ",", "1", "]", ",", "[", "0", ",", "-", "1", ",", "0", "]", ",", "[", "0", ",", "0", ",", "-", "1", "]", "]", ")", "# Vertice colors", "c", "=", "np", ".", "array", "(", "[", "[", "1", ",", "1", ",", "1", ",", "1", "]", ",", "[", "0", ",", "1", ",", "1", ",", "1", "]", ",", "[", "0", ",", "0", ",", "1", ",", "1", "]", ",", "[", "1", ",", "0", ",", "1", ",", "1", "]", ",", "[", "1", ",", "0", ",", "0", ",", "1", "]", ",", "[", "1", ",", "1", ",", "0", ",", "1", "]", ",", "[", "0", ",", "1", ",", "0", ",", "1", "]", ",", "[", "0", ",", "0", ",", "0", ",", "1", "]", "]", ")", "# Texture coords", "t", "=", "np", ".", "array", "(", "[", "[", "0", ",", "0", "]", ",", "[", "0", ",", "1", "]", ",", "[", "1", ",", "1", "]", ",", "[", "1", ",", "0", "]", "]", ")", "faces_p", "=", "[", "0", ",", "1", ",", "2", ",", "3", ",", "0", ",", "3", ",", "4", ",", "5", ",", "0", ",", "5", ",", "6", ",", "1", ",", "1", ",", "6", ",", "7", ",", "2", ",", "7", ",", "4", ",", "3", ",", "2", ",", "4", ",", "7", ",", "6", ",", "5", "]", "faces_c", "=", "[", "0", ",", "1", ",", "2", ",", "3", ",", "0", ",", "3", ",", "4", ",", "5", ",", "0", ",", "5", ",", "6", ",", "1", ",", "1", ",", "6", ",", "7", ",", "2", ",", "7", ",", "4", ",", "3", ",", "2", ",", "4", ",", "7", ",", "6", ",", "5", "]", "faces_n", "=", "[", "0", ",", "0", ",", "0", ",", "0", ",", "1", ",", "1", ",", "1", ",", "1", ",", "2", ",", "2", ",", "2", ",", "2", ",", "3", ",", "3", ",", "3", ",", "3", ",", "4", ",", "4", ",", "4", ",", "4", ",", "5", ",", "5", ",", "5", ",", "5", "]", "faces_t", "=", "[", "0", ",", "1", ",", "2", ",", "3", ",", "0", ",", "1", ",", "2", ",", "3", ",", "0", ",", "1", ",", "2", ",", "3", ",", "3", ",", "2", ",", "1", ",", "0", ",", "0", ",", "1", ",", "2", ",", "3", ",", "0", ",", "1", ",", "2", ",", "3", "]", "vertices", "=", "np", ".", "zeros", "(", "24", ",", "vtype", ")", "vertices", "[", "'position'", "]", "=", "p", "[", "faces_p", "]", "vertices", "[", "'normal'", "]", "=", "n", "[", "faces_n", "]", "vertices", "[", "'color'", "]", "=", "c", "[", "faces_c", "]", "vertices", "[", "'texcoord'", "]", "=", "t", "[", "faces_t", "]", "filled", "=", "np", ".", "resize", "(", "np", ".", "array", "(", "[", "0", ",", "1", ",", "2", ",", "0", ",", "2", ",", "3", "]", ",", "dtype", "=", "itype", ")", ",", "6", "*", "(", "2", "*", "3", ")", ")", "filled", "+=", "np", ".", "repeat", "(", "4", "*", "np", ".", "arange", "(", "6", ",", "dtype", "=", "itype", ")", ",", "6", ")", "filled", "=", "filled", ".", "reshape", "(", "(", "len", "(", "filled", ")", "//", "3", ",", "3", ")", ")", "outline", "=", "np", ".", "resize", "(", "np", ".", "array", "(", "[", "0", ",", "1", ",", "1", ",", "2", ",", "2", ",", "3", ",", "3", ",", "0", "]", ",", "dtype", "=", "itype", ")", ",", "6", "*", "(", "2", "*", "4", ")", ")", "outline", "+=", "np", ".", "repeat", "(", "4", "*", "np", ".", "arange", "(", "6", ",", "dtype", "=", "itype", ")", ",", "8", ")", "return", "vertices", ",", "filled", ",", "outline" ]
Generate vertices & indices for a filled and outlined cube Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. filled : array Indices to use to produce a filled cube. outline : array Indices to use to produce an outline of the cube.
[ "Generate", "vertices", "&", "indices", "for", "a", "filled", "and", "outlined", "cube" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/generation.py#L16-L89
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/generation.py
create_plane
def create_plane(width=1, height=1, width_segments=1, height_segments=1, direction='+z'): """ Generate vertices & indices for a filled and outlined plane. Parameters ---------- width : float Plane width. height : float Plane height. width_segments : int Plane segments count along the width. height_segments : float Plane segments count along the height. direction: unicode ``{'-x', '+x', '-y', '+y', '-z', '+z'}`` Direction the plane will be facing. Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. faces : array Indices to use to produce a filled plane. outline : array Indices to use to produce an outline of the plane. References ---------- .. [1] Cabello, R. (n.d.). PlaneBufferGeometry.js. Retrieved May 12, 2015, from http://git.io/vU1Fh """ x_grid = width_segments y_grid = height_segments x_grid1 = x_grid + 1 y_grid1 = y_grid + 1 # Positions, normals and texcoords. positions = np.zeros(x_grid1 * y_grid1 * 3) normals = np.zeros(x_grid1 * y_grid1 * 3) texcoords = np.zeros(x_grid1 * y_grid1 * 2) y = np.arange(y_grid1) * height / y_grid - height / 2 x = np.arange(x_grid1) * width / x_grid - width / 2 positions[::3] = np.tile(x, y_grid1) positions[1::3] = -np.repeat(y, x_grid1) normals[2::3] = 1 texcoords[::2] = np.tile(np.arange(x_grid1) / x_grid, y_grid1) texcoords[1::2] = np.repeat(1 - np.arange(y_grid1) / y_grid, x_grid1) # Faces and outline. faces, outline = [], [] for i_y in range(y_grid): for i_x in range(x_grid): a = i_x + x_grid1 * i_y b = i_x + x_grid1 * (i_y + 1) c = (i_x + 1) + x_grid1 * (i_y + 1) d = (i_x + 1) + x_grid1 * i_y faces.extend(((a, b, d), (b, c, d))) outline.extend(((a, b), (b, c), (c, d), (d, a))) positions = np.reshape(positions, (-1, 3)) texcoords = np.reshape(texcoords, (-1, 2)) normals = np.reshape(normals, (-1, 3)) faces = np.reshape(faces, (-1, 3)).astype(np.uint32) outline = np.reshape(outline, (-1, 2)).astype(np.uint32) direction = direction.lower() if direction in ('-x', '+x'): shift, neutral_axis = 1, 0 elif direction in ('-y', '+y'): shift, neutral_axis = -1, 1 elif direction in ('-z', '+z'): shift, neutral_axis = 0, 2 sign = -1 if '-' in direction else 1 positions = np.roll(positions, shift, -1) normals = np.roll(normals, shift, -1) * sign colors = np.ravel(positions) colors = np.hstack((np.reshape(np.interp(colors, (np.min(colors), np.max(colors)), (0, 1)), positions.shape), np.ones((positions.shape[0], 1)))) colors[..., neutral_axis] = 0 vertices = np.zeros(positions.shape[0], [('position', np.float32, 3), ('texcoord', np.float32, 2), ('normal', np.float32, 3), ('color', np.float32, 4)]) vertices['position'] = positions vertices['texcoord'] = texcoords vertices['normal'] = normals vertices['color'] = colors return vertices, faces, outline
python
def create_plane(width=1, height=1, width_segments=1, height_segments=1, direction='+z'): """ Generate vertices & indices for a filled and outlined plane. Parameters ---------- width : float Plane width. height : float Plane height. width_segments : int Plane segments count along the width. height_segments : float Plane segments count along the height. direction: unicode ``{'-x', '+x', '-y', '+y', '-z', '+z'}`` Direction the plane will be facing. Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. faces : array Indices to use to produce a filled plane. outline : array Indices to use to produce an outline of the plane. References ---------- .. [1] Cabello, R. (n.d.). PlaneBufferGeometry.js. Retrieved May 12, 2015, from http://git.io/vU1Fh """ x_grid = width_segments y_grid = height_segments x_grid1 = x_grid + 1 y_grid1 = y_grid + 1 # Positions, normals and texcoords. positions = np.zeros(x_grid1 * y_grid1 * 3) normals = np.zeros(x_grid1 * y_grid1 * 3) texcoords = np.zeros(x_grid1 * y_grid1 * 2) y = np.arange(y_grid1) * height / y_grid - height / 2 x = np.arange(x_grid1) * width / x_grid - width / 2 positions[::3] = np.tile(x, y_grid1) positions[1::3] = -np.repeat(y, x_grid1) normals[2::3] = 1 texcoords[::2] = np.tile(np.arange(x_grid1) / x_grid, y_grid1) texcoords[1::2] = np.repeat(1 - np.arange(y_grid1) / y_grid, x_grid1) # Faces and outline. faces, outline = [], [] for i_y in range(y_grid): for i_x in range(x_grid): a = i_x + x_grid1 * i_y b = i_x + x_grid1 * (i_y + 1) c = (i_x + 1) + x_grid1 * (i_y + 1) d = (i_x + 1) + x_grid1 * i_y faces.extend(((a, b, d), (b, c, d))) outline.extend(((a, b), (b, c), (c, d), (d, a))) positions = np.reshape(positions, (-1, 3)) texcoords = np.reshape(texcoords, (-1, 2)) normals = np.reshape(normals, (-1, 3)) faces = np.reshape(faces, (-1, 3)).astype(np.uint32) outline = np.reshape(outline, (-1, 2)).astype(np.uint32) direction = direction.lower() if direction in ('-x', '+x'): shift, neutral_axis = 1, 0 elif direction in ('-y', '+y'): shift, neutral_axis = -1, 1 elif direction in ('-z', '+z'): shift, neutral_axis = 0, 2 sign = -1 if '-' in direction else 1 positions = np.roll(positions, shift, -1) normals = np.roll(normals, shift, -1) * sign colors = np.ravel(positions) colors = np.hstack((np.reshape(np.interp(colors, (np.min(colors), np.max(colors)), (0, 1)), positions.shape), np.ones((positions.shape[0], 1)))) colors[..., neutral_axis] = 0 vertices = np.zeros(positions.shape[0], [('position', np.float32, 3), ('texcoord', np.float32, 2), ('normal', np.float32, 3), ('color', np.float32, 4)]) vertices['position'] = positions vertices['texcoord'] = texcoords vertices['normal'] = normals vertices['color'] = colors return vertices, faces, outline
[ "def", "create_plane", "(", "width", "=", "1", ",", "height", "=", "1", ",", "width_segments", "=", "1", ",", "height_segments", "=", "1", ",", "direction", "=", "'+z'", ")", ":", "x_grid", "=", "width_segments", "y_grid", "=", "height_segments", "x_grid1", "=", "x_grid", "+", "1", "y_grid1", "=", "y_grid", "+", "1", "# Positions, normals and texcoords.", "positions", "=", "np", ".", "zeros", "(", "x_grid1", "*", "y_grid1", "*", "3", ")", "normals", "=", "np", ".", "zeros", "(", "x_grid1", "*", "y_grid1", "*", "3", ")", "texcoords", "=", "np", ".", "zeros", "(", "x_grid1", "*", "y_grid1", "*", "2", ")", "y", "=", "np", ".", "arange", "(", "y_grid1", ")", "*", "height", "/", "y_grid", "-", "height", "/", "2", "x", "=", "np", ".", "arange", "(", "x_grid1", ")", "*", "width", "/", "x_grid", "-", "width", "/", "2", "positions", "[", ":", ":", "3", "]", "=", "np", ".", "tile", "(", "x", ",", "y_grid1", ")", "positions", "[", "1", ":", ":", "3", "]", "=", "-", "np", ".", "repeat", "(", "y", ",", "x_grid1", ")", "normals", "[", "2", ":", ":", "3", "]", "=", "1", "texcoords", "[", ":", ":", "2", "]", "=", "np", ".", "tile", "(", "np", ".", "arange", "(", "x_grid1", ")", "/", "x_grid", ",", "y_grid1", ")", "texcoords", "[", "1", ":", ":", "2", "]", "=", "np", ".", "repeat", "(", "1", "-", "np", ".", "arange", "(", "y_grid1", ")", "/", "y_grid", ",", "x_grid1", ")", "# Faces and outline.", "faces", ",", "outline", "=", "[", "]", ",", "[", "]", "for", "i_y", "in", "range", "(", "y_grid", ")", ":", "for", "i_x", "in", "range", "(", "x_grid", ")", ":", "a", "=", "i_x", "+", "x_grid1", "*", "i_y", "b", "=", "i_x", "+", "x_grid1", "*", "(", "i_y", "+", "1", ")", "c", "=", "(", "i_x", "+", "1", ")", "+", "x_grid1", "*", "(", "i_y", "+", "1", ")", "d", "=", "(", "i_x", "+", "1", ")", "+", "x_grid1", "*", "i_y", "faces", ".", "extend", "(", "(", "(", "a", ",", "b", ",", "d", ")", ",", "(", "b", ",", "c", ",", "d", ")", ")", ")", "outline", ".", "extend", "(", "(", "(", "a", ",", "b", ")", ",", "(", "b", ",", "c", ")", ",", "(", "c", ",", "d", ")", ",", "(", "d", ",", "a", ")", ")", ")", "positions", "=", "np", ".", "reshape", "(", "positions", ",", "(", "-", "1", ",", "3", ")", ")", "texcoords", "=", "np", ".", "reshape", "(", "texcoords", ",", "(", "-", "1", ",", "2", ")", ")", "normals", "=", "np", ".", "reshape", "(", "normals", ",", "(", "-", "1", ",", "3", ")", ")", "faces", "=", "np", ".", "reshape", "(", "faces", ",", "(", "-", "1", ",", "3", ")", ")", ".", "astype", "(", "np", ".", "uint32", ")", "outline", "=", "np", ".", "reshape", "(", "outline", ",", "(", "-", "1", ",", "2", ")", ")", ".", "astype", "(", "np", ".", "uint32", ")", "direction", "=", "direction", ".", "lower", "(", ")", "if", "direction", "in", "(", "'-x'", ",", "'+x'", ")", ":", "shift", ",", "neutral_axis", "=", "1", ",", "0", "elif", "direction", "in", "(", "'-y'", ",", "'+y'", ")", ":", "shift", ",", "neutral_axis", "=", "-", "1", ",", "1", "elif", "direction", "in", "(", "'-z'", ",", "'+z'", ")", ":", "shift", ",", "neutral_axis", "=", "0", ",", "2", "sign", "=", "-", "1", "if", "'-'", "in", "direction", "else", "1", "positions", "=", "np", ".", "roll", "(", "positions", ",", "shift", ",", "-", "1", ")", "normals", "=", "np", ".", "roll", "(", "normals", ",", "shift", ",", "-", "1", ")", "*", "sign", "colors", "=", "np", ".", "ravel", "(", "positions", ")", "colors", "=", "np", ".", "hstack", "(", "(", "np", ".", "reshape", "(", "np", ".", "interp", "(", "colors", ",", "(", "np", ".", "min", "(", "colors", ")", ",", "np", ".", "max", "(", "colors", ")", ")", ",", "(", "0", ",", "1", ")", ")", ",", "positions", ".", "shape", ")", ",", "np", ".", "ones", "(", "(", "positions", ".", "shape", "[", "0", "]", ",", "1", ")", ")", ")", ")", "colors", "[", "...", ",", "neutral_axis", "]", "=", "0", "vertices", "=", "np", ".", "zeros", "(", "positions", ".", "shape", "[", "0", "]", ",", "[", "(", "'position'", ",", "np", ".", "float32", ",", "3", ")", ",", "(", "'texcoord'", ",", "np", ".", "float32", ",", "2", ")", ",", "(", "'normal'", ",", "np", ".", "float32", ",", "3", ")", ",", "(", "'color'", ",", "np", ".", "float32", ",", "4", ")", "]", ")", "vertices", "[", "'position'", "]", "=", "positions", "vertices", "[", "'texcoord'", "]", "=", "texcoords", "vertices", "[", "'normal'", "]", "=", "normals", "vertices", "[", "'color'", "]", "=", "colors", "return", "vertices", ",", "faces", ",", "outline" ]
Generate vertices & indices for a filled and outlined plane. Parameters ---------- width : float Plane width. height : float Plane height. width_segments : int Plane segments count along the width. height_segments : float Plane segments count along the height. direction: unicode ``{'-x', '+x', '-y', '+y', '-z', '+z'}`` Direction the plane will be facing. Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. faces : array Indices to use to produce a filled plane. outline : array Indices to use to produce an outline of the plane. References ---------- .. [1] Cabello, R. (n.d.). PlaneBufferGeometry.js. Retrieved May 12, 2015, from http://git.io/vU1Fh
[ "Generate", "vertices", "&", "indices", "for", "a", "filled", "and", "outlined", "plane", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/generation.py#L92-L198
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/generation.py
create_box
def create_box(width=1, height=1, depth=1, width_segments=1, height_segments=1, depth_segments=1, planes=None): """ Generate vertices & indices for a filled and outlined box. Parameters ---------- width : float Box width. height : float Box height. depth : float Box depth. width_segments : int Box segments count along the width. height_segments : float Box segments count along the height. depth_segments : float Box segments count along the depth. planes: array_like Any combination of ``{'-x', '+x', '-y', '+y', '-z', '+z'}`` Included planes in the box construction. Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. faces : array Indices to use to produce a filled box. outline : array Indices to use to produce an outline of the box. """ planes = (('+x', '-x', '+y', '-y', '+z', '-z') if planes is None else [d.lower() for d in planes]) w_s, h_s, d_s = width_segments, height_segments, depth_segments planes_m = [] if '-z' in planes: planes_m.append(create_plane(width, depth, w_s, d_s, '-z')) planes_m[-1][0]['position'][..., 2] -= height / 2 if '+z' in planes: planes_m.append(create_plane(width, depth, w_s, d_s, '+z')) planes_m[-1][0]['position'][..., 2] += height / 2 if '-y' in planes: planes_m.append(create_plane(height, width, h_s, w_s, '-y')) planes_m[-1][0]['position'][..., 1] -= depth / 2 if '+y' in planes: planes_m.append(create_plane(height, width, h_s, w_s, '+y')) planes_m[-1][0]['position'][..., 1] += depth / 2 if '-x' in planes: planes_m.append(create_plane(depth, height, d_s, h_s, '-x')) planes_m[-1][0]['position'][..., 0] -= width / 2 if '+x' in planes: planes_m.append(create_plane(depth, height, d_s, h_s, '+x')) planes_m[-1][0]['position'][..., 0] += width / 2 positions = np.zeros((0, 3), dtype=np.float32) texcoords = np.zeros((0, 2), dtype=np.float32) normals = np.zeros((0, 3), dtype=np.float32) faces = np.zeros((0, 3), dtype=np.uint32) outline = np.zeros((0, 2), dtype=np.uint32) offset = 0 for vertices_p, faces_p, outline_p in planes_m: positions = np.vstack((positions, vertices_p['position'])) texcoords = np.vstack((texcoords, vertices_p['texcoord'])) normals = np.vstack((normals, vertices_p['normal'])) faces = np.vstack((faces, faces_p + offset)) outline = np.vstack((outline, outline_p + offset)) offset += vertices_p['position'].shape[0] vertices = np.zeros(positions.shape[0], [('position', np.float32, 3), ('texcoord', np.float32, 2), ('normal', np.float32, 3), ('color', np.float32, 4)]) colors = np.ravel(positions) colors = np.hstack((np.reshape(np.interp(colors, (np.min(colors), np.max(colors)), (0, 1)), positions.shape), np.ones((positions.shape[0], 1)))) vertices['position'] = positions vertices['texcoord'] = texcoords vertices['normal'] = normals vertices['color'] = colors return vertices, faces, outline
python
def create_box(width=1, height=1, depth=1, width_segments=1, height_segments=1, depth_segments=1, planes=None): """ Generate vertices & indices for a filled and outlined box. Parameters ---------- width : float Box width. height : float Box height. depth : float Box depth. width_segments : int Box segments count along the width. height_segments : float Box segments count along the height. depth_segments : float Box segments count along the depth. planes: array_like Any combination of ``{'-x', '+x', '-y', '+y', '-z', '+z'}`` Included planes in the box construction. Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. faces : array Indices to use to produce a filled box. outline : array Indices to use to produce an outline of the box. """ planes = (('+x', '-x', '+y', '-y', '+z', '-z') if planes is None else [d.lower() for d in planes]) w_s, h_s, d_s = width_segments, height_segments, depth_segments planes_m = [] if '-z' in planes: planes_m.append(create_plane(width, depth, w_s, d_s, '-z')) planes_m[-1][0]['position'][..., 2] -= height / 2 if '+z' in planes: planes_m.append(create_plane(width, depth, w_s, d_s, '+z')) planes_m[-1][0]['position'][..., 2] += height / 2 if '-y' in planes: planes_m.append(create_plane(height, width, h_s, w_s, '-y')) planes_m[-1][0]['position'][..., 1] -= depth / 2 if '+y' in planes: planes_m.append(create_plane(height, width, h_s, w_s, '+y')) planes_m[-1][0]['position'][..., 1] += depth / 2 if '-x' in planes: planes_m.append(create_plane(depth, height, d_s, h_s, '-x')) planes_m[-1][0]['position'][..., 0] -= width / 2 if '+x' in planes: planes_m.append(create_plane(depth, height, d_s, h_s, '+x')) planes_m[-1][0]['position'][..., 0] += width / 2 positions = np.zeros((0, 3), dtype=np.float32) texcoords = np.zeros((0, 2), dtype=np.float32) normals = np.zeros((0, 3), dtype=np.float32) faces = np.zeros((0, 3), dtype=np.uint32) outline = np.zeros((0, 2), dtype=np.uint32) offset = 0 for vertices_p, faces_p, outline_p in planes_m: positions = np.vstack((positions, vertices_p['position'])) texcoords = np.vstack((texcoords, vertices_p['texcoord'])) normals = np.vstack((normals, vertices_p['normal'])) faces = np.vstack((faces, faces_p + offset)) outline = np.vstack((outline, outline_p + offset)) offset += vertices_p['position'].shape[0] vertices = np.zeros(positions.shape[0], [('position', np.float32, 3), ('texcoord', np.float32, 2), ('normal', np.float32, 3), ('color', np.float32, 4)]) colors = np.ravel(positions) colors = np.hstack((np.reshape(np.interp(colors, (np.min(colors), np.max(colors)), (0, 1)), positions.shape), np.ones((positions.shape[0], 1)))) vertices['position'] = positions vertices['texcoord'] = texcoords vertices['normal'] = normals vertices['color'] = colors return vertices, faces, outline
[ "def", "create_box", "(", "width", "=", "1", ",", "height", "=", "1", ",", "depth", "=", "1", ",", "width_segments", "=", "1", ",", "height_segments", "=", "1", ",", "depth_segments", "=", "1", ",", "planes", "=", "None", ")", ":", "planes", "=", "(", "(", "'+x'", ",", "'-x'", ",", "'+y'", ",", "'-y'", ",", "'+z'", ",", "'-z'", ")", "if", "planes", "is", "None", "else", "[", "d", ".", "lower", "(", ")", "for", "d", "in", "planes", "]", ")", "w_s", ",", "h_s", ",", "d_s", "=", "width_segments", ",", "height_segments", ",", "depth_segments", "planes_m", "=", "[", "]", "if", "'-z'", "in", "planes", ":", "planes_m", ".", "append", "(", "create_plane", "(", "width", ",", "depth", ",", "w_s", ",", "d_s", ",", "'-z'", ")", ")", "planes_m", "[", "-", "1", "]", "[", "0", "]", "[", "'position'", "]", "[", "...", ",", "2", "]", "-=", "height", "/", "2", "if", "'+z'", "in", "planes", ":", "planes_m", ".", "append", "(", "create_plane", "(", "width", ",", "depth", ",", "w_s", ",", "d_s", ",", "'+z'", ")", ")", "planes_m", "[", "-", "1", "]", "[", "0", "]", "[", "'position'", "]", "[", "...", ",", "2", "]", "+=", "height", "/", "2", "if", "'-y'", "in", "planes", ":", "planes_m", ".", "append", "(", "create_plane", "(", "height", ",", "width", ",", "h_s", ",", "w_s", ",", "'-y'", ")", ")", "planes_m", "[", "-", "1", "]", "[", "0", "]", "[", "'position'", "]", "[", "...", ",", "1", "]", "-=", "depth", "/", "2", "if", "'+y'", "in", "planes", ":", "planes_m", ".", "append", "(", "create_plane", "(", "height", ",", "width", ",", "h_s", ",", "w_s", ",", "'+y'", ")", ")", "planes_m", "[", "-", "1", "]", "[", "0", "]", "[", "'position'", "]", "[", "...", ",", "1", "]", "+=", "depth", "/", "2", "if", "'-x'", "in", "planes", ":", "planes_m", ".", "append", "(", "create_plane", "(", "depth", ",", "height", ",", "d_s", ",", "h_s", ",", "'-x'", ")", ")", "planes_m", "[", "-", "1", "]", "[", "0", "]", "[", "'position'", "]", "[", "...", ",", "0", "]", "-=", "width", "/", "2", "if", "'+x'", "in", "planes", ":", "planes_m", ".", "append", "(", "create_plane", "(", "depth", ",", "height", ",", "d_s", ",", "h_s", ",", "'+x'", ")", ")", "planes_m", "[", "-", "1", "]", "[", "0", "]", "[", "'position'", "]", "[", "...", ",", "0", "]", "+=", "width", "/", "2", "positions", "=", "np", ".", "zeros", "(", "(", "0", ",", "3", ")", ",", "dtype", "=", "np", ".", "float32", ")", "texcoords", "=", "np", ".", "zeros", "(", "(", "0", ",", "2", ")", ",", "dtype", "=", "np", ".", "float32", ")", "normals", "=", "np", ".", "zeros", "(", "(", "0", ",", "3", ")", ",", "dtype", "=", "np", ".", "float32", ")", "faces", "=", "np", ".", "zeros", "(", "(", "0", ",", "3", ")", ",", "dtype", "=", "np", ".", "uint32", ")", "outline", "=", "np", ".", "zeros", "(", "(", "0", ",", "2", ")", ",", "dtype", "=", "np", ".", "uint32", ")", "offset", "=", "0", "for", "vertices_p", ",", "faces_p", ",", "outline_p", "in", "planes_m", ":", "positions", "=", "np", ".", "vstack", "(", "(", "positions", ",", "vertices_p", "[", "'position'", "]", ")", ")", "texcoords", "=", "np", ".", "vstack", "(", "(", "texcoords", ",", "vertices_p", "[", "'texcoord'", "]", ")", ")", "normals", "=", "np", ".", "vstack", "(", "(", "normals", ",", "vertices_p", "[", "'normal'", "]", ")", ")", "faces", "=", "np", ".", "vstack", "(", "(", "faces", ",", "faces_p", "+", "offset", ")", ")", "outline", "=", "np", ".", "vstack", "(", "(", "outline", ",", "outline_p", "+", "offset", ")", ")", "offset", "+=", "vertices_p", "[", "'position'", "]", ".", "shape", "[", "0", "]", "vertices", "=", "np", ".", "zeros", "(", "positions", ".", "shape", "[", "0", "]", ",", "[", "(", "'position'", ",", "np", ".", "float32", ",", "3", ")", ",", "(", "'texcoord'", ",", "np", ".", "float32", ",", "2", ")", ",", "(", "'normal'", ",", "np", ".", "float32", ",", "3", ")", ",", "(", "'color'", ",", "np", ".", "float32", ",", "4", ")", "]", ")", "colors", "=", "np", ".", "ravel", "(", "positions", ")", "colors", "=", "np", ".", "hstack", "(", "(", "np", ".", "reshape", "(", "np", ".", "interp", "(", "colors", ",", "(", "np", ".", "min", "(", "colors", ")", ",", "np", ".", "max", "(", "colors", ")", ")", ",", "(", "0", ",", "1", ")", ")", ",", "positions", ".", "shape", ")", ",", "np", ".", "ones", "(", "(", "positions", ".", "shape", "[", "0", "]", ",", "1", ")", ")", ")", ")", "vertices", "[", "'position'", "]", "=", "positions", "vertices", "[", "'texcoord'", "]", "=", "texcoords", "vertices", "[", "'normal'", "]", "=", "normals", "vertices", "[", "'color'", "]", "=", "colors", "return", "vertices", ",", "faces", ",", "outline" ]
Generate vertices & indices for a filled and outlined box. Parameters ---------- width : float Box width. height : float Box height. depth : float Box depth. width_segments : int Box segments count along the width. height_segments : float Box segments count along the height. depth_segments : float Box segments count along the depth. planes: array_like Any combination of ``{'-x', '+x', '-y', '+y', '-z', '+z'}`` Included planes in the box construction. Returns ------- vertices : array Array of vertices suitable for use as a VertexBuffer. faces : array Indices to use to produce a filled box. outline : array Indices to use to produce an outline of the box.
[ "Generate", "vertices", "&", "indices", "for", "a", "filled", "and", "outlined", "box", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/generation.py#L201-L297
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/generation.py
create_sphere
def create_sphere(rows=10, cols=10, depth=10, radius=1.0, offset=True, subdivisions=3, method='latitude'): """Create a sphere Parameters ---------- rows : int Number of rows (for method='latitude' and 'cube'). cols : int Number of columns (for method='latitude' and 'cube'). depth : int Number of depth segments (for method='cube'). radius : float Sphere radius. offset : bool Rotate each row by half a column (for method='latitude'). subdivisions : int Number of subdivisions to perform (for method='ico') method : str Method for generating sphere. Accepts 'latitude' for latitude- longitude, 'ico' for icosahedron, and 'cube' for cube based tessellation. Returns ------- sphere : MeshData Vertices and faces computed for a spherical surface. """ if method == 'latitude': return _latitude(rows, cols, radius, offset) elif method == 'ico': return _ico(radius, subdivisions) elif method == 'cube': return _cube(rows, cols, depth, radius) else: raise Exception("Invalid method. Accepts: 'latitude', 'ico', 'cube'")
python
def create_sphere(rows=10, cols=10, depth=10, radius=1.0, offset=True, subdivisions=3, method='latitude'): """Create a sphere Parameters ---------- rows : int Number of rows (for method='latitude' and 'cube'). cols : int Number of columns (for method='latitude' and 'cube'). depth : int Number of depth segments (for method='cube'). radius : float Sphere radius. offset : bool Rotate each row by half a column (for method='latitude'). subdivisions : int Number of subdivisions to perform (for method='ico') method : str Method for generating sphere. Accepts 'latitude' for latitude- longitude, 'ico' for icosahedron, and 'cube' for cube based tessellation. Returns ------- sphere : MeshData Vertices and faces computed for a spherical surface. """ if method == 'latitude': return _latitude(rows, cols, radius, offset) elif method == 'ico': return _ico(radius, subdivisions) elif method == 'cube': return _cube(rows, cols, depth, radius) else: raise Exception("Invalid method. Accepts: 'latitude', 'ico', 'cube'")
[ "def", "create_sphere", "(", "rows", "=", "10", ",", "cols", "=", "10", ",", "depth", "=", "10", ",", "radius", "=", "1.0", ",", "offset", "=", "True", ",", "subdivisions", "=", "3", ",", "method", "=", "'latitude'", ")", ":", "if", "method", "==", "'latitude'", ":", "return", "_latitude", "(", "rows", ",", "cols", ",", "radius", ",", "offset", ")", "elif", "method", "==", "'ico'", ":", "return", "_ico", "(", "radius", ",", "subdivisions", ")", "elif", "method", "==", "'cube'", ":", "return", "_cube", "(", "rows", ",", "cols", ",", "depth", ",", "radius", ")", "else", ":", "raise", "Exception", "(", "\"Invalid method. Accepts: 'latitude', 'ico', 'cube'\"", ")" ]
Create a sphere Parameters ---------- rows : int Number of rows (for method='latitude' and 'cube'). cols : int Number of columns (for method='latitude' and 'cube'). depth : int Number of depth segments (for method='cube'). radius : float Sphere radius. offset : bool Rotate each row by half a column (for method='latitude'). subdivisions : int Number of subdivisions to perform (for method='ico') method : str Method for generating sphere. Accepts 'latitude' for latitude- longitude, 'ico' for icosahedron, and 'cube' for cube based tessellation. Returns ------- sphere : MeshData Vertices and faces computed for a spherical surface.
[ "Create", "a", "sphere" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/generation.py#L415-L450
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/generation.py
create_cylinder
def create_cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False): """Create a cylinder Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : tuple of float Cylinder radii. length : float Length of the cylinder. offset : bool Rotate each row by half a column. Returns ------- cylinder : MeshData Vertices and faces computed for a cylindrical surface. """ verts = np.empty((rows+1, cols, 3), dtype=np.float32) if isinstance(radius, int): radius = [radius, radius] # convert to list # compute vertices th = np.linspace(2 * np.pi, 0, cols).reshape(1, cols) # radius as a function of z r = np.linspace(radius[0], radius[1], num=rows+1, endpoint=True).reshape(rows+1, 1) verts[..., 2] = np.linspace(0, length, num=rows+1, endpoint=True).reshape(rows+1, 1) # z if offset: # rotate each row by 1/2 column th = th + ((np.pi / cols) * np.arange(rows+1).reshape(rows+1, 1)) verts[..., 0] = r * np.cos(th) # x = r cos(th) verts[..., 1] = r * np.sin(th) # y = r sin(th) # just reshape: no redundant vertices... verts = verts.reshape((rows+1)*cols, 3) # compute faces faces = np.empty((rows*cols*2, 3), dtype=np.uint32) rowtemplate1 = (((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 0]])) % cols) + np.array([[0, 0, cols]])) rowtemplate2 = (((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 1]])) % cols) + np.array([[cols, 0, cols]])) for row in range(rows): start = row * cols * 2 faces[start:start+cols] = rowtemplate1 + row * cols faces[start+cols:start+(cols*2)] = rowtemplate2 + row * cols return MeshData(vertices=verts, faces=faces)
python
def create_cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False): """Create a cylinder Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : tuple of float Cylinder radii. length : float Length of the cylinder. offset : bool Rotate each row by half a column. Returns ------- cylinder : MeshData Vertices and faces computed for a cylindrical surface. """ verts = np.empty((rows+1, cols, 3), dtype=np.float32) if isinstance(radius, int): radius = [radius, radius] # convert to list # compute vertices th = np.linspace(2 * np.pi, 0, cols).reshape(1, cols) # radius as a function of z r = np.linspace(radius[0], radius[1], num=rows+1, endpoint=True).reshape(rows+1, 1) verts[..., 2] = np.linspace(0, length, num=rows+1, endpoint=True).reshape(rows+1, 1) # z if offset: # rotate each row by 1/2 column th = th + ((np.pi / cols) * np.arange(rows+1).reshape(rows+1, 1)) verts[..., 0] = r * np.cos(th) # x = r cos(th) verts[..., 1] = r * np.sin(th) # y = r sin(th) # just reshape: no redundant vertices... verts = verts.reshape((rows+1)*cols, 3) # compute faces faces = np.empty((rows*cols*2, 3), dtype=np.uint32) rowtemplate1 = (((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 0]])) % cols) + np.array([[0, 0, cols]])) rowtemplate2 = (((np.arange(cols).reshape(cols, 1) + np.array([[0, 1, 1]])) % cols) + np.array([[cols, 0, cols]])) for row in range(rows): start = row * cols * 2 faces[start:start+cols] = rowtemplate1 + row * cols faces[start+cols:start+(cols*2)] = rowtemplate2 + row * cols return MeshData(vertices=verts, faces=faces)
[ "def", "create_cylinder", "(", "rows", ",", "cols", ",", "radius", "=", "[", "1.0", ",", "1.0", "]", ",", "length", "=", "1.0", ",", "offset", "=", "False", ")", ":", "verts", "=", "np", ".", "empty", "(", "(", "rows", "+", "1", ",", "cols", ",", "3", ")", ",", "dtype", "=", "np", ".", "float32", ")", "if", "isinstance", "(", "radius", ",", "int", ")", ":", "radius", "=", "[", "radius", ",", "radius", "]", "# convert to list", "# compute vertices", "th", "=", "np", ".", "linspace", "(", "2", "*", "np", ".", "pi", ",", "0", ",", "cols", ")", ".", "reshape", "(", "1", ",", "cols", ")", "# radius as a function of z", "r", "=", "np", ".", "linspace", "(", "radius", "[", "0", "]", ",", "radius", "[", "1", "]", ",", "num", "=", "rows", "+", "1", ",", "endpoint", "=", "True", ")", ".", "reshape", "(", "rows", "+", "1", ",", "1", ")", "verts", "[", "...", ",", "2", "]", "=", "np", ".", "linspace", "(", "0", ",", "length", ",", "num", "=", "rows", "+", "1", ",", "endpoint", "=", "True", ")", ".", "reshape", "(", "rows", "+", "1", ",", "1", ")", "# z", "if", "offset", ":", "# rotate each row by 1/2 column", "th", "=", "th", "+", "(", "(", "np", ".", "pi", "/", "cols", ")", "*", "np", ".", "arange", "(", "rows", "+", "1", ")", ".", "reshape", "(", "rows", "+", "1", ",", "1", ")", ")", "verts", "[", "...", ",", "0", "]", "=", "r", "*", "np", ".", "cos", "(", "th", ")", "# x = r cos(th)", "verts", "[", "...", ",", "1", "]", "=", "r", "*", "np", ".", "sin", "(", "th", ")", "# y = r sin(th)", "# just reshape: no redundant vertices...", "verts", "=", "verts", ".", "reshape", "(", "(", "rows", "+", "1", ")", "*", "cols", ",", "3", ")", "# compute faces", "faces", "=", "np", ".", "empty", "(", "(", "rows", "*", "cols", "*", "2", ",", "3", ")", ",", "dtype", "=", "np", ".", "uint32", ")", "rowtemplate1", "=", "(", "(", "(", "np", ".", "arange", "(", "cols", ")", ".", "reshape", "(", "cols", ",", "1", ")", "+", "np", ".", "array", "(", "[", "[", "0", ",", "1", ",", "0", "]", "]", ")", ")", "%", "cols", ")", "+", "np", ".", "array", "(", "[", "[", "0", ",", "0", ",", "cols", "]", "]", ")", ")", "rowtemplate2", "=", "(", "(", "(", "np", ".", "arange", "(", "cols", ")", ".", "reshape", "(", "cols", ",", "1", ")", "+", "np", ".", "array", "(", "[", "[", "0", ",", "1", ",", "1", "]", "]", ")", ")", "%", "cols", ")", "+", "np", ".", "array", "(", "[", "[", "cols", ",", "0", ",", "cols", "]", "]", ")", ")", "for", "row", "in", "range", "(", "rows", ")", ":", "start", "=", "row", "*", "cols", "*", "2", "faces", "[", "start", ":", "start", "+", "cols", "]", "=", "rowtemplate1", "+", "row", "*", "cols", "faces", "[", "start", "+", "cols", ":", "start", "+", "(", "cols", "*", "2", ")", "]", "=", "rowtemplate2", "+", "row", "*", "cols", "return", "MeshData", "(", "vertices", "=", "verts", ",", "faces", "=", "faces", ")" ]
Create a cylinder Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : tuple of float Cylinder radii. length : float Length of the cylinder. offset : bool Rotate each row by half a column. Returns ------- cylinder : MeshData Vertices and faces computed for a cylindrical surface.
[ "Create", "a", "cylinder" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/generation.py#L453-L504
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/generation.py
create_cone
def create_cone(cols, radius=1.0, length=1.0): """Create a cone Parameters ---------- cols : int Number of faces. radius : float Base cone radius. length : float Length of the cone. Returns ------- cone : MeshData Vertices and faces computed for a cone surface. """ verts = np.empty((cols+1, 3), dtype=np.float32) # compute vertexes th = np.linspace(2 * np.pi, 0, cols+1).reshape(1, cols+1) verts[:-1, 2] = 0.0 verts[:-1, 0] = radius * np.cos(th[0, :-1]) # x = r cos(th) verts[:-1, 1] = radius * np.sin(th[0, :-1]) # y = r sin(th) # Add the extremity verts[-1, 0] = 0.0 verts[-1, 1] = 0.0 verts[-1, 2] = length verts = verts.reshape((cols+1), 3) # just reshape: no redundant vertices # compute faces faces = np.empty((cols, 3), dtype=np.uint32) template = np.array([[0, 1]]) for pos in range(cols): faces[pos, :-1] = template + pos faces[:, 2] = cols faces[-1, 1] = 0 return MeshData(vertices=verts, faces=faces)
python
def create_cone(cols, radius=1.0, length=1.0): """Create a cone Parameters ---------- cols : int Number of faces. radius : float Base cone radius. length : float Length of the cone. Returns ------- cone : MeshData Vertices and faces computed for a cone surface. """ verts = np.empty((cols+1, 3), dtype=np.float32) # compute vertexes th = np.linspace(2 * np.pi, 0, cols+1).reshape(1, cols+1) verts[:-1, 2] = 0.0 verts[:-1, 0] = radius * np.cos(th[0, :-1]) # x = r cos(th) verts[:-1, 1] = radius * np.sin(th[0, :-1]) # y = r sin(th) # Add the extremity verts[-1, 0] = 0.0 verts[-1, 1] = 0.0 verts[-1, 2] = length verts = verts.reshape((cols+1), 3) # just reshape: no redundant vertices # compute faces faces = np.empty((cols, 3), dtype=np.uint32) template = np.array([[0, 1]]) for pos in range(cols): faces[pos, :-1] = template + pos faces[:, 2] = cols faces[-1, 1] = 0 return MeshData(vertices=verts, faces=faces)
[ "def", "create_cone", "(", "cols", ",", "radius", "=", "1.0", ",", "length", "=", "1.0", ")", ":", "verts", "=", "np", ".", "empty", "(", "(", "cols", "+", "1", ",", "3", ")", ",", "dtype", "=", "np", ".", "float32", ")", "# compute vertexes", "th", "=", "np", ".", "linspace", "(", "2", "*", "np", ".", "pi", ",", "0", ",", "cols", "+", "1", ")", ".", "reshape", "(", "1", ",", "cols", "+", "1", ")", "verts", "[", ":", "-", "1", ",", "2", "]", "=", "0.0", "verts", "[", ":", "-", "1", ",", "0", "]", "=", "radius", "*", "np", ".", "cos", "(", "th", "[", "0", ",", ":", "-", "1", "]", ")", "# x = r cos(th)", "verts", "[", ":", "-", "1", ",", "1", "]", "=", "radius", "*", "np", ".", "sin", "(", "th", "[", "0", ",", ":", "-", "1", "]", ")", "# y = r sin(th)", "# Add the extremity", "verts", "[", "-", "1", ",", "0", "]", "=", "0.0", "verts", "[", "-", "1", ",", "1", "]", "=", "0.0", "verts", "[", "-", "1", ",", "2", "]", "=", "length", "verts", "=", "verts", ".", "reshape", "(", "(", "cols", "+", "1", ")", ",", "3", ")", "# just reshape: no redundant vertices", "# compute faces", "faces", "=", "np", ".", "empty", "(", "(", "cols", ",", "3", ")", ",", "dtype", "=", "np", ".", "uint32", ")", "template", "=", "np", ".", "array", "(", "[", "[", "0", ",", "1", "]", "]", ")", "for", "pos", "in", "range", "(", "cols", ")", ":", "faces", "[", "pos", ",", ":", "-", "1", "]", "=", "template", "+", "pos", "faces", "[", ":", ",", "2", "]", "=", "cols", "faces", "[", "-", "1", ",", "1", "]", "=", "0", "return", "MeshData", "(", "vertices", "=", "verts", ",", "faces", "=", "faces", ")" ]
Create a cone Parameters ---------- cols : int Number of faces. radius : float Base cone radius. length : float Length of the cone. Returns ------- cone : MeshData Vertices and faces computed for a cone surface.
[ "Create", "a", "cone" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/generation.py#L507-L543
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/generation.py
create_arrow
def create_arrow(rows, cols, radius=0.1, length=1.0, cone_radius=None, cone_length=None): """Create a 3D arrow using a cylinder plus cone Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : float Base cylinder radius. length : float Length of the arrow. cone_radius : float Radius of the cone base. If None, then this defaults to 2x the cylinder radius. cone_length : float Length of the cone. If None, then this defaults to 1/3 of the arrow length. Returns ------- arrow : MeshData Vertices and faces computed for a cone surface. """ # create the cylinder md_cyl = None if cone_radius is None: cone_radius = radius*2.0 if cone_length is None: con_L = length/3.0 cyl_L = length*2.0/3.0 else: cyl_L = max(0, length - cone_length) con_L = min(cone_length, length) if cyl_L != 0: md_cyl = create_cylinder(rows, cols, radius=[radius, radius], length=cyl_L) # create the cone md_con = create_cone(cols, radius=cone_radius, length=con_L) verts = md_con.get_vertices() nbr_verts_con = verts.size//3 faces = md_con.get_faces() if md_cyl is not None: trans = np.array([[0.0, 0.0, cyl_L]]) verts = np.vstack((verts+trans, md_cyl.get_vertices())) faces = np.vstack((faces, md_cyl.get_faces()+nbr_verts_con)) return MeshData(vertices=verts, faces=faces)
python
def create_arrow(rows, cols, radius=0.1, length=1.0, cone_radius=None, cone_length=None): """Create a 3D arrow using a cylinder plus cone Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : float Base cylinder radius. length : float Length of the arrow. cone_radius : float Radius of the cone base. If None, then this defaults to 2x the cylinder radius. cone_length : float Length of the cone. If None, then this defaults to 1/3 of the arrow length. Returns ------- arrow : MeshData Vertices and faces computed for a cone surface. """ # create the cylinder md_cyl = None if cone_radius is None: cone_radius = radius*2.0 if cone_length is None: con_L = length/3.0 cyl_L = length*2.0/3.0 else: cyl_L = max(0, length - cone_length) con_L = min(cone_length, length) if cyl_L != 0: md_cyl = create_cylinder(rows, cols, radius=[radius, radius], length=cyl_L) # create the cone md_con = create_cone(cols, radius=cone_radius, length=con_L) verts = md_con.get_vertices() nbr_verts_con = verts.size//3 faces = md_con.get_faces() if md_cyl is not None: trans = np.array([[0.0, 0.0, cyl_L]]) verts = np.vstack((verts+trans, md_cyl.get_vertices())) faces = np.vstack((faces, md_cyl.get_faces()+nbr_verts_con)) return MeshData(vertices=verts, faces=faces)
[ "def", "create_arrow", "(", "rows", ",", "cols", ",", "radius", "=", "0.1", ",", "length", "=", "1.0", ",", "cone_radius", "=", "None", ",", "cone_length", "=", "None", ")", ":", "# create the cylinder", "md_cyl", "=", "None", "if", "cone_radius", "is", "None", ":", "cone_radius", "=", "radius", "*", "2.0", "if", "cone_length", "is", "None", ":", "con_L", "=", "length", "/", "3.0", "cyl_L", "=", "length", "*", "2.0", "/", "3.0", "else", ":", "cyl_L", "=", "max", "(", "0", ",", "length", "-", "cone_length", ")", "con_L", "=", "min", "(", "cone_length", ",", "length", ")", "if", "cyl_L", "!=", "0", ":", "md_cyl", "=", "create_cylinder", "(", "rows", ",", "cols", ",", "radius", "=", "[", "radius", ",", "radius", "]", ",", "length", "=", "cyl_L", ")", "# create the cone", "md_con", "=", "create_cone", "(", "cols", ",", "radius", "=", "cone_radius", ",", "length", "=", "con_L", ")", "verts", "=", "md_con", ".", "get_vertices", "(", ")", "nbr_verts_con", "=", "verts", ".", "size", "//", "3", "faces", "=", "md_con", ".", "get_faces", "(", ")", "if", "md_cyl", "is", "not", "None", ":", "trans", "=", "np", ".", "array", "(", "[", "[", "0.0", ",", "0.0", ",", "cyl_L", "]", "]", ")", "verts", "=", "np", ".", "vstack", "(", "(", "verts", "+", "trans", ",", "md_cyl", ".", "get_vertices", "(", ")", ")", ")", "faces", "=", "np", ".", "vstack", "(", "(", "faces", ",", "md_cyl", ".", "get_faces", "(", ")", "+", "nbr_verts_con", ")", ")", "return", "MeshData", "(", "vertices", "=", "verts", ",", "faces", "=", "faces", ")" ]
Create a 3D arrow using a cylinder plus cone Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : float Base cylinder radius. length : float Length of the arrow. cone_radius : float Radius of the cone base. If None, then this defaults to 2x the cylinder radius. cone_length : float Length of the cone. If None, then this defaults to 1/3 of the arrow length. Returns ------- arrow : MeshData Vertices and faces computed for a cone surface.
[ "Create", "a", "3D", "arrow", "using", "a", "cylinder", "plus", "cone" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/generation.py#L546-L595
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/generation.py
create_grid_mesh
def create_grid_mesh(xs, ys, zs): '''Generate vertices and indices for an implicitly connected mesh. The intention is that this makes it simple to generate a mesh from meshgrid data. Parameters ---------- xs : ndarray A 2d array of x coordinates for the vertices of the mesh. Must have the same dimensions as ys and zs. ys : ndarray A 2d array of y coordinates for the vertices of the mesh. Must have the same dimensions as xs and zs. zs : ndarray A 2d array of z coordinates for the vertices of the mesh. Must have the same dimensions as xs and ys. Returns ------- vertices : ndarray The array of vertices in the mesh. indices : ndarray The array of indices for the mesh. ''' shape = xs.shape length = shape[0] * shape[1] vertices = np.zeros((length, 3)) vertices[:, 0] = xs.reshape(length) vertices[:, 1] = ys.reshape(length) vertices[:, 2] = zs.reshape(length) basic_indices = np.array([0, 1, 1 + shape[1], 0, 0 + shape[1], 1 + shape[1]], dtype=np.uint32) inner_grid_length = (shape[0] - 1) * (shape[1] - 1) offsets = np.arange(inner_grid_length) offsets += np.repeat(np.arange(shape[0] - 1), shape[1] - 1) offsets = np.repeat(offsets, 6) indices = np.resize(basic_indices, len(offsets)) + offsets indices = indices.reshape((len(indices) // 3, 3)) return vertices, indices
python
def create_grid_mesh(xs, ys, zs): '''Generate vertices and indices for an implicitly connected mesh. The intention is that this makes it simple to generate a mesh from meshgrid data. Parameters ---------- xs : ndarray A 2d array of x coordinates for the vertices of the mesh. Must have the same dimensions as ys and zs. ys : ndarray A 2d array of y coordinates for the vertices of the mesh. Must have the same dimensions as xs and zs. zs : ndarray A 2d array of z coordinates for the vertices of the mesh. Must have the same dimensions as xs and ys. Returns ------- vertices : ndarray The array of vertices in the mesh. indices : ndarray The array of indices for the mesh. ''' shape = xs.shape length = shape[0] * shape[1] vertices = np.zeros((length, 3)) vertices[:, 0] = xs.reshape(length) vertices[:, 1] = ys.reshape(length) vertices[:, 2] = zs.reshape(length) basic_indices = np.array([0, 1, 1 + shape[1], 0, 0 + shape[1], 1 + shape[1]], dtype=np.uint32) inner_grid_length = (shape[0] - 1) * (shape[1] - 1) offsets = np.arange(inner_grid_length) offsets += np.repeat(np.arange(shape[0] - 1), shape[1] - 1) offsets = np.repeat(offsets, 6) indices = np.resize(basic_indices, len(offsets)) + offsets indices = indices.reshape((len(indices) // 3, 3)) return vertices, indices
[ "def", "create_grid_mesh", "(", "xs", ",", "ys", ",", "zs", ")", ":", "shape", "=", "xs", ".", "shape", "length", "=", "shape", "[", "0", "]", "*", "shape", "[", "1", "]", "vertices", "=", "np", ".", "zeros", "(", "(", "length", ",", "3", ")", ")", "vertices", "[", ":", ",", "0", "]", "=", "xs", ".", "reshape", "(", "length", ")", "vertices", "[", ":", ",", "1", "]", "=", "ys", ".", "reshape", "(", "length", ")", "vertices", "[", ":", ",", "2", "]", "=", "zs", ".", "reshape", "(", "length", ")", "basic_indices", "=", "np", ".", "array", "(", "[", "0", ",", "1", ",", "1", "+", "shape", "[", "1", "]", ",", "0", ",", "0", "+", "shape", "[", "1", "]", ",", "1", "+", "shape", "[", "1", "]", "]", ",", "dtype", "=", "np", ".", "uint32", ")", "inner_grid_length", "=", "(", "shape", "[", "0", "]", "-", "1", ")", "*", "(", "shape", "[", "1", "]", "-", "1", ")", "offsets", "=", "np", ".", "arange", "(", "inner_grid_length", ")", "offsets", "+=", "np", ".", "repeat", "(", "np", ".", "arange", "(", "shape", "[", "0", "]", "-", "1", ")", ",", "shape", "[", "1", "]", "-", "1", ")", "offsets", "=", "np", ".", "repeat", "(", "offsets", ",", "6", ")", "indices", "=", "np", ".", "resize", "(", "basic_indices", ",", "len", "(", "offsets", ")", ")", "+", "offsets", "indices", "=", "indices", ".", "reshape", "(", "(", "len", "(", "indices", ")", "//", "3", ",", "3", ")", ")", "return", "vertices", ",", "indices" ]
Generate vertices and indices for an implicitly connected mesh. The intention is that this makes it simple to generate a mesh from meshgrid data. Parameters ---------- xs : ndarray A 2d array of x coordinates for the vertices of the mesh. Must have the same dimensions as ys and zs. ys : ndarray A 2d array of y coordinates for the vertices of the mesh. Must have the same dimensions as xs and zs. zs : ndarray A 2d array of z coordinates for the vertices of the mesh. Must have the same dimensions as xs and ys. Returns ------- vertices : ndarray The array of vertices in the mesh. indices : ndarray The array of indices for the mesh.
[ "Generate", "vertices", "and", "indices", "for", "an", "implicitly", "connected", "mesh", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/generation.py#L598-L646
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/graphs/util.py
_straight_line_vertices
def _straight_line_vertices(adjacency_mat, node_coords, directed=False): """ Generate the vertices for straight lines between nodes. If it is a directed graph, it also generates the vertices which can be passed to an :class:`ArrowVisual`. Parameters ---------- adjacency_mat : array The adjacency matrix of the graph node_coords : array The current coordinates of all nodes in the graph directed : bool Wether the graph is directed. If this is true it will also generate the vertices for arrows which can be passed to :class:`ArrowVisual`. Returns ------- vertices : tuple Returns a tuple containing containing (`line_vertices`, `arrow_vertices`) """ if not issparse(adjacency_mat): adjacency_mat = np.asarray(adjacency_mat, float) if (adjacency_mat.ndim != 2 or adjacency_mat.shape[0] != adjacency_mat.shape[1]): raise ValueError("Adjacency matrix should be square.") arrow_vertices = np.array([]) edges = _get_edges(adjacency_mat) line_vertices = node_coords[edges.ravel()] if directed: arrows = np.array(list(_get_directed_edges(adjacency_mat))) arrow_vertices = node_coords[arrows.ravel()] arrow_vertices = arrow_vertices.reshape((len(arrow_vertices)/2, 4)) return line_vertices, arrow_vertices
python
def _straight_line_vertices(adjacency_mat, node_coords, directed=False): """ Generate the vertices for straight lines between nodes. If it is a directed graph, it also generates the vertices which can be passed to an :class:`ArrowVisual`. Parameters ---------- adjacency_mat : array The adjacency matrix of the graph node_coords : array The current coordinates of all nodes in the graph directed : bool Wether the graph is directed. If this is true it will also generate the vertices for arrows which can be passed to :class:`ArrowVisual`. Returns ------- vertices : tuple Returns a tuple containing containing (`line_vertices`, `arrow_vertices`) """ if not issparse(adjacency_mat): adjacency_mat = np.asarray(adjacency_mat, float) if (adjacency_mat.ndim != 2 or adjacency_mat.shape[0] != adjacency_mat.shape[1]): raise ValueError("Adjacency matrix should be square.") arrow_vertices = np.array([]) edges = _get_edges(adjacency_mat) line_vertices = node_coords[edges.ravel()] if directed: arrows = np.array(list(_get_directed_edges(adjacency_mat))) arrow_vertices = node_coords[arrows.ravel()] arrow_vertices = arrow_vertices.reshape((len(arrow_vertices)/2, 4)) return line_vertices, arrow_vertices
[ "def", "_straight_line_vertices", "(", "adjacency_mat", ",", "node_coords", ",", "directed", "=", "False", ")", ":", "if", "not", "issparse", "(", "adjacency_mat", ")", ":", "adjacency_mat", "=", "np", ".", "asarray", "(", "adjacency_mat", ",", "float", ")", "if", "(", "adjacency_mat", ".", "ndim", "!=", "2", "or", "adjacency_mat", ".", "shape", "[", "0", "]", "!=", "adjacency_mat", ".", "shape", "[", "1", "]", ")", ":", "raise", "ValueError", "(", "\"Adjacency matrix should be square.\"", ")", "arrow_vertices", "=", "np", ".", "array", "(", "[", "]", ")", "edges", "=", "_get_edges", "(", "adjacency_mat", ")", "line_vertices", "=", "node_coords", "[", "edges", ".", "ravel", "(", ")", "]", "if", "directed", ":", "arrows", "=", "np", ".", "array", "(", "list", "(", "_get_directed_edges", "(", "adjacency_mat", ")", ")", ")", "arrow_vertices", "=", "node_coords", "[", "arrows", ".", "ravel", "(", ")", "]", "arrow_vertices", "=", "arrow_vertices", ".", "reshape", "(", "(", "len", "(", "arrow_vertices", ")", "/", "2", ",", "4", ")", ")", "return", "line_vertices", ",", "arrow_vertices" ]
Generate the vertices for straight lines between nodes. If it is a directed graph, it also generates the vertices which can be passed to an :class:`ArrowVisual`. Parameters ---------- adjacency_mat : array The adjacency matrix of the graph node_coords : array The current coordinates of all nodes in the graph directed : bool Wether the graph is directed. If this is true it will also generate the vertices for arrows which can be passed to :class:`ArrowVisual`. Returns ------- vertices : tuple Returns a tuple containing containing (`line_vertices`, `arrow_vertices`)
[ "Generate", "the", "vertices", "for", "straight", "lines", "between", "nodes", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/graphs/util.py#L54-L95
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/graphs/util.py
_rescale_layout
def _rescale_layout(pos, scale=1): """ Normalize the given coordinate list to the range [0, `scale`]. Parameters ---------- pos : array Coordinate list scale : number The upperbound value for the coordinates range Returns ------- pos : array The rescaled (normalized) coordinates in the range [0, `scale`]. Notes ----- Changes `pos` in place. """ pos -= pos.min(axis=0) pos *= scale / pos.max() return pos
python
def _rescale_layout(pos, scale=1): """ Normalize the given coordinate list to the range [0, `scale`]. Parameters ---------- pos : array Coordinate list scale : number The upperbound value for the coordinates range Returns ------- pos : array The rescaled (normalized) coordinates in the range [0, `scale`]. Notes ----- Changes `pos` in place. """ pos -= pos.min(axis=0) pos *= scale / pos.max() return pos
[ "def", "_rescale_layout", "(", "pos", ",", "scale", "=", "1", ")", ":", "pos", "-=", "pos", ".", "min", "(", "axis", "=", "0", ")", "pos", "*=", "scale", "/", "pos", ".", "max", "(", ")", "return", "pos" ]
Normalize the given coordinate list to the range [0, `scale`]. Parameters ---------- pos : array Coordinate list scale : number The upperbound value for the coordinates range Returns ------- pos : array The rescaled (normalized) coordinates in the range [0, `scale`]. Notes ----- Changes `pos` in place.
[ "Normalize", "the", "given", "coordinate", "list", "to", "the", "range", "[", "0", "scale", "]", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/graphs/util.py#L98-L122
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/freetype.py
get_handle
def get_handle(): ''' Get unique FT_Library handle ''' global __handle__ if not __handle__: __handle__ = FT_Library() error = FT_Init_FreeType(byref(__handle__)) if error: raise RuntimeError(hex(error)) return __handle__
python
def get_handle(): ''' Get unique FT_Library handle ''' global __handle__ if not __handle__: __handle__ = FT_Library() error = FT_Init_FreeType(byref(__handle__)) if error: raise RuntimeError(hex(error)) return __handle__
[ "def", "get_handle", "(", ")", ":", "global", "__handle__", "if", "not", "__handle__", ":", "__handle__", "=", "FT_Library", "(", ")", "error", "=", "FT_Init_FreeType", "(", "byref", "(", "__handle__", ")", ")", "if", "error", ":", "raise", "RuntimeError", "(", "hex", "(", "error", ")", ")", "return", "__handle__" ]
Get unique FT_Library handle
[ "Get", "unique", "FT_Library", "handle" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/freetype.py#L205-L215
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/ext/_bundled/freetype.py
version
def version(): ''' Return the version of the FreeType library being used as a tuple of ( major version number, minor version number, patch version number ) ''' amajor = FT_Int() aminor = FT_Int() apatch = FT_Int() library = get_handle() FT_Library_Version(library, byref(amajor), byref(aminor), byref(apatch)) return (amajor.value, aminor.value, apatch.value)
python
def version(): ''' Return the version of the FreeType library being used as a tuple of ( major version number, minor version number, patch version number ) ''' amajor = FT_Int() aminor = FT_Int() apatch = FT_Int() library = get_handle() FT_Library_Version(library, byref(amajor), byref(aminor), byref(apatch)) return (amajor.value, aminor.value, apatch.value)
[ "def", "version", "(", ")", ":", "amajor", "=", "FT_Int", "(", ")", "aminor", "=", "FT_Int", "(", ")", "apatch", "=", "FT_Int", "(", ")", "library", "=", "get_handle", "(", ")", "FT_Library_Version", "(", "library", ",", "byref", "(", "amajor", ")", ",", "byref", "(", "aminor", ")", ",", "byref", "(", "apatch", ")", ")", "return", "(", "amajor", ".", "value", ",", "aminor", ".", "value", ",", "apatch", ".", "value", ")" ]
Return the version of the FreeType library being used as a tuple of ( major version number, minor version number, patch version number )
[ "Return", "the", "version", "of", "the", "FreeType", "library", "being", "used", "as", "a", "tuple", "of", "(", "major", "version", "number", "minor", "version", "number", "patch", "version", "number", ")" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/ext/_bundled/freetype.py#L218-L228
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/_base.py
make_camera
def make_camera(cam_type, *args, **kwargs): """ Factory function for creating new cameras using a string name. Parameters ---------- cam_type : str May be one of: * 'panzoom' : Creates :class:`PanZoomCamera` * 'turntable' : Creates :class:`TurntableCamera` * None : Creates :class:`Camera` Notes ----- All extra arguments are passed to the __init__ method of the selected Camera class. """ cam_types = {None: BaseCamera} for camType in (BaseCamera, PanZoomCamera, PerspectiveCamera, TurntableCamera, FlyCamera, ArcballCamera): cam_types[camType.__name__[:-6].lower()] = camType try: return cam_types[cam_type](*args, **kwargs) except KeyError: raise KeyError('Unknown camera type "%s". Options are: %s' % (cam_type, cam_types.keys()))
python
def make_camera(cam_type, *args, **kwargs): """ Factory function for creating new cameras using a string name. Parameters ---------- cam_type : str May be one of: * 'panzoom' : Creates :class:`PanZoomCamera` * 'turntable' : Creates :class:`TurntableCamera` * None : Creates :class:`Camera` Notes ----- All extra arguments are passed to the __init__ method of the selected Camera class. """ cam_types = {None: BaseCamera} for camType in (BaseCamera, PanZoomCamera, PerspectiveCamera, TurntableCamera, FlyCamera, ArcballCamera): cam_types[camType.__name__[:-6].lower()] = camType try: return cam_types[cam_type](*args, **kwargs) except KeyError: raise KeyError('Unknown camera type "%s". Options are: %s' % (cam_type, cam_types.keys()))
[ "def", "make_camera", "(", "cam_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cam_types", "=", "{", "None", ":", "BaseCamera", "}", "for", "camType", "in", "(", "BaseCamera", ",", "PanZoomCamera", ",", "PerspectiveCamera", ",", "TurntableCamera", ",", "FlyCamera", ",", "ArcballCamera", ")", ":", "cam_types", "[", "camType", ".", "__name__", "[", ":", "-", "6", "]", ".", "lower", "(", ")", "]", "=", "camType", "try", ":", "return", "cam_types", "[", "cam_type", "]", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "KeyError", ":", "raise", "KeyError", "(", "'Unknown camera type \"%s\". Options are: %s'", "%", "(", "cam_type", ",", "cam_types", ".", "keys", "(", ")", ")", ")" ]
Factory function for creating new cameras using a string name. Parameters ---------- cam_type : str May be one of: * 'panzoom' : Creates :class:`PanZoomCamera` * 'turntable' : Creates :class:`TurntableCamera` * None : Creates :class:`Camera` Notes ----- All extra arguments are passed to the __init__ method of the selected Camera class.
[ "Factory", "function", "for", "creating", "new", "cameras", "using", "a", "string", "name", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/_base.py#L12-L38
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/scatter/multi_scatter.py
MultiColorScatter.set_data_values
def set_data_values(self, label, x, y, z): """ Set the position of the datapoints """ # TODO: avoid re-allocating an array every time self.layers[label]['data'] = np.array([x, y, z]).transpose() self._update()
python
def set_data_values(self, label, x, y, z): """ Set the position of the datapoints """ # TODO: avoid re-allocating an array every time self.layers[label]['data'] = np.array([x, y, z]).transpose() self._update()
[ "def", "set_data_values", "(", "self", ",", "label", ",", "x", ",", "y", ",", "z", ")", ":", "# TODO: avoid re-allocating an array every time", "self", ".", "layers", "[", "label", "]", "[", "'data'", "]", "=", "np", ".", "array", "(", "[", "x", ",", "y", ",", "z", "]", ")", ".", "transpose", "(", ")", "self", ".", "_update", "(", ")" ]
Set the position of the datapoints
[ "Set", "the", "position", "of", "the", "datapoints" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/scatter/multi_scatter.py#L49-L55
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/collections/segment_collection.py
SegmentCollection
def SegmentCollection(mode="agg-fast", *args, **kwargs): """ mode: string - "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness) - "agg" (speed: slower, size: medium, output: perfect, no dash) """ if mode == "raw": return RawSegmentCollection(*args, **kwargs) return AggSegmentCollection(*args, **kwargs)
python
def SegmentCollection(mode="agg-fast", *args, **kwargs): """ mode: string - "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness) - "agg" (speed: slower, size: medium, output: perfect, no dash) """ if mode == "raw": return RawSegmentCollection(*args, **kwargs) return AggSegmentCollection(*args, **kwargs)
[ "def", "SegmentCollection", "(", "mode", "=", "\"agg-fast\"", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "mode", "==", "\"raw\"", ":", "return", "RawSegmentCollection", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "AggSegmentCollection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
mode: string - "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness) - "agg" (speed: slower, size: medium, output: perfect, no dash)
[ "mode", ":", "string", "-", "raw", "(", "speed", ":", "fastest", "size", ":", "small", "output", ":", "ugly", "no", "dash", "no", "thickness", ")", "-", "agg", "(", "speed", ":", "slower", "size", ":", "medium", "output", ":", "perfect", "no", "dash", ")" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/collections/segment_collection.py#L10-L20
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/geometry/parametric.py
surface
def surface(func, umin=0, umax=2 * np.pi, ucount=64, urepeat=1.0, vmin=0, vmax=2 * np.pi, vcount=64, vrepeat=1.0): """ Computes the parameterization of a parametric surface func: function(u,v) Parametric function used to build the surface """ vtype = [('position', np.float32, 3), ('texcoord', np.float32, 2), ('normal', np.float32, 3)] itype = np.uint32 # umin, umax, ucount = 0, 2*np.pi, 64 # vmin, vmax, vcount = 0, 2*np.pi, 64 vcount += 1 ucount += 1 n = vcount * ucount Un = np.repeat(np.linspace(0, 1, ucount, endpoint=True), vcount) Vn = np.tile(np.linspace(0, 1, vcount, endpoint=True), ucount) U = umin + Un * (umax - umin) V = vmin + Vn * (vmax - vmin) vertices = np.zeros(n, dtype=vtype) for i, (u, v) in enumerate(zip(U, V)): vertices["position"][i] = func(u, v) vertices["texcoord"][:, 0] = Un * urepeat vertices["texcoord"][:, 1] = Vn * vrepeat indices = [] for i in range(ucount - 1): for j in range(vcount - 1): indices.append(i * (vcount) + j) indices.append(i * (vcount) + j + 1) indices.append(i * (vcount) + j + vcount + 1) indices.append(i * (vcount) + j + vcount) indices.append(i * (vcount) + j + vcount + 1) indices.append(i * (vcount) + j) indices = np.array(indices, dtype=itype) vertices["normal"] = normals(vertices["position"], indices.reshape(len(indices) / 3, 3)) return vertices, indices
python
def surface(func, umin=0, umax=2 * np.pi, ucount=64, urepeat=1.0, vmin=0, vmax=2 * np.pi, vcount=64, vrepeat=1.0): """ Computes the parameterization of a parametric surface func: function(u,v) Parametric function used to build the surface """ vtype = [('position', np.float32, 3), ('texcoord', np.float32, 2), ('normal', np.float32, 3)] itype = np.uint32 # umin, umax, ucount = 0, 2*np.pi, 64 # vmin, vmax, vcount = 0, 2*np.pi, 64 vcount += 1 ucount += 1 n = vcount * ucount Un = np.repeat(np.linspace(0, 1, ucount, endpoint=True), vcount) Vn = np.tile(np.linspace(0, 1, vcount, endpoint=True), ucount) U = umin + Un * (umax - umin) V = vmin + Vn * (vmax - vmin) vertices = np.zeros(n, dtype=vtype) for i, (u, v) in enumerate(zip(U, V)): vertices["position"][i] = func(u, v) vertices["texcoord"][:, 0] = Un * urepeat vertices["texcoord"][:, 1] = Vn * vrepeat indices = [] for i in range(ucount - 1): for j in range(vcount - 1): indices.append(i * (vcount) + j) indices.append(i * (vcount) + j + 1) indices.append(i * (vcount) + j + vcount + 1) indices.append(i * (vcount) + j + vcount) indices.append(i * (vcount) + j + vcount + 1) indices.append(i * (vcount) + j) indices = np.array(indices, dtype=itype) vertices["normal"] = normals(vertices["position"], indices.reshape(len(indices) / 3, 3)) return vertices, indices
[ "def", "surface", "(", "func", ",", "umin", "=", "0", ",", "umax", "=", "2", "*", "np", ".", "pi", ",", "ucount", "=", "64", ",", "urepeat", "=", "1.0", ",", "vmin", "=", "0", ",", "vmax", "=", "2", "*", "np", ".", "pi", ",", "vcount", "=", "64", ",", "vrepeat", "=", "1.0", ")", ":", "vtype", "=", "[", "(", "'position'", ",", "np", ".", "float32", ",", "3", ")", ",", "(", "'texcoord'", ",", "np", ".", "float32", ",", "2", ")", ",", "(", "'normal'", ",", "np", ".", "float32", ",", "3", ")", "]", "itype", "=", "np", ".", "uint32", "# umin, umax, ucount = 0, 2*np.pi, 64", "# vmin, vmax, vcount = 0, 2*np.pi, 64", "vcount", "+=", "1", "ucount", "+=", "1", "n", "=", "vcount", "*", "ucount", "Un", "=", "np", ".", "repeat", "(", "np", ".", "linspace", "(", "0", ",", "1", ",", "ucount", ",", "endpoint", "=", "True", ")", ",", "vcount", ")", "Vn", "=", "np", ".", "tile", "(", "np", ".", "linspace", "(", "0", ",", "1", ",", "vcount", ",", "endpoint", "=", "True", ")", ",", "ucount", ")", "U", "=", "umin", "+", "Un", "*", "(", "umax", "-", "umin", ")", "V", "=", "vmin", "+", "Vn", "*", "(", "vmax", "-", "vmin", ")", "vertices", "=", "np", ".", "zeros", "(", "n", ",", "dtype", "=", "vtype", ")", "for", "i", ",", "(", "u", ",", "v", ")", "in", "enumerate", "(", "zip", "(", "U", ",", "V", ")", ")", ":", "vertices", "[", "\"position\"", "]", "[", "i", "]", "=", "func", "(", "u", ",", "v", ")", "vertices", "[", "\"texcoord\"", "]", "[", ":", ",", "0", "]", "=", "Un", "*", "urepeat", "vertices", "[", "\"texcoord\"", "]", "[", ":", ",", "1", "]", "=", "Vn", "*", "vrepeat", "indices", "=", "[", "]", "for", "i", "in", "range", "(", "ucount", "-", "1", ")", ":", "for", "j", "in", "range", "(", "vcount", "-", "1", ")", ":", "indices", ".", "append", "(", "i", "*", "(", "vcount", ")", "+", "j", ")", "indices", ".", "append", "(", "i", "*", "(", "vcount", ")", "+", "j", "+", "1", ")", "indices", ".", "append", "(", "i", "*", "(", "vcount", ")", "+", "j", "+", "vcount", "+", "1", ")", "indices", ".", "append", "(", "i", "*", "(", "vcount", ")", "+", "j", "+", "vcount", ")", "indices", ".", "append", "(", "i", "*", "(", "vcount", ")", "+", "j", "+", "vcount", "+", "1", ")", "indices", ".", "append", "(", "i", "*", "(", "vcount", ")", "+", "j", ")", "indices", "=", "np", ".", "array", "(", "indices", ",", "dtype", "=", "itype", ")", "vertices", "[", "\"normal\"", "]", "=", "normals", "(", "vertices", "[", "\"position\"", "]", ",", "indices", ".", "reshape", "(", "len", "(", "indices", ")", "/", "3", ",", "3", ")", ")", "return", "vertices", ",", "indices" ]
Computes the parameterization of a parametric surface func: function(u,v) Parametric function used to build the surface
[ "Computes", "the", "parameterization", "of", "a", "parametric", "surface" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/geometry/parametric.py#L11-L57
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/collections/point_collection.py
PointCollection
def PointCollection(mode="raw", *args, **kwargs): """ mode: string - "raw" (speed: fastest, size: small, output: ugly) - "agg" (speed: fast, size: small, output: beautiful) """ if mode == "raw": return RawPointCollection(*args, **kwargs) return AggPointCollection(*args, **kwargs)
python
def PointCollection(mode="raw", *args, **kwargs): """ mode: string - "raw" (speed: fastest, size: small, output: ugly) - "agg" (speed: fast, size: small, output: beautiful) """ if mode == "raw": return RawPointCollection(*args, **kwargs) return AggPointCollection(*args, **kwargs)
[ "def", "PointCollection", "(", "mode", "=", "\"raw\"", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "mode", "==", "\"raw\"", ":", "return", "RawPointCollection", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "AggPointCollection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
mode: string - "raw" (speed: fastest, size: small, output: ugly) - "agg" (speed: fast, size: small, output: beautiful)
[ "mode", ":", "string", "-", "raw", "(", "speed", ":", "fastest", "size", ":", "small", "output", ":", "ugly", ")", "-", "agg", "(", "speed", ":", "fast", "size", ":", "small", "output", ":", "beautiful", ")" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/collections/point_collection.py#L11-L20
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/scrolling_lines.py
ScrollingLinesVisual.roll_data
def roll_data(self, data): """Append new data to the right side of every line strip and remove as much data from the left. Parameters ---------- data : array-like A data array to append. """ data = data.astype('float32')[..., np.newaxis] s1 = self._data_shape[1] - self._offset if data.shape[1] > s1: self._pos_tex[:, self._offset:] = data[:, :s1] self._pos_tex[:, :data.shape[1] - s1] = data[:, s1:] self._offset = (self._offset + data.shape[1]) % self._data_shape[1] else: self._pos_tex[:, self._offset:self._offset+data.shape[1]] = data self._offset += data.shape[1] self.shared_program['offset'] = self._offset self.update()
python
def roll_data(self, data): """Append new data to the right side of every line strip and remove as much data from the left. Parameters ---------- data : array-like A data array to append. """ data = data.astype('float32')[..., np.newaxis] s1 = self._data_shape[1] - self._offset if data.shape[1] > s1: self._pos_tex[:, self._offset:] = data[:, :s1] self._pos_tex[:, :data.shape[1] - s1] = data[:, s1:] self._offset = (self._offset + data.shape[1]) % self._data_shape[1] else: self._pos_tex[:, self._offset:self._offset+data.shape[1]] = data self._offset += data.shape[1] self.shared_program['offset'] = self._offset self.update()
[ "def", "roll_data", "(", "self", ",", "data", ")", ":", "data", "=", "data", ".", "astype", "(", "'float32'", ")", "[", "...", ",", "np", ".", "newaxis", "]", "s1", "=", "self", ".", "_data_shape", "[", "1", "]", "-", "self", ".", "_offset", "if", "data", ".", "shape", "[", "1", "]", ">", "s1", ":", "self", ".", "_pos_tex", "[", ":", ",", "self", ".", "_offset", ":", "]", "=", "data", "[", ":", ",", ":", "s1", "]", "self", ".", "_pos_tex", "[", ":", ",", ":", "data", ".", "shape", "[", "1", "]", "-", "s1", "]", "=", "data", "[", ":", ",", "s1", ":", "]", "self", ".", "_offset", "=", "(", "self", ".", "_offset", "+", "data", ".", "shape", "[", "1", "]", ")", "%", "self", ".", "_data_shape", "[", "1", "]", "else", ":", "self", ".", "_pos_tex", "[", ":", ",", "self", ".", "_offset", ":", "self", ".", "_offset", "+", "data", ".", "shape", "[", "1", "]", "]", "=", "data", "self", ".", "_offset", "+=", "data", ".", "shape", "[", "1", "]", "self", ".", "shared_program", "[", "'offset'", "]", "=", "self", ".", "_offset", "self", ".", "update", "(", ")" ]
Append new data to the right side of every line strip and remove as much data from the left. Parameters ---------- data : array-like A data array to append.
[ "Append", "new", "data", "to", "the", "right", "side", "of", "every", "line", "strip", "and", "remove", "as", "much", "data", "from", "the", "left", ".", "Parameters", "----------", "data", ":", "array", "-", "like", "A", "data", "array", "to", "append", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/scrolling_lines.py#L160-L179
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/scrolling_lines.py
ScrollingLinesVisual.set_data
def set_data(self, index, data): """Set the complete data for a single line strip. Parameters ---------- index : int The index of the line strip to be replaced. data : array-like The data to assign to the selected line strip. """ self._pos_tex[index, :] = data self.update()
python
def set_data(self, index, data): """Set the complete data for a single line strip. Parameters ---------- index : int The index of the line strip to be replaced. data : array-like The data to assign to the selected line strip. """ self._pos_tex[index, :] = data self.update()
[ "def", "set_data", "(", "self", ",", "index", ",", "data", ")", ":", "self", ".", "_pos_tex", "[", "index", ",", ":", "]", "=", "data", "self", ".", "update", "(", ")" ]
Set the complete data for a single line strip. Parameters ---------- index : int The index of the line strip to be replaced. data : array-like The data to assign to the selected line strip.
[ "Set", "the", "complete", "data", "for", "a", "single", "line", "strip", ".", "Parameters", "----------", "index", ":", "int", "The", "index", "of", "the", "line", "strip", "to", "be", "replaced", ".", "data", ":", "array", "-", "like", "The", "data", "to", "assign", "to", "the", "selected", "line", "strip", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/scrolling_lines.py#L181-L192
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/shaders/multiprogram.py
MultiProgram.add_program
def add_program(self, name=None): """Create a program and add it to this MultiProgram. It is the caller's responsibility to keep a reference to the returned program. The *name* must be unique, but is otherwise arbitrary and used for debugging purposes. """ if name is None: name = 'program' + str(self._next_prog_id) self._next_prog_id += 1 if name in self._programs: raise KeyError("Program named '%s' already exists." % name) # create a program and update it to look like the rest prog = ModularProgram(self._vcode, self._fcode) for key, val in self._set_items.items(): prog[key] = val self.frag._new_program(prog) self.vert._new_program(prog) self._programs[name] = prog return prog
python
def add_program(self, name=None): """Create a program and add it to this MultiProgram. It is the caller's responsibility to keep a reference to the returned program. The *name* must be unique, but is otherwise arbitrary and used for debugging purposes. """ if name is None: name = 'program' + str(self._next_prog_id) self._next_prog_id += 1 if name in self._programs: raise KeyError("Program named '%s' already exists." % name) # create a program and update it to look like the rest prog = ModularProgram(self._vcode, self._fcode) for key, val in self._set_items.items(): prog[key] = val self.frag._new_program(prog) self.vert._new_program(prog) self._programs[name] = prog return prog
[ "def", "add_program", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "'program'", "+", "str", "(", "self", ".", "_next_prog_id", ")", "self", ".", "_next_prog_id", "+=", "1", "if", "name", "in", "self", ".", "_programs", ":", "raise", "KeyError", "(", "\"Program named '%s' already exists.\"", "%", "name", ")", "# create a program and update it to look like the rest", "prog", "=", "ModularProgram", "(", "self", ".", "_vcode", ",", "self", ".", "_fcode", ")", "for", "key", ",", "val", "in", "self", ".", "_set_items", ".", "items", "(", ")", ":", "prog", "[", "key", "]", "=", "val", "self", ".", "frag", ".", "_new_program", "(", "prog", ")", "self", ".", "vert", ".", "_new_program", "(", "prog", ")", "self", ".", "_programs", "[", "name", "]", "=", "prog", "return", "prog" ]
Create a program and add it to this MultiProgram. It is the caller's responsibility to keep a reference to the returned program. The *name* must be unique, but is otherwise arbitrary and used for debugging purposes.
[ "Create", "a", "program", "and", "add", "it", "to", "this", "MultiProgram", ".", "It", "is", "the", "caller", "s", "responsibility", "to", "keep", "a", "reference", "to", "the", "returned", "program", ".", "The", "*", "name", "*", "must", "be", "unique", "but", "is", "otherwise", "arbitrary", "and", "used", "for", "debugging", "purposes", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/shaders/multiprogram.py#L26-L50
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/shaders/multiprogram.py
MultiShader._new_program
def _new_program(self, p): """New program was added to the multiprogram; update items in the shader. """ for k, v in self._set_items.items(): getattr(p, self._shader)[k] = v
python
def _new_program(self, p): """New program was added to the multiprogram; update items in the shader. """ for k, v in self._set_items.items(): getattr(p, self._shader)[k] = v
[ "def", "_new_program", "(", "self", ",", "p", ")", ":", "for", "k", ",", "v", "in", "self", ".", "_set_items", ".", "items", "(", ")", ":", "getattr", "(", "p", ",", "self", ".", "_shader", ")", "[", "k", "]", "=", "v" ]
New program was added to the multiprogram; update items in the shader.
[ "New", "program", "was", "added", "to", "the", "multiprogram", ";", "update", "items", "in", "the", "shader", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/shaders/multiprogram.py#L125-L130
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/interactive.py
PanZoomTransform.attach
def attach(self, canvas): """Attach this tranform to a canvas Parameters ---------- canvas : instance of Canvas The canvas. """ self._canvas = canvas canvas.events.resize.connect(self.on_resize) canvas.events.mouse_wheel.connect(self.on_mouse_wheel) canvas.events.mouse_move.connect(self.on_mouse_move)
python
def attach(self, canvas): """Attach this tranform to a canvas Parameters ---------- canvas : instance of Canvas The canvas. """ self._canvas = canvas canvas.events.resize.connect(self.on_resize) canvas.events.mouse_wheel.connect(self.on_mouse_wheel) canvas.events.mouse_move.connect(self.on_mouse_move)
[ "def", "attach", "(", "self", ",", "canvas", ")", ":", "self", ".", "_canvas", "=", "canvas", "canvas", ".", "events", ".", "resize", ".", "connect", "(", "self", ".", "on_resize", ")", "canvas", ".", "events", ".", "mouse_wheel", ".", "connect", "(", "self", ".", "on_mouse_wheel", ")", "canvas", ".", "events", ".", "mouse_move", ".", "connect", "(", "self", ".", "on_mouse_move", ")" ]
Attach this tranform to a canvas Parameters ---------- canvas : instance of Canvas The canvas.
[ "Attach", "this", "tranform", "to", "a", "canvas" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/interactive.py#L28-L39
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/interactive.py
PanZoomTransform.on_resize
def on_resize(self, event): """Resize handler Parameters ---------- event : instance of Event The event. """ if self._aspect is None: return w, h = self._canvas.size aspect = self._aspect / (w / h) self.scale = (self.scale[0], self.scale[0] / aspect) self.shader_map()
python
def on_resize(self, event): """Resize handler Parameters ---------- event : instance of Event The event. """ if self._aspect is None: return w, h = self._canvas.size aspect = self._aspect / (w / h) self.scale = (self.scale[0], self.scale[0] / aspect) self.shader_map()
[ "def", "on_resize", "(", "self", ",", "event", ")", ":", "if", "self", ".", "_aspect", "is", "None", ":", "return", "w", ",", "h", "=", "self", ".", "_canvas", ".", "size", "aspect", "=", "self", ".", "_aspect", "/", "(", "w", "/", "h", ")", "self", ".", "scale", "=", "(", "self", ".", "scale", "[", "0", "]", ",", "self", ".", "scale", "[", "0", "]", "/", "aspect", ")", "self", ".", "shader_map", "(", ")" ]
Resize handler Parameters ---------- event : instance of Event The event.
[ "Resize", "handler" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/interactive.py#L47-L60
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/interactive.py
PanZoomTransform.on_mouse_move
def on_mouse_move(self, event): """Mouse move handler Parameters ---------- event : instance of Event The event. """ if event.is_dragging: dxy = event.pos - event.last_event.pos button = event.press_event.button if button == 1: dxy = self.canvas_tr.map(dxy) o = self.canvas_tr.map([0, 0]) t = dxy - o self.move(t) elif button == 2: center = self.canvas_tr.map(event.press_event.pos) if self._aspect is None: self.zoom(np.exp(dxy * (0.01, -0.01)), center) else: s = dxy[1] * -0.01 self.zoom(np.exp(np.array([s, s])), center) self.shader_map()
python
def on_mouse_move(self, event): """Mouse move handler Parameters ---------- event : instance of Event The event. """ if event.is_dragging: dxy = event.pos - event.last_event.pos button = event.press_event.button if button == 1: dxy = self.canvas_tr.map(dxy) o = self.canvas_tr.map([0, 0]) t = dxy - o self.move(t) elif button == 2: center = self.canvas_tr.map(event.press_event.pos) if self._aspect is None: self.zoom(np.exp(dxy * (0.01, -0.01)), center) else: s = dxy[1] * -0.01 self.zoom(np.exp(np.array([s, s])), center) self.shader_map()
[ "def", "on_mouse_move", "(", "self", ",", "event", ")", ":", "if", "event", ".", "is_dragging", ":", "dxy", "=", "event", ".", "pos", "-", "event", ".", "last_event", ".", "pos", "button", "=", "event", ".", "press_event", ".", "button", "if", "button", "==", "1", ":", "dxy", "=", "self", ".", "canvas_tr", ".", "map", "(", "dxy", ")", "o", "=", "self", ".", "canvas_tr", ".", "map", "(", "[", "0", ",", "0", "]", ")", "t", "=", "dxy", "-", "o", "self", ".", "move", "(", "t", ")", "elif", "button", "==", "2", ":", "center", "=", "self", ".", "canvas_tr", ".", "map", "(", "event", ".", "press_event", ".", "pos", ")", "if", "self", ".", "_aspect", "is", "None", ":", "self", ".", "zoom", "(", "np", ".", "exp", "(", "dxy", "*", "(", "0.01", ",", "-", "0.01", ")", ")", ",", "center", ")", "else", ":", "s", "=", "dxy", "[", "1", "]", "*", "-", "0.01", "self", ".", "zoom", "(", "np", ".", "exp", "(", "np", ".", "array", "(", "[", "s", ",", "s", "]", ")", ")", ",", "center", ")", "self", ".", "shader_map", "(", ")" ]
Mouse move handler Parameters ---------- event : instance of Event The event.
[ "Mouse", "move", "handler" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/interactive.py#L62-L87
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/transforms/interactive.py
PanZoomTransform.on_mouse_wheel
def on_mouse_wheel(self, event): """Mouse wheel handler Parameters ---------- event : instance of Event The event. """ self.zoom(np.exp(event.delta * (0.01, -0.01)), event.pos)
python
def on_mouse_wheel(self, event): """Mouse wheel handler Parameters ---------- event : instance of Event The event. """ self.zoom(np.exp(event.delta * (0.01, -0.01)), event.pos)
[ "def", "on_mouse_wheel", "(", "self", ",", "event", ")", ":", "self", ".", "zoom", "(", "np", ".", "exp", "(", "event", ".", "delta", "*", "(", "0.01", ",", "-", "0.01", ")", ")", ",", "event", ".", "pos", ")" ]
Mouse wheel handler Parameters ---------- event : instance of Event The event.
[ "Mouse", "wheel", "handler" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/transforms/interactive.py#L89-L97
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/tube.py
_frenet_frames
def _frenet_frames(points, closed): '''Calculates and returns the tangents, normals and binormals for the tube.''' tangents = np.zeros((len(points), 3)) normals = np.zeros((len(points), 3)) epsilon = 0.0001 # Compute tangent vectors for each segment tangents = np.roll(points, -1, axis=0) - np.roll(points, 1, axis=0) if not closed: tangents[0] = points[1] - points[0] tangents[-1] = points[-1] - points[-2] mags = np.sqrt(np.sum(tangents * tangents, axis=1)) tangents /= mags[:, np.newaxis] # Get initial normal and binormal t = np.abs(tangents[0]) smallest = np.argmin(t) normal = np.zeros(3) normal[smallest] = 1. vec = np.cross(tangents[0], normal) normals[0] = np.cross(tangents[0], vec) # Compute normal and binormal vectors along the path for i in range(1, len(points)): normals[i] = normals[i-1] vec = np.cross(tangents[i-1], tangents[i]) if norm(vec) > epsilon: vec /= norm(vec) theta = np.arccos(np.clip(tangents[i-1].dot(tangents[i]), -1, 1)) normals[i] = rotate(-np.degrees(theta), vec)[:3, :3].dot(normals[i]) if closed: theta = np.arccos(np.clip(normals[0].dot(normals[-1]), -1, 1)) theta /= len(points) - 1 if tangents[0].dot(np.cross(normals[0], normals[-1])) > 0: theta *= -1. for i in range(1, len(points)): normals[i] = rotate(-np.degrees(theta*i), tangents[i])[:3, :3].dot(normals[i]) binormals = np.cross(tangents, normals) return tangents, normals, binormals
python
def _frenet_frames(points, closed): '''Calculates and returns the tangents, normals and binormals for the tube.''' tangents = np.zeros((len(points), 3)) normals = np.zeros((len(points), 3)) epsilon = 0.0001 # Compute tangent vectors for each segment tangents = np.roll(points, -1, axis=0) - np.roll(points, 1, axis=0) if not closed: tangents[0] = points[1] - points[0] tangents[-1] = points[-1] - points[-2] mags = np.sqrt(np.sum(tangents * tangents, axis=1)) tangents /= mags[:, np.newaxis] # Get initial normal and binormal t = np.abs(tangents[0]) smallest = np.argmin(t) normal = np.zeros(3) normal[smallest] = 1. vec = np.cross(tangents[0], normal) normals[0] = np.cross(tangents[0], vec) # Compute normal and binormal vectors along the path for i in range(1, len(points)): normals[i] = normals[i-1] vec = np.cross(tangents[i-1], tangents[i]) if norm(vec) > epsilon: vec /= norm(vec) theta = np.arccos(np.clip(tangents[i-1].dot(tangents[i]), -1, 1)) normals[i] = rotate(-np.degrees(theta), vec)[:3, :3].dot(normals[i]) if closed: theta = np.arccos(np.clip(normals[0].dot(normals[-1]), -1, 1)) theta /= len(points) - 1 if tangents[0].dot(np.cross(normals[0], normals[-1])) > 0: theta *= -1. for i in range(1, len(points)): normals[i] = rotate(-np.degrees(theta*i), tangents[i])[:3, :3].dot(normals[i]) binormals = np.cross(tangents, normals) return tangents, normals, binormals
[ "def", "_frenet_frames", "(", "points", ",", "closed", ")", ":", "tangents", "=", "np", ".", "zeros", "(", "(", "len", "(", "points", ")", ",", "3", ")", ")", "normals", "=", "np", ".", "zeros", "(", "(", "len", "(", "points", ")", ",", "3", ")", ")", "epsilon", "=", "0.0001", "# Compute tangent vectors for each segment", "tangents", "=", "np", ".", "roll", "(", "points", ",", "-", "1", ",", "axis", "=", "0", ")", "-", "np", ".", "roll", "(", "points", ",", "1", ",", "axis", "=", "0", ")", "if", "not", "closed", ":", "tangents", "[", "0", "]", "=", "points", "[", "1", "]", "-", "points", "[", "0", "]", "tangents", "[", "-", "1", "]", "=", "points", "[", "-", "1", "]", "-", "points", "[", "-", "2", "]", "mags", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "tangents", "*", "tangents", ",", "axis", "=", "1", ")", ")", "tangents", "/=", "mags", "[", ":", ",", "np", ".", "newaxis", "]", "# Get initial normal and binormal", "t", "=", "np", ".", "abs", "(", "tangents", "[", "0", "]", ")", "smallest", "=", "np", ".", "argmin", "(", "t", ")", "normal", "=", "np", ".", "zeros", "(", "3", ")", "normal", "[", "smallest", "]", "=", "1.", "vec", "=", "np", ".", "cross", "(", "tangents", "[", "0", "]", ",", "normal", ")", "normals", "[", "0", "]", "=", "np", ".", "cross", "(", "tangents", "[", "0", "]", ",", "vec", ")", "# Compute normal and binormal vectors along the path", "for", "i", "in", "range", "(", "1", ",", "len", "(", "points", ")", ")", ":", "normals", "[", "i", "]", "=", "normals", "[", "i", "-", "1", "]", "vec", "=", "np", ".", "cross", "(", "tangents", "[", "i", "-", "1", "]", ",", "tangents", "[", "i", "]", ")", "if", "norm", "(", "vec", ")", ">", "epsilon", ":", "vec", "/=", "norm", "(", "vec", ")", "theta", "=", "np", ".", "arccos", "(", "np", ".", "clip", "(", "tangents", "[", "i", "-", "1", "]", ".", "dot", "(", "tangents", "[", "i", "]", ")", ",", "-", "1", ",", "1", ")", ")", "normals", "[", "i", "]", "=", "rotate", "(", "-", "np", ".", "degrees", "(", "theta", ")", ",", "vec", ")", "[", ":", "3", ",", ":", "3", "]", ".", "dot", "(", "normals", "[", "i", "]", ")", "if", "closed", ":", "theta", "=", "np", ".", "arccos", "(", "np", ".", "clip", "(", "normals", "[", "0", "]", ".", "dot", "(", "normals", "[", "-", "1", "]", ")", ",", "-", "1", ",", "1", ")", ")", "theta", "/=", "len", "(", "points", ")", "-", "1", "if", "tangents", "[", "0", "]", ".", "dot", "(", "np", ".", "cross", "(", "normals", "[", "0", "]", ",", "normals", "[", "-", "1", "]", ")", ")", ">", "0", ":", "theta", "*=", "-", "1.", "for", "i", "in", "range", "(", "1", ",", "len", "(", "points", ")", ")", ":", "normals", "[", "i", "]", "=", "rotate", "(", "-", "np", ".", "degrees", "(", "theta", "*", "i", ")", ",", "tangents", "[", "i", "]", ")", "[", ":", "3", ",", ":", "3", "]", ".", "dot", "(", "normals", "[", "i", "]", ")", "binormals", "=", "np", ".", "cross", "(", "tangents", ",", "normals", ")", "return", "tangents", ",", "normals", ",", "binormals" ]
Calculates and returns the tangents, normals and binormals for the tube.
[ "Calculates", "and", "returns", "the", "tangents", "normals", "and", "binormals", "for", "the", "tube", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/tube.py#L109-L160
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.max_order
def max_order(self): """ Depth of the smallest HEALPix cells found in the MOC instance. """ # TODO: cache value combo = int(0) for iv in self._interval_set._intervals: combo |= iv[0] | iv[1] ret = AbstractMOC.HPY_MAX_NORDER - (utils.number_trailing_zeros(combo) // 2) if ret < 0: ret = 0 return ret
python
def max_order(self): """ Depth of the smallest HEALPix cells found in the MOC instance. """ # TODO: cache value combo = int(0) for iv in self._interval_set._intervals: combo |= iv[0] | iv[1] ret = AbstractMOC.HPY_MAX_NORDER - (utils.number_trailing_zeros(combo) // 2) if ret < 0: ret = 0 return ret
[ "def", "max_order", "(", "self", ")", ":", "# TODO: cache value", "combo", "=", "int", "(", "0", ")", "for", "iv", "in", "self", ".", "_interval_set", ".", "_intervals", ":", "combo", "|=", "iv", "[", "0", "]", "|", "iv", "[", "1", "]", "ret", "=", "AbstractMOC", ".", "HPY_MAX_NORDER", "-", "(", "utils", ".", "number_trailing_zeros", "(", "combo", ")", "//", "2", ")", "if", "ret", "<", "0", ":", "ret", "=", "0", "return", "ret" ]
Depth of the smallest HEALPix cells found in the MOC instance.
[ "Depth", "of", "the", "smallest", "HEALPix", "cells", "found", "in", "the", "MOC", "instance", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L70-L83
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.intersection
def intersection(self, another_moc, *args): """ Intersection between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used for performing the intersection with self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the intersection with. Returns ------- result : `~mocpy.moc.MOC`/`~mocpy.tmoc.TimeMOC` The resulting MOC. """ interval_set = self._interval_set.intersection(another_moc._interval_set) for moc in args: interval_set = interval_set.intersection(moc._interval_set) return self.__class__(interval_set)
python
def intersection(self, another_moc, *args): """ Intersection between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used for performing the intersection with self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the intersection with. Returns ------- result : `~mocpy.moc.MOC`/`~mocpy.tmoc.TimeMOC` The resulting MOC. """ interval_set = self._interval_set.intersection(another_moc._interval_set) for moc in args: interval_set = interval_set.intersection(moc._interval_set) return self.__class__(interval_set)
[ "def", "intersection", "(", "self", ",", "another_moc", ",", "*", "args", ")", ":", "interval_set", "=", "self", ".", "_interval_set", ".", "intersection", "(", "another_moc", ".", "_interval_set", ")", "for", "moc", "in", "args", ":", "interval_set", "=", "interval_set", ".", "intersection", "(", "moc", ".", "_interval_set", ")", "return", "self", ".", "__class__", "(", "interval_set", ")" ]
Intersection between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used for performing the intersection with self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the intersection with. Returns ------- result : `~mocpy.moc.MOC`/`~mocpy.tmoc.TimeMOC` The resulting MOC.
[ "Intersection", "between", "the", "MOC", "instance", "and", "other", "MOCs", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L85-L105
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.union
def union(self, another_moc, *args): """ Union between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used for performing the union with self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the union with. Returns ------- result : `~mocpy.moc.MOC`/`~mocpy.tmoc.TimeMOC` The resulting MOC. """ interval_set = self._interval_set.union(another_moc._interval_set) for moc in args: interval_set = interval_set.union(moc._interval_set) return self.__class__(interval_set)
python
def union(self, another_moc, *args): """ Union between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used for performing the union with self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the union with. Returns ------- result : `~mocpy.moc.MOC`/`~mocpy.tmoc.TimeMOC` The resulting MOC. """ interval_set = self._interval_set.union(another_moc._interval_set) for moc in args: interval_set = interval_set.union(moc._interval_set) return self.__class__(interval_set)
[ "def", "union", "(", "self", ",", "another_moc", ",", "*", "args", ")", ":", "interval_set", "=", "self", ".", "_interval_set", ".", "union", "(", "another_moc", ".", "_interval_set", ")", "for", "moc", "in", "args", ":", "interval_set", "=", "interval_set", ".", "union", "(", "moc", ".", "_interval_set", ")", "return", "self", ".", "__class__", "(", "interval_set", ")" ]
Union between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used for performing the union with self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the union with. Returns ------- result : `~mocpy.moc.MOC`/`~mocpy.tmoc.TimeMOC` The resulting MOC.
[ "Union", "between", "the", "MOC", "instance", "and", "other", "MOCs", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L107-L127
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.difference
def difference(self, another_moc, *args): """ Difference between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used that will be substracted to self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the difference with. Returns ------- result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC. """ interval_set = self._interval_set.difference(another_moc._interval_set) for moc in args: interval_set = interval_set.difference(moc._interval_set) return self.__class__(interval_set)
python
def difference(self, another_moc, *args): """ Difference between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used that will be substracted to self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the difference with. Returns ------- result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC. """ interval_set = self._interval_set.difference(another_moc._interval_set) for moc in args: interval_set = interval_set.difference(moc._interval_set) return self.__class__(interval_set)
[ "def", "difference", "(", "self", ",", "another_moc", ",", "*", "args", ")", ":", "interval_set", "=", "self", ".", "_interval_set", ".", "difference", "(", "another_moc", ".", "_interval_set", ")", "for", "moc", "in", "args", ":", "interval_set", "=", "interval_set", ".", "difference", "(", "moc", ".", "_interval_set", ")", "return", "self", ".", "__class__", "(", "interval_set", ")" ]
Difference between the MOC instance and other MOCs. Parameters ---------- another_moc : `~mocpy.moc.MOC` The MOC used that will be substracted to self. args : `~mocpy.moc.MOC` Other additional MOCs to perform the difference with. Returns ------- result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC.
[ "Difference", "between", "the", "MOC", "instance", "and", "other", "MOCs", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L129-L149
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC._neighbour_pixels
def _neighbour_pixels(hp, ipix): """ Returns all the pixels neighbours of ``ipix`` """ neigh_ipix = np.unique(hp.neighbours(ipix).ravel()) # Remove negative pixel values returned by `~astropy_healpix.HEALPix.neighbours` return neigh_ipix[np.where(neigh_ipix >= 0)]
python
def _neighbour_pixels(hp, ipix): """ Returns all the pixels neighbours of ``ipix`` """ neigh_ipix = np.unique(hp.neighbours(ipix).ravel()) # Remove negative pixel values returned by `~astropy_healpix.HEALPix.neighbours` return neigh_ipix[np.where(neigh_ipix >= 0)]
[ "def", "_neighbour_pixels", "(", "hp", ",", "ipix", ")", ":", "neigh_ipix", "=", "np", ".", "unique", "(", "hp", ".", "neighbours", "(", "ipix", ")", ".", "ravel", "(", ")", ")", "# Remove negative pixel values returned by `~astropy_healpix.HEALPix.neighbours`", "return", "neigh_ipix", "[", "np", ".", "where", "(", "neigh_ipix", ">=", "0", ")", "]" ]
Returns all the pixels neighbours of ``ipix``
[ "Returns", "all", "the", "pixels", "neighbours", "of", "ipix" ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L187-L193
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.from_cells
def from_cells(cls, cells): """ Creates a MOC from a numpy array representing the HEALPix cells. Parameters ---------- cells : `numpy.ndarray` Must be a numpy structured array (See https://docs.scipy.org/doc/numpy-1.15.0/user/basics.rec.html). The structure of a cell contains 3 attributes: - A `ipix` value being a np.uint64 - A `depth` value being a np.uint32 - A `fully_covered` flag bit stored in a np.uint8 Returns ------- moc : `~mocpy.moc.MOC` The MOC. """ shift = (AbstractMOC.HPY_MAX_NORDER - cells["depth"]) << 1 p1 = cells["ipix"] p2 = cells["ipix"] + 1 intervals = np.vstack((p1 << shift, p2 << shift)).T return cls(IntervalSet(intervals))
python
def from_cells(cls, cells): """ Creates a MOC from a numpy array representing the HEALPix cells. Parameters ---------- cells : `numpy.ndarray` Must be a numpy structured array (See https://docs.scipy.org/doc/numpy-1.15.0/user/basics.rec.html). The structure of a cell contains 3 attributes: - A `ipix` value being a np.uint64 - A `depth` value being a np.uint32 - A `fully_covered` flag bit stored in a np.uint8 Returns ------- moc : `~mocpy.moc.MOC` The MOC. """ shift = (AbstractMOC.HPY_MAX_NORDER - cells["depth"]) << 1 p1 = cells["ipix"] p2 = cells["ipix"] + 1 intervals = np.vstack((p1 << shift, p2 << shift)).T return cls(IntervalSet(intervals))
[ "def", "from_cells", "(", "cls", ",", "cells", ")", ":", "shift", "=", "(", "AbstractMOC", ".", "HPY_MAX_NORDER", "-", "cells", "[", "\"depth\"", "]", ")", "<<", "1", "p1", "=", "cells", "[", "\"ipix\"", "]", "p2", "=", "cells", "[", "\"ipix\"", "]", "+", "1", "intervals", "=", "np", ".", "vstack", "(", "(", "p1", "<<", "shift", ",", "p2", "<<", "shift", ")", ")", ".", "T", "return", "cls", "(", "IntervalSet", "(", "intervals", ")", ")" ]
Creates a MOC from a numpy array representing the HEALPix cells. Parameters ---------- cells : `numpy.ndarray` Must be a numpy structured array (See https://docs.scipy.org/doc/numpy-1.15.0/user/basics.rec.html). The structure of a cell contains 3 attributes: - A `ipix` value being a np.uint64 - A `depth` value being a np.uint32 - A `fully_covered` flag bit stored in a np.uint8 Returns ------- moc : `~mocpy.moc.MOC` The MOC.
[ "Creates", "a", "MOC", "from", "a", "numpy", "array", "representing", "the", "HEALPix", "cells", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L196-L222
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.from_json
def from_json(cls, json_moc): """ Creates a MOC from a dictionary of HEALPix cell arrays indexed by their depth. Parameters ---------- json_moc : dict(str : [int] A dictionary of HEALPix cell arrays indexed by their depth. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` the MOC. """ intervals = np.array([]) for order, pix_l in json_moc.items(): if len(pix_l) == 0: continue pix = np.array(pix_l) p1 = pix p2 = pix + 1 shift = 2 * (AbstractMOC.HPY_MAX_NORDER - int(order)) itv = np.vstack((p1 << shift, p2 << shift)).T if intervals.size == 0: intervals = itv else: intervals = np.vstack((intervals, itv)) return cls(IntervalSet(intervals))
python
def from_json(cls, json_moc): """ Creates a MOC from a dictionary of HEALPix cell arrays indexed by their depth. Parameters ---------- json_moc : dict(str : [int] A dictionary of HEALPix cell arrays indexed by their depth. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` the MOC. """ intervals = np.array([]) for order, pix_l in json_moc.items(): if len(pix_l) == 0: continue pix = np.array(pix_l) p1 = pix p2 = pix + 1 shift = 2 * (AbstractMOC.HPY_MAX_NORDER - int(order)) itv = np.vstack((p1 << shift, p2 << shift)).T if intervals.size == 0: intervals = itv else: intervals = np.vstack((intervals, itv)) return cls(IntervalSet(intervals))
[ "def", "from_json", "(", "cls", ",", "json_moc", ")", ":", "intervals", "=", "np", ".", "array", "(", "[", "]", ")", "for", "order", ",", "pix_l", "in", "json_moc", ".", "items", "(", ")", ":", "if", "len", "(", "pix_l", ")", "==", "0", ":", "continue", "pix", "=", "np", ".", "array", "(", "pix_l", ")", "p1", "=", "pix", "p2", "=", "pix", "+", "1", "shift", "=", "2", "*", "(", "AbstractMOC", ".", "HPY_MAX_NORDER", "-", "int", "(", "order", ")", ")", "itv", "=", "np", ".", "vstack", "(", "(", "p1", "<<", "shift", ",", "p2", "<<", "shift", ")", ")", ".", "T", "if", "intervals", ".", "size", "==", "0", ":", "intervals", "=", "itv", "else", ":", "intervals", "=", "np", ".", "vstack", "(", "(", "intervals", ",", "itv", ")", ")", "return", "cls", "(", "IntervalSet", "(", "intervals", ")", ")" ]
Creates a MOC from a dictionary of HEALPix cell arrays indexed by their depth. Parameters ---------- json_moc : dict(str : [int] A dictionary of HEALPix cell arrays indexed by their depth. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` the MOC.
[ "Creates", "a", "MOC", "from", "a", "dictionary", "of", "HEALPix", "cell", "arrays", "indexed", "by", "their", "depth", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L225-L254
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC._uniq_pixels_iterator
def _uniq_pixels_iterator(self): """ Generator giving the NUNIQ HEALPix pixels of the MOC. Returns ------- uniq : the NUNIQ HEALPix pixels iterator """ intervals_uniq_l = IntervalSet.to_nuniq_interval_set(self._interval_set)._intervals for uniq_iv in intervals_uniq_l: for uniq in range(uniq_iv[0], uniq_iv[1]): yield uniq
python
def _uniq_pixels_iterator(self): """ Generator giving the NUNIQ HEALPix pixels of the MOC. Returns ------- uniq : the NUNIQ HEALPix pixels iterator """ intervals_uniq_l = IntervalSet.to_nuniq_interval_set(self._interval_set)._intervals for uniq_iv in intervals_uniq_l: for uniq in range(uniq_iv[0], uniq_iv[1]): yield uniq
[ "def", "_uniq_pixels_iterator", "(", "self", ")", ":", "intervals_uniq_l", "=", "IntervalSet", ".", "to_nuniq_interval_set", "(", "self", ".", "_interval_set", ")", ".", "_intervals", "for", "uniq_iv", "in", "intervals_uniq_l", ":", "for", "uniq", "in", "range", "(", "uniq_iv", "[", "0", "]", ",", "uniq_iv", "[", "1", "]", ")", ":", "yield", "uniq" ]
Generator giving the NUNIQ HEALPix pixels of the MOC. Returns ------- uniq : the NUNIQ HEALPix pixels iterator
[ "Generator", "giving", "the", "NUNIQ", "HEALPix", "pixels", "of", "the", "MOC", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L256-L268
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.from_fits
def from_fits(cls, filename): """ Loads a MOC from a FITS file. The specified FITS file must store the MOC (i.e. the list of HEALPix cells it contains) in a binary HDU table. Parameters ---------- filename : str The path to the FITS file. Returns ------- result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC. """ table = Table.read(filename) intervals = np.vstack((table['UNIQ'], table['UNIQ']+1)).T nuniq_interval_set = IntervalSet(intervals) interval_set = IntervalSet.from_nuniq_interval_set(nuniq_interval_set) return cls(interval_set)
python
def from_fits(cls, filename): """ Loads a MOC from a FITS file. The specified FITS file must store the MOC (i.e. the list of HEALPix cells it contains) in a binary HDU table. Parameters ---------- filename : str The path to the FITS file. Returns ------- result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC. """ table = Table.read(filename) intervals = np.vstack((table['UNIQ'], table['UNIQ']+1)).T nuniq_interval_set = IntervalSet(intervals) interval_set = IntervalSet.from_nuniq_interval_set(nuniq_interval_set) return cls(interval_set)
[ "def", "from_fits", "(", "cls", ",", "filename", ")", ":", "table", "=", "Table", ".", "read", "(", "filename", ")", "intervals", "=", "np", ".", "vstack", "(", "(", "table", "[", "'UNIQ'", "]", ",", "table", "[", "'UNIQ'", "]", "+", "1", ")", ")", ".", "T", "nuniq_interval_set", "=", "IntervalSet", "(", "intervals", ")", "interval_set", "=", "IntervalSet", ".", "from_nuniq_interval_set", "(", "nuniq_interval_set", ")", "return", "cls", "(", "interval_set", ")" ]
Loads a MOC from a FITS file. The specified FITS file must store the MOC (i.e. the list of HEALPix cells it contains) in a binary HDU table. Parameters ---------- filename : str The path to the FITS file. Returns ------- result : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC.
[ "Loads", "a", "MOC", "from", "a", "FITS", "file", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L271-L293
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.from_str
def from_str(cls, value): """ Create a MOC from a str. This grammar is expressed is the `MOC IVOA <http://ivoa.net/documents/MOC/20190215/WD-MOC-1.1-20190215.pdf>`__ specification at section 2.3.2. Parameters ---------- value : str The MOC as a string following the grammar rules. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC Examples -------- >>> from mocpy import MOC >>> moc = MOC.from_str("2/2-25,28,29 4/0 6/") """ # Import lark parser when from_str is called # at least one time from lark import Lark, Transformer class ParsingException(Exception): pass class TreeToJson(Transformer): def value(self, items): res = {} for item in items: if item is not None: # Do not take into account the "sep" branches res.update(item) return res def sep(self, items): pass def depthpix(self, items): depth = str(items[0]) pixs_l = items[1:][0] return {depth: pixs_l} def uniq_pix(self, pix): if pix: return [int(pix[0])] def range_pix(self, range_pix): lower_bound = int(range_pix[0]) upper_bound = int(range_pix[1]) return np.arange(lower_bound, upper_bound + 1, dtype=int) def pixs(self, items): ipixs = [] for pix in items: if pix is not None: # Do not take into account the "sep" branches ipixs.extend(pix) return ipixs # Initialize the parser when from_str is called # for the first time if AbstractMOC.LARK_PARSER_STR is None: AbstractMOC.LARK_PARSER_STR = Lark(r""" value: depthpix (sep+ depthpix)* depthpix : INT "/" sep* pixs pixs : pix (sep+ pix)* pix : INT? -> uniq_pix | (INT "-" INT) -> range_pix sep : " " | "," | "\n" | "\r" %import common.INT """, start='value') try: tree = AbstractMOC.LARK_PARSER_STR.parse(value) except Exception as err: raise ParsingException("Could not parse {0}. \n Check the grammar section 2.3.2 of http://ivoa.net/documents/MOC/20190215/WD-MOC-1.1-20190215.pdf to see the correct syntax for writing a MOC from a str".format(value)) moc_json = TreeToJson().transform(tree) return cls.from_json(moc_json)
python
def from_str(cls, value): """ Create a MOC from a str. This grammar is expressed is the `MOC IVOA <http://ivoa.net/documents/MOC/20190215/WD-MOC-1.1-20190215.pdf>`__ specification at section 2.3.2. Parameters ---------- value : str The MOC as a string following the grammar rules. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC Examples -------- >>> from mocpy import MOC >>> moc = MOC.from_str("2/2-25,28,29 4/0 6/") """ # Import lark parser when from_str is called # at least one time from lark import Lark, Transformer class ParsingException(Exception): pass class TreeToJson(Transformer): def value(self, items): res = {} for item in items: if item is not None: # Do not take into account the "sep" branches res.update(item) return res def sep(self, items): pass def depthpix(self, items): depth = str(items[0]) pixs_l = items[1:][0] return {depth: pixs_l} def uniq_pix(self, pix): if pix: return [int(pix[0])] def range_pix(self, range_pix): lower_bound = int(range_pix[0]) upper_bound = int(range_pix[1]) return np.arange(lower_bound, upper_bound + 1, dtype=int) def pixs(self, items): ipixs = [] for pix in items: if pix is not None: # Do not take into account the "sep" branches ipixs.extend(pix) return ipixs # Initialize the parser when from_str is called # for the first time if AbstractMOC.LARK_PARSER_STR is None: AbstractMOC.LARK_PARSER_STR = Lark(r""" value: depthpix (sep+ depthpix)* depthpix : INT "/" sep* pixs pixs : pix (sep+ pix)* pix : INT? -> uniq_pix | (INT "-" INT) -> range_pix sep : " " | "," | "\n" | "\r" %import common.INT """, start='value') try: tree = AbstractMOC.LARK_PARSER_STR.parse(value) except Exception as err: raise ParsingException("Could not parse {0}. \n Check the grammar section 2.3.2 of http://ivoa.net/documents/MOC/20190215/WD-MOC-1.1-20190215.pdf to see the correct syntax for writing a MOC from a str".format(value)) moc_json = TreeToJson().transform(tree) return cls.from_json(moc_json)
[ "def", "from_str", "(", "cls", ",", "value", ")", ":", "# Import lark parser when from_str is called", "# at least one time", "from", "lark", "import", "Lark", ",", "Transformer", "class", "ParsingException", "(", "Exception", ")", ":", "pass", "class", "TreeToJson", "(", "Transformer", ")", ":", "def", "value", "(", "self", ",", "items", ")", ":", "res", "=", "{", "}", "for", "item", "in", "items", ":", "if", "item", "is", "not", "None", ":", "# Do not take into account the \"sep\" branches", "res", ".", "update", "(", "item", ")", "return", "res", "def", "sep", "(", "self", ",", "items", ")", ":", "pass", "def", "depthpix", "(", "self", ",", "items", ")", ":", "depth", "=", "str", "(", "items", "[", "0", "]", ")", "pixs_l", "=", "items", "[", "1", ":", "]", "[", "0", "]", "return", "{", "depth", ":", "pixs_l", "}", "def", "uniq_pix", "(", "self", ",", "pix", ")", ":", "if", "pix", ":", "return", "[", "int", "(", "pix", "[", "0", "]", ")", "]", "def", "range_pix", "(", "self", ",", "range_pix", ")", ":", "lower_bound", "=", "int", "(", "range_pix", "[", "0", "]", ")", "upper_bound", "=", "int", "(", "range_pix", "[", "1", "]", ")", "return", "np", ".", "arange", "(", "lower_bound", ",", "upper_bound", "+", "1", ",", "dtype", "=", "int", ")", "def", "pixs", "(", "self", ",", "items", ")", ":", "ipixs", "=", "[", "]", "for", "pix", "in", "items", ":", "if", "pix", "is", "not", "None", ":", "# Do not take into account the \"sep\" branches", "ipixs", ".", "extend", "(", "pix", ")", "return", "ipixs", "# Initialize the parser when from_str is called", "# for the first time", "if", "AbstractMOC", ".", "LARK_PARSER_STR", "is", "None", ":", "AbstractMOC", ".", "LARK_PARSER_STR", "=", "Lark", "(", "r\"\"\"\n value: depthpix (sep+ depthpix)*\n depthpix : INT \"/\" sep* pixs\n pixs : pix (sep+ pix)*\n pix : INT? -> uniq_pix\n | (INT \"-\" INT) -> range_pix\n sep : \" \" | \",\" | \"\\n\" | \"\\r\"\n\n %import common.INT\n \"\"\"", ",", "start", "=", "'value'", ")", "try", ":", "tree", "=", "AbstractMOC", ".", "LARK_PARSER_STR", ".", "parse", "(", "value", ")", "except", "Exception", "as", "err", ":", "raise", "ParsingException", "(", "\"Could not parse {0}. \\n Check the grammar section 2.3.2 of http://ivoa.net/documents/MOC/20190215/WD-MOC-1.1-20190215.pdf to see the correct syntax for writing a MOC from a str\"", ".", "format", "(", "value", ")", ")", "moc_json", "=", "TreeToJson", "(", ")", ".", "transform", "(", "tree", ")", "return", "cls", ".", "from_json", "(", "moc_json", ")" ]
Create a MOC from a str. This grammar is expressed is the `MOC IVOA <http://ivoa.net/documents/MOC/20190215/WD-MOC-1.1-20190215.pdf>`__ specification at section 2.3.2. Parameters ---------- value : str The MOC as a string following the grammar rules. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The resulting MOC Examples -------- >>> from mocpy import MOC >>> moc = MOC.from_str("2/2-25,28,29 4/0 6/")
[ "Create", "a", "MOC", "from", "a", "str", ".", "This", "grammar", "is", "expressed", "is", "the", "MOC", "IVOA", "<http", ":", "//", "ivoa", ".", "net", "/", "documents", "/", "MOC", "/", "20190215", "/", "WD", "-", "MOC", "-", "1", ".", "1", "-", "20190215", ".", "pdf", ">", "__", "specification", "at", "section", "2", ".", "3", ".", "2", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L296-L377
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC._to_json
def _to_json(uniq): """ Serializes a MOC to the JSON format. Parameters ---------- uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Returns ------- result_json : {str : [int]} A dictionary of HEALPix cell lists indexed by their depth. """ result_json = {} depth, ipix = utils.uniq2orderipix(uniq) min_depth = np.min(depth[0]) max_depth = np.max(depth[-1]) for d in range(min_depth, max_depth+1): pix_index = np.where(depth == d)[0] if pix_index.size: # there are pixels belonging to the current order ipix_depth = ipix[pix_index] result_json[str(d)] = ipix_depth.tolist() return result_json
python
def _to_json(uniq): """ Serializes a MOC to the JSON format. Parameters ---------- uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Returns ------- result_json : {str : [int]} A dictionary of HEALPix cell lists indexed by their depth. """ result_json = {} depth, ipix = utils.uniq2orderipix(uniq) min_depth = np.min(depth[0]) max_depth = np.max(depth[-1]) for d in range(min_depth, max_depth+1): pix_index = np.where(depth == d)[0] if pix_index.size: # there are pixels belonging to the current order ipix_depth = ipix[pix_index] result_json[str(d)] = ipix_depth.tolist() return result_json
[ "def", "_to_json", "(", "uniq", ")", ":", "result_json", "=", "{", "}", "depth", ",", "ipix", "=", "utils", ".", "uniq2orderipix", "(", "uniq", ")", "min_depth", "=", "np", ".", "min", "(", "depth", "[", "0", "]", ")", "max_depth", "=", "np", ".", "max", "(", "depth", "[", "-", "1", "]", ")", "for", "d", "in", "range", "(", "min_depth", ",", "max_depth", "+", "1", ")", ":", "pix_index", "=", "np", ".", "where", "(", "depth", "==", "d", ")", "[", "0", "]", "if", "pix_index", ".", "size", ":", "# there are pixels belonging to the current order", "ipix_depth", "=", "ipix", "[", "pix_index", "]", "result_json", "[", "str", "(", "d", ")", "]", "=", "ipix_depth", ".", "tolist", "(", ")", "return", "result_json" ]
Serializes a MOC to the JSON format. Parameters ---------- uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Returns ------- result_json : {str : [int]} A dictionary of HEALPix cell lists indexed by their depth.
[ "Serializes", "a", "MOC", "to", "the", "JSON", "format", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L380-L407
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC._to_str
def _to_str(uniq): """ Serializes a MOC to the STRING format. HEALPix cells are separated by a comma. The HEALPix cell at order 0 and number 10 is encoded by the string: "0/10", the first digit representing the depth and the second the HEALPix cell number for this depth. HEALPix cells next to each other within a specific depth can be expressed as a range and therefore written like that: "12/10-150". This encodes the list of HEALPix cells from 10 to 150 at the depth 12. Parameters ---------- uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Returns ------- result : str The serialized MOC. """ def write_cells(serial, a, b, sep=''): if a == b: serial += '{0}{1}'.format(a, sep) else: serial += '{0}-{1}{2}'.format(a, b, sep) return serial res = '' if uniq.size == 0: return res depth, ipixels = utils.uniq2orderipix(uniq) min_depth = np.min(depth[0]) max_depth = np.max(depth[-1]) for d in range(min_depth, max_depth+1): pix_index = np.where(depth == d)[0] if pix_index.size > 0: # Serialize the depth followed by a slash res += '{0}/'.format(d) # Retrieve the pixel(s) for this depth ipix_depth = ipixels[pix_index] if ipix_depth.size == 1: # If there is only one pixel we serialize it and # go to the next depth res = write_cells(res, ipix_depth[0], ipix_depth[0]) else: # Sort them in case there are several ipix_depth = np.sort(ipix_depth) beg_range = ipix_depth[0] last_range = beg_range # Loop over the sorted pixels by tracking the lower bound of # the current range and the last pixel. for ipix in ipix_depth[1:]: # If the current pixel does not follow the previous one # then we can end a range and serializes it if ipix > last_range + 1: res = write_cells(res, beg_range, last_range, sep=',') # The current pixel is the beginning of a new range beg_range = ipix last_range = ipix # Write the last range res = write_cells(res, beg_range, last_range) # Add a ' ' separator before writing serializing the pixels of the next depth res += ' ' # Remove the last ' ' character res = res[:-1] return res
python
def _to_str(uniq): """ Serializes a MOC to the STRING format. HEALPix cells are separated by a comma. The HEALPix cell at order 0 and number 10 is encoded by the string: "0/10", the first digit representing the depth and the second the HEALPix cell number for this depth. HEALPix cells next to each other within a specific depth can be expressed as a range and therefore written like that: "12/10-150". This encodes the list of HEALPix cells from 10 to 150 at the depth 12. Parameters ---------- uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Returns ------- result : str The serialized MOC. """ def write_cells(serial, a, b, sep=''): if a == b: serial += '{0}{1}'.format(a, sep) else: serial += '{0}-{1}{2}'.format(a, b, sep) return serial res = '' if uniq.size == 0: return res depth, ipixels = utils.uniq2orderipix(uniq) min_depth = np.min(depth[0]) max_depth = np.max(depth[-1]) for d in range(min_depth, max_depth+1): pix_index = np.where(depth == d)[0] if pix_index.size > 0: # Serialize the depth followed by a slash res += '{0}/'.format(d) # Retrieve the pixel(s) for this depth ipix_depth = ipixels[pix_index] if ipix_depth.size == 1: # If there is only one pixel we serialize it and # go to the next depth res = write_cells(res, ipix_depth[0], ipix_depth[0]) else: # Sort them in case there are several ipix_depth = np.sort(ipix_depth) beg_range = ipix_depth[0] last_range = beg_range # Loop over the sorted pixels by tracking the lower bound of # the current range and the last pixel. for ipix in ipix_depth[1:]: # If the current pixel does not follow the previous one # then we can end a range and serializes it if ipix > last_range + 1: res = write_cells(res, beg_range, last_range, sep=',') # The current pixel is the beginning of a new range beg_range = ipix last_range = ipix # Write the last range res = write_cells(res, beg_range, last_range) # Add a ' ' separator before writing serializing the pixels of the next depth res += ' ' # Remove the last ' ' character res = res[:-1] return res
[ "def", "_to_str", "(", "uniq", ")", ":", "def", "write_cells", "(", "serial", ",", "a", ",", "b", ",", "sep", "=", "''", ")", ":", "if", "a", "==", "b", ":", "serial", "+=", "'{0}{1}'", ".", "format", "(", "a", ",", "sep", ")", "else", ":", "serial", "+=", "'{0}-{1}{2}'", ".", "format", "(", "a", ",", "b", ",", "sep", ")", "return", "serial", "res", "=", "''", "if", "uniq", ".", "size", "==", "0", ":", "return", "res", "depth", ",", "ipixels", "=", "utils", ".", "uniq2orderipix", "(", "uniq", ")", "min_depth", "=", "np", ".", "min", "(", "depth", "[", "0", "]", ")", "max_depth", "=", "np", ".", "max", "(", "depth", "[", "-", "1", "]", ")", "for", "d", "in", "range", "(", "min_depth", ",", "max_depth", "+", "1", ")", ":", "pix_index", "=", "np", ".", "where", "(", "depth", "==", "d", ")", "[", "0", "]", "if", "pix_index", ".", "size", ">", "0", ":", "# Serialize the depth followed by a slash", "res", "+=", "'{0}/'", ".", "format", "(", "d", ")", "# Retrieve the pixel(s) for this depth", "ipix_depth", "=", "ipixels", "[", "pix_index", "]", "if", "ipix_depth", ".", "size", "==", "1", ":", "# If there is only one pixel we serialize it and", "# go to the next depth", "res", "=", "write_cells", "(", "res", ",", "ipix_depth", "[", "0", "]", ",", "ipix_depth", "[", "0", "]", ")", "else", ":", "# Sort them in case there are several", "ipix_depth", "=", "np", ".", "sort", "(", "ipix_depth", ")", "beg_range", "=", "ipix_depth", "[", "0", "]", "last_range", "=", "beg_range", "# Loop over the sorted pixels by tracking the lower bound of", "# the current range and the last pixel.", "for", "ipix", "in", "ipix_depth", "[", "1", ":", "]", ":", "# If the current pixel does not follow the previous one", "# then we can end a range and serializes it", "if", "ipix", ">", "last_range", "+", "1", ":", "res", "=", "write_cells", "(", "res", ",", "beg_range", ",", "last_range", ",", "sep", "=", "','", ")", "# The current pixel is the beginning of a new range", "beg_range", "=", "ipix", "last_range", "=", "ipix", "# Write the last range", "res", "=", "write_cells", "(", "res", ",", "beg_range", ",", "last_range", ")", "# Add a ' ' separator before writing serializing the pixels of the next depth", "res", "+=", "' '", "# Remove the last ' ' character", "res", "=", "res", "[", ":", "-", "1", "]", "return", "res" ]
Serializes a MOC to the STRING format. HEALPix cells are separated by a comma. The HEALPix cell at order 0 and number 10 is encoded by the string: "0/10", the first digit representing the depth and the second the HEALPix cell number for this depth. HEALPix cells next to each other within a specific depth can be expressed as a range and therefore written like that: "12/10-150". This encodes the list of HEALPix cells from 10 to 150 at the depth 12. Parameters ---------- uniq : `~numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. Returns ------- result : str The serialized MOC.
[ "Serializes", "a", "MOC", "to", "the", "STRING", "format", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L410-L487
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC._to_fits
def _to_fits(self, uniq, optional_kw_dict=None): """ Serializes a MOC to the FITS format. Parameters ---------- uniq : `numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. optional_kw_dict : dict Optional keywords arguments added to the FITS header. Returns ------- thdulist : `astropy.io.fits.HDUList` The list of HDU tables. """ depth = self.max_order if depth <= 13: fits_format = '1J' else: fits_format = '1K' tbhdu = fits.BinTableHDU.from_columns( fits.ColDefs([ fits.Column(name='UNIQ', format=fits_format, array=uniq) ])) tbhdu.header['PIXTYPE'] = 'HEALPIX' tbhdu.header['ORDERING'] = 'NUNIQ' tbhdu.header.update(self._fits_header_keywords) tbhdu.header['MOCORDER'] = depth tbhdu.header['MOCTOOL'] = 'MOCPy' if optional_kw_dict: for key in optional_kw_dict: tbhdu.header[key] = optional_kw_dict[key] thdulist = fits.HDUList([fits.PrimaryHDU(), tbhdu]) return thdulist
python
def _to_fits(self, uniq, optional_kw_dict=None): """ Serializes a MOC to the FITS format. Parameters ---------- uniq : `numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. optional_kw_dict : dict Optional keywords arguments added to the FITS header. Returns ------- thdulist : `astropy.io.fits.HDUList` The list of HDU tables. """ depth = self.max_order if depth <= 13: fits_format = '1J' else: fits_format = '1K' tbhdu = fits.BinTableHDU.from_columns( fits.ColDefs([ fits.Column(name='UNIQ', format=fits_format, array=uniq) ])) tbhdu.header['PIXTYPE'] = 'HEALPIX' tbhdu.header['ORDERING'] = 'NUNIQ' tbhdu.header.update(self._fits_header_keywords) tbhdu.header['MOCORDER'] = depth tbhdu.header['MOCTOOL'] = 'MOCPy' if optional_kw_dict: for key in optional_kw_dict: tbhdu.header[key] = optional_kw_dict[key] thdulist = fits.HDUList([fits.PrimaryHDU(), tbhdu]) return thdulist
[ "def", "_to_fits", "(", "self", ",", "uniq", ",", "optional_kw_dict", "=", "None", ")", ":", "depth", "=", "self", ".", "max_order", "if", "depth", "<=", "13", ":", "fits_format", "=", "'1J'", "else", ":", "fits_format", "=", "'1K'", "tbhdu", "=", "fits", ".", "BinTableHDU", ".", "from_columns", "(", "fits", ".", "ColDefs", "(", "[", "fits", ".", "Column", "(", "name", "=", "'UNIQ'", ",", "format", "=", "fits_format", ",", "array", "=", "uniq", ")", "]", ")", ")", "tbhdu", ".", "header", "[", "'PIXTYPE'", "]", "=", "'HEALPIX'", "tbhdu", ".", "header", "[", "'ORDERING'", "]", "=", "'NUNIQ'", "tbhdu", ".", "header", ".", "update", "(", "self", ".", "_fits_header_keywords", ")", "tbhdu", ".", "header", "[", "'MOCORDER'", "]", "=", "depth", "tbhdu", ".", "header", "[", "'MOCTOOL'", "]", "=", "'MOCPy'", "if", "optional_kw_dict", ":", "for", "key", "in", "optional_kw_dict", ":", "tbhdu", ".", "header", "[", "key", "]", "=", "optional_kw_dict", "[", "key", "]", "thdulist", "=", "fits", ".", "HDUList", "(", "[", "fits", ".", "PrimaryHDU", "(", ")", ",", "tbhdu", "]", ")", "return", "thdulist" ]
Serializes a MOC to the FITS format. Parameters ---------- uniq : `numpy.ndarray` The array of HEALPix cells representing the MOC to serialize. optional_kw_dict : dict Optional keywords arguments added to the FITS header. Returns ------- thdulist : `astropy.io.fits.HDUList` The list of HDU tables.
[ "Serializes", "a", "MOC", "to", "the", "FITS", "format", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L489-L525
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.serialize
def serialize(self, format='fits', optional_kw_dict=None): """ Serializes the MOC into a specific format. Possible formats are FITS, JSON and STRING Parameters ---------- format : str 'fits' by default. The other possible choice is 'json' or 'str'. optional_kw_dict : dict Optional keywords arguments added to the FITS header. Only used if ``format`` equals to 'fits'. Returns ------- result : `astropy.io.fits.HDUList` or JSON dictionary The result of the serialization. """ formats = ('fits', 'json', 'str') if format not in formats: raise ValueError('format should be one of %s' % (str(formats))) uniq_l = [] for uniq in self._uniq_pixels_iterator(): uniq_l.append(uniq) uniq = np.array(uniq_l) if format == 'fits': result = self._to_fits(uniq=uniq, optional_kw_dict=optional_kw_dict) elif format == 'str': result = self.__class__._to_str(uniq=uniq) else: # json format serialization result = self.__class__._to_json(uniq=uniq) return result
python
def serialize(self, format='fits', optional_kw_dict=None): """ Serializes the MOC into a specific format. Possible formats are FITS, JSON and STRING Parameters ---------- format : str 'fits' by default. The other possible choice is 'json' or 'str'. optional_kw_dict : dict Optional keywords arguments added to the FITS header. Only used if ``format`` equals to 'fits'. Returns ------- result : `astropy.io.fits.HDUList` or JSON dictionary The result of the serialization. """ formats = ('fits', 'json', 'str') if format not in formats: raise ValueError('format should be one of %s' % (str(formats))) uniq_l = [] for uniq in self._uniq_pixels_iterator(): uniq_l.append(uniq) uniq = np.array(uniq_l) if format == 'fits': result = self._to_fits(uniq=uniq, optional_kw_dict=optional_kw_dict) elif format == 'str': result = self.__class__._to_str(uniq=uniq) else: # json format serialization result = self.__class__._to_json(uniq=uniq) return result
[ "def", "serialize", "(", "self", ",", "format", "=", "'fits'", ",", "optional_kw_dict", "=", "None", ")", ":", "formats", "=", "(", "'fits'", ",", "'json'", ",", "'str'", ")", "if", "format", "not", "in", "formats", ":", "raise", "ValueError", "(", "'format should be one of %s'", "%", "(", "str", "(", "formats", ")", ")", ")", "uniq_l", "=", "[", "]", "for", "uniq", "in", "self", ".", "_uniq_pixels_iterator", "(", ")", ":", "uniq_l", ".", "append", "(", "uniq", ")", "uniq", "=", "np", ".", "array", "(", "uniq_l", ")", "if", "format", "==", "'fits'", ":", "result", "=", "self", ".", "_to_fits", "(", "uniq", "=", "uniq", ",", "optional_kw_dict", "=", "optional_kw_dict", ")", "elif", "format", "==", "'str'", ":", "result", "=", "self", ".", "__class__", ".", "_to_str", "(", "uniq", "=", "uniq", ")", "else", ":", "# json format serialization", "result", "=", "self", ".", "__class__", ".", "_to_json", "(", "uniq", "=", "uniq", ")", "return", "result" ]
Serializes the MOC into a specific format. Possible formats are FITS, JSON and STRING Parameters ---------- format : str 'fits' by default. The other possible choice is 'json' or 'str'. optional_kw_dict : dict Optional keywords arguments added to the FITS header. Only used if ``format`` equals to 'fits'. Returns ------- result : `astropy.io.fits.HDUList` or JSON dictionary The result of the serialization.
[ "Serializes", "the", "MOC", "into", "a", "specific", "format", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L527-L564
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.write
def write(self, path, format='fits', overwrite=False, optional_kw_dict=None): """ Writes the MOC to a file. Format can be 'fits' or 'json', though only the fits format is officially supported by the IVOA. Parameters ---------- path : str, optional The path to the file to save the MOC in. format : str, optional The format in which the MOC will be serialized before being saved. Possible formats are "fits" or "json". By default, ``format`` is set to "fits". overwrite : bool, optional If the file already exists and you want to overwrite it, then set the ``overwrite`` keyword. Default to False. optional_kw_dict : optional Optional keywords arguments added to the FITS header. Only used if ``format`` equals to 'fits'. """ serialization = self.serialize(format=format, optional_kw_dict=optional_kw_dict) if format == 'fits': serialization.writeto(path, overwrite=overwrite) else: import json with open(path, 'w') as h: h.write(json.dumps(serialization, sort_keys=True, indent=2))
python
def write(self, path, format='fits', overwrite=False, optional_kw_dict=None): """ Writes the MOC to a file. Format can be 'fits' or 'json', though only the fits format is officially supported by the IVOA. Parameters ---------- path : str, optional The path to the file to save the MOC in. format : str, optional The format in which the MOC will be serialized before being saved. Possible formats are "fits" or "json". By default, ``format`` is set to "fits". overwrite : bool, optional If the file already exists and you want to overwrite it, then set the ``overwrite`` keyword. Default to False. optional_kw_dict : optional Optional keywords arguments added to the FITS header. Only used if ``format`` equals to 'fits'. """ serialization = self.serialize(format=format, optional_kw_dict=optional_kw_dict) if format == 'fits': serialization.writeto(path, overwrite=overwrite) else: import json with open(path, 'w') as h: h.write(json.dumps(serialization, sort_keys=True, indent=2))
[ "def", "write", "(", "self", ",", "path", ",", "format", "=", "'fits'", ",", "overwrite", "=", "False", ",", "optional_kw_dict", "=", "None", ")", ":", "serialization", "=", "self", ".", "serialize", "(", "format", "=", "format", ",", "optional_kw_dict", "=", "optional_kw_dict", ")", "if", "format", "==", "'fits'", ":", "serialization", ".", "writeto", "(", "path", ",", "overwrite", "=", "overwrite", ")", "else", ":", "import", "json", "with", "open", "(", "path", ",", "'w'", ")", "as", "h", ":", "h", ".", "write", "(", "json", ".", "dumps", "(", "serialization", ",", "sort_keys", "=", "True", ",", "indent", "=", "2", ")", ")" ]
Writes the MOC to a file. Format can be 'fits' or 'json', though only the fits format is officially supported by the IVOA. Parameters ---------- path : str, optional The path to the file to save the MOC in. format : str, optional The format in which the MOC will be serialized before being saved. Possible formats are "fits" or "json". By default, ``format`` is set to "fits". overwrite : bool, optional If the file already exists and you want to overwrite it, then set the ``overwrite`` keyword. Default to False. optional_kw_dict : optional Optional keywords arguments added to the FITS header. Only used if ``format`` equals to 'fits'.
[ "Writes", "the", "MOC", "to", "a", "file", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L566-L590
train
cds-astro/mocpy
mocpy/abstract_moc.py
AbstractMOC.degrade_to_order
def degrade_to_order(self, new_order): """ Degrades the MOC instance to a new, less precise, MOC. The maximum depth (i.e. the depth of the smallest HEALPix cells that can be found in the MOC) of the degraded MOC is set to ``new_order``. Parameters ---------- new_order : int Maximum depth of the output degraded MOC. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The degraded MOC. """ shift = 2 * (AbstractMOC.HPY_MAX_NORDER - new_order) ofs = (int(1) << shift) - 1 mask = ~ofs adda = int(0) addb = ofs iv_set = [] for iv in self._interval_set._intervals: a = (iv[0] + adda) & mask b = (iv[1] + addb) & mask if b > a: iv_set.append((a, b)) return self.__class__(IntervalSet(np.asarray(iv_set)))
python
def degrade_to_order(self, new_order): """ Degrades the MOC instance to a new, less precise, MOC. The maximum depth (i.e. the depth of the smallest HEALPix cells that can be found in the MOC) of the degraded MOC is set to ``new_order``. Parameters ---------- new_order : int Maximum depth of the output degraded MOC. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The degraded MOC. """ shift = 2 * (AbstractMOC.HPY_MAX_NORDER - new_order) ofs = (int(1) << shift) - 1 mask = ~ofs adda = int(0) addb = ofs iv_set = [] for iv in self._interval_set._intervals: a = (iv[0] + adda) & mask b = (iv[1] + addb) & mask if b > a: iv_set.append((a, b)) return self.__class__(IntervalSet(np.asarray(iv_set)))
[ "def", "degrade_to_order", "(", "self", ",", "new_order", ")", ":", "shift", "=", "2", "*", "(", "AbstractMOC", ".", "HPY_MAX_NORDER", "-", "new_order", ")", "ofs", "=", "(", "int", "(", "1", ")", "<<", "shift", ")", "-", "1", "mask", "=", "~", "ofs", "adda", "=", "int", "(", "0", ")", "addb", "=", "ofs", "iv_set", "=", "[", "]", "for", "iv", "in", "self", ".", "_interval_set", ".", "_intervals", ":", "a", "=", "(", "iv", "[", "0", "]", "+", "adda", ")", "&", "mask", "b", "=", "(", "iv", "[", "1", "]", "+", "addb", ")", "&", "mask", "if", "b", ">", "a", ":", "iv_set", ".", "append", "(", "(", "a", ",", "b", ")", ")", "return", "self", ".", "__class__", "(", "IntervalSet", "(", "np", ".", "asarray", "(", "iv_set", ")", ")", ")" ]
Degrades the MOC instance to a new, less precise, MOC. The maximum depth (i.e. the depth of the smallest HEALPix cells that can be found in the MOC) of the degraded MOC is set to ``new_order``. Parameters ---------- new_order : int Maximum depth of the output degraded MOC. Returns ------- moc : `~mocpy.moc.MOC` or `~mocpy.tmoc.TimeMOC` The degraded MOC.
[ "Degrades", "the", "MOC", "instance", "to", "a", "new", "less", "precise", "MOC", "." ]
09472cabe537f6bfdb049eeea64d3ea57b391c21
https://github.com/cds-astro/mocpy/blob/09472cabe537f6bfdb049eeea64d3ea57b391c21/mocpy/abstract_moc.py#L592-L623
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_name
def set_name(self, name): """ Set Screen Name """ self.name = name self.server.request("screen_set %s name %s" % (self.ref, self.name))
python
def set_name(self, name): """ Set Screen Name """ self.name = name self.server.request("screen_set %s name %s" % (self.ref, self.name))
[ "def", "set_name", "(", "self", ",", "name", ")", ":", "self", ".", "name", "=", "name", "self", ".", "server", ".", "request", "(", "\"screen_set %s name %s\"", "%", "(", "self", ".", "ref", ",", "self", ".", "name", ")", ")" ]
Set Screen Name
[ "Set", "Screen", "Name" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L53-L57
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_width
def set_width(self, width): """ Set Screen Width """ if width > 0 and width <= self.server.server_info.get("screen_width"): self.width = width self.server.request("screen_set %s wid %i" % (self.ref, self.width))
python
def set_width(self, width): """ Set Screen Width """ if width > 0 and width <= self.server.server_info.get("screen_width"): self.width = width self.server.request("screen_set %s wid %i" % (self.ref, self.width))
[ "def", "set_width", "(", "self", ",", "width", ")", ":", "if", "width", ">", "0", "and", "width", "<=", "self", ".", "server", ".", "server_info", ".", "get", "(", "\"screen_width\"", ")", ":", "self", ".", "width", "=", "width", "self", ".", "server", ".", "request", "(", "\"screen_set %s wid %i\"", "%", "(", "self", ".", "ref", ",", "self", ".", "width", ")", ")" ]
Set Screen Width
[ "Set", "Screen", "Width" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L59-L64
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_height
def set_height(self, height): """ Set Screen Height """ if height > 0 and height <= self.server.server_info.get("screen_height"): self.height = height self.server.request("screen_set %s hgt %i" % (self.ref, self.height))
python
def set_height(self, height): """ Set Screen Height """ if height > 0 and height <= self.server.server_info.get("screen_height"): self.height = height self.server.request("screen_set %s hgt %i" % (self.ref, self.height))
[ "def", "set_height", "(", "self", ",", "height", ")", ":", "if", "height", ">", "0", "and", "height", "<=", "self", ".", "server", ".", "server_info", ".", "get", "(", "\"screen_height\"", ")", ":", "self", ".", "height", "=", "height", "self", ".", "server", ".", "request", "(", "\"screen_set %s hgt %i\"", "%", "(", "self", ".", "ref", ",", "self", ".", "height", ")", ")" ]
Set Screen Height
[ "Set", "Screen", "Height" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L66-L71
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_cursor_x
def set_cursor_x(self, x): """ Set Screen Cursor X Position """ if x >= 0 and x <= self.server.server_info.get("screen_width"): self.cursor_x = x self.server.request("screen_set %s cursor_x %i" % (self.ref, self.cursor_x))
python
def set_cursor_x(self, x): """ Set Screen Cursor X Position """ if x >= 0 and x <= self.server.server_info.get("screen_width"): self.cursor_x = x self.server.request("screen_set %s cursor_x %i" % (self.ref, self.cursor_x))
[ "def", "set_cursor_x", "(", "self", ",", "x", ")", ":", "if", "x", ">=", "0", "and", "x", "<=", "self", ".", "server", ".", "server_info", ".", "get", "(", "\"screen_width\"", ")", ":", "self", ".", "cursor_x", "=", "x", "self", ".", "server", ".", "request", "(", "\"screen_set %s cursor_x %i\"", "%", "(", "self", ".", "ref", ",", "self", ".", "cursor_x", ")", ")" ]
Set Screen Cursor X Position
[ "Set", "Screen", "Cursor", "X", "Position" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L73-L78
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_cursor_y
def set_cursor_y(self, y): """ Set Screen Cursor Y Position """ if y >= 0 and y <= self.server.server_info.get("screen_height"): self.cursor_y = y self.server.request("screen_set %s cursor_y %i" % (self.ref, self.cursor_y))
python
def set_cursor_y(self, y): """ Set Screen Cursor Y Position """ if y >= 0 and y <= self.server.server_info.get("screen_height"): self.cursor_y = y self.server.request("screen_set %s cursor_y %i" % (self.ref, self.cursor_y))
[ "def", "set_cursor_y", "(", "self", ",", "y", ")", ":", "if", "y", ">=", "0", "and", "y", "<=", "self", ".", "server", ".", "server_info", ".", "get", "(", "\"screen_height\"", ")", ":", "self", ".", "cursor_y", "=", "y", "self", ".", "server", ".", "request", "(", "\"screen_set %s cursor_y %i\"", "%", "(", "self", ".", "ref", ",", "self", ".", "cursor_y", ")", ")" ]
Set Screen Cursor Y Position
[ "Set", "Screen", "Cursor", "Y", "Position" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L80-L85
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_duration
def set_duration(self, duration): """ Set Screen Change Interval Duration """ if duration > 0: self.duration = duration self.server.request("screen_set %s duration %i" % (self.ref, (self.duration * 8)))
python
def set_duration(self, duration): """ Set Screen Change Interval Duration """ if duration > 0: self.duration = duration self.server.request("screen_set %s duration %i" % (self.ref, (self.duration * 8)))
[ "def", "set_duration", "(", "self", ",", "duration", ")", ":", "if", "duration", ">", "0", ":", "self", ".", "duration", "=", "duration", "self", ".", "server", ".", "request", "(", "\"screen_set %s duration %i\"", "%", "(", "self", ".", "ref", ",", "(", "self", ".", "duration", "*", "8", ")", ")", ")" ]
Set Screen Change Interval Duration
[ "Set", "Screen", "Change", "Interval", "Duration" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L87-L92
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_timeout
def set_timeout(self, timeout): """ Set Screen Timeout Duration """ if timeout > 0: self.timeout = timeout self.server.request("screen_set %s timeout %i" % (self.ref, (self.timeout * 8)))
python
def set_timeout(self, timeout): """ Set Screen Timeout Duration """ if timeout > 0: self.timeout = timeout self.server.request("screen_set %s timeout %i" % (self.ref, (self.timeout * 8)))
[ "def", "set_timeout", "(", "self", ",", "timeout", ")", ":", "if", "timeout", ">", "0", ":", "self", ".", "timeout", "=", "timeout", "self", ".", "server", ".", "request", "(", "\"screen_set %s timeout %i\"", "%", "(", "self", ".", "ref", ",", "(", "self", ".", "timeout", "*", "8", ")", ")", ")" ]
Set Screen Timeout Duration
[ "Set", "Screen", "Timeout", "Duration" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L94-L99
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_priority
def set_priority(self, priority): """ Set Screen Priority Class """ if priority in ["hidden", "background", "info", "foreground", "alert", "input"]: self.priority = priority self.server.request("screen_set %s priority %s" % (self.ref, self.priority))
python
def set_priority(self, priority): """ Set Screen Priority Class """ if priority in ["hidden", "background", "info", "foreground", "alert", "input"]: self.priority = priority self.server.request("screen_set %s priority %s" % (self.ref, self.priority))
[ "def", "set_priority", "(", "self", ",", "priority", ")", ":", "if", "priority", "in", "[", "\"hidden\"", ",", "\"background\"", ",", "\"info\"", ",", "\"foreground\"", ",", "\"alert\"", ",", "\"input\"", "]", ":", "self", ".", "priority", "=", "priority", "self", ".", "server", ".", "request", "(", "\"screen_set %s priority %s\"", "%", "(", "self", ".", "ref", ",", "self", ".", "priority", ")", ")" ]
Set Screen Priority Class
[ "Set", "Screen", "Priority", "Class" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L101-L106
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_backlight
def set_backlight(self, state): """ Set Screen Backlight Mode """ if state in ["on", "off", "toggle", "open", "blink", "flash"]: self.backlight = state self.server.request("screen_set %s backlight %s" % (self.ref, self.backlight))
python
def set_backlight(self, state): """ Set Screen Backlight Mode """ if state in ["on", "off", "toggle", "open", "blink", "flash"]: self.backlight = state self.server.request("screen_set %s backlight %s" % (self.ref, self.backlight))
[ "def", "set_backlight", "(", "self", ",", "state", ")", ":", "if", "state", "in", "[", "\"on\"", ",", "\"off\"", ",", "\"toggle\"", ",", "\"open\"", ",", "\"blink\"", ",", "\"flash\"", "]", ":", "self", ".", "backlight", "=", "state", "self", ".", "server", ".", "request", "(", "\"screen_set %s backlight %s\"", "%", "(", "self", ".", "ref", ",", "self", ".", "backlight", ")", ")" ]
Set Screen Backlight Mode
[ "Set", "Screen", "Backlight", "Mode" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L108-L113
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_heartbeat
def set_heartbeat(self, state): """ Set Screen Heartbeat Display Mode """ if state in ["on", "off", "open"]: self.heartbeat = state self.server.request("screen_set %s heartbeat %s" % (self.ref, self.heartbeat))
python
def set_heartbeat(self, state): """ Set Screen Heartbeat Display Mode """ if state in ["on", "off", "open"]: self.heartbeat = state self.server.request("screen_set %s heartbeat %s" % (self.ref, self.heartbeat))
[ "def", "set_heartbeat", "(", "self", ",", "state", ")", ":", "if", "state", "in", "[", "\"on\"", ",", "\"off\"", ",", "\"open\"", "]", ":", "self", ".", "heartbeat", "=", "state", "self", ".", "server", ".", "request", "(", "\"screen_set %s heartbeat %s\"", "%", "(", "self", ".", "ref", ",", "self", ".", "heartbeat", ")", ")" ]
Set Screen Heartbeat Display Mode
[ "Set", "Screen", "Heartbeat", "Display", "Mode" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L115-L120
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.set_cursor
def set_cursor(self, cursor): """ Set Screen Cursor Mode """ if cursor in ["on", "off", "under", "block"]: self.cursor = cursor self.server.request("screen_set %s cursor %s" % (self.ref, self.cursor))
python
def set_cursor(self, cursor): """ Set Screen Cursor Mode """ if cursor in ["on", "off", "under", "block"]: self.cursor = cursor self.server.request("screen_set %s cursor %s" % (self.ref, self.cursor))
[ "def", "set_cursor", "(", "self", ",", "cursor", ")", ":", "if", "cursor", "in", "[", "\"on\"", ",", "\"off\"", ",", "\"under\"", ",", "\"block\"", "]", ":", "self", ".", "cursor", "=", "cursor", "self", ".", "server", ".", "request", "(", "\"screen_set %s cursor %s\"", "%", "(", "self", ".", "ref", ",", "self", ".", "cursor", ")", ")" ]
Set Screen Cursor Mode
[ "Set", "Screen", "Cursor", "Mode" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L122-L127
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.clear
def clear(self): """ Clear Screen """ widgets.StringWidget(self, ref="_w1_", text=" " * 20, x=1, y=1) widgets.StringWidget(self, ref="_w2_", text=" " * 20, x=1, y=2) widgets.StringWidget(self, ref="_w3_", text=" " * 20, x=1, y=3) widgets.StringWidget(self, ref="_w4_", text=" " * 20, x=1, y=4)
python
def clear(self): """ Clear Screen """ widgets.StringWidget(self, ref="_w1_", text=" " * 20, x=1, y=1) widgets.StringWidget(self, ref="_w2_", text=" " * 20, x=1, y=2) widgets.StringWidget(self, ref="_w3_", text=" " * 20, x=1, y=3) widgets.StringWidget(self, ref="_w4_", text=" " * 20, x=1, y=4)
[ "def", "clear", "(", "self", ")", ":", "widgets", ".", "StringWidget", "(", "self", ",", "ref", "=", "\"_w1_\"", ",", "text", "=", "\" \"", "*", "20", ",", "x", "=", "1", ",", "y", "=", "1", ")", "widgets", ".", "StringWidget", "(", "self", ",", "ref", "=", "\"_w2_\"", ",", "text", "=", "\" \"", "*", "20", ",", "x", "=", "1", ",", "y", "=", "2", ")", "widgets", ".", "StringWidget", "(", "self", ",", "ref", "=", "\"_w3_\"", ",", "text", "=", "\" \"", "*", "20", ",", "x", "=", "1", ",", "y", "=", "3", ")", "widgets", ".", "StringWidget", "(", "self", ",", "ref", "=", "\"_w4_\"", ",", "text", "=", "\" \"", "*", "20", ",", "x", "=", "1", ",", "y", "=", "4", ")" ]
Clear Screen
[ "Clear", "Screen" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L129-L134
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.add_string_widget
def add_string_widget(self, ref, text="Text", x=1, y=1): """ Add String Widget """ if ref not in self.widgets: widget = widgets.StringWidget(screen=self, ref=ref, text=text, x=x, y=y) self.widgets[ref] = widget return self.widgets[ref]
python
def add_string_widget(self, ref, text="Text", x=1, y=1): """ Add String Widget """ if ref not in self.widgets: widget = widgets.StringWidget(screen=self, ref=ref, text=text, x=x, y=y) self.widgets[ref] = widget return self.widgets[ref]
[ "def", "add_string_widget", "(", "self", ",", "ref", ",", "text", "=", "\"Text\"", ",", "x", "=", "1", ",", "y", "=", "1", ")", ":", "if", "ref", "not", "in", "self", ".", "widgets", ":", "widget", "=", "widgets", ".", "StringWidget", "(", "screen", "=", "self", ",", "ref", "=", "ref", ",", "text", "=", "text", ",", "x", "=", "x", ",", "y", "=", "y", ")", "self", ".", "widgets", "[", "ref", "]", "=", "widget", "return", "self", ".", "widgets", "[", "ref", "]" ]
Add String Widget
[ "Add", "String", "Widget" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L136-L142
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.add_title_widget
def add_title_widget(self, ref, text="Title"): """ Add Title Widget """ if ref not in self.widgets: widget = widgets.TitleWidget(screen=self, ref=ref, text=text) self.widgets[ref] = widget return self.widgets[ref]
python
def add_title_widget(self, ref, text="Title"): """ Add Title Widget """ if ref not in self.widgets: widget = widgets.TitleWidget(screen=self, ref=ref, text=text) self.widgets[ref] = widget return self.widgets[ref]
[ "def", "add_title_widget", "(", "self", ",", "ref", ",", "text", "=", "\"Title\"", ")", ":", "if", "ref", "not", "in", "self", ".", "widgets", ":", "widget", "=", "widgets", ".", "TitleWidget", "(", "screen", "=", "self", ",", "ref", "=", "ref", ",", "text", "=", "text", ")", "self", ".", "widgets", "[", "ref", "]", "=", "widget", "return", "self", ".", "widgets", "[", "ref", "]" ]
Add Title Widget
[ "Add", "Title", "Widget" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L144-L150
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.add_hbar_widget
def add_hbar_widget(self, ref, x=1, y=1, length=10): """ Add Horizontal Bar Widget """ if ref not in self.widgets: widget = widgets.HBarWidget(screen=self, ref=ref, x=x, y=y, length=length) self.widgets[ref] = widget return self.widgets[ref]
python
def add_hbar_widget(self, ref, x=1, y=1, length=10): """ Add Horizontal Bar Widget """ if ref not in self.widgets: widget = widgets.HBarWidget(screen=self, ref=ref, x=x, y=y, length=length) self.widgets[ref] = widget return self.widgets[ref]
[ "def", "add_hbar_widget", "(", "self", ",", "ref", ",", "x", "=", "1", ",", "y", "=", "1", ",", "length", "=", "10", ")", ":", "if", "ref", "not", "in", "self", ".", "widgets", ":", "widget", "=", "widgets", ".", "HBarWidget", "(", "screen", "=", "self", ",", "ref", "=", "ref", ",", "x", "=", "x", ",", "y", "=", "y", ",", "length", "=", "length", ")", "self", ".", "widgets", "[", "ref", "]", "=", "widget", "return", "self", ".", "widgets", "[", "ref", "]" ]
Add Horizontal Bar Widget
[ "Add", "Horizontal", "Bar", "Widget" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L152-L158
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.add_vbar_widget
def add_vbar_widget(self, ref, x=1, y=1, length=10): """ Add Vertical Bar Widget """ if ref not in self.widgets: widget = widgets.VBarWidget(screen=self, ref=ref, x=x, y=y, length=length) self.widgets[ref] = widget return self.widgets[ref]
python
def add_vbar_widget(self, ref, x=1, y=1, length=10): """ Add Vertical Bar Widget """ if ref not in self.widgets: widget = widgets.VBarWidget(screen=self, ref=ref, x=x, y=y, length=length) self.widgets[ref] = widget return self.widgets[ref]
[ "def", "add_vbar_widget", "(", "self", ",", "ref", ",", "x", "=", "1", ",", "y", "=", "1", ",", "length", "=", "10", ")", ":", "if", "ref", "not", "in", "self", ".", "widgets", ":", "widget", "=", "widgets", ".", "VBarWidget", "(", "screen", "=", "self", ",", "ref", "=", "ref", ",", "x", "=", "x", ",", "y", "=", "y", ",", "length", "=", "length", ")", "self", ".", "widgets", "[", "ref", "]", "=", "widget", "return", "self", ".", "widgets", "[", "ref", "]" ]
Add Vertical Bar Widget
[ "Add", "Vertical", "Bar", "Widget" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L160-L166
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.add_frame_widget
def add_frame_widget(self, ref, left=1, top=1, right=20, bottom=1, width=20, height=4, direction="h", speed=1): """ Add Frame Widget """ if ref not in self.widgets: widget = widgets.FrameWidget( screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, width=width, height=height, direction=direction, speed=speed, ) self.widgets[ref] = widget return self.widgets[ref]
python
def add_frame_widget(self, ref, left=1, top=1, right=20, bottom=1, width=20, height=4, direction="h", speed=1): """ Add Frame Widget """ if ref not in self.widgets: widget = widgets.FrameWidget( screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, width=width, height=height, direction=direction, speed=speed, ) self.widgets[ref] = widget return self.widgets[ref]
[ "def", "add_frame_widget", "(", "self", ",", "ref", ",", "left", "=", "1", ",", "top", "=", "1", ",", "right", "=", "20", ",", "bottom", "=", "1", ",", "width", "=", "20", ",", "height", "=", "4", ",", "direction", "=", "\"h\"", ",", "speed", "=", "1", ")", ":", "if", "ref", "not", "in", "self", ".", "widgets", ":", "widget", "=", "widgets", ".", "FrameWidget", "(", "screen", "=", "self", ",", "ref", "=", "ref", ",", "left", "=", "left", ",", "top", "=", "top", ",", "right", "=", "right", ",", "bottom", "=", "bottom", ",", "width", "=", "width", ",", "height", "=", "height", ",", "direction", "=", "direction", ",", "speed", "=", "speed", ",", ")", "self", ".", "widgets", "[", "ref", "]", "=", "widget", "return", "self", ".", "widgets", "[", "ref", "]" ]
Add Frame Widget
[ "Add", "Frame", "Widget" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L187-L196
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.add_number_widget
def add_number_widget(self, ref, x=1, value=1): """ Add Number Widget """ if ref not in self.widgets: widget = widgets.NumberWidget(screen=self, ref=ref, x=x, value=value) self.widgets[ref] = widget return self.widgets[ref]
python
def add_number_widget(self, ref, x=1, value=1): """ Add Number Widget """ if ref not in self.widgets: widget = widgets.NumberWidget(screen=self, ref=ref, x=x, value=value) self.widgets[ref] = widget return self.widgets[ref]
[ "def", "add_number_widget", "(", "self", ",", "ref", ",", "x", "=", "1", ",", "value", "=", "1", ")", ":", "if", "ref", "not", "in", "self", ".", "widgets", ":", "widget", "=", "widgets", ".", "NumberWidget", "(", "screen", "=", "self", ",", "ref", "=", "ref", ",", "x", "=", "x", ",", "value", "=", "value", ")", "self", ".", "widgets", "[", "ref", "]", "=", "widget", "return", "self", ".", "widgets", "[", "ref", "]" ]
Add Number Widget
[ "Add", "Number", "Widget" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L198-L204
train
rbarrois/mpdlcd
mpdlcd/vendor/lcdproc/screen.py
Screen.del_widget
def del_widget(self, ref): """ Delete/Remove A Widget """ self.server.request("widget_del %s %s" % (self.name, ref)) del(self.widgets[ref])
python
def del_widget(self, ref): """ Delete/Remove A Widget """ self.server.request("widget_del %s %s" % (self.name, ref)) del(self.widgets[ref])
[ "def", "del_widget", "(", "self", ",", "ref", ")", ":", "self", ".", "server", ".", "request", "(", "\"widget_del %s %s\"", "%", "(", "self", ".", "name", ",", "ref", ")", ")", "del", "(", "self", ".", "widgets", "[", "ref", "]", ")" ]
Delete/Remove A Widget
[ "Delete", "/", "Remove", "A", "Widget" ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/vendor/lcdproc/screen.py#L206-L209
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/turntable.py
TurntableCamera.orbit
def orbit(self, azim, elev): """ Orbits the camera around the center position. Parameters ---------- azim : float Angle in degrees to rotate horizontally around the center point. elev : float Angle in degrees to rotate vertically around the center point. """ self.azimuth += azim self.elevation = np.clip(self.elevation + elev, -90, 90) self.view_changed()
python
def orbit(self, azim, elev): """ Orbits the camera around the center position. Parameters ---------- azim : float Angle in degrees to rotate horizontally around the center point. elev : float Angle in degrees to rotate vertically around the center point. """ self.azimuth += azim self.elevation = np.clip(self.elevation + elev, -90, 90) self.view_changed()
[ "def", "orbit", "(", "self", ",", "azim", ",", "elev", ")", ":", "self", ".", "azimuth", "+=", "azim", "self", ".", "elevation", "=", "np", ".", "clip", "(", "self", ".", "elevation", "+", "elev", ",", "-", "90", ",", "90", ")", "self", ".", "view_changed", "(", ")" ]
Orbits the camera around the center position. Parameters ---------- azim : float Angle in degrees to rotate horizontally around the center point. elev : float Angle in degrees to rotate vertically around the center point.
[ "Orbits", "the", "camera", "around", "the", "center", "position", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/turntable.py#L111-L123
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/turntable.py
TurntableCamera._update_rotation
def _update_rotation(self, event): """Update rotation parmeters based on mouse movement""" p1 = event.mouse_event.press_event.pos p2 = event.mouse_event.pos if self._event_value is None: self._event_value = self.azimuth, self.elevation self.azimuth = self._event_value[0] - (p2 - p1)[0] * 0.5 self.elevation = self._event_value[1] + (p2 - p1)[1] * 0.5
python
def _update_rotation(self, event): """Update rotation parmeters based on mouse movement""" p1 = event.mouse_event.press_event.pos p2 = event.mouse_event.pos if self._event_value is None: self._event_value = self.azimuth, self.elevation self.azimuth = self._event_value[0] - (p2 - p1)[0] * 0.5 self.elevation = self._event_value[1] + (p2 - p1)[1] * 0.5
[ "def", "_update_rotation", "(", "self", ",", "event", ")", ":", "p1", "=", "event", ".", "mouse_event", ".", "press_event", ".", "pos", "p2", "=", "event", ".", "mouse_event", ".", "pos", "if", "self", ".", "_event_value", "is", "None", ":", "self", ".", "_event_value", "=", "self", ".", "azimuth", ",", "self", ".", "elevation", "self", ".", "azimuth", "=", "self", ".", "_event_value", "[", "0", "]", "-", "(", "p2", "-", "p1", ")", "[", "0", "]", "*", "0.5", "self", ".", "elevation", "=", "self", ".", "_event_value", "[", "1", "]", "+", "(", "p2", "-", "p1", ")", "[", "1", "]", "*", "0.5" ]
Update rotation parmeters based on mouse movement
[ "Update", "rotation", "parmeters", "based", "on", "mouse", "movement" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/turntable.py#L125-L132
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/turntable.py
TurntableCamera._rotate_tr
def _rotate_tr(self): """Rotate the transformation matrix based on camera parameters""" up, forward, right = self._get_dim_vectors() self.transform.rotate(self.elevation, -right) self.transform.rotate(self.azimuth, up)
python
def _rotate_tr(self): """Rotate the transformation matrix based on camera parameters""" up, forward, right = self._get_dim_vectors() self.transform.rotate(self.elevation, -right) self.transform.rotate(self.azimuth, up)
[ "def", "_rotate_tr", "(", "self", ")", ":", "up", ",", "forward", ",", "right", "=", "self", ".", "_get_dim_vectors", "(", ")", "self", ".", "transform", ".", "rotate", "(", "self", ".", "elevation", ",", "-", "right", ")", "self", ".", "transform", ".", "rotate", "(", "self", ".", "azimuth", ",", "up", ")" ]
Rotate the transformation matrix based on camera parameters
[ "Rotate", "the", "transformation", "matrix", "based", "on", "camera", "parameters" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/turntable.py#L134-L138
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/turntable.py
TurntableCamera._dist_to_trans
def _dist_to_trans(self, dist): """Convert mouse x, y movement into x, y, z translations""" rae = np.array([self.roll, self.azimuth, self.elevation]) * np.pi / 180 sro, saz, sel = np.sin(rae) cro, caz, cel = np.cos(rae) dx = (+ dist[0] * (cro * caz + sro * sel * saz) + dist[1] * (sro * caz - cro * sel * saz)) dy = (+ dist[0] * (cro * saz - sro * sel * caz) + dist[1] * (sro * saz + cro * sel * caz)) dz = (- dist[0] * sro * cel + dist[1] * cro * cel) return dx, dy, dz
python
def _dist_to_trans(self, dist): """Convert mouse x, y movement into x, y, z translations""" rae = np.array([self.roll, self.azimuth, self.elevation]) * np.pi / 180 sro, saz, sel = np.sin(rae) cro, caz, cel = np.cos(rae) dx = (+ dist[0] * (cro * caz + sro * sel * saz) + dist[1] * (sro * caz - cro * sel * saz)) dy = (+ dist[0] * (cro * saz - sro * sel * caz) + dist[1] * (sro * saz + cro * sel * caz)) dz = (- dist[0] * sro * cel + dist[1] * cro * cel) return dx, dy, dz
[ "def", "_dist_to_trans", "(", "self", ",", "dist", ")", ":", "rae", "=", "np", ".", "array", "(", "[", "self", ".", "roll", ",", "self", ".", "azimuth", ",", "self", ".", "elevation", "]", ")", "*", "np", ".", "pi", "/", "180", "sro", ",", "saz", ",", "sel", "=", "np", ".", "sin", "(", "rae", ")", "cro", ",", "caz", ",", "cel", "=", "np", ".", "cos", "(", "rae", ")", "dx", "=", "(", "+", "dist", "[", "0", "]", "*", "(", "cro", "*", "caz", "+", "sro", "*", "sel", "*", "saz", ")", "+", "dist", "[", "1", "]", "*", "(", "sro", "*", "caz", "-", "cro", "*", "sel", "*", "saz", ")", ")", "dy", "=", "(", "+", "dist", "[", "0", "]", "*", "(", "cro", "*", "saz", "-", "sro", "*", "sel", "*", "caz", ")", "+", "dist", "[", "1", "]", "*", "(", "sro", "*", "saz", "+", "cro", "*", "sel", "*", "caz", ")", ")", "dz", "=", "(", "-", "dist", "[", "0", "]", "*", "sro", "*", "cel", "+", "dist", "[", "1", "]", "*", "cro", "*", "cel", ")", "return", "dx", ",", "dy", ",", "dz" ]
Convert mouse x, y movement into x, y, z translations
[ "Convert", "mouse", "x", "y", "movement", "into", "x", "y", "z", "translations" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/turntable.py#L140-L150
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/app/backends/_glfw.py
_set_config
def _set_config(c): """Set gl configuration for GLFW """ glfw.glfwWindowHint(glfw.GLFW_RED_BITS, c['red_size']) glfw.glfwWindowHint(glfw.GLFW_GREEN_BITS, c['green_size']) glfw.glfwWindowHint(glfw.GLFW_BLUE_BITS, c['blue_size']) glfw.glfwWindowHint(glfw.GLFW_ALPHA_BITS, c['alpha_size']) glfw.glfwWindowHint(glfw.GLFW_ACCUM_RED_BITS, 0) glfw.glfwWindowHint(glfw.GLFW_ACCUM_GREEN_BITS, 0) glfw.glfwWindowHint(glfw.GLFW_ACCUM_BLUE_BITS, 0) glfw.glfwWindowHint(glfw.GLFW_ACCUM_ALPHA_BITS, 0) glfw.glfwWindowHint(glfw.GLFW_DEPTH_BITS, c['depth_size']) glfw.glfwWindowHint(glfw.GLFW_STENCIL_BITS, c['stencil_size']) # glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, c['major_version']) # glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, c['minor_version']) # glfw.glfwWindowHint(glfw.GLFW_SRGB_CAPABLE, c['srgb']) glfw.glfwWindowHint(glfw.GLFW_SAMPLES, c['samples']) glfw.glfwWindowHint(glfw.GLFW_STEREO, c['stereo']) if not c['double_buffer']: raise RuntimeError('GLFW must double buffer, consider using a ' 'different backend, or using double buffering')
python
def _set_config(c): """Set gl configuration for GLFW """ glfw.glfwWindowHint(glfw.GLFW_RED_BITS, c['red_size']) glfw.glfwWindowHint(glfw.GLFW_GREEN_BITS, c['green_size']) glfw.glfwWindowHint(glfw.GLFW_BLUE_BITS, c['blue_size']) glfw.glfwWindowHint(glfw.GLFW_ALPHA_BITS, c['alpha_size']) glfw.glfwWindowHint(glfw.GLFW_ACCUM_RED_BITS, 0) glfw.glfwWindowHint(glfw.GLFW_ACCUM_GREEN_BITS, 0) glfw.glfwWindowHint(glfw.GLFW_ACCUM_BLUE_BITS, 0) glfw.glfwWindowHint(glfw.GLFW_ACCUM_ALPHA_BITS, 0) glfw.glfwWindowHint(glfw.GLFW_DEPTH_BITS, c['depth_size']) glfw.glfwWindowHint(glfw.GLFW_STENCIL_BITS, c['stencil_size']) # glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, c['major_version']) # glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, c['minor_version']) # glfw.glfwWindowHint(glfw.GLFW_SRGB_CAPABLE, c['srgb']) glfw.glfwWindowHint(glfw.GLFW_SAMPLES, c['samples']) glfw.glfwWindowHint(glfw.GLFW_STEREO, c['stereo']) if not c['double_buffer']: raise RuntimeError('GLFW must double buffer, consider using a ' 'different backend, or using double buffering')
[ "def", "_set_config", "(", "c", ")", ":", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_RED_BITS", ",", "c", "[", "'red_size'", "]", ")", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_GREEN_BITS", ",", "c", "[", "'green_size'", "]", ")", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_BLUE_BITS", ",", "c", "[", "'blue_size'", "]", ")", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_ALPHA_BITS", ",", "c", "[", "'alpha_size'", "]", ")", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_ACCUM_RED_BITS", ",", "0", ")", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_ACCUM_GREEN_BITS", ",", "0", ")", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_ACCUM_BLUE_BITS", ",", "0", ")", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_ACCUM_ALPHA_BITS", ",", "0", ")", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_DEPTH_BITS", ",", "c", "[", "'depth_size'", "]", ")", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_STENCIL_BITS", ",", "c", "[", "'stencil_size'", "]", ")", "# glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MAJOR, c['major_version'])", "# glfw.glfwWindowHint(glfw.GLFW_CONTEXT_VERSION_MINOR, c['minor_version'])", "# glfw.glfwWindowHint(glfw.GLFW_SRGB_CAPABLE, c['srgb'])", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_SAMPLES", ",", "c", "[", "'samples'", "]", ")", "glfw", ".", "glfwWindowHint", "(", "glfw", ".", "GLFW_STEREO", ",", "c", "[", "'stereo'", "]", ")", "if", "not", "c", "[", "'double_buffer'", "]", ":", "raise", "RuntimeError", "(", "'GLFW must double buffer, consider using a '", "'different backend, or using double buffering'", ")" ]
Set gl configuration for GLFW
[ "Set", "gl", "configuration", "for", "GLFW" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/app/backends/_glfw.py#L133-L154
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/app/backends/_glfw.py
CanvasBackend._process_mod
def _process_mod(self, key, down): """Process (possible) keyboard modifiers GLFW provides "mod" with many callbacks, but not (critically) the scroll callback, so we keep track on our own here. """ if key in MOD_KEYS: if down: if key not in self._mod: self._mod.append(key) elif key in self._mod: self._mod.pop(self._mod.index(key)) return self._mod
python
def _process_mod(self, key, down): """Process (possible) keyboard modifiers GLFW provides "mod" with many callbacks, but not (critically) the scroll callback, so we keep track on our own here. """ if key in MOD_KEYS: if down: if key not in self._mod: self._mod.append(key) elif key in self._mod: self._mod.pop(self._mod.index(key)) return self._mod
[ "def", "_process_mod", "(", "self", ",", "key", ",", "down", ")", ":", "if", "key", "in", "MOD_KEYS", ":", "if", "down", ":", "if", "key", "not", "in", "self", ".", "_mod", ":", "self", ".", "_mod", ".", "append", "(", "key", ")", "elif", "key", "in", "self", ".", "_mod", ":", "self", ".", "_mod", ".", "pop", "(", "self", ".", "_mod", ".", "index", "(", "key", ")", ")", "return", "self", ".", "_mod" ]
Process (possible) keyboard modifiers GLFW provides "mod" with many callbacks, but not (critically) the scroll callback, so we keep track on our own here.
[ "Process", "(", "possible", ")", "keyboard", "modifiers" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/app/backends/_glfw.py#L483-L495
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/gl/pyopengl2.py
_patch
def _patch(): """ Monkey-patch pyopengl to fix a bug in glBufferSubData. """ import sys from OpenGL import GL if sys.version_info > (3,): buffersubdatafunc = GL.glBufferSubData if hasattr(buffersubdatafunc, 'wrapperFunction'): buffersubdatafunc = buffersubdatafunc.wrapperFunction _m = sys.modules[buffersubdatafunc.__module__] _m.long = int # Fix missing enum try: from OpenGL.GL.VERSION import GL_2_0 GL_2_0.GL_OBJECT_SHADER_SOURCE_LENGTH = GL_2_0.GL_SHADER_SOURCE_LENGTH except Exception: pass
python
def _patch(): """ Monkey-patch pyopengl to fix a bug in glBufferSubData. """ import sys from OpenGL import GL if sys.version_info > (3,): buffersubdatafunc = GL.glBufferSubData if hasattr(buffersubdatafunc, 'wrapperFunction'): buffersubdatafunc = buffersubdatafunc.wrapperFunction _m = sys.modules[buffersubdatafunc.__module__] _m.long = int # Fix missing enum try: from OpenGL.GL.VERSION import GL_2_0 GL_2_0.GL_OBJECT_SHADER_SOURCE_LENGTH = GL_2_0.GL_SHADER_SOURCE_LENGTH except Exception: pass
[ "def", "_patch", "(", ")", ":", "import", "sys", "from", "OpenGL", "import", "GL", "if", "sys", ".", "version_info", ">", "(", "3", ",", ")", ":", "buffersubdatafunc", "=", "GL", ".", "glBufferSubData", "if", "hasattr", "(", "buffersubdatafunc", ",", "'wrapperFunction'", ")", ":", "buffersubdatafunc", "=", "buffersubdatafunc", ".", "wrapperFunction", "_m", "=", "sys", ".", "modules", "[", "buffersubdatafunc", ".", "__module__", "]", "_m", ".", "long", "=", "int", "# Fix missing enum", "try", ":", "from", "OpenGL", ".", "GL", ".", "VERSION", "import", "GL_2_0", "GL_2_0", ".", "GL_OBJECT_SHADER_SOURCE_LENGTH", "=", "GL_2_0", ".", "GL_SHADER_SOURCE_LENGTH", "except", "Exception", ":", "pass" ]
Monkey-patch pyopengl to fix a bug in glBufferSubData.
[ "Monkey", "-", "patch", "pyopengl", "to", "fix", "a", "bug", "in", "glBufferSubData", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/gl/pyopengl2.py#L18-L34
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/gl/pyopengl2.py
_get_function_from_pyopengl
def _get_function_from_pyopengl(funcname): """ Try getting the given function from PyOpenGL, return a dummy function (that shows a warning when called) if it could not be found. """ func = None # Get function from GL try: func = getattr(_GL, funcname) except AttributeError: # Get function from FBO try: func = getattr(_FBO, funcname) except AttributeError: func = None # Try using "alias" if not bool(func): # Some functions are known by a slightly different name # e.g. glDepthRangef, glClearDepthf if funcname.endswith('f'): try: func = getattr(_GL, funcname[:-1]) except AttributeError: pass # Set dummy function if we could not find it if func is None: func = _make_unavailable_func(funcname) logger.warning('warning: %s not available' % funcname) return func
python
def _get_function_from_pyopengl(funcname): """ Try getting the given function from PyOpenGL, return a dummy function (that shows a warning when called) if it could not be found. """ func = None # Get function from GL try: func = getattr(_GL, funcname) except AttributeError: # Get function from FBO try: func = getattr(_FBO, funcname) except AttributeError: func = None # Try using "alias" if not bool(func): # Some functions are known by a slightly different name # e.g. glDepthRangef, glClearDepthf if funcname.endswith('f'): try: func = getattr(_GL, funcname[:-1]) except AttributeError: pass # Set dummy function if we could not find it if func is None: func = _make_unavailable_func(funcname) logger.warning('warning: %s not available' % funcname) return func
[ "def", "_get_function_from_pyopengl", "(", "funcname", ")", ":", "func", "=", "None", "# Get function from GL", "try", ":", "func", "=", "getattr", "(", "_GL", ",", "funcname", ")", "except", "AttributeError", ":", "# Get function from FBO", "try", ":", "func", "=", "getattr", "(", "_FBO", ",", "funcname", ")", "except", "AttributeError", ":", "func", "=", "None", "# Try using \"alias\"", "if", "not", "bool", "(", "func", ")", ":", "# Some functions are known by a slightly different name", "# e.g. glDepthRangef, glClearDepthf", "if", "funcname", ".", "endswith", "(", "'f'", ")", ":", "try", ":", "func", "=", "getattr", "(", "_GL", ",", "funcname", "[", ":", "-", "1", "]", ")", "except", "AttributeError", ":", "pass", "# Set dummy function if we could not find it", "if", "func", "is", "None", ":", "func", "=", "_make_unavailable_func", "(", "funcname", ")", "logger", ".", "warning", "(", "'warning: %s not available'", "%", "funcname", ")", "return", "func" ]
Try getting the given function from PyOpenGL, return a dummy function (that shows a warning when called) if it could not be found.
[ "Try", "getting", "the", "given", "function", "from", "PyOpenGL", "return", "a", "dummy", "function", "(", "that", "shows", "a", "warning", "when", "called", ")", "if", "it", "could", "not", "be", "found", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/gl/pyopengl2.py#L48-L79
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/gloo/gl/pyopengl2.py
_inject
def _inject(): """ Copy functions from OpenGL.GL into _pyopengl namespace. """ NS = _pyopengl2.__dict__ for glname, ourname in _pyopengl2._functions_to_import: func = _get_function_from_pyopengl(glname) NS[ourname] = func
python
def _inject(): """ Copy functions from OpenGL.GL into _pyopengl namespace. """ NS = _pyopengl2.__dict__ for glname, ourname in _pyopengl2._functions_to_import: func = _get_function_from_pyopengl(glname) NS[ourname] = func
[ "def", "_inject", "(", ")", ":", "NS", "=", "_pyopengl2", ".", "__dict__", "for", "glname", ",", "ourname", "in", "_pyopengl2", ".", "_functions_to_import", ":", "func", "=", "_get_function_from_pyopengl", "(", "glname", ")", "NS", "[", "ourname", "]", "=", "func" ]
Copy functions from OpenGL.GL into _pyopengl namespace.
[ "Copy", "functions", "from", "OpenGL", ".", "GL", "into", "_pyopengl", "namespace", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/gloo/gl/pyopengl2.py#L82-L88
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/util/fonts/_vispy_fonts.py
_get_vispy_font_filename
def _get_vispy_font_filename(face, bold, italic): """Fetch a remote vispy font""" name = face + '-' name += 'Regular' if not bold and not italic else '' name += 'Bold' if bold else '' name += 'Italic' if italic else '' name += '.ttf' return load_data_file('fonts/%s' % name)
python
def _get_vispy_font_filename(face, bold, italic): """Fetch a remote vispy font""" name = face + '-' name += 'Regular' if not bold and not italic else '' name += 'Bold' if bold else '' name += 'Italic' if italic else '' name += '.ttf' return load_data_file('fonts/%s' % name)
[ "def", "_get_vispy_font_filename", "(", "face", ",", "bold", ",", "italic", ")", ":", "name", "=", "face", "+", "'-'", "name", "+=", "'Regular'", "if", "not", "bold", "and", "not", "italic", "else", "''", "name", "+=", "'Bold'", "if", "bold", "else", "''", "name", "+=", "'Italic'", "if", "italic", "else", "''", "name", "+=", "'.ttf'", "return", "load_data_file", "(", "'fonts/%s'", "%", "name", ")" ]
Fetch a remote vispy font
[ "Fetch", "a", "remote", "vispy", "font" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/util/fonts/_vispy_fonts.py#L13-L20
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/color/color_space.py
_check_color_dim
def _check_color_dim(val): """Ensure val is Nx(n_col), usually Nx3""" val = np.atleast_2d(val) if val.shape[1] not in (3, 4): raise RuntimeError('Value must have second dimension of size 3 or 4') return val, val.shape[1]
python
def _check_color_dim(val): """Ensure val is Nx(n_col), usually Nx3""" val = np.atleast_2d(val) if val.shape[1] not in (3, 4): raise RuntimeError('Value must have second dimension of size 3 or 4') return val, val.shape[1]
[ "def", "_check_color_dim", "(", "val", ")", ":", "val", "=", "np", ".", "atleast_2d", "(", "val", ")", "if", "val", ".", "shape", "[", "1", "]", "not", "in", "(", "3", ",", "4", ")", ":", "raise", "RuntimeError", "(", "'Value must have second dimension of size 3 or 4'", ")", "return", "val", ",", "val", ".", "shape", "[", "1", "]" ]
Ensure val is Nx(n_col), usually Nx3
[ "Ensure", "val", "is", "Nx", "(", "n_col", ")", "usually", "Nx3" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/color_space.py#L14-L19
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/color/color_space.py
_hex_to_rgba
def _hex_to_rgba(hexs): """Convert hex to rgba, permitting alpha values in hex""" hexs = np.atleast_1d(np.array(hexs, '|U9')) out = np.ones((len(hexs), 4), np.float32) for hi, h in enumerate(hexs): assert isinstance(h, string_types) off = 1 if h[0] == '#' else 0 assert len(h) in (6+off, 8+off) e = (len(h)-off) // 2 out[hi, :e] = [int(h[i:i+2], 16) / 255. for i in range(off, len(h), 2)] return out
python
def _hex_to_rgba(hexs): """Convert hex to rgba, permitting alpha values in hex""" hexs = np.atleast_1d(np.array(hexs, '|U9')) out = np.ones((len(hexs), 4), np.float32) for hi, h in enumerate(hexs): assert isinstance(h, string_types) off = 1 if h[0] == '#' else 0 assert len(h) in (6+off, 8+off) e = (len(h)-off) // 2 out[hi, :e] = [int(h[i:i+2], 16) / 255. for i in range(off, len(h), 2)] return out
[ "def", "_hex_to_rgba", "(", "hexs", ")", ":", "hexs", "=", "np", ".", "atleast_1d", "(", "np", ".", "array", "(", "hexs", ",", "'|U9'", ")", ")", "out", "=", "np", ".", "ones", "(", "(", "len", "(", "hexs", ")", ",", "4", ")", ",", "np", ".", "float32", ")", "for", "hi", ",", "h", "in", "enumerate", "(", "hexs", ")", ":", "assert", "isinstance", "(", "h", ",", "string_types", ")", "off", "=", "1", "if", "h", "[", "0", "]", "==", "'#'", "else", "0", "assert", "len", "(", "h", ")", "in", "(", "6", "+", "off", ",", "8", "+", "off", ")", "e", "=", "(", "len", "(", "h", ")", "-", "off", ")", "//", "2", "out", "[", "hi", ",", ":", "e", "]", "=", "[", "int", "(", "h", "[", "i", ":", "i", "+", "2", "]", ",", "16", ")", "/", "255.", "for", "i", "in", "range", "(", "off", ",", "len", "(", "h", ")", ",", "2", ")", "]", "return", "out" ]
Convert hex to rgba, permitting alpha values in hex
[ "Convert", "hex", "to", "rgba", "permitting", "alpha", "values", "in", "hex" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/color_space.py#L25-L36
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/color/color_space.py
_rgb_to_hex
def _rgb_to_hex(rgbs): """Convert rgb to hex triplet""" rgbs, n_dim = _check_color_dim(rgbs) return np.array(['#%02x%02x%02x' % tuple((255*rgb[:3]).astype(np.uint8)) for rgb in rgbs], '|U7')
python
def _rgb_to_hex(rgbs): """Convert rgb to hex triplet""" rgbs, n_dim = _check_color_dim(rgbs) return np.array(['#%02x%02x%02x' % tuple((255*rgb[:3]).astype(np.uint8)) for rgb in rgbs], '|U7')
[ "def", "_rgb_to_hex", "(", "rgbs", ")", ":", "rgbs", ",", "n_dim", "=", "_check_color_dim", "(", "rgbs", ")", "return", "np", ".", "array", "(", "[", "'#%02x%02x%02x'", "%", "tuple", "(", "(", "255", "*", "rgb", "[", ":", "3", "]", ")", ".", "astype", "(", "np", ".", "uint8", ")", ")", "for", "rgb", "in", "rgbs", "]", ",", "'|U7'", ")" ]
Convert rgb to hex triplet
[ "Convert", "rgb", "to", "hex", "triplet" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/color_space.py#L39-L43
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/color/color_space.py
_rgb_to_hsv
def _rgb_to_hsv(rgbs): """Convert Nx3 or Nx4 rgb to hsv""" rgbs, n_dim = _check_color_dim(rgbs) hsvs = list() for rgb in rgbs: rgb = rgb[:3] # don't use alpha here idx = np.argmax(rgb) val = rgb[idx] c = val - np.min(rgb) if c == 0: hue = 0 sat = 0 else: if idx == 0: # R == max hue = ((rgb[1] - rgb[2]) / c) % 6 elif idx == 1: # G == max hue = (rgb[2] - rgb[0]) / c + 2 else: # B == max hue = (rgb[0] - rgb[1]) / c + 4 hue *= 60 sat = c / val hsv = [hue, sat, val] hsvs.append(hsv) hsvs = np.array(hsvs, dtype=np.float32) if n_dim == 4: hsvs = np.concatenate((hsvs, rgbs[:, 3]), axis=1) return hsvs
python
def _rgb_to_hsv(rgbs): """Convert Nx3 or Nx4 rgb to hsv""" rgbs, n_dim = _check_color_dim(rgbs) hsvs = list() for rgb in rgbs: rgb = rgb[:3] # don't use alpha here idx = np.argmax(rgb) val = rgb[idx] c = val - np.min(rgb) if c == 0: hue = 0 sat = 0 else: if idx == 0: # R == max hue = ((rgb[1] - rgb[2]) / c) % 6 elif idx == 1: # G == max hue = (rgb[2] - rgb[0]) / c + 2 else: # B == max hue = (rgb[0] - rgb[1]) / c + 4 hue *= 60 sat = c / val hsv = [hue, sat, val] hsvs.append(hsv) hsvs = np.array(hsvs, dtype=np.float32) if n_dim == 4: hsvs = np.concatenate((hsvs, rgbs[:, 3]), axis=1) return hsvs
[ "def", "_rgb_to_hsv", "(", "rgbs", ")", ":", "rgbs", ",", "n_dim", "=", "_check_color_dim", "(", "rgbs", ")", "hsvs", "=", "list", "(", ")", "for", "rgb", "in", "rgbs", ":", "rgb", "=", "rgb", "[", ":", "3", "]", "# don't use alpha here", "idx", "=", "np", ".", "argmax", "(", "rgb", ")", "val", "=", "rgb", "[", "idx", "]", "c", "=", "val", "-", "np", ".", "min", "(", "rgb", ")", "if", "c", "==", "0", ":", "hue", "=", "0", "sat", "=", "0", "else", ":", "if", "idx", "==", "0", ":", "# R == max", "hue", "=", "(", "(", "rgb", "[", "1", "]", "-", "rgb", "[", "2", "]", ")", "/", "c", ")", "%", "6", "elif", "idx", "==", "1", ":", "# G == max", "hue", "=", "(", "rgb", "[", "2", "]", "-", "rgb", "[", "0", "]", ")", "/", "c", "+", "2", "else", ":", "# B == max", "hue", "=", "(", "rgb", "[", "0", "]", "-", "rgb", "[", "1", "]", ")", "/", "c", "+", "4", "hue", "*=", "60", "sat", "=", "c", "/", "val", "hsv", "=", "[", "hue", ",", "sat", ",", "val", "]", "hsvs", ".", "append", "(", "hsv", ")", "hsvs", "=", "np", ".", "array", "(", "hsvs", ",", "dtype", "=", "np", ".", "float32", ")", "if", "n_dim", "==", "4", ":", "hsvs", "=", "np", ".", "concatenate", "(", "(", "hsvs", ",", "rgbs", "[", ":", ",", "3", "]", ")", ",", "axis", "=", "1", ")", "return", "hsvs" ]
Convert Nx3 or Nx4 rgb to hsv
[ "Convert", "Nx3", "or", "Nx4", "rgb", "to", "hsv" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/color_space.py#L49-L75
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/color/color_space.py
_hsv_to_rgb
def _hsv_to_rgb(hsvs): """Convert Nx3 or Nx4 hsv to rgb""" hsvs, n_dim = _check_color_dim(hsvs) # In principle, we *might* be able to vectorize this, but might as well # wait until a compelling use case appears rgbs = list() for hsv in hsvs: c = hsv[1] * hsv[2] m = hsv[2] - c hp = hsv[0] / 60 x = c * (1 - abs(hp % 2 - 1)) if 0 <= hp < 1: r, g, b = c, x, 0 elif hp < 2: r, g, b = x, c, 0 elif hp < 3: r, g, b = 0, c, x elif hp < 4: r, g, b = 0, x, c elif hp < 5: r, g, b = x, 0, c else: r, g, b = c, 0, x rgb = [r + m, g + m, b + m] rgbs.append(rgb) rgbs = np.array(rgbs, dtype=np.float32) if n_dim == 4: rgbs = np.concatenate((rgbs, hsvs[:, 3]), axis=1) return rgbs
python
def _hsv_to_rgb(hsvs): """Convert Nx3 or Nx4 hsv to rgb""" hsvs, n_dim = _check_color_dim(hsvs) # In principle, we *might* be able to vectorize this, but might as well # wait until a compelling use case appears rgbs = list() for hsv in hsvs: c = hsv[1] * hsv[2] m = hsv[2] - c hp = hsv[0] / 60 x = c * (1 - abs(hp % 2 - 1)) if 0 <= hp < 1: r, g, b = c, x, 0 elif hp < 2: r, g, b = x, c, 0 elif hp < 3: r, g, b = 0, c, x elif hp < 4: r, g, b = 0, x, c elif hp < 5: r, g, b = x, 0, c else: r, g, b = c, 0, x rgb = [r + m, g + m, b + m] rgbs.append(rgb) rgbs = np.array(rgbs, dtype=np.float32) if n_dim == 4: rgbs = np.concatenate((rgbs, hsvs[:, 3]), axis=1) return rgbs
[ "def", "_hsv_to_rgb", "(", "hsvs", ")", ":", "hsvs", ",", "n_dim", "=", "_check_color_dim", "(", "hsvs", ")", "# In principle, we *might* be able to vectorize this, but might as well", "# wait until a compelling use case appears", "rgbs", "=", "list", "(", ")", "for", "hsv", "in", "hsvs", ":", "c", "=", "hsv", "[", "1", "]", "*", "hsv", "[", "2", "]", "m", "=", "hsv", "[", "2", "]", "-", "c", "hp", "=", "hsv", "[", "0", "]", "/", "60", "x", "=", "c", "*", "(", "1", "-", "abs", "(", "hp", "%", "2", "-", "1", ")", ")", "if", "0", "<=", "hp", "<", "1", ":", "r", ",", "g", ",", "b", "=", "c", ",", "x", ",", "0", "elif", "hp", "<", "2", ":", "r", ",", "g", ",", "b", "=", "x", ",", "c", ",", "0", "elif", "hp", "<", "3", ":", "r", ",", "g", ",", "b", "=", "0", ",", "c", ",", "x", "elif", "hp", "<", "4", ":", "r", ",", "g", ",", "b", "=", "0", ",", "x", ",", "c", "elif", "hp", "<", "5", ":", "r", ",", "g", ",", "b", "=", "x", ",", "0", ",", "c", "else", ":", "r", ",", "g", ",", "b", "=", "c", ",", "0", ",", "x", "rgb", "=", "[", "r", "+", "m", ",", "g", "+", "m", ",", "b", "+", "m", "]", "rgbs", ".", "append", "(", "rgb", ")", "rgbs", "=", "np", ".", "array", "(", "rgbs", ",", "dtype", "=", "np", ".", "float32", ")", "if", "n_dim", "==", "4", ":", "rgbs", "=", "np", ".", "concatenate", "(", "(", "rgbs", ",", "hsvs", "[", ":", ",", "3", "]", ")", ",", "axis", "=", "1", ")", "return", "rgbs" ]
Convert Nx3 or Nx4 hsv to rgb
[ "Convert", "Nx3", "or", "Nx4", "hsv", "to", "rgb" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/color_space.py#L78-L106
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/color/color_space.py
_lab_to_rgb
def _lab_to_rgb(labs): """Convert Nx3 or Nx4 lab to rgb""" # adapted from BSD-licensed work in MATLAB by Mark Ruzon # Based on ITU-R Recommendation BT.709 using the D65 labs, n_dim = _check_color_dim(labs) # Convert Lab->XYZ (silly indexing used to preserve dimensionality) y = (labs[:, 0] + 16.) / 116. x = (labs[:, 1] / 500.) + y z = y - (labs[:, 2] / 200.) xyz = np.concatenate(([x], [y], [z])) # 3xN over = xyz > 0.2068966 xyz[over] = xyz[over] ** 3. xyz[~over] = (xyz[~over] - 0.13793103448275862) / 7.787 # Convert XYZ->LAB rgbs = np.dot(_xyz2rgb_norm, xyz).T over = rgbs > 0.0031308 rgbs[over] = 1.055 * (rgbs[over] ** (1. / 2.4)) - 0.055 rgbs[~over] *= 12.92 if n_dim == 4: rgbs = np.concatenate((rgbs, labs[:, 3]), axis=1) rgbs = np.clip(rgbs, 0., 1.) return rgbs
python
def _lab_to_rgb(labs): """Convert Nx3 or Nx4 lab to rgb""" # adapted from BSD-licensed work in MATLAB by Mark Ruzon # Based on ITU-R Recommendation BT.709 using the D65 labs, n_dim = _check_color_dim(labs) # Convert Lab->XYZ (silly indexing used to preserve dimensionality) y = (labs[:, 0] + 16.) / 116. x = (labs[:, 1] / 500.) + y z = y - (labs[:, 2] / 200.) xyz = np.concatenate(([x], [y], [z])) # 3xN over = xyz > 0.2068966 xyz[over] = xyz[over] ** 3. xyz[~over] = (xyz[~over] - 0.13793103448275862) / 7.787 # Convert XYZ->LAB rgbs = np.dot(_xyz2rgb_norm, xyz).T over = rgbs > 0.0031308 rgbs[over] = 1.055 * (rgbs[over] ** (1. / 2.4)) - 0.055 rgbs[~over] *= 12.92 if n_dim == 4: rgbs = np.concatenate((rgbs, labs[:, 3]), axis=1) rgbs = np.clip(rgbs, 0., 1.) return rgbs
[ "def", "_lab_to_rgb", "(", "labs", ")", ":", "# adapted from BSD-licensed work in MATLAB by Mark Ruzon", "# Based on ITU-R Recommendation BT.709 using the D65", "labs", ",", "n_dim", "=", "_check_color_dim", "(", "labs", ")", "# Convert Lab->XYZ (silly indexing used to preserve dimensionality)", "y", "=", "(", "labs", "[", ":", ",", "0", "]", "+", "16.", ")", "/", "116.", "x", "=", "(", "labs", "[", ":", ",", "1", "]", "/", "500.", ")", "+", "y", "z", "=", "y", "-", "(", "labs", "[", ":", ",", "2", "]", "/", "200.", ")", "xyz", "=", "np", ".", "concatenate", "(", "(", "[", "x", "]", ",", "[", "y", "]", ",", "[", "z", "]", ")", ")", "# 3xN", "over", "=", "xyz", ">", "0.2068966", "xyz", "[", "over", "]", "=", "xyz", "[", "over", "]", "**", "3.", "xyz", "[", "~", "over", "]", "=", "(", "xyz", "[", "~", "over", "]", "-", "0.13793103448275862", ")", "/", "7.787", "# Convert XYZ->LAB", "rgbs", "=", "np", ".", "dot", "(", "_xyz2rgb_norm", ",", "xyz", ")", ".", "T", "over", "=", "rgbs", ">", "0.0031308", "rgbs", "[", "over", "]", "=", "1.055", "*", "(", "rgbs", "[", "over", "]", "**", "(", "1.", "/", "2.4", ")", ")", "-", "0.055", "rgbs", "[", "~", "over", "]", "*=", "12.92", "if", "n_dim", "==", "4", ":", "rgbs", "=", "np", ".", "concatenate", "(", "(", "rgbs", ",", "labs", "[", ":", ",", "3", "]", ")", ",", "axis", "=", "1", ")", "rgbs", "=", "np", ".", "clip", "(", "rgbs", ",", "0.", ",", "1.", ")", "return", "rgbs" ]
Convert Nx3 or Nx4 lab to rgb
[ "Convert", "Nx3", "or", "Nx4", "lab", "to", "rgb" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/color/color_space.py#L160-L183
train
rbarrois/mpdlcd
mpdlcd/mpdwrapper.py
SongTag.get
def get(self, tags): """Find an adequate value for this field from a dict of tags.""" # Try to find our name value = tags.get(self.name, '') for name in self.alternate_tags: # Iterate of alternates until a non-empty value is found value = value or tags.get(name, '') # If we still have nothing, return our default value = value or self.default return value
python
def get(self, tags): """Find an adequate value for this field from a dict of tags.""" # Try to find our name value = tags.get(self.name, '') for name in self.alternate_tags: # Iterate of alternates until a non-empty value is found value = value or tags.get(name, '') # If we still have nothing, return our default value = value or self.default return value
[ "def", "get", "(", "self", ",", "tags", ")", ":", "# Try to find our name", "value", "=", "tags", ".", "get", "(", "self", ".", "name", ",", "''", ")", "for", "name", "in", "self", ".", "alternate_tags", ":", "# Iterate of alternates until a non-empty value is found", "value", "=", "value", "or", "tags", ".", "get", "(", "name", ",", "''", ")", "# If we still have nothing, return our default", "value", "=", "value", "or", "self", ".", "default", "return", "value" ]
Find an adequate value for this field from a dict of tags.
[ "Find", "an", "adequate", "value", "for", "this", "field", "from", "a", "dict", "of", "tags", "." ]
85f16c8cc0883f8abb4c2cc7f69729c3e2f857da
https://github.com/rbarrois/mpdlcd/blob/85f16c8cc0883f8abb4c2cc7f69729c3e2f857da/mpdlcd/mpdwrapper.py#L135-L146
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/shaders/parsing.py
parse_function_signature
def parse_function_signature(code): """ Return the name, arguments, and return type of the first function definition found in *code*. Arguments are returned as [(type, name), ...]. """ m = re.search("^\s*" + re_func_decl + "\s*{", code, re.M) if m is None: print(code) raise Exception("Failed to parse function signature. " "Full code is printed above.") rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] else: args = [tuple(arg.strip().split(' ')) for arg in args.split(',')] return name, args, rtype
python
def parse_function_signature(code): """ Return the name, arguments, and return type of the first function definition found in *code*. Arguments are returned as [(type, name), ...]. """ m = re.search("^\s*" + re_func_decl + "\s*{", code, re.M) if m is None: print(code) raise Exception("Failed to parse function signature. " "Full code is printed above.") rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] else: args = [tuple(arg.strip().split(' ')) for arg in args.split(',')] return name, args, rtype
[ "def", "parse_function_signature", "(", "code", ")", ":", "m", "=", "re", ".", "search", "(", "\"^\\s*\"", "+", "re_func_decl", "+", "\"\\s*{\"", ",", "code", ",", "re", ".", "M", ")", "if", "m", "is", "None", ":", "print", "(", "code", ")", "raise", "Exception", "(", "\"Failed to parse function signature. \"", "\"Full code is printed above.\"", ")", "rtype", ",", "name", ",", "args", "=", "m", ".", "groups", "(", ")", "[", ":", "3", "]", "if", "args", "==", "'void'", "or", "args", ".", "strip", "(", ")", "==", "''", ":", "args", "=", "[", "]", "else", ":", "args", "=", "[", "tuple", "(", "arg", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", ")", "for", "arg", "in", "args", ".", "split", "(", "','", ")", "]", "return", "name", ",", "args", ",", "rtype" ]
Return the name, arguments, and return type of the first function definition found in *code*. Arguments are returned as [(type, name), ...].
[ "Return", "the", "name", "arguments", "and", "return", "type", "of", "the", "first", "function", "definition", "found", "in", "*", "code", "*", ".", "Arguments", "are", "returned", "as", "[", "(", "type", "name", ")", "...", "]", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/shaders/parsing.py#L55-L70
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/shaders/parsing.py
find_functions
def find_functions(code): """ Return a list of (name, arguments, return type) for all function definition2 found in *code*. Arguments are returned as [(type, name), ...]. """ regex = "^\s*" + re_func_decl + "\s*{" funcs = [] while True: m = re.search(regex, code, re.M) if m is None: return funcs rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] else: args = [tuple(arg.strip().split(' ')) for arg in args.split(',')] funcs.append((name, args, rtype)) code = code[m.end():]
python
def find_functions(code): """ Return a list of (name, arguments, return type) for all function definition2 found in *code*. Arguments are returned as [(type, name), ...]. """ regex = "^\s*" + re_func_decl + "\s*{" funcs = [] while True: m = re.search(regex, code, re.M) if m is None: return funcs rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] else: args = [tuple(arg.strip().split(' ')) for arg in args.split(',')] funcs.append((name, args, rtype)) code = code[m.end():]
[ "def", "find_functions", "(", "code", ")", ":", "regex", "=", "\"^\\s*\"", "+", "re_func_decl", "+", "\"\\s*{\"", "funcs", "=", "[", "]", "while", "True", ":", "m", "=", "re", ".", "search", "(", "regex", ",", "code", ",", "re", ".", "M", ")", "if", "m", "is", "None", ":", "return", "funcs", "rtype", ",", "name", ",", "args", "=", "m", ".", "groups", "(", ")", "[", ":", "3", "]", "if", "args", "==", "'void'", "or", "args", ".", "strip", "(", ")", "==", "''", ":", "args", "=", "[", "]", "else", ":", "args", "=", "[", "tuple", "(", "arg", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", ")", "for", "arg", "in", "args", ".", "split", "(", "','", ")", "]", "funcs", ".", "append", "(", "(", "name", ",", "args", ",", "rtype", ")", ")", "code", "=", "code", "[", "m", ".", "end", "(", ")", ":", "]" ]
Return a list of (name, arguments, return type) for all function definition2 found in *code*. Arguments are returned as [(type, name), ...].
[ "Return", "a", "list", "of", "(", "name", "arguments", "return", "type", ")", "for", "all", "function", "definition2", "found", "in", "*", "code", "*", ".", "Arguments", "are", "returned", "as", "[", "(", "type", "name", ")", "...", "]", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/shaders/parsing.py#L73-L93
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/shaders/parsing.py
find_prototypes
def find_prototypes(code): """ Return a list of signatures for each function prototype declared in *code*. Format is [(name, [args], rtype), ...]. """ prots = [] lines = code.split('\n') for line in lines: m = re.match("\s*" + re_func_prot, line) if m is not None: rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] else: args = [tuple(arg.strip().split(' ')) for arg in args.split(',')] prots.append((name, args, rtype)) return prots
python
def find_prototypes(code): """ Return a list of signatures for each function prototype declared in *code*. Format is [(name, [args], rtype), ...]. """ prots = [] lines = code.split('\n') for line in lines: m = re.match("\s*" + re_func_prot, line) if m is not None: rtype, name, args = m.groups()[:3] if args == 'void' or args.strip() == '': args = [] else: args = [tuple(arg.strip().split(' ')) for arg in args.split(',')] prots.append((name, args, rtype)) return prots
[ "def", "find_prototypes", "(", "code", ")", ":", "prots", "=", "[", "]", "lines", "=", "code", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "m", "=", "re", ".", "match", "(", "\"\\s*\"", "+", "re_func_prot", ",", "line", ")", "if", "m", "is", "not", "None", ":", "rtype", ",", "name", ",", "args", "=", "m", ".", "groups", "(", ")", "[", ":", "3", "]", "if", "args", "==", "'void'", "or", "args", ".", "strip", "(", ")", "==", "''", ":", "args", "=", "[", "]", "else", ":", "args", "=", "[", "tuple", "(", "arg", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", ")", "for", "arg", "in", "args", ".", "split", "(", "','", ")", "]", "prots", ".", "append", "(", "(", "name", ",", "args", ",", "rtype", ")", ")", "return", "prots" ]
Return a list of signatures for each function prototype declared in *code*. Format is [(name, [args], rtype), ...].
[ "Return", "a", "list", "of", "signatures", "for", "each", "function", "prototype", "declared", "in", "*", "code", "*", ".", "Format", "is", "[", "(", "name", "[", "args", "]", "rtype", ")", "...", "]", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/shaders/parsing.py#L96-L115
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/visuals/shaders/parsing.py
find_program_variables
def find_program_variables(code): """ Return a dict describing program variables:: {'var_name': ('uniform|attribute|varying', type), ...} """ vars = {} lines = code.split('\n') for line in lines: m = re.match(r"\s*" + re_prog_var_declaration + r"\s*(=|;)", line) if m is not None: vtype, dtype, names = m.groups()[:3] for name in names.split(','): vars[name.strip()] = (vtype, dtype) return vars
python
def find_program_variables(code): """ Return a dict describing program variables:: {'var_name': ('uniform|attribute|varying', type), ...} """ vars = {} lines = code.split('\n') for line in lines: m = re.match(r"\s*" + re_prog_var_declaration + r"\s*(=|;)", line) if m is not None: vtype, dtype, names = m.groups()[:3] for name in names.split(','): vars[name.strip()] = (vtype, dtype) return vars
[ "def", "find_program_variables", "(", "code", ")", ":", "vars", "=", "{", "}", "lines", "=", "code", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "m", "=", "re", ".", "match", "(", "r\"\\s*\"", "+", "re_prog_var_declaration", "+", "r\"\\s*(=|;)\"", ",", "line", ")", "if", "m", "is", "not", "None", ":", "vtype", ",", "dtype", ",", "names", "=", "m", ".", "groups", "(", ")", "[", ":", "3", "]", "for", "name", "in", "names", ".", "split", "(", "','", ")", ":", "vars", "[", "name", ".", "strip", "(", ")", "]", "=", "(", "vtype", ",", "dtype", ")", "return", "vars" ]
Return a dict describing program variables:: {'var_name': ('uniform|attribute|varying', type), ...}
[ "Return", "a", "dict", "describing", "program", "variables", "::" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/visuals/shaders/parsing.py#L118-L133
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/app/backends/_sdl2.py
_set_config
def _set_config(c): """Set gl configuration for SDL2""" func = sdl2.SDL_GL_SetAttribute func(sdl2.SDL_GL_RED_SIZE, c['red_size']) func(sdl2.SDL_GL_GREEN_SIZE, c['green_size']) func(sdl2.SDL_GL_BLUE_SIZE, c['blue_size']) func(sdl2.SDL_GL_ALPHA_SIZE, c['alpha_size']) func(sdl2.SDL_GL_DEPTH_SIZE, c['depth_size']) func(sdl2.SDL_GL_STENCIL_SIZE, c['stencil_size']) func(sdl2.SDL_GL_DOUBLEBUFFER, 1 if c['double_buffer'] else 0) samps = c['samples'] func(sdl2.SDL_GL_MULTISAMPLEBUFFERS, 1 if samps > 0 else 0) func(sdl2.SDL_GL_MULTISAMPLESAMPLES, samps if samps > 0 else 0) func(sdl2.SDL_GL_STEREO, c['stereo'])
python
def _set_config(c): """Set gl configuration for SDL2""" func = sdl2.SDL_GL_SetAttribute func(sdl2.SDL_GL_RED_SIZE, c['red_size']) func(sdl2.SDL_GL_GREEN_SIZE, c['green_size']) func(sdl2.SDL_GL_BLUE_SIZE, c['blue_size']) func(sdl2.SDL_GL_ALPHA_SIZE, c['alpha_size']) func(sdl2.SDL_GL_DEPTH_SIZE, c['depth_size']) func(sdl2.SDL_GL_STENCIL_SIZE, c['stencil_size']) func(sdl2.SDL_GL_DOUBLEBUFFER, 1 if c['double_buffer'] else 0) samps = c['samples'] func(sdl2.SDL_GL_MULTISAMPLEBUFFERS, 1 if samps > 0 else 0) func(sdl2.SDL_GL_MULTISAMPLESAMPLES, samps if samps > 0 else 0) func(sdl2.SDL_GL_STEREO, c['stereo'])
[ "def", "_set_config", "(", "c", ")", ":", "func", "=", "sdl2", ".", "SDL_GL_SetAttribute", "func", "(", "sdl2", ".", "SDL_GL_RED_SIZE", ",", "c", "[", "'red_size'", "]", ")", "func", "(", "sdl2", ".", "SDL_GL_GREEN_SIZE", ",", "c", "[", "'green_size'", "]", ")", "func", "(", "sdl2", ".", "SDL_GL_BLUE_SIZE", ",", "c", "[", "'blue_size'", "]", ")", "func", "(", "sdl2", ".", "SDL_GL_ALPHA_SIZE", ",", "c", "[", "'alpha_size'", "]", ")", "func", "(", "sdl2", ".", "SDL_GL_DEPTH_SIZE", ",", "c", "[", "'depth_size'", "]", ")", "func", "(", "sdl2", ".", "SDL_GL_STENCIL_SIZE", ",", "c", "[", "'stencil_size'", "]", ")", "func", "(", "sdl2", ".", "SDL_GL_DOUBLEBUFFER", ",", "1", "if", "c", "[", "'double_buffer'", "]", "else", "0", ")", "samps", "=", "c", "[", "'samples'", "]", "func", "(", "sdl2", ".", "SDL_GL_MULTISAMPLEBUFFERS", ",", "1", "if", "samps", ">", "0", "else", "0", ")", "func", "(", "sdl2", ".", "SDL_GL_MULTISAMPLESAMPLES", ",", "samps", "if", "samps", ">", "0", "else", "0", ")", "func", "(", "sdl2", ".", "SDL_GL_STEREO", ",", "c", "[", "'stereo'", "]", ")" ]
Set gl configuration for SDL2
[ "Set", "gl", "configuration", "for", "SDL2" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/app/backends/_sdl2.py#L119-L132
train
anjishnu/ask-alexa-pykit
ask/alexa_io.py
ResponseBuilder.create_response
def create_response(self, message=None, end_session=False, card_obj=None, reprompt_message=None, is_ssml=None): """ message - text message to be spoken out by the Echo end_session - flag to determine whether this interaction should end the session card_obj = JSON card object to substitute the 'card' field in the raw_response """ response = dict(self.base_response) if message: response['response'] = self.create_speech(message, is_ssml) response['response']['shouldEndSession'] = end_session if card_obj: response['response']['card'] = card_obj if reprompt_message: response['response']['reprompt'] = self.create_speech(reprompt_message, is_ssml) return Response(response)
python
def create_response(self, message=None, end_session=False, card_obj=None, reprompt_message=None, is_ssml=None): """ message - text message to be spoken out by the Echo end_session - flag to determine whether this interaction should end the session card_obj = JSON card object to substitute the 'card' field in the raw_response """ response = dict(self.base_response) if message: response['response'] = self.create_speech(message, is_ssml) response['response']['shouldEndSession'] = end_session if card_obj: response['response']['card'] = card_obj if reprompt_message: response['response']['reprompt'] = self.create_speech(reprompt_message, is_ssml) return Response(response)
[ "def", "create_response", "(", "self", ",", "message", "=", "None", ",", "end_session", "=", "False", ",", "card_obj", "=", "None", ",", "reprompt_message", "=", "None", ",", "is_ssml", "=", "None", ")", ":", "response", "=", "dict", "(", "self", ".", "base_response", ")", "if", "message", ":", "response", "[", "'response'", "]", "=", "self", ".", "create_speech", "(", "message", ",", "is_ssml", ")", "response", "[", "'response'", "]", "[", "'shouldEndSession'", "]", "=", "end_session", "if", "card_obj", ":", "response", "[", "'response'", "]", "[", "'card'", "]", "=", "card_obj", "if", "reprompt_message", ":", "response", "[", "'response'", "]", "[", "'reprompt'", "]", "=", "self", ".", "create_speech", "(", "reprompt_message", ",", "is_ssml", ")", "return", "Response", "(", "response", ")" ]
message - text message to be spoken out by the Echo end_session - flag to determine whether this interaction should end the session card_obj = JSON card object to substitute the 'card' field in the raw_response
[ "message", "-", "text", "message", "to", "be", "spoken", "out", "by", "the", "Echo", "end_session", "-", "flag", "to", "determine", "whether", "this", "interaction", "should", "end", "the", "session", "card_obj", "=", "JSON", "card", "object", "to", "substitute", "the", "card", "field", "in", "the", "raw_response" ]
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/ask/alexa_io.py#L103-L118
train
anjishnu/ask-alexa-pykit
ask/alexa_io.py
ResponseBuilder.create_card
def create_card(self, title=None, subtitle=None, content=None, card_type="Simple"): """ card_obj = JSON card object to substitute the 'card' field in the raw_response format: { "type": "Simple", #COMPULSORY "title": "string", #OPTIONAL "subtitle": "string", #OPTIONAL "content": "string" #OPTIONAL } """ card = {"type": card_type} if title: card["title"] = title if subtitle: card["subtitle"] = subtitle if content: card["content"] = content return card
python
def create_card(self, title=None, subtitle=None, content=None, card_type="Simple"): """ card_obj = JSON card object to substitute the 'card' field in the raw_response format: { "type": "Simple", #COMPULSORY "title": "string", #OPTIONAL "subtitle": "string", #OPTIONAL "content": "string" #OPTIONAL } """ card = {"type": card_type} if title: card["title"] = title if subtitle: card["subtitle"] = subtitle if content: card["content"] = content return card
[ "def", "create_card", "(", "self", ",", "title", "=", "None", ",", "subtitle", "=", "None", ",", "content", "=", "None", ",", "card_type", "=", "\"Simple\"", ")", ":", "card", "=", "{", "\"type\"", ":", "card_type", "}", "if", "title", ":", "card", "[", "\"title\"", "]", "=", "title", "if", "subtitle", ":", "card", "[", "\"subtitle\"", "]", "=", "subtitle", "if", "content", ":", "card", "[", "\"content\"", "]", "=", "content", "return", "card" ]
card_obj = JSON card object to substitute the 'card' field in the raw_response format: { "type": "Simple", #COMPULSORY "title": "string", #OPTIONAL "subtitle": "string", #OPTIONAL "content": "string" #OPTIONAL }
[ "card_obj", "=", "JSON", "card", "object", "to", "substitute", "the", "card", "field", "in", "the", "raw_response", "format", ":", "{", "type", ":", "Simple", "#COMPULSORY", "title", ":", "string", "#OPTIONAL", "subtitle", ":", "string", "#OPTIONAL", "content", ":", "string", "#OPTIONAL", "}" ]
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/ask/alexa_io.py#L135-L150
train
anjishnu/ask-alexa-pykit
ask/alexa_io.py
VoiceHandler.intent
def intent(self, intent): ''' Decorator to register intent handler''' def _handler(func): self._handlers['IntentRequest'][intent] = func return func return _handler
python
def intent(self, intent): ''' Decorator to register intent handler''' def _handler(func): self._handlers['IntentRequest'][intent] = func return func return _handler
[ "def", "intent", "(", "self", ",", "intent", ")", ":", "def", "_handler", "(", "func", ")", ":", "self", ".", "_handlers", "[", "'IntentRequest'", "]", "[", "intent", "]", "=", "func", "return", "func", "return", "_handler" ]
Decorator to register intent handler
[ "Decorator", "to", "register", "intent", "handler" ]
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/ask/alexa_io.py#L177-L184
train
anjishnu/ask-alexa-pykit
ask/alexa_io.py
VoiceHandler.request
def request(self, request_type): ''' Decorator to register generic request handler ''' def _handler(func): self._handlers[request_type] = func return func return _handler
python
def request(self, request_type): ''' Decorator to register generic request handler ''' def _handler(func): self._handlers[request_type] = func return func return _handler
[ "def", "request", "(", "self", ",", "request_type", ")", ":", "def", "_handler", "(", "func", ")", ":", "self", ".", "_handlers", "[", "request_type", "]", "=", "func", "return", "func", "return", "_handler" ]
Decorator to register generic request handler
[ "Decorator", "to", "register", "generic", "request", "handler" ]
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/ask/alexa_io.py#L186-L193
train
anjishnu/ask-alexa-pykit
ask/alexa_io.py
VoiceHandler.route_request
def route_request(self, request_json, metadata=None): ''' Route the request object to the right handler function ''' request = Request(request_json) request.metadata = metadata # add reprompt handler or some such for default? handler_fn = self._handlers[self._default] # Set default handling for noisy requests if not request.is_intent() and (request.request_type() in self._handlers): ''' Route request to a non intent handler ''' handler_fn = self._handlers[request.request_type()] elif request.is_intent() and request.intent_name() in self._handlers['IntentRequest']: ''' Route to right intent handler ''' handler_fn = self._handlers['IntentRequest'][request.intent_name()] response = handler_fn(request) response.set_session(request.session) return response.to_json()
python
def route_request(self, request_json, metadata=None): ''' Route the request object to the right handler function ''' request = Request(request_json) request.metadata = metadata # add reprompt handler or some such for default? handler_fn = self._handlers[self._default] # Set default handling for noisy requests if not request.is_intent() and (request.request_type() in self._handlers): ''' Route request to a non intent handler ''' handler_fn = self._handlers[request.request_type()] elif request.is_intent() and request.intent_name() in self._handlers['IntentRequest']: ''' Route to right intent handler ''' handler_fn = self._handlers['IntentRequest'][request.intent_name()] response = handler_fn(request) response.set_session(request.session) return response.to_json()
[ "def", "route_request", "(", "self", ",", "request_json", ",", "metadata", "=", "None", ")", ":", "request", "=", "Request", "(", "request_json", ")", "request", ".", "metadata", "=", "metadata", "# add reprompt handler or some such for default?", "handler_fn", "=", "self", ".", "_handlers", "[", "self", ".", "_default", "]", "# Set default handling for noisy requests", "if", "not", "request", ".", "is_intent", "(", ")", "and", "(", "request", ".", "request_type", "(", ")", "in", "self", ".", "_handlers", ")", ":", "''' Route request to a non intent handler '''", "handler_fn", "=", "self", ".", "_handlers", "[", "request", ".", "request_type", "(", ")", "]", "elif", "request", ".", "is_intent", "(", ")", "and", "request", ".", "intent_name", "(", ")", "in", "self", ".", "_handlers", "[", "'IntentRequest'", "]", ":", "''' Route to right intent handler '''", "handler_fn", "=", "self", ".", "_handlers", "[", "'IntentRequest'", "]", "[", "request", ".", "intent_name", "(", ")", "]", "response", "=", "handler_fn", "(", "request", ")", "response", ".", "set_session", "(", "request", ".", "session", ")", "return", "response", ".", "to_json", "(", ")" ]
Route the request object to the right handler function
[ "Route", "the", "request", "object", "to", "the", "right", "handler", "function" ]
a47c278ca7a60532bbe1a9b789f6c37e609fea8b
https://github.com/anjishnu/ask-alexa-pykit/blob/a47c278ca7a60532bbe1a9b789f6c37e609fea8b/ask/alexa_io.py#L195-L213
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py
BaseCamera._viewbox_set
def _viewbox_set(self, viewbox): """ Friend method of viewbox to register itself. """ self._viewbox = viewbox # Connect viewbox.events.mouse_press.connect(self.viewbox_mouse_event) viewbox.events.mouse_release.connect(self.viewbox_mouse_event) viewbox.events.mouse_move.connect(self.viewbox_mouse_event) viewbox.events.mouse_wheel.connect(self.viewbox_mouse_event) viewbox.events.resize.connect(self.viewbox_resize_event)
python
def _viewbox_set(self, viewbox): """ Friend method of viewbox to register itself. """ self._viewbox = viewbox # Connect viewbox.events.mouse_press.connect(self.viewbox_mouse_event) viewbox.events.mouse_release.connect(self.viewbox_mouse_event) viewbox.events.mouse_move.connect(self.viewbox_mouse_event) viewbox.events.mouse_wheel.connect(self.viewbox_mouse_event) viewbox.events.resize.connect(self.viewbox_resize_event)
[ "def", "_viewbox_set", "(", "self", ",", "viewbox", ")", ":", "self", ".", "_viewbox", "=", "viewbox", "# Connect", "viewbox", ".", "events", ".", "mouse_press", ".", "connect", "(", "self", ".", "viewbox_mouse_event", ")", "viewbox", ".", "events", ".", "mouse_release", ".", "connect", "(", "self", ".", "viewbox_mouse_event", ")", "viewbox", ".", "events", ".", "mouse_move", ".", "connect", "(", "self", ".", "viewbox_mouse_event", ")", "viewbox", ".", "events", ".", "mouse_wheel", ".", "connect", "(", "self", ".", "viewbox_mouse_event", ")", "viewbox", ".", "events", ".", "resize", ".", "connect", "(", "self", ".", "viewbox_resize_event", ")" ]
Friend method of viewbox to register itself.
[ "Friend", "method", "of", "viewbox", "to", "register", "itself", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py#L118-L127
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py
BaseCamera._viewbox_unset
def _viewbox_unset(self, viewbox): """ Friend method of viewbox to unregister itself. """ self._viewbox = None # Disconnect viewbox.events.mouse_press.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_release.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_move.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_wheel.disconnect(self.viewbox_mouse_event) viewbox.events.resize.disconnect(self.viewbox_resize_event)
python
def _viewbox_unset(self, viewbox): """ Friend method of viewbox to unregister itself. """ self._viewbox = None # Disconnect viewbox.events.mouse_press.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_release.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_move.disconnect(self.viewbox_mouse_event) viewbox.events.mouse_wheel.disconnect(self.viewbox_mouse_event) viewbox.events.resize.disconnect(self.viewbox_resize_event)
[ "def", "_viewbox_unset", "(", "self", ",", "viewbox", ")", ":", "self", ".", "_viewbox", "=", "None", "# Disconnect", "viewbox", ".", "events", ".", "mouse_press", ".", "disconnect", "(", "self", ".", "viewbox_mouse_event", ")", "viewbox", ".", "events", ".", "mouse_release", ".", "disconnect", "(", "self", ".", "viewbox_mouse_event", ")", "viewbox", ".", "events", ".", "mouse_move", ".", "disconnect", "(", "self", ".", "viewbox_mouse_event", ")", "viewbox", ".", "events", ".", "mouse_wheel", ".", "disconnect", "(", "self", ".", "viewbox_mouse_event", ")", "viewbox", ".", "events", ".", "resize", ".", "disconnect", "(", "self", ".", "viewbox_resize_event", ")" ]
Friend method of viewbox to unregister itself.
[ "Friend", "method", "of", "viewbox", "to", "unregister", "itself", "." ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py#L130-L139
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py
BaseCamera.set_range
def set_range(self, x=None, y=None, z=None, margin=0.05): """ Set the range of the view region for the camera Parameters ---------- x : tuple | None X range. y : tuple | None Y range. z : tuple | None Z range. margin : float Margin to use. Notes ----- The view is set to the given range or to the scene boundaries if ranges are not specified. The ranges should be 2-element tuples specifying the min and max for each dimension. For the PanZoomCamera the view is fully defined by the range. For e.g. the TurntableCamera the elevation and azimuth are not set. One should use reset() for that. """ # Flag to indicate that this is an initializing (not user-invoked) init = self._xlim is None # Collect given bounds bounds = [None, None, None] if x is not None: bounds[0] = float(x[0]), float(x[1]) if y is not None: bounds[1] = float(y[0]), float(y[1]) if z is not None: bounds[2] = float(z[0]), float(z[1]) # If there is no viewbox, store given bounds in lim variables, and stop if self._viewbox is None: self._set_range_args = bounds[0], bounds[1], bounds[2], margin return # There is a viewbox, we're going to set the range for real self._resetting = True # Get bounds from viewbox if not given if all([(b is None) for b in bounds]): bounds = self._viewbox.get_scene_bounds() else: for i in range(3): if bounds[i] is None: bounds[i] = self._viewbox.get_scene_bounds(i) # Calculate ranges and margins ranges = [b[1] - b[0] for b in bounds] margins = [(r*margin or 0.1) for r in ranges] # Assign limits for this camera bounds_margins = [(b[0]-m, b[1]+m) for b, m in zip(bounds, margins)] self._xlim, self._ylim, self._zlim = bounds_margins # Store center location if (not init) or (self._center is None): self._center = [(b[0] + r / 2) for b, r in zip(bounds, ranges)] # Let specific camera handle it self._set_range(init) # Finish self._resetting = False self.view_changed()
python
def set_range(self, x=None, y=None, z=None, margin=0.05): """ Set the range of the view region for the camera Parameters ---------- x : tuple | None X range. y : tuple | None Y range. z : tuple | None Z range. margin : float Margin to use. Notes ----- The view is set to the given range or to the scene boundaries if ranges are not specified. The ranges should be 2-element tuples specifying the min and max for each dimension. For the PanZoomCamera the view is fully defined by the range. For e.g. the TurntableCamera the elevation and azimuth are not set. One should use reset() for that. """ # Flag to indicate that this is an initializing (not user-invoked) init = self._xlim is None # Collect given bounds bounds = [None, None, None] if x is not None: bounds[0] = float(x[0]), float(x[1]) if y is not None: bounds[1] = float(y[0]), float(y[1]) if z is not None: bounds[2] = float(z[0]), float(z[1]) # If there is no viewbox, store given bounds in lim variables, and stop if self._viewbox is None: self._set_range_args = bounds[0], bounds[1], bounds[2], margin return # There is a viewbox, we're going to set the range for real self._resetting = True # Get bounds from viewbox if not given if all([(b is None) for b in bounds]): bounds = self._viewbox.get_scene_bounds() else: for i in range(3): if bounds[i] is None: bounds[i] = self._viewbox.get_scene_bounds(i) # Calculate ranges and margins ranges = [b[1] - b[0] for b in bounds] margins = [(r*margin or 0.1) for r in ranges] # Assign limits for this camera bounds_margins = [(b[0]-m, b[1]+m) for b, m in zip(bounds, margins)] self._xlim, self._ylim, self._zlim = bounds_margins # Store center location if (not init) or (self._center is None): self._center = [(b[0] + r / 2) for b, r in zip(bounds, ranges)] # Let specific camera handle it self._set_range(init) # Finish self._resetting = False self.view_changed()
[ "def", "set_range", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ",", "z", "=", "None", ",", "margin", "=", "0.05", ")", ":", "# Flag to indicate that this is an initializing (not user-invoked)", "init", "=", "self", ".", "_xlim", "is", "None", "# Collect given bounds", "bounds", "=", "[", "None", ",", "None", ",", "None", "]", "if", "x", "is", "not", "None", ":", "bounds", "[", "0", "]", "=", "float", "(", "x", "[", "0", "]", ")", ",", "float", "(", "x", "[", "1", "]", ")", "if", "y", "is", "not", "None", ":", "bounds", "[", "1", "]", "=", "float", "(", "y", "[", "0", "]", ")", ",", "float", "(", "y", "[", "1", "]", ")", "if", "z", "is", "not", "None", ":", "bounds", "[", "2", "]", "=", "float", "(", "z", "[", "0", "]", ")", ",", "float", "(", "z", "[", "1", "]", ")", "# If there is no viewbox, store given bounds in lim variables, and stop", "if", "self", ".", "_viewbox", "is", "None", ":", "self", ".", "_set_range_args", "=", "bounds", "[", "0", "]", ",", "bounds", "[", "1", "]", ",", "bounds", "[", "2", "]", ",", "margin", "return", "# There is a viewbox, we're going to set the range for real", "self", ".", "_resetting", "=", "True", "# Get bounds from viewbox if not given", "if", "all", "(", "[", "(", "b", "is", "None", ")", "for", "b", "in", "bounds", "]", ")", ":", "bounds", "=", "self", ".", "_viewbox", ".", "get_scene_bounds", "(", ")", "else", ":", "for", "i", "in", "range", "(", "3", ")", ":", "if", "bounds", "[", "i", "]", "is", "None", ":", "bounds", "[", "i", "]", "=", "self", ".", "_viewbox", ".", "get_scene_bounds", "(", "i", ")", "# Calculate ranges and margins", "ranges", "=", "[", "b", "[", "1", "]", "-", "b", "[", "0", "]", "for", "b", "in", "bounds", "]", "margins", "=", "[", "(", "r", "*", "margin", "or", "0.1", ")", "for", "r", "in", "ranges", "]", "# Assign limits for this camera", "bounds_margins", "=", "[", "(", "b", "[", "0", "]", "-", "m", ",", "b", "[", "1", "]", "+", "m", ")", "for", "b", ",", "m", "in", "zip", "(", "bounds", ",", "margins", ")", "]", "self", ".", "_xlim", ",", "self", ".", "_ylim", ",", "self", ".", "_zlim", "=", "bounds_margins", "# Store center location", "if", "(", "not", "init", ")", "or", "(", "self", ".", "_center", "is", "None", ")", ":", "self", ".", "_center", "=", "[", "(", "b", "[", "0", "]", "+", "r", "/", "2", ")", "for", "b", ",", "r", "in", "zip", "(", "bounds", ",", "ranges", ")", "]", "# Let specific camera handle it", "self", ".", "_set_range", "(", "init", ")", "# Finish", "self", ".", "_resetting", "=", "False", "self", ".", "view_changed", "(", ")" ]
Set the range of the view region for the camera Parameters ---------- x : tuple | None X range. y : tuple | None Y range. z : tuple | None Z range. margin : float Margin to use. Notes ----- The view is set to the given range or to the scene boundaries if ranges are not specified. The ranges should be 2-element tuples specifying the min and max for each dimension. For the PanZoomCamera the view is fully defined by the range. For e.g. the TurntableCamera the elevation and azimuth are not set. One should use reset() for that.
[ "Set", "the", "range", "of", "the", "view", "region", "for", "the", "camera" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py#L228-L294
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py
BaseCamera.get_state
def get_state(self): """ Get the current view state of the camera Returns a dict of key-value pairs. The exact keys depend on the camera. Can be passed to set_state() (of this or another camera of the same type) to reproduce the state. """ D = {} for key in self._state_props: D[key] = getattr(self, key) return D
python
def get_state(self): """ Get the current view state of the camera Returns a dict of key-value pairs. The exact keys depend on the camera. Can be passed to set_state() (of this or another camera of the same type) to reproduce the state. """ D = {} for key in self._state_props: D[key] = getattr(self, key) return D
[ "def", "get_state", "(", "self", ")", ":", "D", "=", "{", "}", "for", "key", "in", "self", ".", "_state_props", ":", "D", "[", "key", "]", "=", "getattr", "(", "self", ",", "key", ")", "return", "D" ]
Get the current view state of the camera Returns a dict of key-value pairs. The exact keys depend on the camera. Can be passed to set_state() (of this or another camera of the same type) to reproduce the state.
[ "Get", "the", "current", "view", "state", "of", "the", "camera" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py#L310-L320
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py
BaseCamera.set_state
def set_state(self, state=None, **kwargs): """ Set the view state of the camera Should be a dict (or kwargs) as returned by get_state. It can be an incomlete dict, in which case only the specified properties are set. Parameters ---------- state : dict The camera state. **kwargs : dict Unused keyword arguments. """ D = state or {} D.update(kwargs) for key, val in D.items(): if key not in self._state_props: raise KeyError('Not a valid camera state property %r' % key) setattr(self, key, val)
python
def set_state(self, state=None, **kwargs): """ Set the view state of the camera Should be a dict (or kwargs) as returned by get_state. It can be an incomlete dict, in which case only the specified properties are set. Parameters ---------- state : dict The camera state. **kwargs : dict Unused keyword arguments. """ D = state or {} D.update(kwargs) for key, val in D.items(): if key not in self._state_props: raise KeyError('Not a valid camera state property %r' % key) setattr(self, key, val)
[ "def", "set_state", "(", "self", ",", "state", "=", "None", ",", "*", "*", "kwargs", ")", ":", "D", "=", "state", "or", "{", "}", "D", ".", "update", "(", "kwargs", ")", "for", "key", ",", "val", "in", "D", ".", "items", "(", ")", ":", "if", "key", "not", "in", "self", ".", "_state_props", ":", "raise", "KeyError", "(", "'Not a valid camera state property %r'", "%", "key", ")", "setattr", "(", "self", ",", "key", ",", "val", ")" ]
Set the view state of the camera Should be a dict (or kwargs) as returned by get_state. It can be an incomlete dict, in which case only the specified properties are set. Parameters ---------- state : dict The camera state. **kwargs : dict Unused keyword arguments.
[ "Set", "the", "view", "state", "of", "the", "camera" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py#L322-L341
train
glue-viz/glue-vispy-viewers
glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py
BaseCamera.link
def link(self, camera): """ Link this camera with another camera of the same type Linked camera's keep each-others' state in sync. Parameters ---------- camera : instance of Camera The other camera to link. """ cam1, cam2 = self, camera # Remove if already linked while cam1 in cam2._linked_cameras: cam2._linked_cameras.remove(cam1) while cam2 in cam1._linked_cameras: cam1._linked_cameras.remove(cam2) # Link both ways cam1._linked_cameras.append(cam2) cam2._linked_cameras.append(cam1)
python
def link(self, camera): """ Link this camera with another camera of the same type Linked camera's keep each-others' state in sync. Parameters ---------- camera : instance of Camera The other camera to link. """ cam1, cam2 = self, camera # Remove if already linked while cam1 in cam2._linked_cameras: cam2._linked_cameras.remove(cam1) while cam2 in cam1._linked_cameras: cam1._linked_cameras.remove(cam2) # Link both ways cam1._linked_cameras.append(cam2) cam2._linked_cameras.append(cam1)
[ "def", "link", "(", "self", ",", "camera", ")", ":", "cam1", ",", "cam2", "=", "self", ",", "camera", "# Remove if already linked", "while", "cam1", "in", "cam2", ".", "_linked_cameras", ":", "cam2", ".", "_linked_cameras", ".", "remove", "(", "cam1", ")", "while", "cam2", "in", "cam1", ".", "_linked_cameras", ":", "cam1", ".", "_linked_cameras", ".", "remove", "(", "cam2", ")", "# Link both ways", "cam1", ".", "_linked_cameras", ".", "append", "(", "cam2", ")", "cam2", ".", "_linked_cameras", ".", "append", "(", "cam1", ")" ]
Link this camera with another camera of the same type Linked camera's keep each-others' state in sync. Parameters ---------- camera : instance of Camera The other camera to link.
[ "Link", "this", "camera", "with", "another", "camera", "of", "the", "same", "type" ]
54a4351d98c1f90dfb1a557d1b447c1f57470eea
https://github.com/glue-viz/glue-vispy-viewers/blob/54a4351d98c1f90dfb1a557d1b447c1f57470eea/glue_vispy_viewers/extern/vispy/scene/cameras/base_camera.py#L343-L361
train