예제 #1
0
파일: pyds9.py 프로젝트: jberlanga/pyds9
def ds9_openlist(target='DS9:*', n=1024):
    """
    :param target: the ds9 target template (default: all ds9 instances)
    :param n: maximum number of targets to connect to (default: 1024)

    :rtype: list of connected ds9 objects

    To open multiple instances of ds9, use the ds9_openlist() routine. Specify
    the target template and an (optional) max target count, and the routine
    returns a list of ds9 objects. For example, assuming 3 instances of ds9
    are running with names foo1, foo2, foo3::

        >>> ds9list = ds9_openlist("foo*")
        >>> for d in ds9list:
        ...     print d.target, d.id
        ...
        DS9:foo1 a000104:56249
        DS9:foo2 a000104:56254
        DS9:foo3 a000104:56256
        >>> ds9list[1].set("file test.fits")

    """
    tlist = xpa.xpaaccess(target, None, n)
    if not tlist:
        raise ValueError, 'no active ds9 found for target: %s' % target
    else:
        ds9list = []
        for item in tlist:
            ds9list.append(ds9(item.split()[0]))
        return ds9list
예제 #2
0
파일: pyds9.py 프로젝트: bamford/pyds9
def ds9_openlist(target='DS9:*', n=1024):
    """
    :param target: the ds9 target template (default: all ds9 instances)
    :param n: maximum number of targets to connect to (default: 1024)

    :rtype: list of connected ds9 objects

    To open multiple instances of ds9, use the ds9_openlist() routine. Specify
    the target template and an (optional) max target count, and the routine
    returns a list of ds9 objects. For example, assuming 3 instances of ds9
    are running with names foo1, foo2, foo3::

        >>> ds9list = ds9_openlist("foo*")
        >>> for d in ds9list:
        ...     print d.target, d.id
        ...
        DS9:foo1 a000104:56249
        DS9:foo2 a000104:56254
        DS9:foo3 a000104:56256
        >>> ds9list[1].set("file test.fits")

    """
    tlist = xpa.xpaaccess(target, None, n)
    if not tlist:
        raise ValueError, 'no active ds9 found for target: %s' % target
    else:
        ds9list = []
        for item in tlist:
            ds9list.append(ds9(item.split()[0]))
        return ds9list
예제 #3
0
파일: pyds9.py 프로젝트: TESScience/pyds9
 def _selftest(self):
     """
     An internal test to make sure that ds9 is still running."
     """
     if self.verify and not xpa.xpaaccess(string_to_bytes(self.id), None,
                                          1):
         raise ValueError('ds9 is no longer running (%s)' % self.id)
예제 #4
0
 def _selftest(self):
     """
     An internal test to make sure that ds9 is still running."
     """
     if self.verify and not xpa.xpaaccess(string_to_bytes(self.id), None,
                                          1):
         raise ValueError('ds9 is no longer running (%s)' % self.id)
예제 #5
0
파일: pyds9.py 프로젝트: kuanghan/pyds9
def ds9_xpans():
    """
    :rtype: 0 => xpans already running, 1 => xpans started by this routine

    ds9_xpans() starts the xpans name server, if its not already running.
    If xpans was not running (and so was started by this routine) while ds9
    was already running, an explanation on how to connect to that instance
    of ds9 is displayed.
    """
    if xpa.xpaaccess(b"xpans", None, 1) is None:
        _cmd = False
        # look in install directories for xpans
        for _dir in sys.path:
            _fname = os.path.join(_dir, ds9Globals["progs"][0])
            if os.path.exists(_fname):
                _cmd = True
                break
        # look in development directory
        if not _cmd:
            _fname = os.path.join(os.path.dirname(__file__), 'xpa',
                                  ds9Globals["progs"][0])
            if os.path.exists(_fname):
                _cmd = True
        if _cmd:
            # start up xpans
            subprocess.Popen([_fname, "-e"])
            # if ds9 is already running, issue a warning
            p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE,
                                 universal_newlines=True)
            pslist = p.communicate()[0]   # get the std out
            if 'ds9' in pslist:
                print(tw.dedent("""
                    An instance of ds9 was found to be running before we could
                    start the 'xpans' name server. You will need to perform a
                    bit of manual intervention in order to connect this
                    existing ds9 to Python.

                    For ds9 version 5.7 and beyond, simply register the
                    existing ds9 with the xpans name server by selecting the
                    ds9 File->XPA->Connect menu option. Your ds9 will now be
                    fully accessible to pyds9 (e.g., it appear in the list
                    returned by the ds9_targets() routine).

                    For ds9 versions prior to 5.7, you cannot (easily) register
                    with xpans, but you can view ds9's File->XPA Information
                    menu option and pass the value associated with XPA_METHOD
                    directly to the Python DS9() constructor, e.g.:

                        d = DS9('a000101:12345')

                    The good news is that new instances of ds9 will be
                    registered with xpans, and will be known to ds9_targets()
                    and the DS9() constructor.
                    """))
            return 1
        else:
            raise ValueError("xpans is not running and cannot be located. You"
                             " will not be able to communicate with ds9")
    else:
        return 0
예제 #6
0
파일: pyds9.py 프로젝트: bamford/pyds9
    def access(self):
        """
        :rtype: xpa target name and id

        The 'access' method returns the xpa id of the current instance of ds9,
        by making a direct contact with ds9 itself.
        """
        self._selftest()
        x = xpa.xpaaccess(self.id, None, 1)
        return x[0]
예제 #7
0
파일: pyds9.py 프로젝트: jberlanga/pyds9
    def access(self):
        """
        :rtype: xpa target name and id

        The 'access' method returns the xpa id of the current instance of ds9,
        by making a direct contact with ds9 itself.
        """
        self._selftest()
        x = xpa.xpaaccess(self.id, None, 1)
        return x[0]
예제 #8
0
파일: pyds9.py 프로젝트: jberlanga/pyds9
def ds9_xpans():
    """
    :rtype: 0 => xpans already running, 1 => xpans started by this routine

    ds9_xpans() starts the xpans name server, if its not already running.
    If xpans was not running (and so was started by this routine) while ds9
    was already running, an explanation on how to connect to that instance
    of ds9 is displayed.
    """
    if xpa.xpaaccess("xpans", None, 1) == None:
        _cmd = False
        # look in install directories for xpans
        for _dir in sys.path:
            _fname = os.path.join(_dir, ds9Globals["progs"][0])
            if os.path.exists(_fname):
                _cmd = True
                break
        # look in development directory
        if not _cmd:
            _fname = './xpa/' + ds9Globals["progs"][0]
            if os.path.exists(_fname):
                _cmd = True
        if _cmd:
            # start up xpans
            subprocess.Popen([_fname, "-e"])
            # if ds9 is already running, issue a warning
            pslist = commands.getoutput('ps -A')
            if 'ds9' in pslist:
                print """
An instance of ds9 was found to be running before we could start the 'xpans'
name server. You will need to perform a bit of manual intervention in order
to connect this existing ds9 to Python.

For ds9 version 5.7 and beyond, simply register the existing ds9 with the xpans
name server by selecting the ds9 File->XPA->Connect menu option. Your ds9 will
now be fully accessible to pyds9 (e.g., it appear in the list returned by the
ds9_targets() routine).

For ds9 versions prior to 5.7, you cannot (easily) register with xpans,
but you can view ds9's File->XPA Information menu option and pass the value
associated with XPA_METHOD directly to the Python DS9() constructor, e.g.:

    d = DS9('a000101:12345')

The good news is that new instances of ds9 will be registered with xpans, and
will be known to ds9_targets() and the DS9() constructor.
"""
            return 1
        else:
            raise ValueError, "xpans is not running and cannot be located. You will not be able to communicate with ds9"
    else:
        return 0
예제 #9
0
파일: pyds9.py 프로젝트: TESScience/pyds9
def ds9_xpans():
    """
    :rtype: 0 => xpans already running, 1 => xpans started by this routine

    ds9_xpans() starts the xpans name server, if its not already running.
    If xpans was not running (and so was started by this routine) while ds9
    was already running, an explanation on how to connect to that instance
    of ds9 is displayed.
    """
    if xpa.xpaaccess(b"xpans", None, 1) is None:
        _fname = ds9Globals["progs"][0]
        if _fname:
            # start up xpans
            subprocess.Popen([_fname, "-e"])
            # if ds9 is already running, issue a warning
            p = subprocess.Popen(['ps', '-A'],
                                 stdout=subprocess.PIPE,
                                 universal_newlines=True)
            pslist = p.communicate()[0]  # get the std out
            if 'ds9' in pslist:
                print(
                    tw.dedent("""
                    An instance of ds9 was found to be running before we could
                    start the 'xpans' name server. You will need to perform a
                    bit of manual intervention in order to connect this
                    existing ds9 to Python.

                    For ds9 version 5.7 and beyond, simply register the
                    existing ds9 with the xpans name server by selecting the
                    ds9 File->XPA->Connect menu option. Your ds9 will now be
                    fully accessible to pyds9 (e.g., it appear in the list
                    returned by the ds9_targets() routine).

                    For ds9 versions prior to 5.7, you cannot (easily) register
                    with xpans, but you can view ds9's File->XPA Information
                    menu option and pass the value associated with XPA_METHOD
                    directly to the Python DS9() constructor, e.g.:

                        d = DS9('a000101:12345')

                    The good news is that new instances of ds9 will be
                    registered with xpans, and will be known to ds9_targets()
                    and the DS9() constructor.
                    """))
            return 1
        else:
            raise ValueError("xpans is not running and cannot be located. You"
                             " will not be able to communicate with ds9")
    else:
        return 0
예제 #10
0
파일: pyds9.py 프로젝트: bamford/pyds9
def ds9_targets(target='DS9:*'):
    """
    :param target: ds9 target template (default: all ds9 instances)

    :rtype: list of available targets matching template (name and id)

    To see all actively running ds9 instances for a given target, use the
    ds9_targets() routine::

      >>> ds9_targets()
      ['DS9:foo1 838e29d4:42873', 'DS9:foo2 838e29d4:35739']

    You then can pass one of the ids (or names) to the DS9() constructor.
    """
    return xpa.xpaaccess(target, None, 1024)
예제 #11
0
파일: pyds9.py 프로젝트: jberlanga/pyds9
def ds9_targets(target='DS9:*'):
    """
    :param target: ds9 target template (default: all ds9 instances)

    :rtype: list of available targets matching template (name and id)

    To see all actively running ds9 instances for a given target, use the
    ds9_targets() routine::

      >>> ds9_targets()
      ['DS9:foo1 838e29d4:42873', 'DS9:foo2 838e29d4:35739']

    You then can pass one of the ids (or names) to the DS9() constructor.
    """
    return xpa.xpaaccess(target, None, 1024)
예제 #12
0
파일: pyds9.py 프로젝트: bamford/pyds9
    def __init__(self, target='DS9:*', start=True, wait=10, verify=True):
        """
        :param target: the ds9 target name or id (default is all ds9 instances)
        :param start:  start ds9 if its not already running (optional: instead
         of True, you can specify a string or a list of ds9 command line args)
        :param wait: seconds to wait for ds9 to start
        :param verify: perform xpaaccess check before each set or get?

        :rtype: DS9 object connected to a single instance of ds9

        The DS9() contructor takes a ds9 target as its main argument. If start
        is True (default), the ds9 program will be started automatically if its
        not already running.

        The default target matches all ds9 instances. (Note that ds9 instances
        are given unique names using the -title switch on the command line). In
        general, this is the correct way to find ds9 if only one instance of the
        program is running. However, this default target will throw an error if
        more than one ds9 instance is running. In this case, you will be shown
        a list of the actively running programs and will be asked to use one of
        them to specify which ds9 is wanted::

          >>> DS9()
          More than one ds9 is running for target DS9:*:
          DS9:foo1 838e29d4:42873
          DS9:foo2 838e29d4:35739
          Use a specific name or id to construct a ds9 object, e.g.:
          d = ds9('foo1')
          d = ds9('DS9:foo1')
          d = ds9('838e29d4:42873')
          The 'ip:port' id (3rd example) will always be unique.
          ...
          ValueError: too many ds9 instances running for target: DS9:*

        You then can choose one of these to pass to the contructor::

           d = DS9('838e29d4:35739')

        Of course, you can always specify a name for this instance of ds9. A
        unique target name is especially appropriate if you want to start up
        ds9 with a specified command line. This is because pyds9 will start up
        ds9 only if a ds9 with the target name is not already running.

        If the verify flag is turned on, each ds9 method call will check whether
        ds9 is still running, and will throw an exception if this is not the
        case. Otherwise, the method return value can be used to detect failure.
        Using verification allows ds9 methods to used in try/except constructs,
        at the expense of a slight decrease in performance.
        """
        tlist = xpa.xpaaccess(target, None, 1024)
        if not tlist and start:
            if '?' in target or '*' in target:
                target = "ds9"
            try:
                args = shlex.split(start)
            except AttributeError:      # Not a parsable string-like object
                try:
                    args = list(start)
                except TypeError:       # Not an iterable object
                    args = []
            self.pid = subprocess.Popen([ds9Globals["progs"][1], '-title', target] + args)
            for i in range(wait):
                tlist = xpa.xpaaccess(target, None, 1024)
                if tlist: break
                time.sleep(1)
        if not tlist:
            raise ValueError, 'no active ds9 running for target: %s' % target
        elif len(tlist) > 1:
            a = tlist[0].split()
            if 'XPA_METHOD' in os.environ.keys():
                method = os.environ['XPA_METHOD']
            else:
                method = 'inet'
            if method == 'local' or method == 'unix':
                s = 'local file'
            else:
                s = 'ip:port'
            print 'More than one ds9 is running for target %s:' % target
            for l in tlist: print "  %s" % l
            print 'Use a specific name or id to construct a DS9 object, e.g.:'
            print "  d = DS9('%s')" % a[0].split()[0].split(':')[1]
            print "  d = DS9('%s')" % a[0]
            print "  d = DS9('%s')" % a[1]
            print "The '%s' id (3rd example) will always be unique.\n" % s
            raise ValueError, 'too many ds9 instances for target: %s' % target
        else:
            a = tlist[0].split()
            self.__dict__['target']  = target
            self.__dict__['id']  = a[1]
            self.verify = verify
        self.clear()
        self._wrap_per_frame_functions()
예제 #13
0
    def ds9(self, xpamsg=None, origin=None, new=True, **keywords):
        """
        Display the array using ds9.

        The ds9 process will be given an random id. By default, the
        following access point are set before the array is loaded:
            -cmap heat
            -scale scope local
            -scale mode 99.5
        Other access points can be set before the data is loaded though
        the keywords (see examples below).
        After the array is loaded, the map's header is set and the user
        may add other XPA messages through the xpamsg argument or by
        setting them through the returned ds9 instance.

        Parameters
        ----------
        xpamsg : string or tuple of string
            XPA access point message to be set after the array is loaded.
            (see http://hea-www.harvard.edu/RD/ds9/ref/xpa.html).
        origin: string
            Set origin to 'upper' for Y increasing downwards
        new: boolean
            If true, open the array in a new ds9 instance.
        **keywords : string or tuple of string
            Specify more access points to be set before array loading.
            a keyword such as 'height=400' will be appended to the command
            that launches ds9 in the form 'ds9 [...] -height 400'

        Returns
        -------
        The returned object is a ds9 instance. It can be manipulated using
        XPA access points.

        Examples
        --------
        >>> m = Map('myfits.fits')
        >>> d=m.ds9(('zoom to fit', 'saveimage png myfits.png'),
        ...         scale='histequ', cmap='invert yes', height=400)
        >>> d.set('exit')

        """
        try:
            import pyds9
        except ImportError:
            raise ImportError('The library pyds9 has not been installed.')
        import xpa

        id = None
        if not new:
            list = pyds9.ds9_targets()
            if list is not None:
                id = list[-1]

        if id is None:
            if 'cmap' not in keywords:
                keywords['cmap'] = 'heat'

            if 'scale' not in keywords:
                keywords['scale'] = ('scope local', 'mode 99.5')

            if origin is None:
                origin = getattr(self, 'origin', 'lower')
            if origin == 'upper' and 'orient' not in keywords:
                keywords['orient'] = 'y'

            wait = 10

            id_ = 'ds9_' + str(uuid.uuid1())[4:8]

            command = 'ds9 -title ' + id_

            for k, v in keywords.items():
                k = str(k)
                if type(v) is not tuple:
                    v = (v, )
                command += reduce(
                    lambda x, y: str(x) + ' -' + k + ' ' + str(y), v, '')

            os.system(command + ' &')

            # start the xpans name server
            if xpa.xpaaccess("xpans", None, 1) is None:
                _cmd = None
                # look in install directories
                for _dir in sys.path:
                    _fname = os.path.join(_dir, "xpans")
                    if os.path.exists(_fname):
                        _cmd = _fname + " -e &"
                if _cmd:
                    os.system(_cmd)

            for i in range(wait):
                list = xpa.xpaaccess(id_, None, 1024)
                if list is not None:
                    break
                time.sleep(1)
            if not list:
                raise ValueError('No active ds9 running for target: %s' % list)

        # get ds9 instance with given id
        d = pyds9.DS9(id_)

        # load array
        input = self.view(np.ndarray)
        if input.dtype.kind in ('b', 'i'):
            input = np.array(input, np.int32, copy=False)
        d.set_np2arr(input.T)

        # load header
        if self.has_wcs():
            d.set('wcs append', str(self.header))

        if xpamsg is not None:
            if isinstance(xpamsg, str):
                xpamsg = (xpamsg, )
            for v in xpamsg:
                d.set(v)

        return d
예제 #14
0
    def ds9(self, xpamsg=None, origin=None, new=True, **keywords):
        """
        Display the array using ds9.

        The ds9 process will be given an random id. By default, the
        following access point are set before the array is loaded:
            -cmap heat
            -scale scope local
            -scale mode 99.5
        Other access points can be set before the data is loaded though
        the keywords (see examples below).
        After the array is loaded, the map's header is set and the user
        may add other XPA messages through the xpamsg argument or by
        setting them through the returned ds9 instance.

        Parameters
        ----------
        xpamsg : string or tuple of string
            XPA access point message to be set after the array is loaded.
            (see http://hea-www.harvard.edu/RD/ds9/ref/xpa.html).
        origin: string
            Set origin to 'upper' for Y increasing downwards
        new: boolean
            If true, open the array in a new ds9 instance.
        **keywords : string or tuple of string
            Specify more access points to be set before array loading.
            a keyword such as 'height=400' will be appended to the command
            that launches ds9 in the form 'ds9 [...] -height 400'

        Returns
        -------
        The returned object is a ds9 instance. It can be manipulated using
        XPA access points.

        Examples
        --------
        >>> m = Map('myfits.fits')
        >>> d=m.ds9(('zoom to fit', 'saveimage png myfits.png'),
        ...         scale='histequ', cmap='invert yes', height=400)
        >>> d.set('exit')

        """
        try:
            import pyds9
        except ImportError:
            raise ImportError('The library pyds9 has not been installed.')
        import xpa

        id = None
        if not new:
            list = pyds9.ds9_targets()
            if list is not None:
                id = list[-1]

        if id is None:
            if 'cmap' not in keywords:
                keywords['cmap'] = 'heat'

            if 'scale' not in keywords:
                keywords['scale'] = ('scope local', 'mode 99.5')

            if origin is None:
                origin = getattr(self, 'origin', 'lower')
            if origin == 'upper' and 'orient' not in keywords:
                keywords['orient'] = 'y'

            wait = 10

            id_ = 'ds9_' + str(uuid.uuid1())[4:8]

            command = 'ds9 -title ' + id_

            for k, v in keywords.items():
                k = str(k)
                if type(v) is not tuple:
                    v = (v,)
                command += reduce(lambda x, y:
                                  str(x) + ' -' + k + ' ' + str(y), v, '')

            os.system(command + ' &')

            # start the xpans name server
            if xpa.xpaaccess("xpans", None, 1) is None:
                _cmd = None
                # look in install directories
                for _dir in sys.path:
                    _fname = os.path.join(_dir, "xpans")
                    if os.path.exists(_fname):
                        _cmd = _fname + " -e &"
                if _cmd:
                    os.system(_cmd)

            for i in range(wait):
                list = xpa.xpaaccess(id_, None, 1024)
                if list is not None:
                    break
                time.sleep(1)
            if not list:
                raise ValueError('No active ds9 running for target: %s' % list)

        # get ds9 instance with given id
        d = pyds9.DS9(id_)

        # load array
        input = self.view(np.ndarray)
        if input.dtype.kind in ('b', 'i'):
            input = np.array(input, np.int32, copy=False)
        d.set_np2arr(input.T)

        # load header
        if self.has_wcs():
            d.set('wcs append', str(self.header))

        if xpamsg is not None:
            if isinstance(xpamsg, str):
                xpamsg = (xpamsg,)
            for v in xpamsg:
                d.set(v)

        return d
예제 #15
0
파일: pyds9.py 프로젝트: jberlanga/pyds9
    def __init__(self, target='DS9:*', start=True, wait=10, verify=True):
        """
        :param target: the ds9 target name or id (default is all ds9 instances)
        :param start:  start ds9 if its not already running (optional: instead
         of True, you can specify a string or a list of ds9 command line args)
        :param wait: seconds to wait for ds9 to start
        :param verify: perform xpaaccess check before each set or get?

        :rtype: DS9 object connected to a single instance of ds9

        The DS9() contructor takes a ds9 target as its main argument. If start
        is True (default), the ds9 program will be started automatically if its
        not already running.

        The default target matches all ds9 instances. (Note that ds9 instances
        are given unique names using the -title switch on the command line). In
        general, this is the correct way to find ds9 if only one instance of the
        program is running. However, this default target will throw an error if
        more than one ds9 instance is running. In this case, you will be shown
        a list of the actively running programs and will be asked to use one of
        them to specify which ds9 is wanted::

          >>> DS9()
          More than one ds9 is running for target DS9:*:
          DS9:foo1 838e29d4:42873
          DS9:foo2 838e29d4:35739
          Use a specific name or id to construct a ds9 object, e.g.:
          d = ds9('foo1')
          d = ds9('DS9:foo1')
          d = ds9('838e29d4:42873')
          The 'ip:port' id (3rd example) will always be unique.
          ...
          ValueError: too many ds9 instances running for target: DS9:*

        You then can choose one of these to pass to the contructor::

           d = DS9('838e29d4:35739')

        Of course, you can always specify a name for this instance of ds9. A
        unique target name is especially appropriate if you want to start up
        ds9 with a specified command line. This is because pyds9 will start up
        ds9 only if a ds9 with the target name is not already running.

        If the verify flag is turned on, each ds9 method call will check whether
        ds9 is still running, and will throw an exception if this is not the
        case. Otherwise, the method return value can be used to detect failure.
        Using verification allows ds9 methods to used in try/except constructs,
        at the expense of a slight decrease in performance.
        """
        tlist = xpa.xpaaccess(target, None, 1024)
        if not tlist and start:
            if '?' in target or '*' in target:
                target = "ds9"
            try:
                args = shlex.split(start)
            except AttributeError:  # Not a parsable string-like object
                try:
                    args = list(start)
                except TypeError:  # Not an iterable object
                    args = []
            self.pid = subprocess.Popen(
                [ds9Globals["progs"][1], '-title', target] + args)
            for i in range(wait):
                tlist = xpa.xpaaccess(target, None, 1024)
                if tlist: break
                time.sleep(1)
        if not tlist:
            raise ValueError, 'no active ds9 running for target: %s' % target
        elif len(tlist) > 1:
            a = tlist[0].split()
            if 'XPA_METHOD' in os.environ.keys():
                method = os.environ['XPA_METHOD']
            else:
                method = 'inet'
            if method == 'local' or method == 'unix':
                s = 'local file'
            else:
                s = 'ip:port'
            print 'More than one ds9 is running for target %s:' % target
            for l in tlist:
                print "  %s" % l
            print 'Use a specific name or id to construct a DS9 object, e.g.:'
            print "  d = DS9('%s')" % a[0].split()[0].split(':')[1]
            print "  d = DS9('%s')" % a[0]
            print "  d = DS9('%s')" % a[1]
            print "The '%s' id (3rd example) will always be unique.\n" % s
            raise ValueError, 'too many ds9 instances for target: %s' % target
        else:
            a = tlist[0].split()
            self.__dict__['target'] = target
            self.__dict__['id'] = a[1]
            self.verify = verify