22__all__ = [
"Ds9Error",
"getXpaAccessPoint",
"ds9Version",
"Buffer",
23 "selectFrame",
"ds9Cmd",
"initDS9",
"Ds9Event",
"DisplayImpl"]
33import lsst.afw.display.interface
as interface
34import lsst.afw.display.virtualDevice
as virtualDevice
35import lsst.afw.display.ds9Regions
as ds9Regions
38 from .
import xpa
as xpa
39except ImportError
as e:
40 print(f
"Cannot import xpa: {e}", file=sys.stderr)
42import lsst.afw.display
as afwDisplay
43import lsst.afw.math
as afwMath
52 """Represents an error communicating with DS9.
59 _maskTransparency =
None
63 """Parse XPA_PORT if set and return an identifier to send DS9 commands.
68 xpaAccessPoint : `str`
69 Either a reference to the local host with the configured port, or the
74 If you don't have XPA_PORT set, the usual xpans tricks will be played
75 when we return ``"ds9"``.
77 xpa_port = os.environ.get(
"XPA_PORT")
79 mat = re.search(
r"^DS9:ds9\s+(\d+)\s+(\d+)", xpa_port)
81 port1, port2 = mat.groups()
83 return f
"127.0.0.1:{port1}"
85 print(f
"Failed to parse XPA_PORT={xpa_port}", file=sys.stderr)
91 """Get the version of DS9 in use.
96 Version of DS9 in use.
99 v =
ds9Cmd(
"about", get=
True)
100 return v.splitlines()[1].split()[1]
101 except Exception
as e:
102 print(f
"Error reading version: {e}", file=sys.stderr)
110 XPA_SZ_LINE = 4096 - 100
113 """Buffer to control sending commands to DS9.
117 The usual usage pattern is:
119 >>> with ds9.Buffering():
120 ... # bunches of ds9.{dot,line} commands
122 ... # bunches more ds9.{dot,line} commands
132 def set(self, size, silent=True):
133 """Set the ds9 buffer size to size.
138 Size of buffer. Requesting a negative size provides the
139 largest possible buffer given bugs in xpa.
140 silent : `bool`, optional
141 Do not print error messages (default `True`).
144 size = XPA_SZ_LINE - 5
146 if size > XPA_SZ_LINE:
147 print(
"xpa silently hardcodes a limit of %d for buffer sizes (you asked for %d) " %
148 (XPA_SZ_LINE, size), file=sys.stderr)
157 self.
flush(silent=silent)
160 """Get the current DS9 buffer size.
170 """Replace current DS9 command buffer size.
174 size : `int`, optional
175 Size of buffer. A negative value sets the largest possible
182 self.
flush(silent=
True)
184 self.
set(size, silent=
True)
187 """Switch back to the previous command buffer size.
193 self.
flush(silent=
True)
199 """Flush the pending commands.
203 silent : `bool`, optional
204 Do not print error messages.
206 ds9Cmd(flush=
True, silent=silent)
212 """Convert integer frame number to DS9 command syntax.
223 return f
"frame {frame}"
226def ds9Cmd(cmd=None, trap=True, flush=False, silent=True, frame=None, get=False):
227 """Issue a DS9 command, raising errors as appropriate.
231 cmd : `str`, optional
233 trap : `bool`, optional
235 flush : `bool`, optional
237 silent : `bool`, optional
238 Do not print trapped error messages.
239 frame : `int`, optional
240 Frame number on which to execute command.
241 get : `bool`, optional
247 if frame
is not None:
248 cmd = f
"{selectFrame(frame)};{cmd}"
255 if cmdBuffer._lenCommands + len(cmd) > XPA_SZ_LINE - 5:
256 ds9Cmd(flush=
True, silent=silent)
258 cmdBuffer._commands +=
";" + cmd
259 cmdBuffer._lenCommands += 1 + len(cmd)
261 if flush
or cmdBuffer._lenCommands >= cmdBuffer._getSize():
262 cmd = (cmdBuffer._commands +
"\n")
263 cmdBuffer._commands =
""
264 cmdBuffer._lenCommands = 0
278 raise Ds9Error(f
"XPA: {e}, ({cmd})")
280 print(f
"Caught ds9 exception processing command \"{cmd}\": {e}", file=sys.stderr)
288 execDs9 : `bool`, optional
289 If DS9 is not running, attempt to execute it.
293 ds9Cmd(
"iconify no; raise",
False)
301 needShow = (int(v1) <= 4)
304 except Ds9Error
as e:
305 if not re.search(
'xpa', os.environ[
'PATH']):
306 raise Ds9Error(
'You need the xpa binaries in your path to use ds9 with python')
311 if not shutil.which(
"ds9"):
312 raise NameError(
"ds9 doesn't appear to be on your path")
313 if "DISPLAY" not in os.environ:
314 raise RuntimeError(
"$DISPLAY isn't set, so I won't be able to start ds9 for you")
316 print(f
"ds9 doesn't appear to be running ({e}), I'll try to exec it for you")
324 print(
"waiting for ds9...\r", end=
"")
337 """An event generated by a mouse or key click on the display.
341 interface.Event.__init__(self, k, x, y)
345 """Virtual device display implementation.
348 def __init__(self, display, verbose=False, *args, **kwargs):
349 virtualDevice.DisplayImpl.__init__(self, display, verbose)
352 """Called when the device is closed.
357 """Specify DS9's mask transparency.
362 Percent transparency.
363 maskplane : `NoneType`
364 If `None`, transparency is enabled. Otherwise, this parameter is
367 if maskplane
is not None:
368 print(f
"ds9 is unable to set transparency for individual maskplanes ({maskplane})",
371 ds9Cmd(f
"mask transparency {transparency}", frame=self.display.frame)
374 """Return the current DS9's mask transparency.
379 This parameter does nothing.
382 return float(
ds9Cmd(
"mask transparency", get=
True))
385 """Uniconify and raise DS9.
389 Raises if ``self.display.frame`` doesn't exist.
391 ds9Cmd(
"raise", trap=
False, frame=self.display.frame)
393 def _mtv(self, image, mask=None, wcs=None, title=""):
394 """Display an Image and/or Mask on a DS9 display.
398 image : subclass of `lsst.afw.image.Image`
400 mask : subclass of `lsst.afw.image.Mask`, optional
402 wcs : `lsst.afw.geom.SkyWcs`, optional
404 title : `str`, optional
412 print(
"waiting for ds9...\r", end=
"")
426 _i_mtv(image, wcs, title,
False)
429 maskPlanes = mask.getMaskPlaneDict()
430 nMaskPlanes = max(maskPlanes.values()) + 1
433 for key
in maskPlanes:
434 planes[maskPlanes[key]] = key
436 planeList = range(nMaskPlanes)
437 usedPlanes = int(afwMath.makeStatistics(mask, afwMath.SUM).getValue())
438 mask1 = mask.Factory(mask.getBBox())
440 colorGenerator = self.display.maskColorGenerator(omitBW=
True)
445 if not ((1 << p) & usedPlanes):
451 color = self.display.getMaskPlaneColor(pname)
454 color = next(colorGenerator)
455 elif color.lower() ==
"ignore":
458 ds9Cmd(f
"mask color {color}")
459 _i_mtv(mask1, wcs, title,
True)
465 """Push and pop buffer size.
469 enable : `bool`, optional
470 If `True` (default), push size; else pop it.
483 """Erase all regions in current frame.
485 ds9Cmd(
"regions delete all", flush=
True, frame=self.display.frame)
487 def _dot(self, symb, c, r, size, ctype, fontFamily="helvetica", textAngle=None):
488 """Draw a symbol onto the specified DS9 frame.
492 symb : `str`, or subclass of `lsst.afw.geom.ellipses.BaseCore`
493 Symbol to be drawn. Possible values are:
495 - ``"+"``: Draw a "+"
496 - ``"x"``: Draw an "x"
497 - ``"*"``: Draw a "*"
498 - ``"o"``: Draw a circle
499 - ``"@:Mxx,Mxy,Myy"``: Draw an ellipse with moments (Mxx, Mxy,
500 Myy);(the ``size`` parameter is ignored)
501 - An object derived from `lsst.afw.geom.ellipses.BaseCore`: Draw
502 the ellipse (argument size is ignored)
504 Any other value is interpreted as a string to be drawn.
506 Column to draw symbol [0-based coordinates].
508 Row to draw symbol [0-based coordinates].
512 the name of a colour (e.g. ``"red"``)
513 fontFamily : `str`, optional
514 String font. May be extended with other characteristics,
515 e.g. ``"times bold italic"``.
516 textAngle: `float`, optional
517 Text will be drawn rotated by ``textAngle``.
521 Objects derived from `lsst.afw.geom.ellipses.BaseCore` include
522 `~lsst.afw.geom.ellipses.Axes` and `lsst.afw.geom.ellipses.Quadrupole`.
525 for region
in ds9Regions.dot(symb, c, r, size, ctype, fontFamily, textAngle):
526 cmd += f
'regions command {{{region}}}; '
531 """Connect the points.
535 points : `list` of (`int`, `int`)
536 A list of points specified as (col, row).
538 The name of a colour (e.g. ``"red"``).
541 for region
in ds9Regions.drawLines(points, ctype):
542 cmd += f
'regions command {{{region}}}; '
546 def _scale(self, algorithm, min, max, unit, *args, **kwargs):
547 """Set image color scale.
551 algorithm : {``"linear"``, ``"log"``, ``"pow"``, ``"sqrt"``, ``"squared"``, ``"asinh"``, ``"sinh"``, ``"histequ"``} # noqa: E501
552 Scaling algorithm. May be any value supported by DS9.
554 Minimum value for scale.
556 Maximum value for scale.
565 ds9Cmd(f
"scale {algorithm}", frame=self.display.frame)
567 if min
in (
"minmax",
"zscale"):
568 ds9Cmd(f
"scale mode {min}")
571 print(f
"ds9: ignoring scale unit {unit}")
573 ds9Cmd(f
"scale limits {min:g} {max:g}", frame=self.display.frame)
579 """Zoom frame by specified amount.
587 cmd += f
"zoom to {zoomfac}; "
597 Physical column to which to pan.
599 Physical row to which to pan.
603 cmd += f
"pan to {colc + 1:g} {rowc + 1:g} physical; "
608 """Listen for a key press on a frame in DS9 and return an event.
613 Event with (key, x, y).
615 vals =
ds9Cmd(
"imexam key coordinate", get=
True).split()
616 if vals[0] ==
"XPA$ERROR":
617 if vals[1:4] == [
'unknown',
'option',
'"-state"']:
620 print(
"Error return from imexam:",
" ".join(vals), file=sys.stderr)
638 haveGzip =
not os.system(
"gzip < /dev/null > /dev/null 2>&1")
642 """Internal routine to display an image or a mask on a DS9 display.
646 data : Subclass of `lsst.afw.image.Image` or `lsst.afw.image.Mask`
648 wcs : `lsst.afw.geom.SkyWcs`
655 title = str(title)
if title
else ""
658 xpa_cmd = f
"xpaset {getXpaAccessPoint()} fits mask"
662 if data.getArray().dtype == np.uint16:
665 xpa_cmd = f
"xpaset {getXpaAccessPoint()} fits"
668 xpa_cmd =
"gzip | " + xpa_cmd
670 pfd = os.popen(xpa_cmd,
"w")
672 ds9Cmd(flush=
True, silent=
True)
675 afwDisplay.writeFitsImage(pfd.fileno(), data, wcs, title)
676 except Exception
as e:
set(self, size, silent=True)
_getMaskTransparency(self, maskplane)
__init__(self, display, verbose=False, *args, **kwargs)
_drawLines(self, points, ctype)
_buffer(self, enable=True)
_scale(self, algorithm, min, max, unit, *args, **kwargs)
_dot(self, symb, c, r, size, ctype, fontFamily="helvetica", textAngle=None)
_setMaskTransparency(self, transparency, maskplane)
_mtv(self, image, mask=None, wcs=None, title="")
ds9Cmd(cmd=None, trap=True, flush=False, silent=True, frame=None, get=False)
_i_mtv(data, wcs, title, isMask)