sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _get_k_p_a(font, left, right): """This actually calculates the kerning + advance""" # http://lists.apple.com/archives/coretext-dev/2010/Dec/msg00020.html # 1) set up a CTTypesetter chars = left + right args = [None, 1, cf.kCFTypeDictionaryKeyCallBacks, cf.kCFTypeDictionaryValueCallBa...
This actually calculates the kerning + advance
entailment
def set_data(self, xs=None, ys=None, zs=None, colors=None): '''Update the mesh data. Parameters ---------- xs : ndarray | None A 2d array of x coordinates for the vertices of the mesh. ys : ndarray | None A 2d array of y coordinates for the vertices of th...
Update the mesh data. Parameters ---------- xs : ndarray | None A 2d array of x coordinates for the vertices of the mesh. ys : ndarray | None A 2d array of y coordinates for the vertices of the mesh. zs : ndarray | None A 2d array of z coordin...
entailment
def _make_png(data, level=6): """Convert numpy array to PNG byte array. Parameters ---------- data : numpy.ndarray Data must be (H, W, 3 | 4) with dtype = np.ubyte (np.uint8) level : int https://docs.python.org/2/library/zlib.html#zlib.compress An integer from 0 to 9 control...
Convert numpy array to PNG byte array. Parameters ---------- data : numpy.ndarray Data must be (H, W, 3 | 4) with dtype = np.ubyte (np.uint8) level : int https://docs.python.org/2/library/zlib.html#zlib.compress An integer from 0 to 9 controlling the level of compression: ...
entailment
def read_png(filename): """Read a PNG file to RGB8 or RGBA8 Unlike imread, this requires no external dependencies. Parameters ---------- filename : str File to read. Returns ------- data : array Image data. See also -------- write_png, imread, imsave "...
Read a PNG file to RGB8 or RGBA8 Unlike imread, this requires no external dependencies. Parameters ---------- filename : str File to read. Returns ------- data : array Image data. See also -------- write_png, imread, imsave
entailment
def write_png(filename, data): """Write a PNG file Unlike imsave, this requires no external dependencies. Parameters ---------- filename : str File to save to. data : array Image data. See also -------- read_png, imread, imsave """ data = np.asarray(data) ...
Write a PNG file Unlike imsave, this requires no external dependencies. Parameters ---------- filename : str File to save to. data : array Image data. See also -------- read_png, imread, imsave
entailment
def imread(filename, format=None): """Read image data from disk Requires imageio or PIL. Parameters ---------- filename : str Filename to read. format : str | None Format of the file. If None, it will be inferred from the filename. Returns ------- data : array ...
Read image data from disk Requires imageio or PIL. Parameters ---------- filename : str Filename to read. format : str | None Format of the file. If None, it will be inferred from the filename. Returns ------- data : array Image data. See also --------...
entailment
def imsave(filename, im, format=None): """Save image data to disk Requires imageio or PIL. Parameters ---------- filename : str Filename to write. im : array Image data. format : str | None Format of the file. If None, it will be inferred from the filename. See...
Save image data to disk Requires imageio or PIL. Parameters ---------- filename : str Filename to write. im : array Image data. format : str | None Format of the file. If None, it will be inferred from the filename. See also -------- imread, read_png, write...
entailment
def _check_img_lib(): """Utility to search for imageio or PIL""" # Import imageio or PIL imageio = PIL = None try: import imageio except ImportError: try: import PIL.Image except ImportError: pass return imageio, PIL
Utility to search for imageio or PIL
entailment
def read_from_user(input_type, *args, **kwargs): ''' Helper function to prompt user for input of a specific type e.g. float, str, int Designed to work with both python 2 and 3 Yes I know this is ugly. ''' def _read_in(*args, **kwargs): while True: try: tmp = raw_inpu...
Helper function to prompt user for input of a specific type e.g. float, str, int Designed to work with both python 2 and 3 Yes I know this is ugly.
entailment
def load_builtin_slots(): ''' Helper function to load builtin slots from the data location ''' builtin_slots = {} for index, line in enumerate(open(BUILTIN_SLOTS_LOCATION)): o = line.strip().split('\t') builtin_slots[index] = {'name' : o[0], 'descript...
Helper function to load builtin slots from the data location
entailment
def timer(logger=None, level=logging.INFO, fmt="function %(function_name)s execution time: %(execution_time).3f", *func_or_func_args, **timer_kwargs): """ Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor. """ ...
Function decorator displaying the function execution time All kwargs are the arguments taken by the Timer class constructor.
entailment
def append(self, points, indices, **kwargs): """ Append a new set of vertices to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- points : np.array Vertices composing the t...
Append a new set of vertices to the collection. For kwargs argument, n is the number of vertices (local) or the number of item (shared) Parameters ---------- points : np.array Vertices composing the triangles indices : np.array Indices describi...
entailment
def _mpl_to_vispy(fig): """Convert a given matplotlib figure to vispy This function is experimental and subject to change! Requires matplotlib and mplexporter. Parameters ---------- fig : instance of matplotlib Figure The populated figure to display. Returns ------- canvas...
Convert a given matplotlib figure to vispy This function is experimental and subject to change! Requires matplotlib and mplexporter. Parameters ---------- fig : instance of matplotlib Figure The populated figure to display. Returns ------- canvas : instance of Canvas T...
entailment
def show(block=False): """Show current figures using vispy Parameters ---------- block : bool If True, blocking mode will be used. If False, then non-blocking / interactive mode will be used. Returns ------- canvases : list List of the vispy canvases that were creat...
Show current figures using vispy Parameters ---------- block : bool If True, blocking mode will be used. If False, then non-blocking / interactive mode will be used. Returns ------- canvases : list List of the vispy canvases that were created.
entailment
def _mpl_ax_to(self, mplobj, output='vb'): """Helper to get the parent axes of a given mplobj""" for ax in self._axs.values(): if ax['ax'] is mplobj.axes: return ax[output] raise RuntimeError('Parent axes could not be found!')
Helper to get the parent axes of a given mplobj
entailment
def random(adjacency_mat, directed=False, random_state=None): """ Place the graph nodes at random places. Parameters ---------- adjacency_mat : matrix or sparse The graph adjacency matrix directed : bool Whether the graph is directed. If this is True, is will also genera...
Place the graph nodes at random places. Parameters ---------- adjacency_mat : matrix or sparse The graph adjacency matrix directed : bool Whether the graph is directed. If this is True, is will also generate the vertices for arrows, which can be passed to an ArrowVisual....
entailment
def isocurve(data, level, connected=False, extend_to_edge=False): """ Generate isocurve from 2D data using marching squares algorithm. Parameters ---------- data : ndarray 2D numpy array of scalar values level : float The level at which to generate an isosurface connected : ...
Generate isocurve from 2D data using marching squares algorithm. Parameters ---------- data : ndarray 2D numpy array of scalar values level : float The level at which to generate an isosurface connected : bool If False, return a single long list of point pairs If Tru...
entailment
def pos(self): """ The position of this event in the local coordinate system of the visual. """ if self._pos is None: tr = self.visual.get_transform('canvas', 'visual') self._pos = tr.map(self.mouse_event.pos) return self._pos
The position of this event in the local coordinate system of the visual.
entailment
def last_event(self): """ The mouse event immediately prior to this one. This property is None when no mouse buttons are pressed. """ if self.mouse_event.last_event is None: return None ev = self.copy() ev.mouse_event = self.mouse_event.last_event retu...
The mouse event immediately prior to this one. This property is None when no mouse buttons are pressed.
entailment
def press_event(self): """ The mouse press event that initiated a mouse drag, if any. """ if self.mouse_event.press_event is None: return None ev = self.copy() ev.mouse_event = self.mouse_event.press_event return ev
The mouse press event that initiated a mouse drag, if any.
entailment
def check_enum(enum, name=None, valid=None): """ Get lowercase string representation of enum. """ name = name or 'enum' # Try to convert res = None if isinstance(enum, int): if hasattr(enum, 'name') and enum.name.startswith('GL_'): res = enum.name[3:].lower() elif isinsta...
Get lowercase string representation of enum.
entailment
def draw_texture(tex): """Draw a 2D texture to the current viewport Parameters ---------- tex : instance of Texture2D The texture to draw. """ from .program import Program program = Program(vert_draw, frag_draw) program['u_texture'] = tex program['a_position'] = [[-1., -1.],...
Draw a 2D texture to the current viewport Parameters ---------- tex : instance of Texture2D The texture to draw.
entailment
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, ...
Match pattern against the output of func, passing the results as floats to func. If anything fails, return None.
entailment
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...
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.
entailment
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: ...
Set the data Parameters ---------- adjacency_mat : ndarray | None The adjacency matrix. **kwargs : dict Keyword arguments to pass to the arrows.
entailment
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"...
Calculate a size Parameters ---------- rect : rectangle The rectangle. orientation : str Either "bottom" or "top".
entailment
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'),...
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 ...
entailment
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....
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 Attribu...
entailment
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 o...
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.
entailment
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 ...
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. ...
entailment
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 ...
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...
entailment
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...
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...
entailment
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. ...
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 ------- ...
entailment
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 co...
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.
entailment
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. ...
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. ...
entailment
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 ...
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....
entailment
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 ...
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 coordi...
entailment
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 (no...
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`]...
entailment
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__
Get unique FT_Library handle
entailment
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), byre...
Return the version of the FreeType library being used as a tuple of ( major version number, minor version number, patch version number )
entailment
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` *...
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 -----...
entailment
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()
Set the position of the datapoints
entailment
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...
mode: string - "raw" (speed: fastest, size: small, output: ugly, no dash, no thickness) - "agg" (speed: slower, size: medium, output: perfect, no dash)
entailment
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...
Computes the parameterization of a parametric surface func: function(u,v) Parametric function used to build the surface
entailment
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,...
mode: string - "raw" (speed: fastest, size: small, output: ugly) - "agg" (speed: fast, size: small, output: beautiful)
entailment
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] ...
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.
entailment
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. """ s...
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.
entailment
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. ...
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.
entailment
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
New program was added to the multiprogram; update items in the shader.
entailment
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_...
Attach this tranform to a canvas Parameters ---------- canvas : instance of Canvas The canvas.
entailment
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[...
Resize handler Parameters ---------- event : instance of Event The event.
entailment
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 ...
Mouse move handler Parameters ---------- event : instance of Event The event.
entailment
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)
Mouse wheel handler Parameters ---------- event : instance of Event The event.
entailment
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) -...
Calculates and returns the tangents, normals and binormals for the tube.
entailment
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_ze...
Depth of the smallest HEALPix cells found in the MOC instance.
entailment
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 additi...
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 ...
entailment
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 ...
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 ------- ...
entailment
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 ...
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 ------- ...
entailment
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)]
Returns all the pixels neighbours of ``ipix``
entailment
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 structu...
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: ...
entailment
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...
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` ...
entailment
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 uni...
Generator giving the NUNIQ HEALPix pixels of the MOC. Returns ------- uniq : the NUNIQ HEALPix pixels iterator
entailment
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 ...
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...
entailment
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...
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. ...
entailment
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 H...
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...
entailment
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...
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 spec...
entailment
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 argument...
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 ------- ...
entailment
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'. o...
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 FIT...
entailment
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 t...
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 ...
entailment
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 ---------- ne...
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 degra...
entailment
def set_name(self, name): """ Set Screen Name """ self.name = name self.server.request("screen_set %s name %s" % (self.ref, self.name))
Set Screen Name
entailment
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))
Set Screen Width
entailment
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))
Set Screen Height
entailment
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))
Set Screen Cursor X Position
entailment
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))
Set Screen Cursor Y Position
entailment
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)))
Set Screen Change Interval Duration
entailment
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)))
Set Screen Timeout Duration
entailment
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))
Set Screen Priority Class
entailment
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))
Set Screen Backlight Mode
entailment
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))
Set Screen Heartbeat Display Mode
entailment
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))
Set Screen Cursor Mode
entailment
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=" " * ...
Clear Screen
entailment
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]
Add String Widget
entailment
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]
Add Title Widget
entailment
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]
Add Horizontal Bar Widget
entailment
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]
Add Vertical Bar Widget
entailment
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=widt...
Add Frame Widget
entailment
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]
Add Number Widget
entailment
def del_widget(self, ref): """ Delete/Remove A Widget """ self.server.request("widget_del %s %s" % (self.name, ref)) del(self.widgets[ref])
Delete/Remove A Widget
entailment
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. ...
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.
entailment
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...
Update rotation parmeters based on mouse movement
entailment
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)
Rotate the transformation matrix based on camera parameters
entailment
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) ...
Convert mouse x, y movement into x, y, z translations
entailment
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.glf...
Set gl configuration for GLFW
entailment
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: ...
Process (possible) keyboard modifiers GLFW provides "mod" with many callbacks, but not (critically) the scroll callback, so we keep track on our own here.
entailment
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.wrapperFunc...
Monkey-patch pyopengl to fix a bug in glBufferSubData.
entailment
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: ...
Try getting the given function from PyOpenGL, return a dummy function (that shows a warning when called) if it could not be found.
entailment
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
Copy functions from OpenGL.GL into _pyopengl namespace.
entailment
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)
Fetch a remote vispy font
entailment
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]
Ensure val is Nx(n_col), usually Nx3
entailment