1 from __future__
import absolute_import, division, print_function
2 from builtins
import range
3 from builtins
import object
40 "WHITE",
"BLACK",
"RED",
"GREEN",
"BLUE",
"CYAN",
"MAGENTA",
"YELLOW",
"ORANGE",
"IGNORE",
41 "Display",
"Event",
"noop_callback",
"h_callback",
42 "setDefaultBackend",
"getDefaultBackend",
43 "setDefaultFrame",
"getDefaultFrame",
"incrDefaultFrame",
44 "setDefaultMaskTransparency",
"setDefaultMaskPlaneColor",
45 "getDisplay",
"delAllDisplays",
63 def _makeDisplayImpl(display, backend, *args, **kwargs):
64 """!Return the DisplayImpl for the named backend 66 \param display Name of device. Should be importable, either absolutely or relative to lsst.display 67 \param backend The desired backend 68 \param args Arguments passed to DisplayImpl.__init__ 69 \param kwargs Keywords arguments passed to DisplayImpl.__init__ 72 import lsst.afw.display as afwDisplay 73 display = afwDisplay.Display(display=1, backend="ds9") 75 _makeDisplayImpl(..., "ds9", 1) 76 and import the ds9 implementation of DisplayImpl from lsst.display.ds9 80 for dt
in (
"lsst.display.%s" % backend, backend,
".%s" % backend,
"lsst.afw.display.%s" % backend):
84 if dt.startswith(
"."):
85 impargs[
"package"] =
"lsst.display" 87 _disp = importlib.import_module(dt, **impargs)
89 except (ImportError, SystemError)
as e:
95 if not _disp
or not hasattr(_disp.DisplayImpl,
"_show"):
101 "Could not load the requested backend: {}".format(backend))
104 _impl = _disp.DisplayImpl(display, *args, **kwargs)
105 if not hasattr(_impl,
"frame"):
106 _impl.frame = display.frame
115 _defaultBackend =
None 117 _defaultMaskPlaneColor = dict(
124 DETECTED_NEGATIVE=CYAN,
131 _defaultMaskTransparency = {}
133 def __init__(self, frame=None, backend=None, *args, **kwargs):
134 """!Create an object able to display images and overplot glyphs 136 \param frame An identifier for the display 137 \param backend The backend to use (defaults to value set by setDefaultBackend()) 138 \param args Arguments to pass to the backend 139 \param kwargs Arguments to pass to the backend 145 if Display._defaultBackend
is None:
151 backend = Display._defaultBackend
154 self.
_impl = _makeDisplayImpl(self, backend, *args, **kwargs)
164 for ik
in range(ord(
'a'), ord(
'z') + 1):
169 for k
in (
'Return',
'Shift_L',
'Shift_R'):
172 for k
in (
'q',
'Escape'):
175 def _h_callback(k, x, y):
180 print(
" %-6s %s" % (k, doc.split(
"\n")[0]
if doc
else "???"))
184 Display._displays[frame] = self
187 """!Support for python's with statement""" 191 """!Support for python's with statement""" 198 """Return the attribute of self._impl, or ._impl if it is requested 202 name of the attribute requested 206 the attribute of self._impl for the requested name 210 return object.__getattr__(self, name)
212 if not (hasattr(self,
"_impl")
and self.
_impl):
213 raise AttributeError(
"Device has no _impl attached")
216 return getattr(self.
_impl, name)
217 except AttributeError:
218 raise AttributeError(
219 "Device %s has no attribute \"%s\"" % (self.
name, name))
222 if getattr(self,
"_impl",
None)
is not None:
227 if self.
frame in Display._displays:
228 del Display._displays[self.
frame]
232 """!The backend's verbosity""" 233 return self.
_impl.verbose
238 self.
_impl.verbose = value
241 return "Display[%s]" % (self.
frame)
249 _makeDisplayImpl(
None, backend)
250 except Exception
as e:
252 "Unable to set backend to %s: \"%s\"" % (backend, e))
254 Display._defaultBackend = backend
258 return Display._defaultBackend
262 """Set the default frame for display""" 263 Display._defaultFrame = frame
267 """Get the default frame for display""" 268 return Display._defaultFrame
272 """Increment the default frame for display""" 273 Display._defaultFrame += 1
274 return Display._defaultFrame
278 if hasattr(maskPlaneTransparency,
"copy"):
279 maskPlaneTransparency = maskPlaneTransparency.copy()
281 Display._defaultMaskTransparency = maskPlaneTransparency
285 """!Set the default mapping from mask plane names to colours 286 \param name name of mask plane, or a dict mapping names to colours 287 \param color Desired color, or None if name is a dict 289 If name is None, use the hard-coded default dictionary 293 name = Display._defaultMaskPlaneColor
295 if isinstance(name, dict):
297 for k, v
in name.items():
303 Display._defaultMaskPlaneColor[name] = color
306 def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kwargs):
307 """!Return the Display indexed by frame, creating it if needs be 309 \param frame The desired frame (None => use defaultFrame (see setDefaultFrame)) 310 \param backend create the specified frame using this backend (or the default if None) \ 311 if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame 312 \param create create the display if it doesn't already exist. 313 \param verbose Allow backend to be chatty 314 \param args arguments passed to Display constructor 315 \param kwargs keyword arguments passed to Display constructor 319 frame = Display._defaultFrame
321 if frame
not in Display._displays:
323 raise RuntimeError(
"Frame %s does not exist" % frame)
325 Display._displays[frame] =
Display(
326 frame, backend, verbose=verbose, *args, **kwargs)
328 Display._displays[frame].verbose = verbose
329 return Display._displays[frame]
333 """!Delete and close all known display 335 for disp
in list(Display._displays.values()):
337 Display._displays = {}
340 """!A generator for "standard" colours 342 \param omitBW Don't include Black and White 345 colorGenerator = interface.maskColorGenerator(omitBW=True) 347 print p, next(colorGenerator) 349 _maskColors = [WHITE, BLACK, RED, GREEN,
350 BLUE, CYAN, MAGENTA, YELLOW, ORANGE]
355 color = _maskColors[i%len(_maskColors)]
356 if omitBW
and color
in (BLACK, WHITE):
362 """!Request that mask plane name be displayed as color 364 \param name Name of mask plane or a dictionary of name -> colourName 365 \param color The name of the colour to use (must be None if name is a dict) 367 Colours may be specified as any X11-compliant string (e.g. <tt>"orchid"</tt>), or by one 368 of the following constants defined in \c afwDisplay: \c BLACK, \c WHITE, \c RED, \c BLUE, 369 \c GREEN, \c CYAN, \c MAGENTA, \c YELLOW. 371 If the colour is "ignore" (or \c IGNORE) then that mask plane is not displayed 373 The advantage of using the symbolic names is that the python interpreter can detect typos. 377 if isinstance(name, dict):
379 for k, v
in name.items():
386 """!Return the colour associated with the specified mask plane name 388 @param name Desired mask plane; if None, return entire dict 397 """!Specify display's mask transparency (percent); or None to not set it when loading masks""" 399 if isinstance(transparency, dict):
401 for k, v
in transparency.items():
405 if transparency
is not None and (transparency < 0
or transparency > 100):
407 "Mask transparency should be in the range [0, 100]; clipping", file=sys.stderr)
413 if transparency
is not None:
414 self.
_impl._setMaskTransparency(transparency, name)
417 """!Return the current display's mask transparency""" 419 return self.
_impl._getMaskTransparency(name)
422 """!Uniconify and Raise display. N.b. throws an exception if frame doesn't exit""" 423 return self.
_impl._show()
425 def mtv(self, data, title="", wcs=None):
426 """!Display an Image or Mask on a DISPLAY display 428 Historical note: the name "mtv" comes from Jim Gunn's forth imageprocessing 429 system, Mirella (named after Mirella Freni); The "m" stands for Mirella. 431 if hasattr(data,
"getXY0"):
432 self.
_xy0 = data.getXY0()
440 "You may not specify a wcs with an Exposure")
441 data, wcs = data.getMaskedImage(), data.getWcs()
444 self.
_xy0 = data.getXY0()
447 self.
_impl._mtv(data,
None, wcs, title)
454 self.
_impl._mtv(afwImage.ImageI(data.getArray()), data, wcs, title)
457 self.
_impl._mtv(data.getImage(), data.getMask(), wcs, title)
459 raise RuntimeError(
"Unsupported type %s" % repr(data))
465 """A class intended to be used with python's with statement""" 471 self.
_impl._buffer(
True)
474 self.
_impl._buffer(
False)
478 """Return a class intended to be used with python's with statement 480 with display.Buffering(): 481 display.dot("+", xc, yc) 486 """!Flush the buffers""" 490 """!Erase the specified DISPLAY frame 494 def dot(self, symb, c, r, size=2, ctype=None, origin=afwImage.PARENT, *args, **kwargs):
495 """!Draw a symbol onto the specified DISPLAY frame at (col,row) = (c,r) 496 [0-based coordinates] 503 @:Mxx,Mxy,Myy Draw an ellipse with moments (Mxx, Mxy, Myy) (argument size is ignored) 504 An object derived from afwGeom.ellipses.BaseCore Draw the ellipse (argument size is ignored) 505 Any other value is interpreted as a string to be drawn. Strings obey the fontFamily (which may be 506 extended with other characteristics, e.g. "times bold italic". Text will be drawn rotated by 507 textAngle (textAngle is ignored otherwise). 509 N.b. objects derived from BaseCore include Axes and Quadrupole. 511 if isinstance(symb, int):
514 if origin == afwImage.PARENT
and self.
_xy0 is not None:
519 if isinstance(symb, afwGeom.ellipses.BaseCore)
or re.search(
r"^@:", symb):
521 mat = re.search(
r"^@:([^,]+),([^,]+),([^,]+)", symb)
526 mxx, mxy, myy = [float(_)
for _
in mat.groups()]
529 symb = afwGeom.ellipses.Axes(symb)
531 self.
_impl._dot(symb, c, r, size, ctype, **kwargs)
533 def line(self, points, origin=afwImage.PARENT, symbs=False, ctype=None, size=0.5):
534 """!Draw a set of symbols or connect the points, a list of (col,row) 535 If symbs is True, draw points at the specified points using the desired symbol, 536 otherwise connect the dots. Ctype is the name of a colour (e.g. 'red') 538 If symbs supports indexing (which includes a string -- caveat emptor) the 539 elements are used to label the points 545 symbs = len(points)*
list(symbs)
547 for i, xy
in enumerate(points):
548 self.
dot(symbs[i], *xy, size=size, ctype=ctype)
551 if origin == afwImage.PARENT
and self.
_xy0 is not None:
553 _points =
list(points)
554 for i, p
in enumerate(points):
555 _points[i] = (p[0] - x0, p[1] - y0)
558 self.
_impl._drawLines(points, ctype)
563 def scale(self, algorithm, min, max=None, unit=None, *args, **kwargs):
564 """!Set the range of the scaling from DN in the image to the image display 565 \param algorithm Desired scaling (e.g. "linear" or "asinh") 566 \param min Minimum value, or "minmax" or "zscale" 567 \param max Maximum value (must be None for minmax|zscale) 568 \param unit Units for min and max (e.g. Percent, Absolute, Sigma; None if min==minmax|zscale) 569 \param *args Optional arguments 570 \param **kwargs Optional keyword arguments 572 if min
in (
"minmax",
"zscale"):
573 assert max
is None,
"You may not specify \"%s\" and max" % min
574 assert unit
is None,
"You may not specify \"%s\" and unit" % min
576 raise RuntimeError(
"Please specify max")
578 self.
_impl._scale(algorithm, min, max, unit, *args, **kwargs)
583 def zoom(self, zoomfac=None, colc=None, rowc=None, origin=afwImage.PARENT):
584 """!Zoom frame by specified amount, optionally panning also""" 586 if (rowc
and colc
is None)
or (colc
and rowc
is None):
588 "Please specify row and column center to pan about")
591 if origin == afwImage.PARENT
and self.
_xy0 is not None:
596 self.
_impl._pan(colc, rowc)
598 if zoomfac
is None and rowc
is None:
601 if zoomfac
is not None:
602 self.
_impl._zoom(zoomfac)
604 def pan(self, colc=None, rowc=None, origin=afwImage.PARENT):
605 """!Pan to (rowc, colc); see also zoom""" 607 self.
zoom(
None, colc, rowc, origin)
610 """!Enter an interactive loop, listening for key presses in display and firing callbacks. 611 Exit with q, \c CR, \c ESC, or any other callback function that returns a ``True`` value. 613 interactFinished =
False 615 while not interactFinished:
616 ev = self.
_impl._getEvent()
619 k, x, y = ev.k, ev.x, ev.y
622 logger.warn(
"No callback registered for {0}".format(k))
625 interactFinished = self.
_callbacks[k](k, x, y)
626 except Exception
as e:
628 "Display._callbacks['{0}']({0},{1},{2}) failed: {3}".format(k, x, y, e))
631 """!Set the callback for key k to be func, returning the old callback 638 "Key '%s' is already in use by display, so I can't add a callback for it" % k)
641 self.
_callbacks[k] = func
if func
else noop_callback
648 """!Return all callback keys 649 \param onlyActive If true only return keys that do something 653 not (onlyActive
and func == noop_callback)])
661 """!A class to handle events such as key presses in image display windows""" 663 def __init__(self, k, x=float(
'nan'), y=float(
'nan')):
669 return "%s (%.2f, %.2f)" % (self.
k, self.
x, self.
y)
676 """!Callback function: arguments key, x, y""" 681 print(
"Enter q or <ESC> to leave interactive mode, h for this help, or a letter to fire a callback")
692 Display.setDefaultBackend(backend)
696 return Display.getDefaultBackend()
700 return Display.setDefaultFrame(frame)
704 """Get the default frame for display""" 705 return Display.getDefaultFrame()
709 """Increment the default frame for display""" 710 return Display.incrDefaultFrame()
714 return Display.setDefaultMaskTransparency(maskPlaneTransparency)
718 """!Set the default mapping from mask plane names to colours 719 \param name name of mask plane, or a dict mapping names to colours 720 \param color Desired color, or None if name is a dict 722 If name is None, use the hard-coded default dictionary 725 return Display.setDefaultMaskPlaneColor(name, color)
728 def getDisplay(frame=None, backend=None, create=True, verbose=False, *args, **kwargs):
729 """!Return the Display indexed by frame, creating it if needs be 731 See Display.getDisplay 733 \param frame The desired frame (None => use defaultFrame (see setDefaultFrame)) 734 \param backend create the specified frame using this backend (or the default if None) \ 735 if it doesn't already exist. If backend == "", it's an error to specify a non-existent frame 736 \param create create the display if it doesn't already exist. 737 \param verbose Allow backend to be chatty 738 \param args arguments passed to Display constructor 739 \param kwargs keyword arguments passed to Display constructor 742 return Display.getDisplay(frame, backend, create, verbose, *args, **kwargs)
746 """!Delete and close all known display 748 return Display.delAllDisplays()
An ellipse core with quadrupole moments as parameters.
def pan(self, colc=None, rowc=None, origin=afwImage.PARENT)
Pan to (rowc, colc); see also zoom.
def dot(self, symb, c, r, size=2, ctype=None, origin=afwImage.PARENT, args, kwargs)
Draw a symbol onto the specified DISPLAY frame at (col,row) = (c,r) [0-based coordinates].
def maskColorGenerator(self, omitBW=True)
A generator for "standard" colours.
def verbose(self)
The backend's verbosity.
def getDisplay(frame=None, backend=None, create=True, verbose=False, args, kwargs)
Return the Display indexed by frame, creating it if needs be.
def noop_callback(k, x, y)
Callback function: arguments key, x, y.
std::vector< SchemaItem< Flag > > * items
A class to contain the data, WCS, and other information needed to describe an image of the sky...
def setDefaultMaskPlaneColor(name=None, color=None)
Set the default mapping from mask plane names to colours.
def __getattr__(self, name)
def setDefaultMaskTransparency(maskPlaneTransparency={})
def getDisplay(frame=None, backend=None, create=True, verbose=False, args, kwargs)
Return the Display indexed by frame, creating it if needs be.
def setCallback(self, k, func=None, noRaise=False)
Set the callback for key k to be func, returning the old callback.
def __init__(self, k, x=float('nan'), y=float('nan'))
def erase(self)
Erase the specified DISPLAY frame.
def flush(self)
Flush the buffers.
def delAllDisplays()
Delete and close all known display.
def getActiveCallbackKeys(self, onlyActive=True)
Return all callback keys.
A class to handle events such as key presses in image display windows.
Represent a 2-dimensional array of bitmask pixels.
def getMaskPlaneColor(self, name=None)
Return the colour associated with the specified mask plane name.
def setDefaultFrame(frame=0)
def setDefaultBackend(backend)
def __enter__(self)
Support for python's with statement.
def scale(self, algorithm, min, max=None, unit=None, args, kwargs)
Set the range of the scaling from DN in the image to the image display.
A class to manipulate images, masks, and variance as a single object.
def __init__(self, _impl)
def __init__(self, frame=None, backend=None, args, kwargs)
Create an object able to display images and overplot glyphs.
def mtv(self, data, title="", wcs=None)
Display an Image or Mask on a DISPLAY display.
std::shared_ptr< SkyWcs > makeSkyWcs(Point2D const &crpix, SpherePoint const &crval, Eigen::Matrix2d const &cdMatrix, std::string const &projection="TAN")
Construct a simple FITS SkyWcs with no distortion.
def __exit__(self, args)
Support for python's with statement.
def setDefaultMaskPlaneColor(name=None, color=None)
Set the default mapping from mask plane names to colours.
def line(self, points, origin=afwImage.PARENT, symbs=False, ctype=None, size=0.5)
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.
def setMaskPlaneColor(self, name, color=None)
Request that mask plane name be displayed as color.
def getMaskTransparency(self, name=None)
Return the current display's mask transparency.
def delAllDisplays()
Delete and close all known display.
def setDefaultBackend(backend)
def interact(self)
Enter an interactive loop, listening for key presses in display and firing callbacks.
daf::base::PropertyList * list
def setDefaultFrame(frame=0)
static Log getLogger(std::string const &loggername)
def setMaskTransparency(self, transparency=None, name=None)
Specify display's mask transparency (percent); or None to not set it when loading masks...
def zoom(self, zoomfac=None, colc=None, rowc=None, origin=afwImage.PARENT)
Zoom frame by specified amount, optionally panning also.
A class to represent a 2-dimensional array of pixels.
def setDefaultMaskTransparency(maskPlaneTransparency={})
A container for an Image and its associated metadata.
def show(self)
Uniconify and Raise display.