def setup_ds9_connection(reconnect): """ Open a DS9 window. If DS9 already opened spawn a new instance """ # ds9_targets returns None if no ds9 window is opened ds9_running = pyds9.ds9_targets() if ds9_running: if reconnect and len(ds9_running) == 1: connectionstring = (ds9_running[0]).replace("DS9:ds9 ", "") d = pyds9.DS9(connectionstring) time.sleep(0.5) return d, connectionstring elif reconnect and len(ds9_running) != 1: print "Error: multiple ds9 instances running. Unknown which to connect to." exit(1) print "We see that ds9 is already running." sys.stdout.write("Opening a new ds9 window...") sys.stdout.flush() import os launch = os.system( "/Applications/SAOImage\ DS9.app/Contents/MacOS/ds9 &") del (os) time.sleep(3) if launch is 0: print " done" ds9_running_new = pyds9.ds9_targets() unique_entries = list(set(ds9_running_new) - set(ds9_running)) if len(unique_entries) == 1: connectionstring = unique_entries[0] connectionstring = connectionstring.replace("DS9:ds9 ", "") d = pyds9.DS9(connectionstring) time.sleep(0.5) else: exit(1) else: exit(1) else: print "No ds9 instance is running." sys.stdout.write("Opening a new ds9 window ...") sys.stdout.flush() d = pyds9.DS9() time.sleep(0.5) connectionstring = (pyds9.ds9_targets()[0]).replace("DS9:ds9 ", "") print " done" return d, connectionstring
def main(args): # List of commands: http://ds9.si.edu/doc/ref/command.html d, connectionstring = setup_ds9_connection(args.reconnect) header = "DS9 instance in object `d`:" header += " Connectionstring = {0}".format(connectionstring) if args.chandra: sys.stdout.write("\nRestoring ds9 backup of Lx lss and kT lss ...") sys.stdout.flush() lss = "/usr/local/mscproj/runs/ChandraObservation/ds9bck_Lx-lss_kT-lss/ds9.bck" lss_Lx = lss + ".dir/Frame1/cygnus_lss_fill_flux.fits" lss_kT = lss + ".dir/Frame2/working_spectra_kT_map.fits" Lx = pyfits.open(lss_Lx) kT = pyfits.open(lss_kT) header += "\nlss Lx instance in object 'Lx'" header += "\nlss kT instance in object 'kT'" header += "" if not args.reconnect: d.set("restore {0}".format(lss)) print " done" if args.filename: for i, fname in enumerate(args.filename): sys.stdout.write("\nOpening file '{0}' ...".format(fname)) sys.stdout.flush() if not args.reconnect: open_file(d, fname) if has_fits: f = "f{0}".format(i) exec("{0} = pyfits.open(fname)".format(f)) if "fits.fz" in fname: exec("{0}_header, {0}_data = psmac2_fitsfile(fname)". format(f)) exec( "{0}_pix2kpc = float({0}_header['XYSize'])/float({0}_header['XYPix'])" .format(f)) header += "\npyfits instance in object `{0}`".format(f) print " done" IPython.embed(banner1="", header=header) # Close the ds9 window if it is still open if pyds9.ds9_targets() and "DS9:ds9 {0}".format( connectionstring) in pyds9.ds9_targets(): d.set("exit")
def ds9(*instance): ''' Attach to a given ds9 instance or create a new one. ''' if not instance: targets = pyds9.ds9_targets() else: targets = [str(instance[0])] dsn = pyds9.DS9(targets[0]) if targets else pyds9.DS9() return dsn
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")
def get_ds9(i=-1): """ Get ds9 xpa target Parameters ---------- i : int Index of target in `~pyds9.ds9_targets` list. Returns ------- obj : `~grizli.ds9.DS9` DS9 object. """ import pyds9 targets = pyds9.ds9_targets() #print(targets) obj = DS9(target=targets[i].split()[-1]) return obj
def show_open_targets(): """ Summarize open ds9 targets """ import pyds9 import numpy as np targets = pyds9.ds9_targets() print('i target frame ra dec x y ') for i, target in enumerate(targets): targ = target.split()[-1] ds9 = DS9(target=targ) ra, dec = np.cast[float](ds9.get('pan fk5').split()) xi, yi = np.cast[float](ds9.get('pan image').split()) frame = ds9.get('frame') print( f'{i} {targ:14} {frame:>5} {ra:8.4f} {dec:8.4f} ({xi:5.0f} {yi:5.0f})' )
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
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
def XPA_DS9_Region_Generator(evtfilepath, fovfilepath): #THIS CODE IS UNTESTED, XPA_DS9_Region_Generator.py is the current working version of this code, Therefore it is not yet pushed to GitHub """ evtfilepath:-str, Event_Filename, The filepath of the Event 2 File fovfilepath:-str, Feild_Of_View_Filename, The filepath of the FOV 1 File This function take the Event 2 filename of the current observation and the Feild Of View filename of the current observation (Which are the CCD polygon regions) and opens both the evt2.fits file and the fov1.fits files in DS9 and saves the fov1.fits file as a text file with the regions in physical coordinates. In short this function converts the fov.fits files to indentical text files that can be used in the Simple_Region_Generator Code to create simple_region_no_header_modifed files that are used in the Area_Calc code """ print(pyds9.ds9_targets()) d = pyds9.DS9() # will open a new ds9 window or connect to an existing on #81853a27:55005 #The value for the #d = pyds9.DS9("81853a27:55005") #d.set("~/asantini/Desktop/CCD_Region_Testing/evtfname") # send the file to the open ds9 session #d.set("file /path/to/fits") # send the file to the open ds9 session #d.set(str(evtfname) + "~/asantini/Desktop/CCD_Region_Testing/evtfname") #d.set(str(evtfname)) #d.set(str(evtfname) + " ~/asantini/Desktop/CCD_Region_Testing/") #d.set("~/asantini/Desktop/CCD_Region_Testing/"+str(evtfname)) #d.set("/home/asantini/Desktop/XPA-DS9_Region_Generator/acisf03931_repro_evt2.fits") #d.set("acisf03931_repro_evt2.fits") #d.set(acisf03931_repro_evt2.fits) #d.set("DS9 acisf03931_repro_evt2.fits") #pyds9.DS9().set("acisf03931_repro_evt2.fits") #d.set("acisf03931_repro_evt2.fits") #d.set("acisf03931_repro_evt2.fits /path/to/fits") d.set("file " + str(evtfilepath)) #Opens the Event 2file in DS9 #THIS WORKS ! ! ! #d.get("regions acisf03931_repro_fov1.fits") #d.get("regions -load acisf03931_repro_fov1.fits") #acisf03931_repro_evt2.fits -regions acisf03931_repro_fov1.fits -regions system physical -regions save foo2 -exit #d.set("acisf03931_repro_evt2.fits -regions acisf03931_repro_fov1.fits -regions system physical -regions save foo2 -exit") #This only opens the fits file #d.get("-regions acisf03931_repro_fov1.fits") #d.set("-regions acisf03931_repro_fov1.fits") #d.set("regions acisf03931_repro_fov1.fits") #This works ! ! ! d.set("regions " + str(fovfilepath) ) #Loads the Feild Of View 1 file in DS9 #This Works ! ! ! d.set( "regions system physical" ) #This converts the region's coordinate system to physical coordinates (pixels) #This works ! ! ! #d.set("regions save foo2") #This works ! ! ! #CCD Regions print "evtfilepath ", evtfilepath print "fovfilepath ", fovfilepath fovfname_L = fovfilepath.split('/') print "fovfname_L ", fovfname_L fovfname = fovfname_L[len(fovfname_L) - 1] print "fovfname ", fovfname fovfname_Split_L = fovfname.split( '_' ) #fovfname_Split_L:-List, Feild_Of_View_Filename_Split_List, The resulting list of the split string regions of fovfname, The fovfname string was split on "_" print "fovfname_Split_L ", fovfname_Split_L #print "fovfname_Split_L ", fovfname_Split_L fovfname_reduced = fovfname_Split_L[0] + "_" + fovfname_Split_L[ 1] #fovfname_reduced:-str, Feild_Of_View_Filename_Reduced, The Feild_Of_View_Filename without the "_fov1.fits" part, for example the fovfname_reduced of the fovfname "acisf03931_repro_fov1.fits" is "acisf03931_repro" if '.' in fovfname_Split_L[1]: fovfname_reduced = fovfname_Split_L[0] print "fovfname_reduced ", fovfname_reduced #print "fovfname_reduced ", fovfname_reduced #print fovfname_reduced d.set( "regions save " + str(fovfname_reduced) + "_CCD_Regions" ) #Saves the FOV1.fits file as a text file in physical coordinates with the filename in the form of str(fovfname_reduced)+"_CCD_Regions", for example for "acisf03931_repro_fov1.fits" the output file name is "acisf03931_repro_CCD_Regions" d.set("exit") #Exits DS9 #This Works ! ! !
x_step, y_step = np.meshgrid(np.arange(x_start + delta_x/2, x_final + delta_x/2, delta_x), np.arange(y_start + delta_y/2, y_final + delta_y/2, delta_y)) # sum up the function evaluated at the steps, and multiply by the area of each step normalize1 = np.sum(moffat1(x_step, y_step))*delta_x*delta_y normalize2 = np.sum(moffat2(x_step, y_step))*delta_x*delta_y # forget that, just integrate it # normalize, norm_err = dblquad(moffat_fun, -np.inf, np.inf, lambda x: -np.inf, lambda x: np.inf) output = flux1*moffat1(x_in, y_in)/normalize1 + flux2*moffat2(x_in, y_in)/normalize2 return output.ravel() # check if ds9 is accesible if not pyds9.ds9_targets(): input('DS9 target not found. Please start/restart DS9, then press enter') # show the ds9 target print('ds9 target instance') print(pyds9.ds9_targets()) # create a DS9 object ds9 = pyds9.DS9() # import the current fits file loaded in DS9 hdu = ds9.get_pyfits() hdu.info() # import a list of region definitions
def __init__(self, name, fits_dir, regex, scale, zoom, verbose, info, vertical): # Constants and variables self.last_file = '' # Arguments self.name = name self.fits_dir = Path(fits_dir) self.regex = regex self.scale = scale self.zoom = zoom self.verbose = verbose self.info = info self.vertical = vertical hsh = hashlib.sha1(''.join(self.name + str(self.fits_dir) + self.regex + self.scale).encode()) self.ds9_target = '{}:{}'.format(self.name, hsh.hexdigest()[:6]) # self.ds9_target = 'ds9_live:{}'.format(os.getpid()) if self.verbose: print('dir = {}\nName = {}\nscale = {}\nzoom = {}'.format( self.fits_dir, self.name, self.scale, self.zoom)) # Initialize targets = pyds9.ds9_targets() if not targets: targets = [] for ds9 in targets: if self.name in ds9: print('A similar instance of ds9 is already running as {},' ' would you like to connect to it, close it, or create' ' another window with a new name?'.format(ds9)) action = input('[change]/close/connect: ') if ((action.lower() == 'connect') or (action.lower() == '')): self.name = ds9 elif action.lower() == 'close': d = pyds9.DS9(ds9) d.set('exit') else: print('Please provide a new name. This can also be done' ' via the -n argument:') self.name = input('>') if self.verbose: print(self.name) self.ds9 = pyds9.DS9(self.name) if '/data/spectro' in self.fits_dir.as_posix(): self.ds9.set('tile yes') if not self.info: self.ds9.set('view info no') self.ds9.set('view panner no') self.ds9.set('view magnifier no') self.ds9.set('view buttons no') if self.vertical: self.ds9.set('view layout vertical') self.ds9.set('view buttons no')
def main(args): # ds9_targets returns None if no ds9 window is opened # ds9_running = pyds9.ds9_targets() # if ds9_running: # print "ds9 is already running" # for instance in ds9_running: # targetid = instance.replace("DS9:", "") # d = pyds9.DS9(targetid) # print " instance =", targetid # while True: # close = raw_input(" Close [y/n]: ") # if close.lower() in "yn": # if close == "y": # d.set("exit") # break # else: # print " Invalid character" # else: # List of commands: http://ds9.si.edu/doc/ref/command.html if args.chandra: rundir = "/media/SURFlisa/runs/" mosaic = "ChandraObservation/StruisMosaics/mosaic/cygnus_tot_flux.fits" args.filename = rundir + mosaic d = pyds9.DS9() time.sleep(0.5) open_file(d, args.filename) d.set("preserve pan yes") d.set("preserve scale yes") print d.id print d.target header = "DS9 instance in object `d`" if has_fits: f = pyfits.open(args.filename) header += "\npyfits instance in object `f`" if "temperature" in args.filename: d.set("scale linear") d.set("scale limits 2e6 2e8") d.set("cmap bb") time.sleep(0.5) a = d.get_arr2np() d.set("frame new") kB = 8.6173427909e-08 # keV/K d.set_np2arr(a * kB) d.set("scale limits 0.1 9") if "xray" in args.filename: d.set("scale log") d.set("scale limits 2e-16 0.02") d.set("cmap sls") if "density" in args.filename: d.set("scale log") d.set("scale limits 2e-16 0.02") d.set("cmap sls") if "velocity" in args.filename: d.set("scale log") d.set("scale limits 1.1e7 2.2e8") d.set("cmap bb") d.set("scale mode User") # d.set("scale scope global") # takes forever # d.set("scale open") if "fits.fz" in args.filename: # Simulation # seems slow until al frames have been loaded at least once d.set("cube interval 0.125") d.set("cube play") #d.set("cube close") # d.set("cube 35") if "cygnus_tot_flux.fits" in args.filename: # Observation d.set("scale log") d.set("scale limits 7.0e-10 1.0e-6") d.set("cmap sls") d.set("smooth radius 9") d.set("smooth yes") d.set("zoom to fit") # contrast and bias d.set("cmap value 3.08889 0.30112") # default # d.set("cmap value 1 0.5") # reg = "/Users/timohalbesma/Desktop/TemperatureJump/Simulation/"+\ # "20160819T2357.reg" # d.set("regions load '{0}'".format(reg)) # This takes forever # fits = d.get_arr2np() # print fits.shape # print fits.dtype #pyplot.figure(figsize=(12,9)) #pyplot.imshow(fits[0], origin="lower") #pyplot.show() IPython.embed(banner1="", header=header) # Close the ds9 window if it is still open if pyds9.ds9_targets() and "DS9:{0} {1}".format( d.target, d.id) in pyds9.ds9_targets(): d.set("exit")
print('Finished.') exit(0) # d.close() if __name__ == "__main__": automode = False lstfn = sys.argv[1] try: fn = open(lstfn, 'r') except: sys.stderr.write('File open error. Abort.') files = [] for line in fn.readlines(): files.append(line.strip()) fn.close() ds9list = pyds9.ds9_targets() if ds9list == None: print "active ds9 not found. Abort." exit(1) print "%d ds9 windows found." % (len(ds9list)) print "use %s" % ds9list[0] d = pyds9.DS9(target=ds9list[0]) d.set('zoom to fit') d.set('scale zscale') showImages(files, d, automode)