code stringlengths 1 18.2k |
|---|
np.linalg.norm(doc_perp_vector) doc_perp_vector /= perp_len perp_len += border_width perp_len += 5 # pixels perp_len *= ColorBarVisual.text_padding_factor doc_perp_vector *= perp_len doc_center = visual_to_doc.map(np.array([x, y, 0, 0], dtype=np.float32)) doc_label_pos = doc_center + doc_perp_vector visual_label_pos = ... |
visual_ticks_pos.append(doc_to_visual.map(doc_ticks_pos[1])[:3]) return (visual_label_pos, visual_ticks_pos) |
def size(self): """ The size of the ColorBar Returns ------- size: (major_axis_length, minor_axis_length) major and minor axis are defined by the orientation of the ColorBar """ (halfw, halfh) = self._halfdim if self.orientation in ["top", "bottom"]: return (halfw * 2., halfh * 2.) else: return (halfh * 2., halfw * 2.) |
def add_pseudo_fields(self): """Add 'pseudo' fields (e.g non-displayed fields) to the display.""" fields = [] if self.backlight_on != enums.BACKLIGHT_ON_NEVER: fields.append( display_fields.BacklightPseudoField(ref='0', backlight_rule=self.backlight_on) ) fields.append( display_fields.PriorityPseudoField( ref='0', prio... |
def padded(self, padding): """Return a new Rect padded (smaller) by padding on all sides Parameters ---------- padding : float The padding. Returns ------- rect : instance of Rect The padded rectangle. """ return Rect(pos=(self.pos[0]+padding, self.pos[1]+padding), size=(self.size[0]-2*padding, self.size[1]-2*padding)) |
def normalized(self): """Return a Rect covering the same area, but with height and width guaranteed to be positive.""" return Rect(pos=(min(self.left, self.right), min(self.top, self.bottom)), size=(abs(self.width), abs(self.height))) |
def flipped(self, x=False, y=True): """Return a Rect with the same bounds but with axes inverted Parameters ---------- x : bool Flip the X axis. y : bool Flip the Y axis. Returns ------- rect : instance of Rect The flipped rectangle. """ pos = list(self.pos) size = list(self.size) for i, flip in enumerate((x, y)): if f... |
size) |
def _transform_in(self): """Return array of coordinates that can be mapped by Transform classes.""" return np.array([ [self.left, self.bottom, 0, 1], [self.right, self.top, 0, 1]]) |
def configure(self, viewport=None, fbo_size=None, fbo_rect=None, canvas=None): """Automatically configure the TransformSystem: * canvas_transform maps from the Canvas logical pixel coordinate system to the framebuffer coordinate system, taking into account the logical/physical pixel scale factor, current FBO position, ... |
None The GL viewport rectangle (x, y, w, h). If None, then it is assumed to cover the entire canvas. fbo_size : tuple or None The size of the active FBO. If None, then it is assumed to have the same size as the canvas's framebuffer. fbo_rect : tuple or None The position and size (x, y, w, h) of the FBO in the |
coordinate system of the canvas's framebuffer. If None, then the bounds are assumed to cover the entire active framebuffer. canvas : Canvas instance Optionally set the canvas for this TransformSystem. See the `canvas` property. """ # TODO: check that d2f and f2r transforms still contain a single # STTransform (if the u... |
transforms) if canvas is not None: self.canvas = canvas canvas = self._canvas if canvas is None: raise RuntimeError("No canvas assigned to this TransformSystem.") # By default, this should invert the y axis--canvas origin is in top # left, whereas framebuffer origin is in bottom left. map_from = [(0, 0), canvas.size] m... |
(1, 1, 1) self._canvas_transform.transforms[0].translate = (0, 0, 0) else: # Map into FBO coordinates map_from = [(fbo_rect[0], fbo_rect[1]), (fbo_rect[0] + fbo_rect[2], fbo_rect[1] + fbo_rect[3])] map_to = [(0, 0), fbo_size] self._canvas_transform.transforms[0].set_mapping(map_from, map_to) if viewport is None: if fbo... |
(viewport[0] + viewport[2], viewport[1] + viewport[3])] map_to = [(-1, -1), (1, 1)] self._framebuffer_transform.transforms[0].set_mapping(map_from, map_to) |
def dpi(self): """ Physical resolution of the document coordinate system (dots per inch). """ if self._dpi is None: if self._canvas is None: return None else: return self.canvas.dpi else: return self._dpi |
def get_transform(self, map_from='visual', map_to='render'): """Return a transform mapping between any two coordinate systems. Parameters ---------- map_from : str The starting coordinate system to map from. Must be one of: visual, scene, document, canvas, framebuffer, or render. map_to : str The ending coordinate syst... |
'framebuffer', 'render'] ifrom = tr.index(map_from) ito = tr.index(map_to) if ifrom < ito: trs = [getattr(self, '_' + t + '_transform') for t in tr[ifrom:ito]][::-1] else: trs = [getattr(self, '_' + t + '_transform').inverse for t in tr[ito:ifrom]] return self._cache.get(trs) |
def _calculate_delta_pos(adjacency_arr, pos, t, optimal): """Helper to calculate the delta position""" # XXX eventually this should be refactored for the sparse case to only # do the necessary pairwise distances delta = pos[:, np.newaxis, :] - pos # Distance between points distance2 = (delta*delta).sum(axis=-1) # Enfor... |
= np.zeros((len(delta), 2)) for ii in range(2): displacement[:, ii] = ( delta[:, :, ii] * ((optimal * optimal) / (distance*distance) - (adjacency_arr * distance) / optimal)).sum(axis=1) length = np.sqrt((displacement**2).sum(axis=1)) length = np.where(length < 0.01, 0.1, length) delta_pos = displacement * t / length[:,... |
def get_recipe_intent_handler(request): """ You can insert arbitrary business logic code here """ # Get variables like userId, slots, intent name etc from the 'Request' object ingredient = request.slots["Ingredient"] # Gets an Ingredient Slot from the Request object. if ingredient == None: return alexa.create_response(... |
# For e.g. This statement adds a new session attribute (automatically returned with the response) storing the # Last seen ingredient value in the 'last_ingredient' key. request.session['last_ingredient'] = ingredient # Automatically returned as a sessionAttribute # Modifying state like this saves us from explicitly hav... |
of the response card = alexa.create_card(title="GetRecipeIntent activated", subtitle=None, content="asked alexa to find a recipe using {}".format(ingredient)) return alexa.create_response("Finding a recipe with the ingredient {}".format(ingredient), end_session=False, card_obj=card) |
def use(app=None, gl=None): """ Set the usage options for vispy Specify what app backend and GL backend to use. Parameters ---------- app : str The app backend to use (case insensitive). Standard backends: * 'PyQt4': use Qt widget toolkit via PyQt4. * 'PyQt5': use Qt widget toolkit via PyQt5. * 'PySide': use Qt widget ... |
use Glfw backend (successor of Glut). Widely available on Linux. * 'SDL2': use SDL v2 backend. * 'osmesa': Use OSMesa backend Additional backends: * 'ipynb_vnc': render in the IPython notebook via a VNC approach (experimental) gl : str The gl backend to use (case insensitive). Options are: * 'gl2': use Vispy's desktop ... |
* 'es2': (TO COME) use real OpenGL ES 2.0 on Windows via Angle. Availability of ES 2.0 is larger for Windows, since it relies on DirectX. * 'gl+': use the full OpenGL functionality available on your system (via PyOpenGL). Notes ----- If the app option is given, ``vispy.app.use_app()`` is called. If the gl option is giv... |
is provided, and that backend could not be loaded, an error is raised. If no backend name is provided, Vispy will first check if the GUI toolkit corresponding to each backend is already imported, and try that backend first. If this is unsuccessful, it will try the 'default_backend' provided in the vispy config. If stil... |
predetermined order. See Also -------- vispy.app.use_app vispy.gloo.gl.use_gl """ if app is None and gl is None: raise TypeError('Must specify at least one of "app" or "gl".') # Example for future. This wont work (yet). if app == 'ipynb_webgl': app = 'headless' gl = 'webgl' if app == 'osmesa': from ..util.osmesa_gl imp... |
using osmesa") # Apply now if gl: from .. import gloo, config config['gl_backend'] = gl gloo.gl.use_gl(gl) if app: from ..app import use_app use_app(app) |
def run_subprocess(command, return_code=False, **kwargs): """Run command using subprocess.Popen Run command and wait for command to complete. If the return code was zero then return, otherwise raise CalledProcessError. By default, this will also add stdout= and stderr=subproces.PIPE to the call to Popen to suppress pri... |
bool If True, the returncode will be returned, and no error checking will be performed (so this function should always return without error). **kwargs : dict Additional kwargs to pass to ``subprocess.Popen``. Returns ------- stdout : str Stdout returned by the process. stderr : str Stderr returned by the process. code ... |
# code adapted with permission from mne-python use_kwargs = dict(stderr=subprocess.PIPE, stdout=subprocess.PIPE) use_kwargs.update(kwargs) p = subprocess.Popen(command, **use_kwargs) output = p.communicate() # communicate() may return bytes, str, or None depending on the kwargs # passed to Popen(). Convert all to unico... |
output] output = tuple(output) if not return_code and p.returncode: print(output[0]) print(output[1]) err_fun = subprocess.CalledProcessError.__init__ if 'output' in inspect.getargspec(err_fun).args: raise subprocess.CalledProcessError(p.returncode, command, output) else: raise subprocess.CalledProcessError(p.returncod... |
def start(self, interval=None, iterations=None): """Start the timer. A timeout event will be generated every *interval* seconds. If *interval* is None, then self.interval will be used. If *iterations* is specified, the timer will stop after emitting that number of events. If unspecified, then the previous value of self... |
called. If the timer is already running when this function is called, nothing happens (timer continues running as it did previously, without changing the interval, number of iterations, or emitting a timer start event). """ if self.running: return # don't do anything if already running self.iter_count = 0 if interval i... |
self._backend._vispy_start(self.interval) self._running = True self._first_emit_time = precision_time() self._last_emit_time = precision_time() self.events.start(type='timer_start') |
def stop(self): """Stop the timer.""" self._backend._vispy_stop() self._running = False self.events.stop(type='timer_stop') |
def _best_res_pixels(self): """ Returns a numpy array of all the HEALPix indexes contained in the MOC at its max order. Returns ------- result : `~numpy.ndarray` The array of HEALPix at ``max_order`` """ factor = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order) pix_l = [] for iv in self._interval_set._intervals: for v... |
def contains(self, ra, dec, keep_inside=True): """ Returns a boolean mask array of the positions lying inside (or outside) the MOC instance. Parameters ---------- ra : `astropy.units.Quantity` Right ascension array dec : `astropy.units.Quantity` Declination array keep_inside : bool, optional True by default. If so the ... |
outside the MOC. Returns ------- array : `~np.ndarray` A mask boolean array """ depth = self.max_order m = np.zeros(nside2npix(1 << depth), dtype=bool) pix_id = self._best_res_pixels() m[pix_id] = True if not keep_inside: m = np.logical_not(m) hp = HEALPix(nside=(1 << depth), order='nested') pix = hp.lonlat_to_healpix(... |
def add_neighbours(self): """ Extends the MOC instance so that it includes the HEALPix cells touching its border. The depth of the HEALPix cells added at the border is equal to the maximum depth of the MOC instance. Returns ------- moc : `~mocpy.moc.MOC` self extended by one degree of neighbours. """ # Get the pixels a... |
= self._best_res_pixels() hp = HEALPix(nside=(1 << self.max_order), order='nested') # Get the HEALPix array containing the neighbors of ``ipix``. # This array "extends" ``ipix`` by one degree of neighbors. extend_ipix = AbstractMOC._neighbour_pixels(hp, ipix) # Compute the difference between ``extend_ipix`` and ``ipix`... |
self.max_order) neigh_itv = np.vstack((neigh_ipix << shift, (neigh_ipix + 1) << shift)).T # This array of HEALPix neighbors are added to the MOC to get an ``extended`` MOC at its max order. self._interval_set = self._interval_set.union(IntervalSet(neigh_itv)) return self |
def remove_neighbours(self): """ Removes from the MOC instance the HEALPix cells located at its border. The depth of the HEALPix cells removed is equal to the maximum depth of the MOC instance. Returns ------- moc : `~mocpy.moc.MOC` self minus its HEALPix cells located at its border. """ # Get the HEALPix cells of the ... |
HEALPix(nside=(1 << self.max_order), order='nested') # Extend it to include the max depth neighbor cells. extend_ipix = AbstractMOC._neighbour_pixels(hp, ipix) # Get only the max depth HEALPix cells lying at the border of the MOC neigh_ipix = np.setxor1d(extend_ipix, ipix) # Remove these pixels from ``ipix`` border_ipi... |
at its border. shift = 2 * (AbstractMOC.HPY_MAX_NORDER - self.max_order) reduced_itv = np.vstack((reduced_ipix << shift, (reduced_ipix + 1) << shift)).T self._interval_set = IntervalSet(reduced_itv) return self |
def fill(self, ax, wcs, **kw_mpl_pathpatch): """ Draws the MOC on a matplotlib axis. This performs the projection of the cells from the world coordinate system to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.patches.PathPatch` (see the `list of valid keywords <https:... |
Image system projection. kw_mpl_pathpatch Plotting arguments for `matplotlib.patches.PathPatch`. Examples -------- >>> from mocpy import MOC, WCS >>> from astropy.coordinates import Angle, SkyCoord >>> import astropy.units as u >>> # Load a MOC, e.g. the MOC of GALEXGR6-AIS-FUV >>> filename = './../resources/P-GALEXGR6... |
# Define a WCS as a context >>> with WCS(fig, ... fov=50 * u.deg, ... center=SkyCoord(0, 20, unit='deg', frame='icrs'), ... coordsys="icrs", ... rotation=Angle(0, u.degree), ... projection="AIT") as wcs: ... ax = fig.add_subplot(1, 1, 1, projection=wcs) ... # Call fill giving the matplotlib axe and the `~astropy.wcs.WC... |
... # the border of each HEALPix cell. ... # The color can also be specified along with an alpha value. ... moc.fill(ax=ax, wcs=wcs, linewidth=0, alpha=0.5, fill=True, color="green") >>> plt.xlabel('ra') >>> plt.ylabel('dec') >>> plt.grid(color="black", linestyle="dotted") """ fill.fill(self, ax, wcs, **kw_mpl_pathpatc... |
def border(self, ax, wcs, **kw_mpl_pathpatch): """ Draws the MOC border(s) on a matplotlib axis. This performs the projection of the sky coordinates defining the perimeter of the MOC to the pixel image coordinate system. You are able to specify various styling kwargs for `matplotlib.patches.PathPatch` (see the `list of... |
World system <-> Image system projection. kw_mpl_pathpatch Plotting arguments for `matplotlib.patches.PathPatch` Examples -------- >>> from mocpy import MOC, WCS >>> from astropy.coordinates import Angle, SkyCoord >>> import astropy.units as u >>> # Load a MOC, e.g. the MOC of GALEXGR6-AIS-FUV >>> filename = './../reso... |
figsize=(15, 15)) >>> # Define a WCS as a context >>> with WCS(fig, ... fov=50 * u.deg, ... center=SkyCoord(0, 20, unit='deg', frame='icrs'), ... coordsys="icrs", ... rotation=Angle(0, u.degree), ... projection="AIT") as wcs: ... ax = fig.add_subplot(1, 1, 1, projection=wcs) ... # Call border giving the matplotlib axe ... |
ax, wcs, **kw_mpl_pathpatch) |
def from_image(cls, header, max_norder, mask=None): """ Creates a `~mocpy.moc.MOC` from an image stored as a FITS file. Parameters ---------- header : `astropy.io.fits.Header` FITS header containing all the info of where the image is located (position, size, etc...) max_norder : int The moc resolution. mask : `numpy.nd... |
part of the final MOC and pixels having the value 0 are not. Returns ------- moc : `~mocpy.moc.MOC` The resulting MOC. """ # load the image data height = header['NAXIS2'] width = header['NAXIS1'] # use wcs from astropy to locate the image in the world coordinates w = wcs.WCS(header) if mask is not None: # We have an ar... |
of of survey y, x = np.where(mask) pix_crd = np.dstack((x, y))[0] else: # If we do not have a mask array we create the moc of all the image # step_pix = 1 """ Coords returned by wcs_pix2world method correspond to pixel centers. We want to retrieve the moc pix crossing the borders of the image so we have to add 1/2 to t... |
pixels coords before computing the lonlat. The step between two pix_crd is set to `step_pix` but can be diminished to have a better precision at the borders so that all the image is covered (a too big step does not retrieve all the moc pix crossing the borders of the image). """ x, y = np.mgrid[0.5:(width + 0.5 + step_... |
step_pix):step_pix] pix_crd = np.dstack((x.ravel(), y.ravel()))[0] frame = wcs.utils.wcs_to_celestial_frame(w) world_pix_crd = SkyCoord(w.wcs_pix2world(pix_crd, 1), unit='deg', frame=frame) hp = HEALPix(nside=(1 << max_norder), order='nested', frame=ICRS()) ipix = hp.skycoord_to_healpix(world_pix_crd) # remove doubles ... |
or # simply write it to a fits or json file interval_set = IntervalSet(intervals_arr) return cls(interval_set=interval_set) |
def from_fits_images(cls, path_l, max_norder): """ Loads a MOC from a set of FITS file images. Parameters ---------- path_l : [str] A list of path where the fits image are located. max_norder : int The MOC resolution. Returns ------- moc : `~mocpy.moc.MOC` The union of all the MOCs created from the paths found in ``pat... |
fits.getheader(path) current_moc = MOC.from_image(header=header, max_norder=max_norder) moc = moc.union(current_moc) return moc |
def from_vizier_table(cls, table_id, nside=256): """ Creates a `~mocpy.moc.MOC` object from a VizieR table. **Info**: This method is already implemented in `astroquery.cds <https://astroquery.readthedocs.io/en/latest/cds/cds.html>`__. You can ask to get a `mocpy.moc.MOC` object from a vizier catalog ID. Parameters ----... |
128, 256, 512) if nside not in nside_possible_values: raise ValueError('Bad value for nside. Must be in {0}'.format(nside_possible_values)) result = cls.from_ivorn('ivo://CDS/' + table_id, nside) return result |
def from_ivorn(cls, ivorn, nside=256): """ Creates a `~mocpy.moc.MOC` object from a given ivorn. Parameters ---------- ivorn : str nside : int, optional 256 by default Returns ------- result : `~mocpy.moc.MOC` The resulting MOC. """ return cls.from_url('%s?%s' % (MOC.MOC_SERVER_ROOT_URL, urlencode({ 'ivorn': ivorn, 'ge... |
def from_url(cls, url): """ Creates a `~mocpy.moc.MOC` object from a given url. Parameters ---------- url : str The url of a FITS file storing a MOC. Returns ------- result : `~mocpy.moc.MOC` The resulting MOC. """ path = download_file(url, show_progress=False, timeout=60) return cls.from_fits(path) |
def from_skycoords(cls, skycoords, max_norder): """ Creates a MOC from an `astropy.coordinates.SkyCoord`. Parameters ---------- skycoords : `astropy.coordinates.SkyCoord` The sky coordinates that will belong to the MOC. max_norder : int The depth of the smallest HEALPix cells contained in the MOC. Returns ------- resul... |
max_norder) intervals = np.vstack((ipix << shift, (ipix + 1) << shift)).T interval_set = IntervalSet(intervals) return cls(interval_set) |
def from_lonlat(cls, lon, lat, max_norder): """ 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_nor... |
""" hp = HEALPix(nside=(1 << max_norder), order='nested') ipix = hp.lonlat_to_healpix(lon, lat) shift = 2 * (AbstractMOC.HPY_MAX_NORDER - max_norder) intervals = np.vstack((ipix << shift, (ipix + 1) << shift)).T interval_set = IntervalSet(intervals) return cls(interval_set) |
def from_polygon_skycoord(cls, skycoord, inside=None, max_depth=10): """ Creates a MOC from a polygon. The polygon is given as an `astropy.coordinates.SkyCoord` that contains the vertices of the polygon. Concave and convex polygons are accepted but self-intersecting ones are currently not properly handled. Parameters -... |
a self-intersecting one. inside : `astropy.coordinates.SkyCoord`, optional A point that will be inside the MOC is needed as it is not possible to determine the inside area of a polygon on the unit sphere (there is no infinite area that can be considered as the outside because on the sphere, a closed polygon delimits tw... |
the one covering the smallest region on the sphere. If inside=None (default behavior), the mean of all the vertices is taken as lying inside the polygon. That approach may not work for concave polygons. max_depth : int, optional The resolution of the MOC. Set to 10 by default. Returns ------- result : `~mocpy.moc.MOC` ... |
def from_polygon(cls, lon, lat, inside=None, max_depth=10): """ Creates a MOC from a polygon The polygon is given as lon and lat `astropy.units.Quantity` that define the vertices of the polygon. Concave and convex polygons are accepted but self-intersecting ones are currently not properly handled. Parameters ----------... |
: `astropy.units.Quantity` The latitudes defining the polygon. Can describe convex and concave polygons but not self-intersecting ones. inside : `astropy.coordinates.SkyCoord`, optional A point that will be inside the MOC is needed as it is not possible to determine the inside area of a polygon on the unit sphere (ther... |
a closed polygon delimits two finite areas). Possible improvement: take the inside area as the one covering the smallest region on the sphere. If inside=None (default behavior), the mean of all the vertices is taken as lying inside the polygon. That approach may not work for concave polygons. max_depth : int, optional ... |
result : `~mocpy.moc.MOC` The resulting MOC """ from .polygon import PolygonComputer polygon_computer = PolygonComputer(lon, lat, inside, max_depth) # Create the moc from the python dictionary moc = MOC.from_json(polygon_computer.ipix) # We degrade it to the user-requested order if polygon_computer.degrade_to_max_depth... |
def sky_fraction(self): """ Sky fraction covered by the MOC """ pix_id = self._best_res_pixels() nb_pix_filled = pix_id.size return nb_pix_filled / float(3 << (2*(self.max_order + 1))) |
def _query(self, resource_id, max_rows): """ Internal method to query Simbad or a VizieR table for sources in the coverage of the MOC instance """ from astropy.io.votable import parse_single_table if max_rows is not None and max_rows >= 0: max_rows_str = str(max_rows) else: max_rows_str = str(9999999999) tmp_moc = temp... |
stream=True) tmp_vot = BytesIO() tmp_vot.write(r.content) table = parse_single_table(tmp_vot).to_table() # finally delete temp files os.unlink(tmp_moc.name) return table |
def plot(self, title='MOC', frame=None): """ Plot the MOC object using a mollweide projection. **Deprecated**: New `fill` and `border` methods produce more reliable results and allow you to specify additional matplotlib style parameters. Parameters ---------- title : str The title of the plot frame : `astropy.coordinat... |
= ICRS() if frame is None else frame from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt plot_order = 8 if self.max_order > plot_order: plotted_moc = self.degrade_to_order(plot_order) else: plotted_moc = self num_pixels_map = 1024 delta = 2. * np.pi / num_pixels_map x = np.arange(-np.p... |
not isinstance(frame, BaseCoordinateFrame): raise ValueError("Only Galactic/ICRS coordinate systems are supported." "Please set `coord` to either 'C' or 'G'.") pix_map = hp.lonlat_to_healpix(lon_rad * u.rad, lat_rad * u.rad) m = np.zeros(nside2npix(1 << plotted_moc.max_order)) pix_id = plotted_moc._best_res_pixels() # ... |
step=2) sky_crd = SkyCoord(lon, lat, unit='deg') pix_id = hp.lonlat_to_healpix(sky_crd.galactic.l, sky_crd.galactic.b) m[pix_id] = 1 z = np.flip(m[pix_map], axis=1) plt.figure(figsize=(10, 10)) ax = plt.subplot(111, projection="mollweide") ax.set_xticklabels(['150°', '120°', '90°', '60°', '30°', '0°', '330°', '300°', '... |
def inverse(self): """ The inverse of this transform. """ if self._inverse is None: self._inverse = InverseTransform(self) return self._inverse |
def _tile_ticks(self, frac, tickvec): """Tiles tick marks along the axis.""" origins = np.tile(self.axis._vec, (len(frac), 1)) origins = self.axis.pos[0].T + (origins.T*frac).T endpoints = tickvec + origins return origins, endpoints |
def _get_tick_frac_labels(self): """Get the major ticks, minor ticks, and major labels""" minor_num = 4 # number of minor ticks per major division if (self.axis.scale_type == 'linear'): domain = self.axis.domain if domain[1] < domain[0]: flip = True domain = domain[::-1] else: flip = False offset = domain[0] scale = do... |
= np.sqrt(np.sum(length ** 2)) / transforms.dpi # major = np.linspace(domain[0], domain[1], num=11) # major = MaxNLocator(10).tick_values(*domain) major = _get_ticks_talbot(domain[0], domain[1], n_inches, 2) labels = ['%g' % x for x in major] majstep = major[1] - major[0] minor = [] minstep = majstep / (minor_num + 1) ... |
len(major) + minstop): maj = major[0] + i * majstep minor.extend(np.linspace(maj + minstep, maj + majstep - minstep, minor_num)) major_frac = (major - offset) / scale minor_frac = (np.array(minor) - offset) / scale major_frac = major_frac[::-1] if flip else major_frac use_mask = (major_frac > -0.0001) & (major_frac < 1... |
minor_frac[(minor_frac > -0.0001) & (minor_frac < 1.0001)] elif self.axis.scale_type == 'logarithmic': return NotImplementedError elif self.axis.scale_type == 'power': return NotImplementedError return major_frac, minor_frac, labels |
def interleave_planes(ipixels, apixels, ipsize, apsize): """ Interleave (colour) planes, e.g. RGB + A = RGBA. Return an array of pixels consisting of the `ipsize` elements of data from each pixel in `ipixels` followed by the `apsize` elements of data from each pixel in `apixels`. Conventionally `ipixels` and `apixels` ... |
the same type. The returned array is the same type as the input arrays which should be the same type as each other. """ itotal = len(ipixels) atotal = len(apixels) newtotal = itotal + atotal newpsize = ipsize + apsize # Set up the output buffer # See http://www.python.org/doc/2.4.4/lib/module-array.html#l2h-1356 out = ... |
array size :-( out.extend(ipixels) out.extend(apixels) # Interleave in the pixel data for i in range(ipsize): out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize] for i in range(apsize): out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize] return out |
def write_chunks(out, chunks): """Create a PNG file by writing out the chunks.""" out.write(_signature) for chunk in chunks: write_chunk(out, *chunk) |
def filter_scanline(type, line, fo, prev=None): """Apply a scanline filter to a scanline. `type` specifies the filter type (0 to 4); `line` specifies the current (unfiltered) scanline as a sequence of bytes; `prev` specifies the previous (unfiltered) scanline as a sequence of bytes. `fo` specifies the filter offset; no... |
number of channels), but when this is < 1 (for bit depths < 8) then the filter offset is 1. """ assert 0 <= type < 5 # The output array. Which, pathetically, we extend one-byte at a # time (fortunately this is linear). out = array('B', [type]) def sub(): ai = -fo for x in line: if ai >= 0: x = (x |
- line[ai]) & 0xff out.append(x) ai += 1 def up(): for i,x in enumerate(line): x = (x - prev[i]) & 0xff out.append(x) def average(): ai = -fo for i,x in enumerate(line): if ai >= 0: x = (x - ((line[ai] + prev[i]) >> 1)) & 0xff else: x = (x - (prev[i] >> 1)) & 0xff out.append(x) ai += 1 def paeth(): # http://www.w3.org/... |
ai = -fo # also used for ci for i,x in enumerate(line): a = 0 b = prev[i] c = 0 if ai >= 0: a = line[ai] c = prev[ai] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: Pr = a |
elif pb <= pc: Pr = b else: Pr = c x = (x - Pr) & 0xff out.append(x) ai += 1 if not prev: # We're on the first line. Some of the filters can be reduced # to simpler cases which makes handling the line "off the top" # of the image simpler. "up" becomes "none"; "paeth" becomes # "left" (non-trivial, but |
true). "average" needs to be handled # specially. if type == 2: # "up" type = 0 elif type == 3: prev = [0]*len(line) elif type == 4: # "paeth" type = 1 if type == 0: out.extend(line) elif type == 1: sub() elif type == 2: up() elif type == 3: average() else: # type == 4 paeth() return out |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.