예제 #1
0
파일: tpvp.py 프로젝트: janecekp/rts2
    def __run(self, tarf_ra, tarf_dec, pm_ra, pm_dec, timeout, modelname,
              maxspiral, imagescript, mn, useDS9):
        import ds9
        d = None
        if useDS9:
            d = ds9.ds9('Model')

        self.j.executeCommand(
            self.telescope,
            _('move_pm {0} {1} {2} {3}').format(tarf_ra, tarf_dec, pm_ra,
                                                pm_dec))
        time.sleep(2)
        self.j.refresh(self.telescope)
        tmout = 120

        tel = self.j.getValue(self.telescope, 'TEL', True)
        hrz = self.j.getValue(self.telescope, 'TEL_')
        while tmout > 0 and self.j.getState(
                self.telescope) & 0x01000020 == 0x01000000:
            self.j.refresh(self.telescope)
            tel = self.j.getValue(self.telescope, 'TEL')
            hrz = self.j.getValue(self.telescope, 'TEL_')
            print _(
                'moving to {0:.4f} {1:.4f}...at {2:.4f} {3:.4f} HRZ {4:.4f} {5:.4f}\r'
            ).format(tarf_ra, tarf_dec, tel['ra'], tel['dec'], hrz['alt'],
                     hrz['az']),
            sys.stdout.flush()
            time.sleep(1)
            tmout -= 1

        if tmout <= 0:
            print _(
                'destination not reached, continue with new target                         '
            )
            return None, None

        self.__wait(self.sleeptime)

        print _(
            'moved to {0:.4f} {1:.4f}...at {2:.4f} {3:.4f} HRZ {4:.4f} {5:.4f}                      '
        ).format(tarf_ra, tarf_dec, tel['ra'], tel['dec'], hrz['alt'],
                 hrz['az'])
        if imagescript is not None:
            print _('taking script {0}').format(imagescript)
            fn = 'model_{0:03}.fits'.format(mn)
            os.system(
                "rts2-scriptexec --reset -d {0} -s '{1}' -e '{2}'".format(
                    self.camera, imagescript, fn))
            if d is not None:
                try:
                    d.set('file {0}'.format(fn))
                except Exception, ex:
                    d = ds9.ds9()
                    d.set('file {0}'.format(fn))
            return fn, mn
예제 #2
0
def ds9display(filename):
    targs = ds9.ds9_targets()
    if targs is None:
        # Open a new ds9 window
        d = ds9.ds9(start=True)
    else:
        # Default grab the first ds9 instance
        d = ds9.ds9(targs[0])
    d.set('file ' + filename)
    d.set('zoom to fit')
    d.set('zscale')
    d.set("zscale contrast 0.1")
예제 #3
0
def ds9display(filename):
    targs = ds9.ds9_targets()
    if targs is None:
        # Open a new ds9 window
        d = ds9.ds9(start=True)
    else:
        # Default grab the first ds9 instance
        d = ds9.ds9(targs[0])
    d.set('file ' + filename)
    d.set('zoom to fit')
    d.set('zscale')
    d.set("zscale contrast 0.1")
예제 #4
0
파일: displayable.py 프로젝트: R136a1-/MOP
    def __init__(self, cutout_grid):
        super(DisplayableImageTriplet, self).__init__()

        if cutout_grid.shape != (3, 3):
            raise ValueError("Must be a 3 by 3 grid (was given %d by %d)"
                             % (cutout_grid.shape[0], cutout_grid.shape[1]))

        self.cutout_grid = cutout_grid

        d  = ds9.ds9('validate')
        d.set('frame delete all')
        d.set('tile yes')
        d.set('tile grid layout 3 3')
        self.frames = []
        num_frames, num_times = cutout_grid.shape
        for frame_index in range(num_frames):
            frame = []
            for time_index in range(num_times):
                singlet = ImageSinglet(cutout_grid.get_hdulist(frame_index, time_index),
                                       self.figure,
                                       get_rect(cutout_grid.shape, frame_index, time_index,
                                                spacing=0))
                singlet.display_changed.connect(self.redraw)
                frame.append(singlet)

            self.frames.append(frame)
예제 #5
0
파일: brights.py 프로젝트: zguangyu/rts2
def find_brightest(fn, hdu, verbose = 0, useDS9 = False, cube = None):
	"""Find brightest star on the image. Returns tuple of X,Y,flux and ratio of the flux to the second brightest star."""
	s_objects = find_stars(fn, hdu, verbose, useDS9, cube)
	if len(s_objects) == 0:
		return None, None, None, None
	b_x = s_objects[0]['x']
	b_y = s_objects[0]['y']
	b_flux = s_objects[0]['flux']
	if verbose:
		print 'detected {0} objects'.format(len(s_objects))
		print 'brightest at {0:.2f} {1:.2f}'.format(b_x,b_y)
		if verbose > 1:
			for o in s_objects:
				print 'object {0}'.format(o)

	bb_flux = b_flux
	if len(s_objects) > 1:
		bb_flux = s_objects[1]['flux']
	if useDS9:
		import ds9
		d=ds9.ds9(__DS9)
		d.set('file {0}'.format(fn))
		d.set('regions','image; point({0},{1}) # point=cross 25, color=green'.format(b_x,b_y))
		if verbose > 1:
			w_flux = s_objects[-1]['flux']
			for o in s_objects[1:]:
				w = 1 + (o['flux'] - w_flux) / (bb_flux - w_flux)
				w = np.log(w)
				w = 20 * w
				w = w if w > 1 else 1
				d.set('regions','image; point({0},{1}) # point=cross {2},color=green'.format(o['x'],o['y'],int(w)))
	return b_x,b_y,b_flux,b_flux / bb_flux
예제 #6
0
def add_wcs(fn,
            asecpix,
            rotang,
            flip='',
            verbose=0,
            dss=False,
            useDS9=False,
            outfn='out.fits',
            save_regions=None,
            center=None):
    """Add WCS solution to the image."""
    import ds9
    d = None
    if useDS9 and (verbose or dss):
        d = ds9.ds9(__DS9)
        d.set('frame delete all')
        d.set('frame new')

    hdu = fits.open(fn)
    x, y, flux, flux_ratio = find_brightest(fn, hdu, verbose, useDS9)
    if x is None:
        return None, None, None, None
    b_ra = hdu[0].header['OBJRA']
    b_dec = hdu[0].header['OBJDEC']

    paoff = 0

    try:
        paoff = hdu[0].header['DER1.PA']
    except KeyError, ke:
        print 'cannot find DER1.PA, using defaults'
예제 #7
0
파일: displayable.py 프로젝트: R136a1-/MOP
    def show_image(self, colorbar=False):
        # start xpans if needed
        ds9.ds9_xpans()
        # start ds9 if need, or connect to existing
        display = ds9.ds9(target='validate')
        if self.frame_number is None:
            # display.set('frame delete all')
            display.set('frame new')
            display.set('scale zscale')
            display.set('cmap invert yes')
            f = StringIO()
            self.hdulist.writeto(f)
            f.flush()
            f.seek(0)
            hdulist = fits.open(f)
            for hdu in hdulist:
                del(hdu.header['PV*'])
            display.set_pyfits(hdulist)
            self.frame_number = display.get('frame frameno')
            display.set('frame center {}'.format(self.frame_number))
            display.set('zoom to fit')
            display.set('wcs align yes')
        display.set('frame frameno {}'.format(self.frame_number))

        self._interaction_context = InteractionContext(self)

        self.number_of_images_displayed += 1
예제 #8
0
def positions_of_stars_from_ds9(image_name, message, catalogue_name):
    # Display image
    d = ds9.ds9()
    d.set("file " + image_name)

    # Tell the user to select the regions
    answer = False
    while answer == False:
        window = myWindow(message)
        window.box()
        try:
            region = pyregion.parse(d.get("region"))
            answer = True
        except ValueError:  # No regions defined
                print "\n There is no region loaded in the image! \n"

    coords_RADEC = [cc.coord_list[0:2] for cc in region]

    #hdr = fits.getheader(image_name)
    #w = wcs.WCS(hdr)
    #coords_RADEC = w.all_pix2world(xyout,1)
    with open(catalogue_name, 'w') as fd:
        for reg in coords_RADEC:
            fd.write(" {0}  {1} \n".format(*reg))
    return region
예제 #9
0
def display( fitsfd ):
	"""
Display an single extension of MEF file in DS9 
	"""

	myDS9 = ds9()
	fname = fitsfd.filename()
	if fname is None:
		fname = tempfile.mktemp()+".fits"
		fitsfd.writeto(fname)
		fitsfd.close()

	fitsfd = fits.open(fname)
	if len(fitsfd) > 1:

		myDS9.set( "file mosaicimage {}".format(fname) )
		
	elif len(fitsfd) == 1:

		myDS9.set( "file {}".format(fname) )
		
	else:
		raise Exception( "could not display" )


	myDS9.set( "zoom to fit" )
	return fitsfd
예제 #10
0
def main():
    parser = argparse.ArgumentParser(description='Send regions to ds9')
    parser.add_argument('infile', type=str, help='[filename x y size]')

    args = parser.parse_args()

    d = ds9.ds9(target='pyds9')

    data = genfromtxt(args.infile,
                      names=['fname', 'x', 'y', 'rad'],
                      dtype=['a100', 'f8', 'f8', 'f8'],
                      autostrip=True)

    print 'Printing regions to %i frames' % len(data['fname'])
    for idx, dat in enumerate(data):
        d.set('frame %i' % (idx + 1))
        d.set('file %s' % dat['fname'])

        d.set('zscale')
        d.set('zoom to fit')

        d.set('regions command  "image; circle %f %f %f"' %
              (dat['x'], dat['y'], dat['rad']))
    d.set('match scale')
    d.set('match colorbar')
    d.set('frame 1')

    return 0
예제 #11
0
 def __init__(self,file_path=None):
     #if no path use gui to select image
     if file_path is None:
         file_path = tk.askopenfilename(filetypes=[('Fits Files',
                                                    ('*.fit','*.fits'))])
     self.data = fits.open(file_path)
     self.file_path = file_path
     self.XYinfo = []
     self.photo = []
     #start ds9
     self.ds9_class = ds9.ds9()
     self.ds9_class.set_pyfits(self.data)
     #set viewing and other options to ds9
     self.ds9_class.set('scale log')
     self.ds9_class.set('magnifier to fit')
     #make limits
     lower = self.data[0].data.mean() - self.data[0].data.std()
     upper = self.data[0].data.mean() + 3*self.data[0].data.std()
     self.ds9_class.set('scale limits %f %f'%(lower,upper))
     #make catolog of stars
     self._image = gui.ImgCat(self.file_path)
     self._image.makecat(verbose=False)
     self._image.makestarlist(verbose=False)
     for i in self._image.starlist:
         self.XYinfo.append([i.x, i.y])
         self.photo.append([i.flux, i.fwhm])
         #plot cat to ds9
         self.ds9_class.set('regions', 'physical;circle(%f %f %.0f)'%(
                 i.x, i.y,i.fwhm*3))
예제 #12
0
def visual():
	global windows,bands,root,d,def_dir
	
	def_dir = raw_input("Name of directory to save images in (Current Working Directory: D): ")
	while os.path.isdir(def_dir)==False:
		if def_dir=="D":
			break
		print "{0} does not exist".format(def_dir)
		def_dir=raw_input("Try another directory:  ")
	
	d = ds9.ds9(wait=10)
	d.set('regions delete all')
	d.set('mosaic wcs stripe82_60_2.fits')
	d.set('mosaic wcs stripe82_300_2.fits')
	d.set('zoom to fit')
	d.set('grid yes')
	d.set('grid axes no')
	d.set('wcs skyformat degrees')

	d.set('regions stripe82_title.reg')
	
	root = Tk()
	root.withdraw()
	s82_exist = [None]
	windows=[]
	bands=['T','r','far','mid','op','uv','x','save']
	newWindow("Stripe 82","200x260+50+300",bands[0],s82_exist)
	root.mainloop()
예제 #13
0
    def __init__(self, cutout_grid):
        super(DisplayableImageTriplet, self).__init__()

        if cutout_grid.shape != (3, 3):
            raise ValueError("Must be a 3 by 3 grid (was given %d by %d)"
                             % (cutout_grid.shape[0], cutout_grid.shape[1]))

        self.cutout_grid = cutout_grid

        d  = ds9.ds9('validate')
        d.set('frame delete all')
        d.set('tile yes')
        d.set('tile grid layout 3 3')
        self.frames = []
        num_frames, num_times = cutout_grid.shape
        for frame_index in range(num_frames):
            frame = []
            for time_index in range(num_times):
                singlet = ImageSinglet(cutout_grid.get_hdulist(frame_index, time_index),
                                       self.figure,
                                       get_rect(cutout_grid.shape, frame_index, time_index,
                                                spacing=0))
                singlet.display_changed.connect(self.redraw)
                frame.append(singlet)

            self.frames.append(frame)
예제 #14
0
def ini_ds9() : 
    d = ds9.ds9()
    #d.set('width 1280')
    #d.set('height 1024')
    d.set('tile')
    d.set('frame 2')
    return d
예제 #15
0
def startup():
	'''
	Purpose: initialize the list of global variables (params)
	'''

	global params
	lg.info("State %s" % (inspect.stack()[0][3]))
	lg.info(params)

	D = 0
	if len(sys.argv) == 2:
		displayName = sys.argv[1]
	else:
		displayName = "Autodisplay"

	D = ds9.ds9(displayName)

	params["ds9"] = D
	path = path_to_lastfile()
	params["current_file"] = path
	params["previous_file"] = path
	params["grating_mode"] = None
	params["zoom1"] = "to fit" # frame 1
	params["zoom2"] = "to fit" # frame 2

	mosaic.setDs9(D);
	mosaic.start();
예제 #16
0
파일: disptest.py 프로젝트: beevageeva/tobs
def displayImage(fitsfile):

    # Now open ds9 (this assumes no ds9 instance is yet running)
    d = ds9.ds9()

    iraf.display.setParam("image", fitsfile)
    iraf.display(mode="h")

    if saveImage:
        # Zoom to fit
        d.set('zoom to fit')

        # Change the colormap and scaling
        #d.set('cmap bb')
        #d.set('scale log')

        # Add a label
        #d.set('regions command {text 30 20 #text="Fun with pyds9" font="times 18 bold"}')

        # Now you can play in ds9 to your heart's content.
        # Check back to see what the current color scale is.
        #print d.get('scale')

        # Finally, save your completed image (including regions or labels)
        d.set('saveimage png %s2.png' % fitsfile)
        d.pid.terminate()
        time.sleep(2)
예제 #17
0
    def show_image(self, colorbar=False):
        # start xpans if needed
        ds9.ds9_xpans()
        # start ds9 if need, or connect to existing
        display = ds9.ds9(target='validate')
        if self.frame_number is None:
            # display.set('frame delete all')
            display.set('frame new')
            display.set('scale zscale')
            display.set('cmap invert yes')
            f = StringIO()
            self.hdulist.writeto(f)
            f.flush()
            f.seek(0)
            hdulist = fits.open(f)
            for hdu in hdulist:
                del(hdu.header['PV*'])
            display.set_pyfits(hdulist)
            f.close()
            del(hdulist)
            self.frame_number = display.get('frame frameno')
            display.set('frame center {}'.format(self.frame_number))
            display.set('zoom to fit')
            display.set('wcs align yes')
        display.set('frame frameno {}'.format(self.frame_number))

        self._interaction_context = InteractionContext(self)

        self.number_of_images_displayed += 1
예제 #18
0
def conv_reg_coords(f_in, f_img, f_out, fmt='ds9', sys='wcs', sky='fk5'):
    """Convert region file f_in to region f_out, w/ new system/sky

    Warning: does NOT check for overwriting!
    Warning: does NOT check format of input region file

    Inputs:
        f_in (str): input ds9 region file, fk5 coords
        f_img (str): input FITS file on which regions are defined
        f_out (str): output ds9 region file, phys coords
    **kwargs:
        fmt (str): region file format (ds9, ciao, ...)
        sys (str): coordinate system (wcs, physical, ...)
        sky (str): sky coordinates (fk5, fk4, galactic, ...)
                   Only used if sys = 'wcs'
    Output:
        None (f_out written to disk)
    """
    d = ds9.ds9()
    d.set('file ' + f_img)
    d.set('regions load ' + f_in)

    d.set('regions format {}'.format(fmt))
    d.set('regions system {}'.format(sys))
    if sys == 'wcs':
        d.set('regions sky {}'.format(sky))

    d.set('regions save ' + f_out)
    d.set('frame clear')  # In case of un-deletable regions
    d.set('exit')
    reload(ds9)  # Ad hoc fix
예제 #19
0
def main(argv=None):
    if argv is None: argv = sys.argv[1:]
    from optparse import OptionParser, OptionGroup

    usage = '%prog [OPTIONS] FILE1.fits [FILE2.fits ...]'
    usage += '\nPlot each file in a ds9 instance, with optional regions overplotted.'
    parser = OptionParser(usage)
    (opts,args) = parser.parse_args(argv)

    if len(args) == 0:
        parser.error('Need to pass some fits image files!')

    d = ds9.ds9()

    # TBD: just one file at a time for now.
    f = args[0]
    image = pyfits.open(f)[0].data
    d.set_np2arr(image)
    d.set('cmap b')
    d.set('scale log')
    d.set('scale limits 2000 20000')

    regfiles = '../data/sex/'+os.path.splitext(os.path.basename(f))[0]+'*.reg'
    regions = glob.glob(regfiles)
    for r in regions:
        d.set('regions load '+r)

    import pdb
    pdb.set_trace()
예제 #20
0
def take_and_show(camera):
    camera.photo()
    time.sleep(0.5)
    name = camera.save()
    time.sleep(0.5)
    viewer = ds9.ds9()
    to_show = im.open(name)
    viewer.set_np2arr(np.array(to_show))
예제 #21
0
def displayMosaic( fitsfd ):
	"""A taks to display the
	mosaic image in dataserver"""
	myDS9 = ds9()
	fname = fitsfd.filename()

	myDS9.set( "file mosaicimage {}".format(fname) )
	myDS9.set("zoom to fit")
	return fitsfd
예제 #22
0
파일: display.py 프로젝트: zkbt/MITTENS
 def __init__(self,name='general', **kwargs):
     Display.__init__(self, **kwargs)
     self.name = name.replace(' ','_')
     try:
         wait = 10
         self.speak( 'trying to open a new ds9 window called "{0}" (will wait up to {1:.0f} seconds)'.format(self.name, wait))
         self.window = pyds9.ds9(self.name,start=True,wait=wait,verify=True)
     except:
         self.speak('failed!'.format(self.name))
예제 #23
0
 def place_error_ellipse(self, x, y, a, b, pa, color='b'):
     """
     Draws an ErrorEllipse with the given dimensions.  Can not be moved later.
     """
     display = ds9.ds9(target='validate')
     # display.set('regions delete all')
     display.set('regions', 'image; ellipse({},{},{},{},{}'.format(x,y,a,b,pa+90))
     #self.error_ellipse = ErrEllipse(x, y, a, b, pa, color=color)
     #self.error_ellipse.add_to_axes(self.axes)
     self.display_changed.fire()
예제 #24
0
 def __init__(self, debug=False,  dataSxtr=None, logger=None):
     super(Ds9DisplayThread, self).__init__()
     self.debug = debug
     self.dataSxtr = dataSxtr
     self.logger = logger
     self.stoprequest = threading.Event()
     try:
         self.display = ds9()
     except Exception, e:
         self.logger.warn('__init__: forking ds9 failed:\n{0}'.format(e))
예제 #25
0
파일: displayable.py 프로젝트: R136a1-/MOP
 def place_error_ellipse(self, x, y, a, b, pa, color='b'):
     """
     Draws an ErrorEllipse with the given dimensions.  Can not be moved later.
     """
     display = ds9.ds9(target='validate')
     # display.set('regions delete all')
     display.set('regions', 'image; ellipse({},{},{},{},{}'.format(x,y,a,b,pa+90))
     #self.error_ellipse = ErrEllipse(x, y, a, b, pa, color=color)
     #self.error_ellipse.add_to_axes(self.axes)
     self.display_changed.fire()
예제 #26
0
 def __showds9__(self):
     """Show this frame using DS9 and array tools."""
     LOG.log(2,"Showing %s using DS9 and XPA" % self)
     import ds9
     _ds9 = ds9.ds9()
     _ds9.set("frame new")
     _ds9.set_np2arr(self())
     _ds9.set("zoom to fit")
     _ds9.set("scale log")
     _ds9.set("cmap sls")
예제 #27
0
 def __init__(self, debug=False, dataSxtr=None, logger=None):
     super(Ds9DisplayThread, self).__init__()
     self.debug = debug
     self.dataSxtr = dataSxtr
     self.logger = logger
     self.stoprequest = threading.Event()
     try:
         self.display = ds9()
     except Exception, e:
         self.logger.warn('__init__: forking ds9 failed:\n{0}'.format(e))
    def __init__(self, x=None, y=None, zoom=None):
        super(DS9, self).__init__()
        self.x = x if x is not None else 1024
        self.y = y if y is not None else 1024
        self.zoom = zoom if zoom is not None else 1

        self.logger.info("Constructing ds9 object, waiting for construction")
        self.ds9 = ds9.ds9()
        self.ds9.set('regions system wcs sky fk5 skyformat degrees')
        self.logger.info("ds9 object initialized")
예제 #29
0
    def displaycutout(self,i):
        d=ds9.ds9()
        d.set('frame delete all')
        nsa_parent=homedir+'research/LocalClusters/GalfitAnalysis/'+self.prefix+'/NSA/'+str(self.n.IAUNAME[i])+'-parent-'+str(self.n.PID[i])+'.fits'

        s='file new '+nsa_parent
        try:
            d.set(s)
        except:
            print 'problem opening parent image'
            print nas_parent
예제 #30
0
파일: arutils.py 프로젝트: adwasser/PYPIT
 def ds9plot(array):
     # Set up a ds9 instance
     d = ds9.ds9()
     # Load the image
     d.set_np2arr(array)
     # Zoom to fit
     d.set('zoom to fit')
     # Change the colormap and scaling
     d.set('cmap gray')
     d.set('scale log')
     null = raw_input("TEST PLOT GENERATED: Press enter to continue...")
     return
예제 #31
0
파일: wxred.py 프로젝트: beevageeva/tobs
	  def OnOpen(self,e):
				""" Open a file"""
				dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.OPEN)
				if dlg.ShowModal() == wx.ID_OK:
						self.filename = dlg.GetFilename()
						self.dirname = dlg.GetDirectory()
						imagename = os.path.join(self.dirname, self.filename)
						d = ds9.ds9()
						iraf.display.setParam("image", imagename)
						iraf.display(mode="h")
				
				dlg.Destroy()
def display_mosaic(fitsFile):
    fo = pyfits.open(fitsfile)

    q1 = fo[1].data
    q2 = fo[2].data
    q3 = fo[3].data
    q4 = fo[4].data

    d = ds9.ds9()

    d.set('frame delete all')
    d.set('frame frameno 1')
예제 #33
0
    def displaycutout(self, i):
        d = ds9.ds9()
        d.set('frame delete all')
        nsa_parent = homedir + 'research/LocalClusters/GalfitAnalysis/' + self.prefix + '/NSA/' + str(
            self.n.IAUNAME[i]) + '-parent-' + str(self.n.PID[i]) + '.fits'

        s = 'file new ' + nsa_parent
        try:
            d.set(s)
        except:
            print 'problem opening parent image'
            print nas_parent
예제 #34
0
파일: arutils.py 프로젝트: adwasser/PYPIT
 def ds9plot(array):
     # Set up a ds9 instance
     d = ds9.ds9()
     # Load the image
     d.set_np2arr(array)
     # Zoom to fit
     d.set('zoom to fit')
     # Change the colormap and scaling
     d.set('cmap gray')
     d.set('scale log')
     null = raw_input("TEST PLOT GENERATED: Press enter to continue...")
     return
예제 #35
0
파일: cli.py 프로젝트: alexrudy/pyobserver
 def get_ds9(self, target=None):
     """Open DS9"""
     target = self.__class__.__name__ if target is None else target
     try:
         import ds9 as pyds9
         ds9 = pyds9.ds9(target=target)
     except ImportError:
         raise
     except Exception:
         self.log.critical("Can't get to DS9! Try closing all open DS9 windows...")
         raise
     return ds9
예제 #36
0
def display_mosaic(fitsFile):
    fo = pyfits.open(fitsfile)

    q1 = fo[1].data
    q2 = fo[2].data
    q3 = fo[3].data
    q4 = fo[4].data

    d = ds9.ds9()

    d.set('frame delete all')
    d.set('frame frameno 1')
예제 #37
0
    def OnOpen(self, e):
        """ Open a file"""
        dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*",
                            wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            imagename = os.path.join(self.dirname, self.filename)
            d = ds9.ds9()
            iraf.display.setParam("image", imagename)
            iraf.display(mode="h")

        dlg.Destroy()
예제 #38
0
 def __init__(self, config=None):
     """
     Initializes a new connection. This will normally start DS9 running, if necessary,
     or else connect to a previously running instance of DS9. Any config commands provided
     in the optional cmds string will be sent. Separate multiple commands with semicolons.
     """
     import ds9
     self.display = ds9.ds9(start='-geometry 900x1000')
     # are we connecting to a previously running session?
     self.frames = int(self.get('frame frameno'))
     if self.frames == 1 and self.get('frame has fits') == 'no':
         self.frames = 0
     # set defaults for future frames
     self.config(config)
예제 #39
0
파일: testsextractor.py 프로젝트: RTS2/rts2
def measure(fn):
	s = Sextractor(fields=['X_IMAGE','Y_IMAGE','ALPHA_J2000','DELTA_J2000','ERRX2_IMAGE','ERRY2_IMAGE','MAG_BEST','FWHM_IMAGE'])
	s.runSExtractor(fn)

	print s.objects

	# plot on DS9
	d = ds9.ds9('test_sextractor')

	d.set('file ' + fn)
	for o in s.objects:
		print o
		d.set('regions','J2000; circle {0} {1} {2}p'.format(o[2],o[3],int(abs(o[6]))))
		d.set('regions','J2000; circle {0} {1} {2}p # color=red'.format(o[2],o[3],o[7]))
예제 #40
0
파일: display.py 프로젝트: deepzot/bashes
 def __init__(self,config=None):
     """
     Initializes a new connection. This will normally start DS9 running, if necessary,
     or else connect to a previously running instance of DS9. Any config commands provided
     in the optional cmds string will be sent. Separate multiple commands with semicolons.
     """
     import ds9
     self.display = ds9.ds9(start='-geometry 900x1000')
     # are we connecting to a previously running session?
     self.frames = int(self.get('frame frameno'))
     if self.frames == 1 and self.get('frame has fits') == 'no':
         self.frames = 0
     # set defaults for future frames
     self.config(config)
예제 #41
0
def conv_fk5_to_phys(f_in, f_img, f_out):
    """f_in (str) input ds9 region file, fk5 coords
    f_img (str) input FITS file on which regions are defined
    f_out (str) output ds9 region file, phys coords

    Warning: does NOT check for overwriting!
    """
    d = ds9.ds9()
    d.set('file ' + f_img)
    d.set('regions load ' + f_in)
    d.set('regions system physical')
    d.set('regions save ' + f_out)
    d.set('frame clear')  # In case of un-deletable regions
    d.set('exit')
    reload(ds9)  # Ad hoc fix
예제 #42
0
파일: obsimages.py 프로젝트: RTS2/rts2-gtk
	def runds9(self):
		if not DS9_AVAILABLE:
			return
		d = ds9.ds9('runtime')
		d.set('frame delete all')
		first = True
		for x in self.getSelected(0):
			d.set('frame new')
			d.set('file mosaicimage iraf {0}'.format(x))
			d.set('scale zscale')	
			d.set('zoom to fit')	
		d.set('tile mode grid')	
		d.set('tile')
		d.set('zoom to fit')
		d.set('match frames physical')
예제 #43
0
 def runds9(self):
     if not DS9_AVAILABLE:
         return
     d = ds9.ds9('runtime')
     d.set('frame delete all')
     first = True
     for x in self.getSelected(0):
         d.set('frame new')
         d.set('file mosaicimage iraf {0}'.format(x))
         d.set('scale zscale')
         d.set('zoom to fit')
     d.set('tile mode grid')
     d.set('tile')
     d.set('zoom to fit')
     d.set('match frames physical')
예제 #44
0
파일: displayable.py 프로젝트: R136a1-/MOP
    def place_marker(self, x, y, radius, colour="b"):
        """
        Draws a marker with the specified dimensions.  Only one marker can
        be on the image at a time, so any existing marker will be replaced.
        """
        display = ds9.ds9(target='validate')
        colour_string = {'r': 'red', 'b': 'blue'}.get(colour, 'green')
        display.set('regions', 'image; circle({},{},{}) # color={}'.format(x,y,radius,colour_string))

        #if self.marker is not None:
        #    self.marker.remove_from_axes(self.axes)
        #
        #self.marker = Marker(x, y, radius, colour=colour)
        #self.marker.add_to_axes(self.axes)

        self.display_changed.fire()
예제 #45
0
    def place_marker(self, x, y, radius, colour="b"):
        """
        Draws a marker with the specified dimensions.  Only one marker can
        be on the image at a time, so any existing marker will be replaced.
        """
        display = ds9.ds9(target='validate')
        colour_string = {'r': 'red', 'b': 'blue'}.get(colour, 'green')
        display.set('regions', 'image; circle({},{},{}) # color={}'.format(x,y,radius,colour_string))

        #if self.marker is not None:
        #    self.marker.remove_from_axes(self.axes)
        #
        #self.marker = Marker(x, y, radius, colour=colour)
        #self.marker.add_to_axes(self.axes)

        self.display_changed.fire()
예제 #46
0
def mask_from_ds9(image_name, message):
    # Display image
    d = ds9.ds9()
    d.set("file " + image_name)

    # Tell the user to select the regions
    answer = False
    while answer == False:
        window = myWindow(message)
        window.box()
        try:
            region = pyregion.parse(d.get("region"))
            answer = True
        except ValueError:  # No regions defined
            print "\n There is no region loaded in the image! \n"
    return region
예제 #47
0
파일: ds9_phot.py 프로젝트: wiai/agpy
def ds9_photometry(xpapoint):
    D = ds9.ds9(xpapoint)
    try:
        reg = pyregion.parse(D.get("regions selected -format ds9 -system wcs -sky fk5 -skyformat sexagesimal"))
    except Exception as ex:
        print ex
        raise ex
    pf = D.get_pyfits()
    ph = pyfits.PrimaryHDU(data=pf[0].data,header=pf[0].header)
    mask = reg.get_mask(ph)
    arr = pf[0].data
    wherenotnan = (arr == arr)
    mask = mask*wherenotnan
    hdr = pf[0].header
    try:
        wcs = pywcs.WCS(hdr.tostring())
    except AttributeError:
        wcs = pywcs.WCS(hdr)
    try:
        try:
            bmaj = float(hdr['BMAJ'])
            bmin = float(hdr['BMIN'])
        except KeyError:
            # VLA imfits
            bmin = None; bmaj = None
            for k,v in hdr.iteritems():
                if numpy.iterable(v) and "BMAJ" in v:
                    bmaj = float(v.split()[3])
                    bmin = float(v.split()[5])
            if bmin is None or bmaj is None:
                raise KeyError("BMIN and BMAJ not found")
        try:
            cd1 = wcs.wcs.cd[0,0]
            cd2 = wcs.wcs.cd[1,1]
        except AttributeError:
            cd1,cd2 = wcs.wcs.cdelt[:2]
        ppbeam = 2*numpy.pi*bmin*bmaj / abs(cd1*cd2) / (8*numpy.log(2))
        #print "CD1: %g  CD2: %g" % (cd1, cd2)
        sys.stdout.write( "BMAJ: %g  BMIN: %g  PPBEAM: %g   SUM/PPBEAM: %g\n" % (bmaj,bmin,ppbeam,arr[mask].sum()/ppbeam) )
    except KeyError:
        print "ds9_phot failed - check for BMAJ/BMIN in header"
        pass
    except Exception as inst:
        print "ds9_phot failed - not a header KeyError, something else"
        print inst.args
        pass
    return arr[mask].sum(),arr[mask].mean(),numpy.median(arr[mask]),arr[mask].std(),mask.sum()
예제 #48
0
def generate_dat_files(rspecs, datroot, bands, labels):
    """Start DS9 and iterate through bands/regions to save data"""
    d = ds9.ds9()
    d.set('rgb')
    d.set('rgb red')

    # Save plaintext projection data
    # Idea: minimize file (band) loading operations
    for fname, flab in zip(bands, labels):
        d.set('file ' + fname)  # Load a band
        for i in xrange(len(rspecs)):
            d.set('regions', rspecs[i])  # Load a region
            d.set('rgb red')  # Plot projection data
            dat_fname = '{0}_{1:02d}_band_{2}.dat'.format(datroot, i+1, flab)
            d.set('plot {0} save {1}'.format(d.get('plot'), dat_fname))
            d.set('regions delete all')
    d.set('exit')
예제 #49
0
def mk_regions(obsid, mode, ProcDir = '/Users/corcoran/research/WR140/Swift/data/2016',
               evtfile=''):
    """
    displays the cleaned events file (of the form sw<OBSID>xpc*po_cl.evt or sw<OBSID>xwt*po_cl.evt)
    and allows the user to display and adjust the region file

    uses a template region file stored in RegionDir; saves region to
        ProcDir/work/OBSID/xsel

    Note that region file templates must be named <something>_<src|bkg>_<pc|wt>.reg for source, bkg, regions
       in pc or wt mode


    :param obsid: observation id of form '00081901001'
    :param mode: either 'pc' or 'wt' for photon counting or windowed timing
    :param ProcDir: root processing directory
    :param RegionDir: location of region files
    :return:
    """
    from ds9 import ds9
    import glob
    import os
    obsid=obsid.strip()
    mode=mode.strip().lower()
    RegionDir = ProcDir+'/work/regions'
    if not evtfile:
        try:
            fname = "{0}/work/{1}/{2}/xsel/sw{1}x{2}*po_cl.evt".format(ProcDir,obsid,mode)
            evt = glob.glob(fname)[0]
        except:
            status= "{0} Not Found; returning".format(fname)
            sys.exit(status)
    else:
        evt=evtfile.strip()
    d = ds9('Reduce_XRT')
    #
    # first do the source regions
    #
    d.set('file '+evt)
    d.set('smooth')
    s = RegionDir+'/*src*'+mode+'.reg'
    try:
        sregion = glob.glob(s)[0]
    except Exception, errmsg:
        print "mk_regions: Problem getting region file like {0}".format(s)
        print errmsg
예제 #50
0
def generate_dat_files(rspecs, datroot, bands, labels):
    """Start DS9 and iterate through bands/regions to save data"""
    d = ds9.ds9()
    d.set('rgb')
    d.set('rgb red')

    # Save plaintext projection data
    # Idea: minimize file (band) loading operations
    for fname, flab in zip(bands, labels):
        d.set('file ' + fname)  # Load a band
        for i in xrange(len(rspecs)):
            d.set('regions', rspecs[i])  # Load a region
            d.set('rgb red')  # Plot projection data
            dat_fname = '{0}_{1:02d}_band_{2}.dat'.format(datroot, i+1, flab)
            d.set('plot {0} save {1}'.format(d.get('plot'), dat_fname))
            d.set('regions delete all')
    d.set('exit')
예제 #51
0
파일: LCSsfprop.py 프로젝트: rfinn/LCS
    def nozoo(self):

        try:
            d.set('frame delete all')
        except:
            d=ds9.ds9()

        names=self.n.NSAID[~self.zoo.match_flag & self.On24ImageFlag]
        index=[]
        for n in names:
            index.append(self.nsadict[n])
        for j in range(len(names)):
            i=index[j]
            print self.prefix, self.n.NSAID[i]
            s='file new '+homedir+'research/LocalClusters/GalfitAnalysis/'+self.prefix+'/NSA/'+self.prefix+'-'+str(self.n.NSAID[i])+'-parent-r.fits'
            d.set(s)
            d.set('zoom to fit')
            t=raw_input('hit any key to continue \n')
예제 #52
0
파일: plotDS9.py 프로젝트: astroPDR/PMAP
def plotDS9(image, frame=1, zscale=True, fit=True, ext=None, adjust=True,
            minLimZero=False, keepScale=False, scale=False, delete=False):
    ddd = ds9.ds9()

    if delete: ddd.set('frame delete all')
    ddd.set('frame ' + str(frame))

    if keepScale is True:
        zMin, zMax = map(float, ddd.get('scale limits').split())

    if adjust is True:
        ddd.set('cmap heat')
        ddd.set('cmap value 1. 0.5')
    ddd.set('file ' + os.path.realpath(image))

    if fit is True: ddd.set('zoom to fit')

    if keepScale is True:
        ddd.set('scale mode zscale')
        ddd.set('scale limits %f %f' % (zMin, zMax))
        zscale = False
        scale = False

    if zscale is True:
        ddd.set('scale mode zscale')
        ddd.set('zscale contrast .25')
        ddd.set('zscale sample 600')
        ddd.set('zscale line 120')
        ddd.set('scale linear')
        if minLimZero is True:
            zMin, zMax = map(float, ddd.get('scale limits').split())
            ddd.set('scale limits %f %f' % (0.0, zMax))

    if scale is not False:
        try:
            zMin = float(scale[0])
            zMax = float(scale[1])
        except:
            print 'Problem found parsing scale values'
            return
        ddd.set('scale limits %f %f' % (zMin, zMax))

    return
예제 #53
0
def measure(fn):
    s = Sextractor(fields=[
        'X_IMAGE', 'Y_IMAGE', 'ALPHA_J2000', 'DELTA_J2000', 'ERRX2_IMAGE',
        'ERRY2_IMAGE', 'MAG_BEST', 'FWHM_IMAGE'
    ])
    s.runSExtractor(fn)

    print s.objects

    # plot on DS9
    d = ds9.ds9('test_sextractor')

    d.set('file ' + fn)
    for o in s.objects:
        print o
        d.set('regions',
              'J2000; circle {0} {1} {2}p'.format(o[2], o[3], int(abs(o[6]))))
        d.set(
            'regions',
            'J2000; circle {0} {1} {2}p # color=red'.format(o[2], o[3], o[7]))
예제 #54
0
def display(datalist, regions=None):
    d = ds9.ds9()

    for idx, f in enumerate(datalist):
        d.set("frame %i" % (idx + 1))
        if isinstance(f, str):
            d.set("file %s" % f)
        elif isinstance(f, np.ndarray):
            d.set_np2arr(f, dtype=float)

        if regions is not None:
            for region in regions:
                d.set("regions load %s" % region)

        d.set("zscale")
        d.set("zoom to fit")

    d.set("match colorbar")
    d.set("match scale")
    d.set("frame 1")
    return
예제 #55
0
def main():
    parser = argparse.ArgumentParser(description='Generate regions from ds9')
    parser.add_argument('-o',dest='outfile',type=str, default=None,help='Output file.')

    args = parser.parse_args()
    
    d = ds9.ds9()

    frames = d.get('frame all').split()

    files = []
    coords = []
    print 'Loading regions from %i frames' % len(frames)
    for frame in frames:
        d.set('frame %s' % frame)
        regions = d.get('regions')
        try:
            r = pyregion.parse(regions)[0].coord_list
        except:
            continue
        files.append(d.get('file'))
        coords.append((r[0],r[1],r[2]))

    if len(coords) == 0:
        print 'No regions found'
        return 1

    if args.outfile == None:
        for fo,coo in zip(files,coords):
            print '%s\t%f\t%f\t%f' % (fo,coo[0],coo[1],coo[2])
        
    else:
        f = open(args.outfile,'w')
        for fo,coo in zip(files,coords):
            f.write('%s\t%f\t%f\t%f\n' % (fo,coo[0],coo[1],coo[2]))

        f.close()
    return 0
예제 #56
0
def find_brightest(fn, hdu, verbose=0, useDS9=False, cube=None):
    """Find brightest star on the image. Returns tuple of X,Y,flux and ratio of the flux to the second brightest star."""
    s_objects = find_stars(fn, hdu, verbose, useDS9, cube)
    if len(s_objects) == 0:
        return None, None, None, None
    b_x = s_objects[0]['x']
    b_y = s_objects[0]['y']
    b_flux = s_objects[0]['flux']
    if verbose:
        print 'detected {0} objects'.format(len(s_objects))
        print 'brightest at {0:.2f} {1:.2f}'.format(b_x, b_y)
        if verbose > 1:
            for o in s_objects:
                print 'object {0}'.format(o)

    bb_flux = b_flux
    if len(s_objects) > 1:
        bb_flux = s_objects[1]['flux']
    if useDS9:
        import ds9
        d = ds9.ds9(__DS9)
        d.set('file {0}'.format(fn))
        d.set(
            'regions',
            'image; point({0},{1}) # point=cross 25, color=green'.format(
                b_x, b_y))
        if verbose > 1:
            w_flux = s_objects[-1]['flux']
            for o in s_objects[1:]:
                w = 1 + (o['flux'] - w_flux) / (bb_flux - w_flux)
                w = np.log(w)
                w = 20 * w
                w = w if w > 1 else 1
                d.set(
                    'regions',
                    'image; point({0},{1}) # point=cross {2},color=green'.
                    format(o['x'], o['y'], int(w)))
    return b_x, b_y, b_flux, b_flux / bb_flux
예제 #57
0
from spectral_cube import SpectralCube

files = [
    "SgrB2_a_03_7M.CH3CN_5-4_3.image.pbcor.fits",
    "SgrB2_a_03_7M.H2CO615-616.image.pbcor.fits",
    "SgrB2_a_03_7M.H2CS303-202.image.pbcor.fits",
    "SgrB2_a_03_7M.H2CS321-220.image.pbcor.fits",
    "SgrB2_a_03_7M.H41a.image.pbcor.fits",
    "SgrB2_a_03_7M.HC3N.image.pbcor.fits",
    "SgrB2_a_03_7M.HCN.image.pbcor.fits",
    "SgrB2_a_03_7M.HCOp.image.pbcor.fits",
    "SgrB2_a_03_7M.HNC.image.pbcor.fits",
]

if 'dd' not in locals():
    dd = ds9.ds9(target='rgbstepped')

vrange = [-95, 135] * u.km / u.s

for fn in files:
    species = fn.split(".")[1]
    if 'CH3CN' in species:
        rest_value = 91987.094 * u.MHz
    else:
        rest_value = None
    cubeg = (SpectralCube.read(fn).with_spectral_unit(
        u.km / u.s, rest_value=rest_value,
        velocity_convention='radio').spectral_slab(vrange[0], vrange[1]))
    cuber = (SpectralCube.read(fn).with_spectral_unit(
        u.km / u.s, rest_value=rest_value,
        velocity_convention='radio').spectral_slab(vrange[0] + 3 * u.km / u.s,
예제 #58
0
        ]

    # Set display dimensions, pixels
    if args.height:
        height = args.height
    else:
        height = 500

    if args.width:
        width = args.width
    else:
        width = len(nccds) * height

    # Fire up ds9
    import ds9
    ds = ds9.ds9()
    ds.set('frame delete all')
    ds.set('width %d' % (width))
    ds.set('height %d' % (height))
    for i, nccd in enumerate(nccds):

        if mccd.head.value('Instrument.instrument') == 'ULTRACAM':
            ccd = mccd[nccd]
        else:
            ccd = mccd

        if nccd == 0:
            ccdname = 'Red CCD'
        elif nccd == 1:
            ccdname = 'Green CCD'
        elif nccd == 2: