Exemple #1
0
def sdss_fits(coo, filtro='r'):
    
    try:
        n_coo=len(coo)
    except:
        n_coo=1
        coo=[coo]

    n_col=np.min([n_coo,4])
    n_row=np.ceil(n_coo*1./n_col)
    fig, ax = plt.subplots(figsize=(5*n_col,5*n_row), sharex=True, sharey=True)
    for i in range(len(coo)):
        ax = plt.subplot(n_row, n_col, i+1)
        print 'Procesando galaxia '+str(i)
        xid = SDSS.query_region(coo[i], spectro=True)
        image=SDSS.get_images(matches=xid, band=filtro)[0][0]

        im_h=image.header
        im_data=image.data

        im_median=np.median(im_data)
        im_std=np.std(im_data)

        im_wcs = WCS(im_h)
        im_data = Cutout2D(im_data, coo[i], u.Quantity((1., 1.), u.arcmin), wcs=im_wcs).data

#        ax.imshow(im_data,vmin=im_median-1*im_std, vmax=im_median+5*im_std, cmap=plt.get_cmap('gray'), interpolation='nearest')
        ax.imshow(imtoasinh(im_data.T), vmin=0.1, vmax=0.8, cmap=plt.get_cmap('gray'), interpolation='nearest', origin='lower')
        ax.axis('off')
        ax.text(0.05,0.05, str(i), transform=ax.transAxes, color='white', fontsize=16)
        ax.text(0.95,0.05, 'Filtro '+filtro, transform=ax.transAxes, color='white', fontsize=16, horizontalalignment='right')
        ax.invert_xaxis()
        
    fig.subplots_adjust(hspace=0.1, wspace=0.1)
Exemple #2
0
 def download_and_save_image(self):
     pos = coords.SkyCoord(ra=self.ra * u.degree,
                           dec=self.dec * u.degree,
                           frame='fk5')
     img = SDSS.get_images(self.sdss_id, band='g')[0]
     print(pos)
     print(img[0])
     img.writeto('test.fits', overwrite=True)
def query_sdss(ra, dec, unit='deg', frame='icrs', band='i', spectro=False):
    '''Query SDSS. Many filters are available. See this URL for more:
    http://skyserver.sdss.org/dr2/en/proj/advanced/color/sdssfilters.asp.'''

    position = coords.SkyCoord(ra, dec, unit=unit, frame=frame)
    id = SDSS.query_region(position, spectro=spectro)
    images = SDSS.get_images(matches=id, band=band)

    return images[0]  # use first image, which is the corrected one I think
Exemple #4
0
def sdss_fits(coo, filtro='r'):

    try:
        n_coo = len(coo)
    except:
        n_coo = 1
        coo = [coo]

    n_col = np.min([n_coo, 4])
    n_row = np.ceil(n_coo * 1. / n_col)
    fig, ax = plt.subplots(figsize=(5 * n_col, 5 * n_row),
                           sharex=True,
                           sharey=True)
    for i in range(len(coo)):
        ax = plt.subplot(n_row, n_col, i + 1)
        print 'Procesando galaxia ' + str(i)
        xid = SDSS.query_region(coo[i], spectro=True)
        image = SDSS.get_images(matches=xid, band=filtro)[0][0]

        im_h = image.header
        im_data = image.data

        im_median = np.median(im_data)
        im_std = np.std(im_data)

        im_wcs = WCS(im_h)
        im_data = Cutout2D(im_data,
                           coo[i],
                           u.Quantity((1., 1.), u.arcmin),
                           wcs=im_wcs).data

        #        ax.imshow(im_data,vmin=im_median-1*im_std, vmax=im_median+5*im_std, cmap=plt.get_cmap('gray'), interpolation='nearest')
        ax.imshow(imtoasinh(im_data.T),
                  vmin=0.1,
                  vmax=0.8,
                  cmap=plt.get_cmap('gray'),
                  interpolation='nearest',
                  origin='lower')
        ax.axis('off')
        ax.text(0.05,
                0.05,
                str(i),
                transform=ax.transAxes,
                color='white',
                fontsize=16)
        ax.text(0.95,
                0.05,
                'Filtro ' + filtro,
                transform=ax.transAxes,
                color='white',
                fontsize=16,
                horizontalalignment='right')
        ax.invert_xaxis()

    fig.subplots_adjust(hspace=0.1, wspace=0.1)
Exemple #5
0
    def load_image(self):

        im_size = self.cutout_size.to(u.arcsec).value
        mag_aperture = self.aperture.to(u.arcsec).value

        # keep original coords of image for bounds checking later
        self.orig_coords = self.coords

        with self.bottombox:
            try:
                self.cutout = self.catlib.get_cutouts(
                    position=self.coords,
                    side=im_size,
                    aperture=mag_aperture,
                    dynamic=False,
                    filter=["r", "g", "f606W"],
                    first=True,
                )[0]

                im = NDData(self.cutout["cutout"].data,
                            wcs=self.cutout["cutout"].wcs)
                self.im_path = self.cutout["path"]
                self.imw.load_nddata(im)

            except:
                try:
                    sdss_im = SDSS.get_images(coordinates=self.coords,
                                              band="g")
                    im = sdss_im[0][0]
                except:
                    sdss_im = SDSS.get_images(coordinates=self.coords,
                                              band="g",
                                              radius=30.0 * u.arcsec)
                    im = sdss_im[0][0]

                self.im_path = "SDSS Astroquery result"
                self.imw.load_fits(im)

            self.imw.center_on(self.coords)
            self.imw.zoom_level = self.zoom
            self.textimpath.value = self.im_path
Exemple #6
0
def get_obj_data(ra, dec):
    # Coordinates from SDSS SQL search
    objCoord = SkyCoord(ra=ra * u.degree, dec=dec * u.degree)
    # Get SDSS images
    xObj = SDSS.query_region(objCoord, spectro=True)
    imgObj = SDSS.get_images(matches=xObj)
    image_i = imgObj[0][0]
    data_i = image_i.data
    # Get image coordinates
    wcs = WCS(image_i.header)
    # Cut the Field of view 25.0 x 25.0 arcsec
    FoV = np.array([ra_cut, ra_cut])
    FoV_dimen = u.Quantity((FoV[0], FoV[1]), u.arcsec)
    cutout = Cutout2D(data_i, objCoord, FoV_dimen, wcs=wcs)
    wcs_cut = cutout.wcs
    ret = cutout.data.astype(float)
    #normalizing cutout data
    ret = normalize_data(ret)
    #for i in cutout.data.size: ret.append(cutout.data[i])
    #plot(objCoord,cutout)
    #print(cutout.data.size)
    return ret
Exemple #7
0
def getPlateFits(position,bandName):
    """Get SDSS plate in fits format
    
    This function takes a position and band and returns the available fits images from 
    SDSS using Astroquery
    
    Parameters
    ----------
    position: string
        Ra/Dec position with units e.g. ' 35.2345342d 5.3452346d'
    bandName: string
        Name of band e.g. i from ugrizy


    Returns
    -------
    images astropy.table.Table
        i think the return is an HDUlist of all the available fits for a position/band.
    """
    #First check if it is already there by looping through files
    pos = coordinates.SkyCoord(position, frame='icrs')
    xid = SDSS.query_region(pos)
    #    bandName = 'g'
    #    plate = xid[0]['plate']
    images = SDSS.get_images(matches=xid, band=bandName)
    #    filename = str(plate) + '-' + bandName + '.fits'
    #    alreadyDownloaded = False
    #    for f in os.listdir('/Users/rs548/Documents/Science/PeteHurley/SDSS/'):
    #        print(f)
    #        if f == filename:
    #            alreadyDownloaded = True
    #    
    #    if alreadyDownloaded == False:
    #        im = SDSS.get_images(matches=xid, band=bandName)
    #        im.writeto('/Users/rs548/Documents/Science/PeteHurley/SDSS/' + filename)
    #    else:
    #        im = fits.open('/Users/rs548/Documents/Science/PeteHurley/SDSS/' + filename)
        
    return images
Exemple #8
0
    def _make_frame(self, band='r', overwrite=True):
        """ 
		download frame image if it does not exist

		Params
		-------
		band (string) = 'r'

		Return
		-------
		status (bool): True if successful, False if not
		"""
        file = self._get_frame_filepath(band)

        if (not os.path.isfile(file)) or overwrite:
            print(("[sdssimgLoader] downloading frame image band {0}".format(
                band)))
            im = SDSS.get_images(matches=self.obj.sdss.xid, band=band)
            im[0].writeto(file, overwrite=True)
        else:
            print(("[sdssimgLoader] skip downloading frame image band {0}".
                   format(band)))

        return os.path.isfile(file)
Exemple #9
0
def top_ten_pics(galaxies, filter_one):
    galaxies.sort(filter_one)
    top_ten = galaxies[:9]
    top_ten_pos = coords.SkyCoord(ra=top_ten['ra'] * u.degree,
                                  dec=top_ten['dec'] * u.degree)
    data_list_img = []

    for i in np.arange(len(top_ten)):
        imgs = SDSS.get_images(top_ten_pos[i])

        for v in np.arange(len(imgs)):
            a = fits.HDUList(imgs[v])
            b = a[0].data

            data_list_img.append(b)

            plt.figure()
            plt.title("Plate image _(%s); number (%s), plate (%s)" %
                      (filter_one, i, v))
            plt.imshow(data_list_img[i])
            plt.savefig(
                "Plate_Pics/Plate image _(%s); number (%s), plate (%s)" %
                (filter_one, i, v))
    return data_list_img
Exemple #10
0
#print result_table['RA(deg)'][0]

pos = coords.SkyCoord(ra=result_table['RA(deg)'][0] * u.deg,
                      dec=result_table['DEC(deg)'][0] * u.deg,
                      frame='icrs')
xid = SDSS.query_region(pos)
#print xid
sdsscoords = coords.SkyCoord(ra=xid['ra'] * u.deg,
                             dec=xid['dec'] * u.deg,
                             frame='icrs')

distance = pos.separation(sdsscoords)
match = (distance == min(distance))
print sdsscoords[match]

im = SDSS.get_images(matches=xid[match], band='g')

#Now retreieve image using wget:

run = (xid[match]['run'][0])
rerun = xid[match]['rerun'][0]
camcol = xid[match]['camcol'][0]
field = (xid[match]['field'][0])
band = 'r'

# taking a lot of this from core.py in astropy.sdss
baseurl = 'http://data.sdss3.org/sas'
IMAGING_URL_SUFFIX = ('{base}/dr{dr}/boss/photoObj/frames/'
                      '{rerun}/{run:04d}/{camcol}/'
                      'frame-{band}-{run:06d}-{camcol}-'
                      '{field:04d}.fits.bz2')
Exemple #11
0
def downloadsdss(_ra,_dec,_band,_radius=20, force=False):
    from astroquery.sdss import SDSS
    from astropy import coordinates as coords
    import astropy.units as u
    from astropy.io import fits
    import os
    import sys
    import string
    import numpy as np
    from scipy import interpolate
    pos = coords.SkyCoord(ra=float(_ra)*u.deg,dec=float(_dec)*u.deg)
    print 'pos =', pos
    xid = SDSS.query_region(pos, spectro=False, radius=_radius*u.arcsec)
    print xid
    if xid:
       pointing=[]
       for i in xid:
          if i['run'] > 300:
             if (i['run'],i['camcol'],i['field']) not in pointing:
                pointing.append((i['run'],i['camcol'],i['field']))
       # if too many pointing, take only first 40
       if len(pointing) > 50:
          nn=50
       else: 
          nn=len(pointing)
       filevec=[]
       print len(pointing)
       for run, camcol, field in pointing[:nn]:
          #  naomaggie image
          output1 = _band+'_SDSS_'+str(run)+'_'+str(camcol)+'_'+str(field)+'.fits'
          #  image in count
          output2 = _band+'_SDSS_'+str(run)+'_'+str(camcol)+'_'+str(field)+'c.fits'
          #  weight image
          output3 = _band+'_SDSS_'+str(run)+'_'+str(camcol)+'_'+str(field)+'.weight.fits'
          #  sky image
          output4 = _band+'_SDSS_'+str(run)+'_'+str(camcol)+'_'+str(field)+'.sky.fits'
          if os.path.isfile(output1) and not force:
              print 'already downloaded', output1
              filevec.append(output2)
              filevec.append(output3)
              continue
          im = SDSS.get_images(run=run, camcol=camcol, field=field, band=_band, cache=True)
          if os.path.isfile(output1):
             os.system('rm '+output1)
          if os.path.isfile(output2):
             os.system('rm '+output2)
          if os.path.isfile(output3):
             os.system('rm '+output3)
          if os.path.isfile(output4):
             os.system('rm '+output4)
          im[0].writeto(output1)
#         im[0][0].writeto(output2)

          FITS_file = fits.open(output1)
          new_header = FITS_file[0].header
          camcol     = FITS_file[0].header['CAMCOL']  # camcol
          ugriz      = FITS_file[0].header['FILTER']  # ugriz filter
          run1        = FITS_file[0].header['RUN']     # run
          gain, dark_var = SDSS_gain_dark(camcol, ugriz, run1)
          new_header['gain']  = gain
          new_header['dark']  = dark_var
          new_header['BUNIT']  = 'counts'
          new_header['rdnoise']  = 2
          frame_image = FITS_file[0].data.transpose()
          allsky     = FITS_file[2].data['ALLSKY'].transpose()
          allsky     = allsky[:,:,0]
          xinterp    = FITS_file[2].data['XINTERP'].transpose()
          xinterp    = xinterp[:,0]
          yinterp    = FITS_file[2].data['YINTERP'].transpose()
          yinterp    = yinterp[:,0]
          sky_function = interpolate.interp2d(np.arange(allsky.shape[1]),\
                                              np.arange(allsky.shape[0]), allsky, kind='linear')
          sky_image    = sky_function(yinterp, xinterp) # in counts
          calib     = FITS_file[1].data #  nanomaggies per count
          calib_image = np.empty_like(frame_image)
          for i in np.arange(calib_image.shape[1]):
             calib_image[:,i] = calib
          # Calculate the error in the frame image for use fitting algorithms later.
          dn_image        = frame_image / calib_image  # + sky_image # counts
          dn_err_image    = np.sqrt((dn_image + sky_image)/ gain + dark_var)
          # frame_image_err = dn_err_image * calib_image  converts to nanomaggies
          
          frame_weight = 1 / ((dn_err_image)**2)
          new_header['SKYLEVEL']  = np.mean(sky_image)
          #  save image in count
          fits.writeto(output2, dn_image.transpose(), new_header,overwrite=True)
          #  save weight image
          fits.writeto(output3, frame_weight.transpose(), new_header,overwrite=True)
          #  save sky image 
          fits.writeto(output4, sky_image.transpose(), new_header,overwrite=True)
          filevec.append(output2)
          filevec.append(output3)
       return filevec
    else:
       return ''
Exemple #12
0
        name_root = "spiral_{}".format(objectID)
    else:
        sys.exit("\n ERROR! Something is wrong with the classification")

    print name_root + ".npy"

    # check if the file is present or not
    if not objectID in remaining_objectIDs:
        print "\tfile exists! continuing..."
        continue
    else:
        os.system("sed -i '/" + str(objectID) + "/d' 00_to_be_downloaded.lst")
# object will be downloaded: it is removed from hte list of remaining objectIDs

# getting g-band image from SDSS
    img = SDSS.get_images(run=runID, camcol=camcolID, field=fieldID, band='g')
    """
    # in case of debugging 
    print "image info --> "
    print img[0].info()   
    print img[0][0].header
    img_data = img[0][0].data
    print img_data
    # if you want to save the original image
    img[0].writeto(name_root+str('_original.fits'))
    """

    naxis1 = float(img[0][0].header['NAXIS1'])
    naxis2 = float(img[0][0].header['NAXIS2'])

    # WCS <-> pixel coordinate conversion
Exemple #13
0
for i, (ra, dec, name) in enumerate(zip(data['RA'], data['Dec'],
                                        data['Name'])):
    # make string comparisons work
    name = name.replace(' ', '_')

    # here's the little bit for persistance (see below)
    if i <= done:
        continue
    print(name)
    if not os.path.isdir(name):
        os.mkdir(name)

    pos = coords.SkyCoord(ra, dec, frame='icrs', unit='deg')
    print('fetching images....')
    imgs = SDSS.get_images(pos, radius="20'", band='ugriz', data_release=12)

    if imgs:
        print('writing %s' % name, end='')
        counter = 0
        for HDU, band in zip(imgs, cycle('ugriz')):
            print('.', end='')
            if os.path.isfile(f'./{name}/{name}_sdss_{band}_{counter}.fits'):
                HDU.writeto(f'./{name}/{name}_sdss_{band}_{counter + 1}.fits',
                            clobber=True)
                if band == 'z':
                    counter += 1
            else:
                HDU.writeto(f'./{name}/{name}_sdss_{band}_{counter}.fits',
                            clobber=True)
Exemple #14
0
#1586 is corrupted!
istart=0
iend=1000 #number of images to download for training (~230k)

for k in range(iend-istart):
    i=k+istart
    run=xuniq['run'][i]
    rerun=xuniq['rerun'][i]
    camcol=xuniq['camcol'][i]
    field=xuniq['field'][i]
    fnamer='images/%s.r.fits'%(xuniq['imagename'][i])    
    fnameg='images/%s.g.fits'%(xuniq['imagename'][i])    
    fnamei='images/%s.i.fits'%(xuniq['imagename'][i])    
    if os.path.isfile(fnamer):    
	print('i=%d file exist %s'%(i,fnamer))
    if not os.path.isfile(fnamer):
        im = SDSS.get_images(run=run,rerun=rerun,camcol=camcol,field=field,band=['r','g','i'],timeout=120)
        if len(im) < 3:
		print('i=%d no data file skip!!!!!'%(i))
        if len(im) >= 3:
	        imr=im[0]
       		img=im[1]
        	imi=im[2]
        	imr.writeto(fnamer)
        	img.writeto(fnameg)
        	imi.writeto(fnamei)
		print('i=%d downloaded %s'%(i,fnamer))
#   if i%10==0:
#       print('i=%d'%i)
def downloadsdss(_ra, _dec, _band, _radius=20, force=False):
    from astroquery.sdss import SDSS
    from astropy import coordinates as coords
    import astropy.units as u
    from astropy.io import fits
    import os
    import sys
    import string
    import numpy as np
    from scipy import interpolate
    pos = coords.SkyCoord(ra=float(_ra) * u.deg, dec=float(_dec) * u.deg)
    print 'pos =', pos
    xid = SDSS.query_region(pos, spectro=False, radius=_radius * u.arcsec)
    print xid
    if xid:
        pointing = []
        for i in xid:
            if i['run'] > 300:
                if (i['run'], i['camcol'], i['field']) not in pointing:
                    pointing.append((i['run'], i['camcol'], i['field']))
        # if too many pointing, take only first 40
        if len(pointing) > 50:
            nn = 50
        else:
            nn = len(pointing)
        filevec = []
        print len(pointing)
        for run, camcol, field in pointing[:nn]:
            #  naomaggie image
            output1 = _band + '_SDSS_' + str(run) + '_' + str(
                camcol) + '_' + str(field) + '.fits'
            #  image in count
            output2 = _band + '_SDSS_' + str(run) + '_' + str(
                camcol) + '_' + str(field) + 'c.fits'
            #  weight image
            output3 = _band + '_SDSS_' + str(run) + '_' + str(
                camcol) + '_' + str(field) + '.weight.fits'
            #  sky image
            output4 = _band + '_SDSS_' + str(run) + '_' + str(
                camcol) + '_' + str(field) + '.sky.fits'
            if os.path.isfile(output1) and not force:
                print 'already downloaded', output1
                filevec.append(output2)
                filevec.append(output3)
                continue
            im = SDSS.get_images(run=run,
                                 camcol=camcol,
                                 field=field,
                                 band=_band,
                                 cache=True)
            if os.path.isfile(output1):
                os.system('rm ' + output1)
            if os.path.isfile(output2):
                os.system('rm ' + output2)
            if os.path.isfile(output3):
                os.system('rm ' + output3)
            if os.path.isfile(output4):
                os.system('rm ' + output4)
            im[0].writeto(output1)
            #         im[0][0].writeto(output2)

            FITS_file = fits.open(output1)
            new_header = FITS_file[0].header
            camcol = FITS_file[0].header['CAMCOL']  # camcol
            ugriz = FITS_file[0].header['FILTER']  # ugriz filter
            run1 = FITS_file[0].header['RUN']  # run
            gain, dark_var = SDSS_gain_dark(camcol, ugriz, run1)
            new_header['gain'] = gain
            new_header['dark'] = dark_var
            new_header['BUNIT'] = 'counts'
            new_header['rdnoise'] = 2
            frame_image = FITS_file[0].data.transpose()
            allsky = FITS_file[2].data['ALLSKY'].transpose()
            allsky = allsky[:, :, 0]
            xinterp = FITS_file[2].data['XINTERP'].transpose()
            xinterp = xinterp[:, 0]
            yinterp = FITS_file[2].data['YINTERP'].transpose()
            yinterp = yinterp[:, 0]
            sky_function = interpolate.interp2d(np.arange(allsky.shape[1]),\
                                                np.arange(allsky.shape[0]), allsky, kind='linear')
            sky_image = sky_function(yinterp, xinterp)  # in counts
            calib = FITS_file[1].data  #  nanomaggies per count
            calib_image = np.empty_like(frame_image)
            for i in np.arange(calib_image.shape[1]):
                calib_image[:, i] = calib
            # Calculate the error in the frame image for use fitting algorithms later.
            dn_image = frame_image / calib_image  # + sky_image # counts
            dn_err_image = np.sqrt((dn_image + sky_image) / gain + dark_var)
            # frame_image_err = dn_err_image * calib_image  converts to nanomaggies

            frame_weight = 1 / ((dn_err_image)**2)
            new_header['SKYLEVEL'] = np.mean(sky_image)
            #  save image in count
            fits.writeto(output2,
                         dn_image.transpose(),
                         new_header,
                         clobber=True)
            #  save weight image
            fits.writeto(output3,
                         frame_weight.transpose(),
                         new_header,
                         clobber=True)
            #  save sky image
            fits.writeto(output4,
                         sky_image.transpose(),
                         new_header,
                         clobber=True)
            filevec.append(output2)
            filevec.append(output3)
        return filevec
    else:
        return ''
R_A = 0.5 * view_d.to(U.arcsec)  # angular radius in angular second unit
band = ['u', 'g', 'r', 'i', 'z']
for k in range(len(z)):
    pos = coords.SkyCoord('%fd %fd' % (ra[k], dec[k]), frame='icrs')
    try:
        xid = SDSS.query_region(pos,
                                spectro=False,
                                radius=R_A[k] / 2,
                                timeout=None)
        # for galaxy, don't take spectra into account
        name = xid.colnames
        aa = np.array([xid['ra'], xid['dec']])
        da = np.sqrt((aa[0, :] - ra[k])**2 + (aa[1, :] - dec[k])**2)
        # select the goal region
        dl = da.tolist()
        pl = dl.index(np.min(da))
        # change the list as the astropy table type
        fd = Table(xid[pl])
        for p in range(len(band)):
            imdata = SDSS.get_images(matches=fd, band=band[p])
            hdu_tot = aft.HDUList(imdata[0])
            hdu_tot.writeto(
                '/mnt/ddnfs/data_users/cxkttwl/ICL/data/img_ra%.3f_dec%.3f_tot_z%.3f_bnd%s.fits'
                % (ra[k], dec[k], z[k], band[p]),
                overwrite=True)
            # save the total information of the data
        data.clear_download_cache()
        # after saving, clear the cache
    except KeyError:
        continue
Exemple #17
0
def sdss(input_file, output_dir, filters, output_format, pmin_r, pmax_r,
         pmin_g, pmax_g, pmin_b, pmax_b):
    """
    Generates RGB images using SDSS data and APLPY. Information for parameters can be found in inputHandler(). I separated them up to allow easier access from makeTable.py
    """

    warnings.filterwarnings("ignore")

    # get parameters and inputs into a suitable format
    df = pd.read_csv(input_file, header=None)
    output_format = output_format.lower()
    filters = filters.split(',')

    if len(filters) != 3:
        raise Exception('Error. Please provide 3 filters separated by commas')

    try:
        os.mkdir(output_dir)
    except:
        typer.echo(
            f'A dir with the name {typer.style(output_dir, bold=True, fg=typer.colors.RED)} already exists'
        )

    for i, line in df.iterrows():
        try:

            name = line[0]
            ra = line[1]
            dec = line[2]

            styled_name = typer.style(name, fg=typer.colors.MAGENTA, bold=True)

            typer.echo(f'Plotting: ' + styled_name)

            pos = coords.SkyCoord(ra, dec, unit='deg')

            # query SDSS for each target and get the images
            try:
                xid = Table(SDSS.query_region(pos, spectro=False)[0])
            except:
                raise Exception(f'No images found on SDSS for target {name}')

            im = SDSS.get_images(matches=xid, band=filters)

            # raise exception if no images are found
            if len(im) == 0:
                raise Exception(f'No images found on SDSS for target {name}')

            # Obtain the PrimaryHDU from the HDUList for each band
            r, g, b = im[0][0], im[1][0], im[2][0]

            # save the fits files so they can be combined into a single rgb cube
            r.writeto('r.fits', overwrite=True)
            g.writeto('g.fits', overwrite=True)
            b.writeto('b.fits', overwrite=True)
            aplpy.make_rgb_cube(['r.fits', 'g.fits', 'b.fits'],
                                f'image.fits',
                                north=True)

            aplpy.make_rgb_image(f'image.fits',
                                 fr'{output_dir}/{name}.{output_format}',
                                 pmin_r=pmin_r,
                                 pmax_r=pmax_r,
                                 pmin_g=pmin_g,
                                 pmax_g=pmax_g,
                                 pmin_b=pmin_b,
                                 pmax_b=pmax_b)
            image = aplpy.FITSFigure(fr'{output_dir}/{name}.{output_format}')
            image.show_rgb()

            # add labels for filters used
            image.add_label(0.08,
                            0.15,
                            "FILTERS:",
                            relative=True,
                            color='white')

            filter_wavelengths = {
                'z': 913,
                'i': 763,
                'r': 623,
                'g': 477,
                'u': 354
            }
            bandColours = ['red', 'green', 'cyan']
            for i in range(3):
                w = filter_wavelengths[filters[i]]
                c = bandColours[i]
                image.add_label(0.08,
                                0.11 - 0.03 * i,
                                f"{filters[i]} ({w}nm)",
                                relative=True,
                                color=c)

            # add arrows pointing to object
            image.show_arrows(
                x=[ra + 0.01, ra - 0.01, ra + 0.01, ra - 0.01],
                y=[dec + 0.01, dec - 0.01, dec - 0.01, dec + 0.01],
                dx=[-0.007, 0.007, -0.007, 0.007],
                dy=[-0.007, 0.007, 0.007, -0.007],
                color='red')

            # add object name as label
            image.add_label(ra, dec + 0.02, name, color='red')

            # get redshift for scalebar
            resTable = Ned.query_region(pos, radius=0.01 * u.deg)
            resTable = resTable.to_pandas()
            redshift = 0
            for i, row in resTable.iterrows():
                if row['Redshift'] > 0:
                    redshift = row['Redshift']
                    break

            kpcArcmin = cosmo.kpc_proper_per_arcmin(float(redshift)).value
            length = round(kpcArcmin * 2, 1)

            # add scalebar
            image.add_scalebar(1 / 30,
                               label=f'120" | {length}kpc | r = {redshift}',
                               color='red')

            # save to output dir in the appropriate format
            image.save(fr'{output_dir}/{name}.{output_format}')

            typer.echo('Finished plotting: ' + styled_name)

        except Exception as e:
            typer.echo('Failed for: ' + styled_name)
            print(e)

    cleanup()
from astroquery.simbad import Simbad
result_table = Simbad.query_object("m1")
result_table.pprint(show_unit=True)

from astroquery.sdss import SDSS
from astropy import coordinates as coords
#pos = coords.SkyCoord(packet['candidate']['ra'],packet['candidate']['dec'], unit="deg”) #to use info from avro packet
pos = coords.SkyCoord(244.566202,16.138884, unit="deg”) #to test query

xid = SDSS.query_region(pos, spectro=True)
print(xid)
print(xid.columns)
xid['z']

sp = SDSS.get_spectra(matches=xid)
im = SDSS.get_images(matches=xid, band='r')
        twomass_images = SkyView.get_images(position=pos,
                                            survey=['DSS2 Red'],
                                            pixels=500)
        # print(twomass_images)
        if len(twomass_images) > 0:
            pix_2mass = twomass_images[0][0].data
            hdr_2mass = twomass_images[0][0].header
    except astroquery.exceptions.TimeoutError, urllib.HTTPError:
        pix_2mass, hdr_2mass = None, None

    # Get SDSS r image
    pix, hdr, im = None, None, None
    xid = SDSS.query_region(pos)
    if xid is not None:
        one_match = table.Table(xid[0])
        im = SDSS.get_images(matches=one_match, band='r')
        pix = im[0][0].data
        hdr = im[0][0].header

    # Plot K2 image
    # Set up the GridHelper to merge the axes
    grid_helper = pywcsgrid2.GridHelper(wcs=w2)

    # Plot the pixel stamp as usual, except with the WCS
    ax1 = pywcsgrid2.subplot(441,
                             grid_helper=grid_helper,
                             aspect=1,
                             adjustable="box-forced")
    ax1.matshow(coadd, origin="lower", cmap=cmap, norm=colors.LogNorm())
    if pix is not None:
        median = np.median(pix)