INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Extends the MOC instance so that it includes the HEALPix cells touching its border.
def add_neighbours(self): """ Extends the MOC instance so that it includes the HEALPix cells touching its border. The depth of the HEALPix cells added at the border is equal to the maximum depth of the MOC instance. Returns ------- moc : `~mocpy.moc.MOC` sel...
Removes from the MOC instance the HEALPix cells located at its border.
def remove_neighbours(self): """ Removes from the MOC instance the HEALPix cells located at its border. The depth of the HEALPix cells removed is equal to the maximum depth of the MOC instance. Returns ------- moc : `~mocpy.moc.MOC` self minus its HEALPix ce...
Draws the MOC on a matplotlib axis.
def fill(self, ax, wcs, **kw_mpl_pathpatch): """ Draws the MOC on a matplotlib axis. This performs the projection of the cells from the world coordinate system to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.patches.PathPatch` ...
Draws the MOC border ( s ) on a matplotlib axis.
def border(self, ax, wcs, **kw_mpl_pathpatch): """ Draws the MOC border(s) on a matplotlib axis. This performs the projection of the sky coordinates defining the perimeter of the MOC to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.pat...
Creates a ~mocpy. moc. MOC from an image stored as a FITS file.
def from_image(cls, header, max_norder, mask=None): """ Creates a `~mocpy.moc.MOC` from an image stored as a FITS file. Parameters ---------- header : `astropy.io.fits.Header` FITS header containing all the info of where the image is located (position, size, etc...) ...
Loads a MOC from a set of FITS file images.
def from_fits_images(cls, path_l, max_norder): """ Loads a MOC from a set of FITS file images. Parameters ---------- path_l : [str] A list of path where the fits image are located. max_norder : int The MOC resolution. Returns ----...
Creates a ~mocpy. moc. MOC object from a VizieR table.
def from_vizier_table(cls, table_id, nside=256): """ Creates a `~mocpy.moc.MOC` object from a VizieR table. **Info**: This method is already implemented in `astroquery.cds <https://astroquery.readthedocs.io/en/latest/cds/cds.html>`__. You can ask to get a `mocpy.moc.MOC` object from a v...
Creates a ~mocpy. moc. MOC object from a given ivorn.
def from_ivorn(cls, ivorn, nside=256): """ Creates a `~mocpy.moc.MOC` object from a given ivorn. Parameters ---------- ivorn : str nside : int, optional 256 by default Returns ------- result : `~mocpy.moc.MOC` The resultin...
Creates a ~mocpy. moc. MOC object from a given url.
def from_url(cls, url): """ Creates a `~mocpy.moc.MOC` object from a given url. Parameters ---------- url : str The url of a FITS file storing a MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC. """ ...
Creates a MOC from an astropy. coordinates. SkyCoord.
def from_skycoords(cls, skycoords, max_norder): """ Creates a MOC from an `astropy.coordinates.SkyCoord`. Parameters ---------- skycoords : `astropy.coordinates.SkyCoord` The sky coordinates that will belong to the MOC. max_norder : int The depth ...
Creates a MOC from astropy lon lat astropy. units. Quantity. Parameters ---------- lon: astropy. units. Quantity The longitudes of the sky coordinates belonging to the MOC. lat: astropy. units. Quantity The latitudes of the sky coordinates belonging to the MOC. max_norder: int The depth of the smallest HEALPix cells co...
def from_lonlat(cls, lon, lat, max_norder): """ Creates a MOC from astropy lon, lat `astropy.units.Quantity`. Parameters ---------- lon : `astropy.units.Quantity` The longitudes of the sky coordinates belonging to the MOC. lat : `astropy.units.Quantit...
Creates a MOC from a polygon.
def from_polygon_skycoord(cls, skycoord, inside=None, max_depth=10): """ Creates a MOC from a polygon. The polygon is given as an `astropy.coordinates.SkyCoord` that contains the vertices of the polygon. Concave and convex polygons are accepted but self-intersecting ones are cu...
Creates a MOC from a polygon
def from_polygon(cls, lon, lat, inside=None, max_depth=10): """ Creates a MOC from a polygon The polygon is given as lon and lat `astropy.units.Quantity` that define the vertices of the polygon. Concave and convex polygons are accepted but self-intersecting ones are currently n...
Sky fraction covered by the MOC
def sky_fraction(self): """ Sky fraction covered by the MOC """ pix_id = self._best_res_pixels() nb_pix_filled = pix_id.size return nb_pix_filled / float(3 << (2*(self.max_order + 1)))
Internal method to query Simbad or a VizieR table for sources in the coverage of the MOC instance
def _query(self, resource_id, max_rows): """ Internal method to query Simbad or a VizieR table for sources in the coverage of the MOC instance """ from astropy.io.votable import parse_single_table if max_rows is not None and max_rows >= 0: max_rows_str = str(...
Plot the MOC object using a mollweide projection.
def plot(self, title='MOC', frame=None): """ Plot the MOC object using a mollweide projection. **Deprecated**: New `fill` and `border` methods produce more reliable results and allow you to specify additional matplotlib style parameters. Parameters ---------- t...
The inverse of this transform.
def inverse(self): """ The inverse of this transform. """ if self._inverse is None: self._inverse = InverseTransform(self) return self._inverse
Tiles tick marks along the axis.
def _tile_ticks(self, frac, tickvec): """Tiles tick marks along the axis.""" origins = np.tile(self.axis._vec, (len(frac), 1)) origins = self.axis.pos[0].T + (origins.T*frac).T endpoints = tickvec + origins return origins, endpoints
Get the major ticks minor ticks and major labels
def _get_tick_frac_labels(self): """Get the major ticks, minor ticks, and major labels""" minor_num = 4 # number of minor ticks per major division if (self.axis.scale_type == 'linear'): domain = self.axis.domain if domain[1] < domain[0]: flip = True ...
Interleave ( colour ) planes e. g. RGB + A = RGBA.
def interleave_planes(ipixels, apixels, ipsize, apsize): """ Interleave (colour) planes, e.g. RGB + A = RGBA. Return an array of pixels consisting of the `ipsize` elements of data from each pixel in `ipixels` followed by the `apsize` elements of data from each pixel in `apixels`. Conventionally `i...
Create a PNG file by writing out the chunks.
def write_chunks(out, chunks): """Create a PNG file by writing out the chunks.""" out.write(_signature) for chunk in chunks: write_chunk(out, *chunk)
Apply a scanline filter to a scanline. type specifies the filter type ( 0 to 4 ) ; line specifies the current ( unfiltered ) scanline as a sequence of bytes ; prev specifies the previous ( unfiltered ) scanline as a sequence of bytes. fo specifies the filter offset ; normally this is size of a pixel in bytes ( the numb...
def filter_scanline(type, line, fo, prev=None): """Apply a scanline filter to a scanline. `type` specifies the filter type (0 to 4); `line` specifies the current (unfiltered) scanline as a sequence of bytes; `prev` specifies the previous (unfiltered) scanline as a sequence of bytes. `fo` specifies the ...
Create a PNG: class: Image object from a 2 - or 3 - dimensional array. One application of this function is easy PIL - style saving: png. from_array ( pixels L ). save ( foo. png ).
def from_array(a, mode=None, info={}): """Create a PNG :class:`Image` object from a 2- or 3-dimensional array. One application of this function is easy PIL-style saving: ``png.from_array(pixels, 'L').save('foo.png')``. .. note : The use of the term *3-dimensional* is for marketing purposes ...
Create the byte sequences for a PLTE and if necessary a tRNS chunk. Returned as a pair ( * p * * t * ). * t * will be None if no tRNS chunk is necessary.
def make_palette(self): """Create the byte sequences for a ``PLTE`` and if necessary a ``tRNS`` chunk. Returned as a pair (*p*, *t*). *t* will be ``None`` if no ``tRNS`` chunk is necessary. """ p = array('B') t = array('B') for x in self.palette: p...
Write a PNG image to the output file. rows should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image so there should be self. height rows of self. width * self. planes values. If interlace is specified ( when creating the instance ) then an interlaced P...
def write(self, outfile, rows): """Write a PNG image to the output file. `rows` should be an iterable that yields each row in boxed row flat pixel format. The rows should be the rows of the original image, so there should be ``self.height`` rows of ``self.width * self.planes`` ...
Write a PNG image to the output file.
def write_passes(self, outfile, rows, packed=False): """ Write a PNG image to the output file. Most users are expected to find the :meth:`write` or :meth:`write_array` method more convenient. The rows should be given to this method in the order that they appear ...
Write PNG file to outfile. The pixel data comes from rows which should be in boxed row packed format. Each row should be a sequence of packed bytes.
def write_packed(self, outfile, rows): """ Write PNG file to `outfile`. The pixel data comes from `rows` which should be in boxed row packed format. Each row should be a sequence of packed bytes. Technically, this method does work for interlaced images but it is best a...
Convert a PNM file containing raw pixel data into a PNG file with the parameters set in the writer object. Works for ( binary ) PGM PPM and PAM formats.
def convert_pnm(self, infile, outfile): """ Convert a PNM file containing raw pixel data into a PNG file with the parameters set in the writer object. Works for (binary) PGM, PPM, and PAM formats. """ if self.interlace: pixels = array('B') pixels...
Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object.
def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile): """ Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object. """ pixels = array('B') pixels.fromfile(ppmfile, (self.bitdepth/8) *...
Generates boxed rows in flat pixel format from the input file infile. It assumes that the input file is in a Netpbm - like binary format and is positioned at the beginning of the first pixel. The number of pixels to read is taken from the image dimensions ( width height planes ) and the number of bytes per value is imp...
def file_scanlines(self, infile): """ Generates boxed rows in flat pixel format, from the input file `infile`. It assumes that the input file is in a "Netpbm-like" binary format, and is positioned at the beginning of the first pixel. The number of pixels to read is taken from t...
Generator for interlaced scanlines from an array. pixels is the full source image in flat row flat pixel format. The generator yields each scanline of the reduced passes in turn in boxed row flat pixel format.
def array_scanlines_interlace(self, pixels): """ Generator for interlaced scanlines from an array. `pixels` is the full source image in flat row flat pixel format. The generator yields each scanline of the reduced passes in turn, in boxed row flat pixel format. """ ...
Undo the filter for a scanline. scanline is a sequence of bytes that does not include the initial filter type byte. previous is decoded previous scanline ( for straightlaced images this is the previous pixel row but for interlaced images it is the previous scanline in the reduced image which in general is not the previ...
def undo_filter(self, filter_type, scanline, previous): """Undo the filter for a scanline. `scanline` is a sequence of bytes that does not include the initial filter type byte. `previous` is decoded previous scanline (for straightlaced images this is the previous pixel row, but for inte...
Read raw pixel data undo filters deinterlace and flatten. Return in flat row flat pixel format.
def deinterlace(self, raw): """ Read raw pixel data, undo filters, deinterlace, and flatten. Return in flat row flat pixel format. """ # Values per row (of the target image) vpr = self.width * self.planes # Make a result array, and make it big enough. Interleav...
Iterator that yields each scanline in boxed row flat pixel format. rows should be an iterator that yields the bytes of each row in turn.
def iterboxed(self, rows): """Iterator that yields each scanline in boxed row flat pixel format. `rows` should be an iterator that yields the bytes of each row in turn. """ def asvalues(raw): """Convert a row of raw bytes into a flat row. Result will be...
Convert serial format ( byte stream ) pixel data to flat row flat pixel.
def serialtoflat(self, bytes, width=None): """Convert serial format (byte stream) pixel data to flat row flat pixel. """ if self.bitdepth == 8: return bytes if self.bitdepth == 16: bytes = tostring(bytes) return array('H', struct...
Iterator that undoes the effect of filtering and yields each row in serialised format ( as a sequence of bytes ). Assumes input is straightlaced. raw should be an iterable that yields the raw bytes in chunks of arbitrary size.
def iterstraight(self, raw): """Iterator that undoes the effect of filtering, and yields each row in serialised format (as a sequence of bytes). Assumes input is straightlaced. `raw` should be an iterable that yields the raw bytes in chunks of arbitrary size. """ # leng...
Reads just enough of the input to determine the next chunk s length and type returned as a ( * length * * type * ) pair where * type * is a string. If there are no more chunks None is returned.
def chunklentype(self): """Reads just enough of the input to determine the next chunk's length and type, returned as a (*length*, *type*) pair where *type* is a string. If there are no more chunks, ``None`` is returned. """ x = self.file.read(8) if not x: ...
Read the PNG file and decode it. Returns ( width height pixels metadata ).
def read(self, lenient=False): """ Read the PNG file and decode it. Returns (`width`, `height`, `pixels`, `metadata`). May use excessive memory. `pixels` are returned in boxed row flat pixel format. If the optional `lenient` argument evaluates to True, checksu...
Returns a palette that is a sequence of 3 - tuples or 4 - tuples synthesizing it from the PLTE and tRNS chunks. These chunks should have already been processed ( for example by calling the: meth: preamble method ). All the tuples are the same size: 3 - tuples if there is no tRNS chunk 4 - tuples when there is a tRNS ch...
def palette(self, alpha='natural'): """Returns a palette that is a sequence of 3-tuples or 4-tuples, synthesizing it from the ``PLTE`` and ``tRNS`` chunks. These chunks should have already been processed (for example, by calling the :meth:`preamble` method). All the tuples are the ...
Returns the image data as a direct representation of an x * y * planes array. This method is intended to remove the need for callers to deal with palettes and transparency themselves. Images with a palette ( colour type 3 ) are converted to RGB or RGBA ; images with transparency ( a tRNS chunk ) are converted to LA or ...
def asDirect(self): """Returns the image data as a direct representation of an ``x * y * planes`` array. This method is intended to remove the need for callers to deal with palettes and transparency themselves. Images with a palette (colour type 3) are converted to RGB or RGBA;...
Return image pixels as per: meth: asDirect method but scale all pixel values to be floating point values between 0. 0 and * maxval *.
def asFloat(self, maxval=1.0): """Return image pixels as per :meth:`asDirect` method, but scale all pixel values to be floating point values between 0.0 and *maxval*. """ x,y,pixels,info = self.asDirect() sourcemaxval = 2**info['bitdepth']-1 del info['bitdepth'] ...
Helper used by: meth: asRGB8 and: meth: asRGBA8.
def _as_rescale(self, get, targetbitdepth): """Helper used by :meth:`asRGB8` and :meth:`asRGBA8`.""" width,height,pixels,meta = get() maxval = 2**meta['bitdepth'] - 1 targetmaxval = 2**targetbitdepth - 1 factor = float(targetmaxval) / float(maxval) meta['bitdepth'] = tar...
Return image as RGB pixels. RGB colour images are passed through unchanged ; greyscales are expanded into RGB triplets ( there is a small speed overhead for doing this ).
def asRGB(self): """Return image as RGB pixels. RGB colour images are passed through unchanged; greyscales are expanded into RGB triplets (there is a small speed overhead for doing this). An alpha channel in the source image will raise an exception. The return values a...
Return image as RGBA pixels. Greyscales are expanded into RGB triplets ; an alpha channel is synthesized if necessary. The return values are as for the: meth: read method except that the * metadata * reflect the returned pixels not the source image. In particular for this method metadata [ greyscale ] will be False and...
def asRGBA(self): """Return image as RGBA pixels. Greyscales are expanded into RGB triplets; an alpha channel is synthesized if necessary. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In parti...
Get a standard vispy demo data file
def load_data_file(fname, directory=None, force_download=False): """Get a standard vispy demo data file Parameters ---------- fname : str The filename on the remote ``demo-data`` repository to download, e.g. ``'molecular_viewer/micelle.npy'``. These correspond to paths on ``http...
Download a file chunk by chunk and show advancement
def _chunk_read(response, local_file, chunk_size=65536, initial_size=0): """Download a file chunk by chunk and show advancement Can also be used when resuming downloads over http. Parameters ---------- response: urllib.response.addinfourl Response to the download request in order to get fi...
Write a chunk to file and update the progress bar
def _chunk_write(chunk, local_file, progress): """Write a chunk to file and update the progress bar""" local_file.write(chunk) progress.update_with_increment_value(len(chunk))
Load requested file downloading it if needed or requested
def _fetch_file(url, file_name, print_destination=True): """Load requested file, downloading it if needed or requested Parameters ---------- url: string The url of file to be downloaded. file_name: string Name, along with the path, of where downloaded file will be saved. print_d...
Update progressbar with current value of process
def update(self, cur_value, mesg=None): """Update progressbar with current value of process Parameters ---------- cur_value : number Current value of process. Should be <= max_value (but this is not enforced). The percent of the progressbar will be computed as ...
Update progressbar with the value of the increment instead of the current value of process as in update ()
def update_with_increment_value(self, increment_value, mesg=None): """Update progressbar with the value of the increment instead of the current value of process as in update() Parameters ---------- increment_value : int Value of the increment of process. The percent...
Returns the default widget that occupies the entire area of the canvas.
def central_widget(self): """ Returns the default widget that occupies the entire area of the canvas. """ if self._central_widget is None: self._central_widget = Widget(size=self.size, parent=self.scene) return self._central_widget
Render the scene to an offscreen buffer and return the image array. Parameters ---------- region: tuple | None Specifies the region of the canvas to render. Format is ( x y w h ). By default the entire canvas is rendered. size: tuple | None Specifies the size of the image array to return. If no size is given then the s...
def render(self, region=None, size=None, bgcolor=None): """Render the scene to an offscreen buffer and return the image array. Parameters ---------- region : tuple | None Specifies the region of the canvas to render. Format is (x, y, w, h). By default, t...
Draw a visual and its children to the canvas or currently active framebuffer. Parameters ---------- visual: Visual The visual to draw event: None or DrawEvent Optionally specifies the original canvas draw event that initiated this draw.
def draw_visual(self, visual, event=None): """ Draw a visual and its children to the canvas or currently active framebuffer. Parameters ---------- visual : Visual The visual to draw event : None or DrawEvent Optionally specifies the origin...
Return a list giving the order to draw visuals. Each node appears twice in the list -- ( node True ) appears before the node s children are drawn and ( node False ) appears after.
def _generate_draw_order(self, node=None): """Return a list giving the order to draw visuals. Each node appears twice in the list--(node, True) appears before the node's children are drawn, and (node, False) appears after. """ if node is None: node = self._sc...
Return the visual at a given position
def visual_at(self, pos): """Return the visual at a given position Parameters ---------- pos : tuple The position in logical coordinates to query. Returns ------- visual : instance of Visual | None The visual at the position, if it exists...
Find a visual whose bounding rect encompasses * pos *.
def _visual_bounds_at(self, pos, node=None): """Find a visual whose bounding rect encompasses *pos*. """ if node is None: node = self.scene for ch in node.children: hit = self._visual_bounds_at(pos, ch) if hit is not None: ...
Return a list of visuals within * radius * pixels of * pos *. Visuals are sorted by their proximity to * pos *. Parameters ---------- pos: tuple ( x y ) position at which to find visuals. radius: int Distance away from * pos * to search for visuals.
def visuals_at(self, pos, radius=10): """Return a list of visuals within *radius* pixels of *pos*. Visuals are sorted by their proximity to *pos*. Parameters ---------- pos : tuple (x, y) position at which to find visuals. radius : int ...
Render the scene in picking mode returning a 2D array of visual IDs.
def _render_picking(self, **kwargs): """Render the scene in picking mode, returning a 2D array of visual IDs. """ try: self._scene.picking = True img = self.render(bgcolor=(0, 0, 0, 0), **kwargs) finally: self._scene.picking = False im...
Resize handler
def on_resize(self, event): """Resize handler Parameters ---------- event : instance of Event The resize event. """ self._update_transforms() if self._central_widget is not None: self._central_widget.size = self.size ...
Close event handler
def on_close(self, event): """Close event handler Parameters ---------- event : instance of Event The event. """ self.events.mouse_press.disconnect(self._process_mouse_event) self.events.mouse_move.disconnect(self._process_mouse_event) self.ev...
Push a viewport ( x y w h ) on the stack. Values must be integers relative to the active framebuffer.
def push_viewport(self, viewport): """ Push a viewport (x, y, w, h) on the stack. Values must be integers relative to the active framebuffer. Parameters ---------- viewport : tuple The viewport as (x, y, w, h). """ vp = list(viewport) # Normal...
Pop a viewport from the stack.
def pop_viewport(self): """ Pop a viewport from the stack. """ vp = self._vp_stack.pop() # Activate latest if len(self._vp_stack) > 0: self.context.set_viewport(*self._vp_stack[-1]) else: self.context.set_viewport(0, 0, *self.physical_size) ...
Push an FBO on the stack. This activates the framebuffer and causes subsequent rendering to be written to the framebuffer rather than the canvas s back buffer. This will also set the canvas viewport to cover the boundaries of the framebuffer.
def push_fbo(self, fbo, offset, csize): """ Push an FBO on the stack. This activates the framebuffer and causes subsequent rendering to be written to the framebuffer rather than the canvas's back buffer. This will also set the canvas viewport to cover the boundaries of the ...
Pop an FBO from the stack.
def pop_fbo(self): """ Pop an FBO from the stack. """ fbo = self._fb_stack.pop() fbo[0].deactivate() self.pop_viewport() if len(self._fb_stack) > 0: old_fbo = self._fb_stack[-1] old_fbo[0].activate() self._update_transforms() ...
Update the canvas s TransformSystem to correct for the current canvas size framebuffer and viewport.
def _update_transforms(self): """Update the canvas's TransformSystem to correct for the current canvas size, framebuffer, and viewport. """ if len(self._fb_stack) == 0: fb_size = fb_rect = None else: fb, origin, fb_size = self._fb_stack[-1] fb...
Texture wrapping mode
def wrapping(self): """ Texture wrapping mode """ value = self._wrapping return value[0] if all([v == value[0] for v in value]) else value
Set the texture size and format
def resize(self, shape, format=None, internalformat=None): """Set the texture size and format Parameters ---------- shape : tuple of integers New texture shape in zyx order. Optionally, an extra dimention may be specified to indicate the number of color channels....
Internal method for resize.
def _resize(self, shape, format=None, internalformat=None): """Internal method for resize. """ shape = self._normalize_shape(shape) # Check if not self._resizable: raise RuntimeError("Texture is not resizable") # Determine format if format is None: ...
Set texture data
def set_data(self, data, offset=None, copy=False): """Set texture data Parameters ---------- data : ndarray Data to be uploaded offset: int | tuple of ints Offset in texture where to start copying data copy: bool Since the operation is...
Internal method for set_data.
def _set_data(self, data, offset=None, copy=False): """Internal method for set_data. """ # Copy if needed, check/normalize shape data = np.array(data, copy=copy) data = self._normalize_shape(data) # Maybe resize to purge DATA commands? if offset ...
Set texture data
def set_data(self, data, offset=None, copy=False): """Set texture data Parameters ---------- data : ndarray Data to be uploaded offset: int | tuple of ints Offset in texture where to start copying data copy: bool Since the operation is...
Set the texture size and format
def resize(self, shape, format=None, internalformat=None): """Set the texture size and format Parameters ---------- shape : tuple of integers New texture shape in zyx order. Optionally, an extra dimention may be specified to indicate the number of color channels....
Get a free region of given size and allocate it
def get_free_region(self, width, height): """Get a free region of given size and allocate it Parameters ---------- width : int Width of region to allocate height : int Height of region to allocate Returns ------- bounds : tuple | ...
Test if region ( width height ) fit into self. _atlas_nodes [ index ]
def _fit(self, index, width, height): """Test if region (width, height) fit into self._atlas_nodes[index]""" node = self._atlas_nodes[index] x, y = node[0], node[1] width_left = width if x+width > self._shape[1]: return -1 i = index while width_left > ...
Convert an object to either a scalar or a row or column vector.
def _vector_or_scalar(x, type='row'): """Convert an object to either a scalar or a row or column vector.""" if isinstance(x, (list, tuple)): x = np.array(x) if isinstance(x, np.ndarray): assert x.ndim == 1 if type == 'column': x = x[:, None] return x
Convert an object to a row or column vector.
def _vector(x, type='row'): """Convert an object to a row or column vector.""" if isinstance(x, (list, tuple)): x = np.array(x, dtype=np.float32) elif not isinstance(x, np.ndarray): x = np.array([x], dtype=np.float32) assert x.ndim == 1 if type == 'column': x = x[:, None] ...
Normalize an array from the range [ cmin cmax ] to [ 0 1 ] with optional clipping.
def _normalize(x, cmin=None, cmax=None, clip=True): """Normalize an array from the range [cmin, cmax] to [0,1], with optional clipping.""" if not isinstance(x, np.ndarray): x = np.array(x) if cmin is None: cmin = x.min() if cmax is None: cmax = x.max() if cmin == cmax: ...
Mix b ( with proportion x ) with a.
def _mix_simple(a, b, x): """Mix b (with proportion x) with a.""" x = np.clip(x, 0.0, 1.0) return (1.0 - x)*a + x*b
performs smooth Hermite interpolation between 0 and 1 when edge0 < x < edge1.
def smoothstep(edge0, edge1, x): """ performs smooth Hermite interpolation between 0 and 1 when edge0 < x < edge1. """ # Scale, bias and saturate x to 0..1 range x = np.clip((x - edge0)/(edge1 - edge0), 0.0, 1.0) # Evaluate polynomial return x*x*(3 - 2*x)
Step interpolation from a set of colors. x belongs in [ 0 1 ].
def step(colors, x, controls=None): x = x.ravel() """Step interpolation from a set of colors. x belongs in [0, 1].""" assert (controls[0], controls[-1]) == (0., 1.) ncolors = len(colors) assert ncolors == len(controls) - 1 assert ncolors >= 2 x_step = _find_controls(x, controls, ncolors-1) ...
Generate a GLSL template function from a given interpolation patterns and control points.
def _glsl_mix(controls=None): """Generate a GLSL template function from a given interpolation patterns and control points.""" assert (controls[0], controls[-1]) == (0., 1.) ncolors = len(controls) assert ncolors >= 2 if ncolors == 2: s = " return mix($color_0, $color_1, t);\n" els...
Replace $color_i by color #i in the GLSL template.
def _process_glsl_template(template, colors): """Replace $color_i by color #i in the GLSL template.""" for i in range(len(colors) - 1, -1, -1): color = colors[i] assert len(color) == 4 vec4_color = 'vec4(%.3f, %.3f, %.3f, %.3f)' % tuple(color) template = template.replace('$color_...
Obtain a colormap
def get_colormap(name, *args, **kwargs): """Obtain a colormap Some colormaps can have additional configuration parameters. Refer to their corresponding documentation for more information. Parameters ---------- name : str | Colormap Colormap name. Can also be a Colormap for pass-through...
The Python mapping function from the [ 0 1 ] interval to a list of rgba colors
def map(self, x): """The Python mapping function from the [0,1] interval to a list of rgba colors Parameters ---------- x : array-like The values to map. Returns ------- colors : list List of rgba colors. """ retur...
The border width in visual coordinates
def visual_border_width(self): """ The border width in visual coordinates """ render_to_doc = \ self.transforms.get_transform('document', 'visual') vec = render_to_doc.map([self.border_width, self.border_width, 0]) origin = render_to_doc.map([0, 0, 0]) visu...
Run the exporter on the given figure
def run(self, fig): """ Run the exporter on the given figure Parmeters --------- fig : matplotlib.Figure instance The figure to export """ # Calling savefig executes the draw() command, putting elements # in the correct place. fig.save...
Process the transform and convert data to figure or data coordinates
def process_transform(transform, ax=None, data=None, return_trans=False, force_trans=None): """Process the transform and convert data to figure or data coordinates Parameters ---------- transform : matplotlib Transform object The transform applied t...
Crawl the figure and process all axes
def crawl_fig(self, fig): """Crawl the figure and process all axes""" with self.renderer.draw_figure(fig=fig, props=utils.get_figure_properties(fig)): for ax in fig.axes: self.crawl_ax(ax)
Crawl the axes and process all elements within
def crawl_ax(self, ax): """Crawl the axes and process all elements within""" with self.renderer.draw_axes(ax=ax, props=utils.get_axes_properties(ax)): for line in ax.lines: self.draw_line(ax, line) for text in ax.texts: ...
Recursively look through objects in legend children
def crawl_legend(self, ax, legend): """ Recursively look through objects in legend children """ legendElements = list(utils.iter_all_children(legend._legend_box, skipContainers=True)) legendElements.append(legend.legendPatch) ...
Process a matplotlib line and call renderer. draw_line
def draw_line(self, ax, line, force_trans=None): """Process a matplotlib line and call renderer.draw_line""" coordinates, data = self.process_transform(line.get_transform(), ax, line.get_xydata(), force...
Process a matplotlib text object and call renderer. draw_text
def draw_text(self, ax, text, force_trans=None, text_type=None): """Process a matplotlib text object and call renderer.draw_text""" content = text.get_text() if content: transform = text.get_transform() position = text.get_position() coords, position = self.pr...
Process a matplotlib patch object and call renderer. draw_path
def draw_patch(self, ax, patch, force_trans=None): """Process a matplotlib patch object and call renderer.draw_path""" vertices, pathcodes = utils.SVG_path(patch.get_path()) transform = patch.get_transform() coordinates, vertices = self.process_transform(transform, ...
Process a matplotlib collection and call renderer. draw_collection
def draw_collection(self, ax, collection, force_pathtrans=None, force_offsettrans=None): """Process a matplotlib collection and call renderer.draw_collection""" (transform, transOffset, offsets, paths) = collection._prepare_points() offse...
Process a matplotlib image object and call renderer. draw_image
def draw_image(self, ax, image): """Process a matplotlib image object and call renderer.draw_image""" self.renderer.draw_image(imdata=utils.image_to_base64(image), extent=image.get_extent(), coordinates="data", ...
Draw a line that also has markers.
def draw_marked_line(self, data, coordinates, linestyle, markerstyle, label, mplobj=None): """Draw a line that also has markers. If this isn't reimplemented by a renderer object, by default, it will make a call to BOTH draw_line and draw_markers when both markerstyle ...
Draw a line. By default draw the line via the draw_path () command. Some renderers might wish to override this and provide more fine - grained behavior.
def draw_line(self, data, coordinates, style, label, mplobj=None): """ Draw a line. By default, draw the line via the draw_path() command. Some renderers might wish to override this and provide more fine-grained behavior. In matplotlib, lines are generally created via the plt.pl...
Build an iterator over the elements of the path collection
def _iter_path_collection(paths, path_transforms, offsets, styles): """Build an iterator over the elements of the path collection""" N = max(len(paths), len(offsets)) if not path_transforms: path_transforms = [np.eye(3)] edgecolor = styles['edgecolor'] if np.size(ed...
Draw a collection of paths. The paths offsets and styles are all iterables and the number of paths is max ( len ( paths ) len ( offsets )).
def draw_path_collection(self, paths, path_coordinates, path_transforms, offsets, offset_coordinates, offset_order, styles, mplobj=None): """ Draw a collection of paths. The paths, offsets, and styles are all iterables, and the number of ...
Draw a set of markers. By default this is done by repeatedly calling draw_path () but renderers should generally overload this method to provide a more efficient implementation.
def draw_markers(self, data, coordinates, style, label, mplobj=None): """ Draw a set of markers. By default, this is done by repeatedly calling draw_path(), but renderers should generally overload this method to provide a more efficient implementation. In matplotlib, markers are...