Coverage for python/lsst/afw/display/interface.py : 72%
Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
|
# # LSST Data Management System # Copyright 2008, 2009, 2010, 2015 LSST Corporation. # # This product includes software developed by the # LSST Project (http://www.lsst.org/). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the LSST License Statement and # the GNU General Public License along with this program. If not, # see <http://www.lsstcorp.org/LegalNotices/>. #
## # @file # @brief Support for talking to image displays from python
"WHITE", "BLACK", "RED", "GREEN", "BLUE", "CYAN", "MAGENTA", "YELLOW", "ORANGE", "IGNORE", "Display", "Event", "noop_callback", "h_callback", "setDefaultBackend", "getDefaultBackend", "setDefaultFrame", "getDefaultFrame", "incrDefaultFrame", "setDefaultMaskTransparency", "setDefaultMaskPlaneColor", "getDisplay", "delAllDisplays", )
# # Symbolic names for mask/line colours. N.b. ds9 supports any X11 colour for masks #
"""!Return the DisplayImpl for the named backend
@param display Name of device. Should be importable, either absolutely or relative to lsst.display @param backend The desired backend @param args Arguments passed to DisplayImpl.__init__ @param kwargs Keywords arguments passed to DisplayImpl.__init__
E.g. import lsst.afw.display as afwDisplay display = afwDisplay.Display(display=1, backend="ds9") would call _makeDisplayImpl(..., "ds9", 1) and import the ds9 implementation of DisplayImpl from lsst.display.ds9 """ # only specify the root package if we are not doing an absolute import # SystemError can be raised in Python 3.5 if a relative import # is attempted when the root package, lsst.display, does not exist. # Copy the exception into outer scope
# re-raise the final exception else: raise ImportError( "Could not load the requested backend: {}".format(backend))
else:
BAD=RED, CR=MAGENTA, EDGE=YELLOW, INTERPOLATED=GREEN, SATURATED=GREEN, DETECTED=BLUE, DETECTED_NEGATIVE=CYAN, SUSPECT=YELLOW, NO_DATA=ORANGE, # deprecated names INTRP=GREEN, SAT=GREEN, )
"""!Create an object able to display images and overplot glyphs
@param frame An identifier for the display @param backend The backend to use (defaults to value set by setDefaultBackend()) @param args Arguments to pass to the backend @param kwargs Arguments to pass to the backend """ frame = getDefaultFrame()
try: setDefaultBackend("ds9") except RuntimeError: setDefaultBackend("virtualDevice")
h_callback(k, x, y)
for k in sorted(self._callbacks.keys()): doc = self._callbacks[k].__doc__ print(" %-6s %s" % (k, doc.split("\n")[0] if doc else "???"))
"""!Support for python's with statement"""
"""!Support for python's with statement"""
"""Return the attribute of self._impl, or ._impl if it is requested Parameters: ----------- name : string name of the attribute requested Returns: -------- attribute : object the attribute of self._impl for the requested name """
if name == '_impl': return object.__getattr__(self, name)
if not (hasattr(self, "_impl") and self._impl): raise AttributeError("Device has no _impl attached")
try: return getattr(self._impl, name) except AttributeError: raise AttributeError( "Device %s has no attribute \"%s\"" % (self.name, name))
def verbose(self): """!The backend's verbosity""" return self._impl.verbose
def verbose(self, value):
return "Display[%s]" % (self.frame)
# # Handle Displays, including the default one (the frame to use when a user specifies None) # def setDefaultBackend(backend): "Unable to set backend to %s: \"%s\"" % (backend, e))
def getDefaultBackend(): return Display._defaultBackend
"""Set the default frame for display""" Display._defaultFrame = frame
def getDefaultFrame(): """Get the default frame for display""" return Display._defaultFrame
def incrDefaultFrame(): """Increment the default frame for display""" Display._defaultFrame += 1 return Display._defaultFrame
if hasattr(maskPlaneTransparency, "copy"): maskPlaneTransparency = maskPlaneTransparency.copy()
Display._defaultMaskTransparency = maskPlaneTransparency
"""!Set the default mapping from mask plane names to colours @param name name of mask plane, or a dict mapping names to colours @param color Desired color, or None if name is a dict
If name is None, use the hard-coded default dictionary """
if name is None: name = Display._defaultMaskPlaneColor
if isinstance(name, dict): assert color is None for k, v in name.items(): setDefaultMaskPlaneColor(k, v) return # # Set the individual colour values # Display._defaultMaskPlaneColor[name] = color
"""!Return the Display indexed by frame, creating it if needs be
@param frame The desired frame (None => use defaultFrame (see setDefaultFrame)) @param backend create the specified frame using this backend (or the default if None) \ if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame @param create create the display if it doesn't already exist. @param verbose Allow backend to be chatty @param args arguments passed to Display constructor @param kwargs keyword arguments passed to Display constructor """
frame = Display._defaultFrame
raise RuntimeError("Frame %s does not exist" % frame)
frame, backend, verbose=verbose, *args, **kwargs)
def delAllDisplays(): """!Delete and close all known display """
"""!A generator for "standard" colours
@param omitBW Don't include Black and White
e.g. colorGenerator = interface.maskColorGenerator(omitBW=True) for p in planeList: print p, next(colorGenerator) """ BLUE, CYAN, MAGENTA, YELLOW, ORANGE]
"""!Request that mask plane name be displayed as color
@param name Name of mask plane or a dictionary of name -> colourName @param color The name of the colour to use (must be None if name is a dict)
Colours may be specified as any X11-compliant string (e.g. <tt>"orchid"</tt>), or by one of the following constants defined in @c afwDisplay: @c BLACK, @c WHITE, @c RED, @c BLUE, @c GREEN, @c CYAN, @c MAGENTA, @c YELLOW.
If the colour is "ignore" (or @c IGNORE) then that mask plane is not displayed
The advantage of using the symbolic names is that the python interpreter can detect typos.
"""
"""!Return the colour associated with the specified mask plane name
@param name Desired mask plane; if None, return entire dict """
else:
"""!Specify display's mask transparency (percent); or None to not set it when loading masks"""
self.setMaskTransparency(k, v)
print( "Mask transparency should be in the range [0, 100]; clipping", file=sys.stderr) if transparency < 0: transparency = 0 else: transparency = 100
"""!Return the current display's mask transparency"""
return self._impl._getMaskTransparency(name)
"""!Uniconify and Raise display. N.b. throws an exception if frame doesn't exit"""
"""!Display an Image or Mask on a DISPLAY display
Historical note: the name "mtv" comes from Jim Gunn's forth imageprocessing system, Mirella (named after Mirella Freni); The "m" stands for Mirella. """ else:
# it's an Exposure; display the MaskedImage with the WCS raise RuntimeError( "You may not specify a wcs with an Exposure")
# it's a Mask; display it, bitplane by bitplane # # Some displays can't display a Mask without an image; so display an Image too, # with pixel values set to the mask # # it's a MaskedImage; display Image and overlay Mask else: raise RuntimeError("Unsupported type %s" % repr(data)) # # Graphics commands #
"""A class intended to be used with python's with statement"""
"""Return a class intended to be used with python's with statement E.g. with display.Buffering(): display.dot("+", xc, yc) """
"""!Flush the buffers""" self._impl._flush()
"""!Erase the specified DISPLAY frame """
"""!Draw a symbol onto the specified DISPLAY frame at (col,row) = (c,r) [0-based coordinates]
Possible values are: + Draw a + x Draw an x * Draw a * o Draw a circle @:Mxx,Mxy,Myy Draw an ellipse with moments (Mxx, Mxy, Myy) (argument size is ignored) An object derived from afwGeom.ellipses.BaseCore Draw the ellipse (argument size is ignored) Any other value is interpreted as a string to be drawn. Strings obey the fontFamily (which may be extended with other characteristics, e.g. "times bold italic". Text will be drawn rotated by textAngle (textAngle is ignored otherwise).
N.b. objects derived from BaseCore include Axes and Quadrupole. """ symb = "%d" % (symb)
try: mat = re.search(r"^@:([^,]+),([^,]+),([^,]+)", symb) except TypeError: pass else: if mat: mxx, mxy, myy = [float(_) for _ in mat.groups()] symb = afwGeom.Quadrupole(mxx, myy, mxy)
symb = afwGeom.ellipses.Axes(symb)
"""!Draw a set of symbols or connect the points, a list of (col,row) If symbs is True, draw points at the specified points using the desired symbol, otherwise connect the dots. Ctype is the name of a colour (e.g. 'red')
If symbs supports indexing (which includes a string -- caveat emptor) the elements are used to label the points """ except TypeError: symbs = len(points)*list(symbs)
else:
# # Set gray scale #
"""!Set the range of the scaling from DN in the image to the image display @param algorithm Desired scaling (e.g. "linear" or "asinh") @param min Minimum value, or "minmax" or "zscale" @param max Maximum value (must be None for minmax|zscale) @param unit Units for min and max (e.g. Percent, Absolute, Sigma; None if min==minmax|zscale) @param *args Optional arguments @param **kwargs Optional keyword arguments """ elif max is None: raise RuntimeError("Please specify max")
# # Zoom and Pan #
"""!Zoom frame by specified amount, optionally panning also"""
raise RuntimeError( "Please specify row and column center to pan about")
x0, y0 = self._xy0 colc -= x0 rowc -= y0
zoomfac = 2
"""!Pan to (rowc, colc); see also zoom"""
"""!Enter an interactive loop, listening for key presses in display and firing callbacks. Exit with q, @c CR, @c ESC, or any other callback function that returns a ``True`` value. """
continue
logger.warn("No callback registered for {0}".format(k)) else: except Exception as e: logger.error( "Display._callbacks['{0}']({0},{1},{2}) failed: {3}".format(k, x, y, e))
"""!Set the callback for key k to be func, returning the old callback """
raise RuntimeError( "Key '%s' is already in use by display, so I can't add a callback for it" % k)
"""!Return all callback keys @param onlyActive If true only return keys that do something """
return sorted([k for k, func in self._callbacks.items() if not (onlyActive and func == noop_callback)])
# # Callbacks for display events #
"""!A class to handle events such as key presses in image display windows"""
# # Default fallback function #
"""!Callback function: arguments key, x, y""" return False
print("Enter q or <ESC> to leave interactive mode, h for this help, or a letter to fire a callback") return False
# # Handle Displays, including the default one (the frame to use when a user specifies None) # # If the default frame is None, image display is disabled #
return Display.getDefaultBackend()
return Display.setDefaultFrame(frame)
"""Get the default frame for display""" return Display.getDefaultFrame()
"""Increment the default frame for display""" return Display.incrDefaultFrame()
return Display.setDefaultMaskTransparency(maskPlaneTransparency)
"""!Set the default mapping from mask plane names to colours @param name name of mask plane, or a dict mapping names to colours @param color Desired color, or None if name is a dict
If name is None, use the hard-coded default dictionary """
return Display.setDefaultMaskPlaneColor(name, color)
"""!Return the Display indexed by frame, creating it if needs be
See Display.getDisplay
@param frame The desired frame (None => use defaultFrame (see setDefaultFrame)) @param backend create the specified frame using this backend (or the default if None) \ if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame @param create create the display if it doesn't already exist. @param verbose Allow backend to be chatty @param args arguments passed to Display constructor @param kwargs keyword arguments passed to Display constructor """
"""!Delete and close all known display """ |