def __init__(self, field_list, max_depth=7): if not os.path.exists(field_list): raise IOError("Cannot find file %s" % field_list) self.fields_df = pd.read_csv(field_list) self.max_depth = max_depth self.region_list = regions.ShapeList() self.moc = MOC() for _, field in self.fields_df.iterrows(): center = SkyCoord(ra=field.RA, dec=field.Dec, unit="hourangle,deg") sep = np.hypot(self.WIDTH, self.HEIGHT) / 2.0 self.region_list.append( regions.RectangleSkyRegion( center, self.WIDTH, self.HEIGHT, self.ASKAP_ROTATION + (field.Rotation * u.deg), )) self.vertices = SkyCoord([ center.directional_offset_by( self.ASKAP_ROTATION + pa + (field.Rotation * u.deg), sep) for pa in [45, 135, 225, 315] * u.deg ]) self.moc = self.moc.union( MOC.from_polygon_skycoord(self.vertices, max_depth=self.max_depth))
def get_bkg_npixels(src_center, nside, npixels=100): order = np.log2(nside).astype(int) bkg_moc_outer = MOC.from_cone(src_center.ra, src_center.dec, 120 * u.arcsec, order) bkg_moc_inner = MOC.from_cone(src_center.ra, src_center.dec, 60 * u.arcsec, order) bkg_moc = bkg_moc_outer.difference(bkg_moc_inner) bkg_npixels = flatten_pixels(bkg_moc._interval_set._intervals, order) return rng.choice(bkg_npixels, size=npixels, replace=False).tolist()
def moc_watchlist(watchlist, max_depth): """ Take a "watchlist" dictionary and builds a MOC at given max_depth, by approximating the disk around a source as a hexagon. """ s = 0.5 * math.sqrt(3) moc = None ralist = watchlist['ra'] # ra list of the watchlist, degrees delist = watchlist['de'] # dec list of the watchlist, degrees radius = watchlist['radius'] # radius list in degrees for i in range(len(ralist)): ra = ralist[i] de = delist[i] q = radius[i] r = q / math.cos(de * math.pi / 180) # make a hexagon lon = [ ra + q, ra + 0.5 * r, ra - 0.5 * r, ra - r, ra - 0.5 * r, ra + 0.5 * r ] * u.deg lat = [de, de + s * q, de + s * q, de, de - s * q, de - s * q] * u.deg # make a moc from the hexagon newmoc = MOC.from_polygon(lon, lat, max_depth=max_depth) # union with previous hexagons if moc: moc = moc.union(newmoc) else: moc = newmoc return moc
def main(args=None): p = parser() opts = parser().parse_args(args) import astropy_healpix as ah import astropy.units as u try: from mocpy import MOC except ImportError: p.error('This command-line tool requires mocpy >= 0.8.2. ' 'Please install it by running "pip install mocpy".') from ..io import read_sky_map # Read multi-order sky map skymap = read_sky_map(opts.input.name, moc=True) uniq = skymap['UNIQ'] probdensity = skymap['PROBDENSITY'] level, ipix = ah.uniq_to_level_ipix(uniq) area = ah.nside_to_pixel_area( ah.level_to_nside(level)).to_value(u.steradian) prob = probdensity * area # Create MOC contour_decimal = opts.contour / 100 moc = MOC.from_valued_healpix_cells( uniq, prob, cumul_from=0.0, cumul_to=contour_decimal) # Write MOC moc.write(opts.output, format='fits', overwrite=True)
def create_moc(self): """ Multi-Order coverage map (MOC) of sky area enclosed within a contour plot at a given confidence level. (Function adapted from Giuseppe Greco github repository) """ #reading skymap hpx = hp.read_map( self.path+self.filename, verbose = False ) npix = len( hpx ) nside = hp.npix2nside( npix ) # Save nside self.nside = nside sort = sorted( hpx, reverse = True ) cumsum = np.cumsum( sort ) index, value = min( enumerate( cumsum ), key = lambda x: abs( x[1] - self.percentage ) ) # finding ipix indices confined in a given percentage index_hpx = range( 0, len( hpx ) ) hpx_index = np.c_[ hpx, index_hpx ] sort_2array = sorted( hpx_index, key = lambda x: x[0], reverse = True ) value_contour = sort_2array[ 0:index ] j = 1 table_ipix_contour = [ ] for i in range ( 0, len( value_contour ) ): ipix_contour = int( value_contour[i][j] ) table_ipix_contour.append( ipix_contour ) # from index to polar coordinates theta, phi = hp.pix2ang( nside, table_ipix_contour ) # converting these to right ascension and declination in degrees ra = np.rad2deg( phi ) dec = np.rad2deg( 0.5 * np.pi - theta ) # Save ra, dec of the pixel associated with highest probability self.RA, self.DEC = ra[0], dec[0] # creating an astropy.table with RA[deg] and DEC[deg] ipix positions contour_ipix = Table([ ra, dec ], names = ('RA[deg]', 'DEC[deg]'), meta = {'ipix': 'ipix table'}) # setting MOC order moc_order = int( log( nside, 2 ) ) # creating a MOC map from the contour_ipix table #moc = MOC.from_table( contour_ipix, 'RA[deg]', 'DEC[deg]', moc_order ) moc = MOC.from_lonlat(contour_ipix['RA[deg]'].T * u.deg, contour_ipix['DEC[deg]'].T * u.deg,moc_order) # writing MOC file in fits #moc.write(path=short_name + '_MOC_' + str( percentage ) +'.json',format='json') # Serialise to json dictionary self.moc = moc.serialize(format='json')
def create_moc(self): """Creating a MOC map from the contour_ipix table.""" self.moc = MOC.from_table(self.contour_ipix, 'RA[deg]', 'DEC[deg]', self.moc_order) return self.moc
def test_set_fromtable_areafrommoc_mags(): from mocpy import MOC from astropy.table import Table mocfile = get_pkg_data_filename('data/testcat_moc_2.moc') moc = MOC.from_fits(mocfile) datafile = get_pkg_data_filename('data/testcat_moc_2.fits') data = Table.read(datafile) mag_cols = ['uMag', 'gMag'] cat = Catalogue(data, area=moc, name='test', coord_cols=['RA', 'DEC'], poserr_cols=['raErr', 'decErr'], poserr_type='rcd_dec_ellipse', mag_cols=mag_cols) assert cat.name == 'test' assert cat.area > 0 assert cat.poserr_type == 'rcd_dec_ellipse' assert isinstance(cat.coords, SkyCoord) assert isinstance(cat.poserr, SkyCoordErr) assert len(cat) == len(data) assert len(cat.coords) == len(data) assert len(cat.poserr) == len(data) assert len(cat.mags) == len(data) assert len(cat.mags.colnames) == len(mag_cols)
def _set_area(self, area): """ Returns the area covered by the catalogue and the corresponding MOC, if defined. Parameters ---------- area : ``str``, ``MOC`` or ``Quantity`` area can be defined as a path to the catalogue MOC, a mocpy ``MOC`` object or an Astropy ``Quantity`` with units consistents with square deg. """ # If area is a string, we assume is the path for a moc file if isinstance(area, str): moc = MOC.from_fits(area) area = moc.sky_fraction * ALLSKY_AREA_DEG elif isinstance(area, MOC): moc, area = area, area.sky_fraction * ALLSKY_AREA_DEG elif isinstance(area, Quantity): area = area.to(u.deg**2) moc = None else: raise ValueError('Invalid `area` value!') return area, moc
def load_ztf(): log.info('downloading and reading ZTF field list') url = 'https://github.com/ZwickyTransientFacility/ztf_information/raw/master/field_grid/ZTF_Fields.txt' with get_readable_fileobj(url, show_progress=False) as f: first_line, *lines = f names = re.split(r'\s\s+', first_line.lstrip('%').strip()) table = Table.read(lines, format='ascii', names=names) log.info('building footprint polygons') lon, lat = get_ztf_footprint_corners() centers = SkyCoord(table['RA'] * u.deg, table['Dec'] * u.deg) vertices = get_footprints_grid(lon, lat, centers) log.info('building MOCs') mocs = [MOC.from_polygon_skycoord(verts) for verts in vertices] log.info('creating ORM records') telescope = Telescope(telescope_name='ZTF', fields=[ Field.from_moc(moc, field_id=field_id) for field_id, moc in zip(table['ID'], mocs) ]) log.info('saving') db.session.add(telescope) db.session.commit() log.info('done')
def get_polygon_moc(row): print('{} ({} {}) {}'.format(row['obs_id'], row['s_ra'], row['s_dec'], row['s_region'])) lon = u.Quantity(row['coords']['ra'] * u.deg) lat = u.Quantity(row['coords']['dec'] * u.deg) temp_moc = MOC.from_polygon(lon, lat, max_depth=MAX_DEPTH) return temp_moc
def read_area_cache_files(cache_dir): """ read_area_cache_files This function reads all the files in the cache directories and keeps them in memory in a list called "arealist". Each area is a dictionary: ar_id: the id from tha database moc : the ingestred moc Args: cache_dir: """ arealist = [] for ar_file in os.listdir(cache_dir): # every file in the cache should be of the form ar_<nn>.fits # where nn is the area id tok = ar_file.split('.') if tok[1] != 'fits': continue try: ar_id = int(tok[0][3:]) except: continue gfile = cache_dir + '/' + ar_file moc = MOC.from_fits(gfile) area = {'ar_id':ar_id, 'moc':moc} arealist.append(area) return arealist
def Fov2Moc(params, config_struct, telescope, ra_pointing, dec_pointing, nside): """Return a MOC in fits file of a fov footprint. The MOC fov is displayed in real time in an Aladin plan. Input: ra--> right ascention of fov center [deg] dec --> declination of fov center [deg] fov_width --> fov width [deg] fov_height --> fov height [deg] nside --> healpix resolution; by default """ moc_struct = {} if config_struct["FOV_type"] == "square": ipix, radecs, patch, area = gwemopt.utils.getSquarePixels(ra_pointing, dec_pointing, config_struct["FOV"], nside) elif config_struct["FOV_type"] == "circle": ipix, radecs, patch, area = gwemopt.utils.getCirclePixels(ra_pointing, dec_pointing, config_struct["FOV"], nside) if params["doChipGaps"]: npix = hp.nside2npix(nside) pixel_index = np.arange(npix) RAs, Decs = hp.pix2ang(nside, pixel_index, lonlat=True, nest=False) if telescope == "ZTF": Z = gwemopt.quadrants.ZTFtile(ra_pointing, dec_pointing, config_struct) #ipix = np.where(Z.inside_nogaps(RAs, Decs))[0] # Ignore chip gaps ipix = np.where(Z.inside(RAs, Decs))[0] else: raise ValueError("Requested chip gaps with non-ZTF detector, failing.") moc_struct["ra"] = ra_pointing moc_struct["dec"] = dec_pointing moc_struct["ipix"] = ipix moc_struct["corners"] = radecs moc_struct["patch"] = patch moc_struct["area"] = area if False: #if len(ipix) > 0: # from index to polar coordinates theta, phi = hp.pix2ang(nside, ipix) # converting these to right ascension and declination in degrees ra = np.rad2deg(phi) dec = np.rad2deg(0.5 * np.pi - theta) box_ipix = Table([ra, dec], names = ('RA[deg]', 'DEC[deg]'), meta = {'ipix': 'ipix table'}) moc_order = int(np.log(nside)/ np.log(2)) moc = MOC.from_table( box_ipix, 'RA[deg]', 'DEC[deg]', moc_order ) moc_struct["moc"] = moc else: moc_struct["moc"] = [] return moc_struct
def test_polygon_issue_50(): from mocpy import MOC from astropy.coordinates import SkyCoord from astropy import units as u coords = SkyCoord([(353.8156714, -56.33202193), (6.1843286, -56.33202193), (5.27558041, -49.49378172), (354.72441959, -49.49378172)], unit=u.deg) moc = MOC.from_polygon_skycoord(coords) assert not moc.empty()
def test_moc_order_param(self, moc_order): moc_region = MOC.from_json({'0': [1]}) result = cds.query_region(region=moc_region, # return a mocpy obj return_moc=True, max_norder=moc_order, get_query_payload=False) assert isinstance(result, MOC)
def create_mocpy_object_from_json(json_moc): # TODO : just call the MOC.from_json classmethod to get the corresponding mocpy object uniq_interval = IntervalSet() for n_order, n_pix_l in json_moc.items(): n_order = int(n_order) for n_pix in n_pix_l: uniq_interval.add(__class__.orderipix2uniq(n_order, n_pix)) moc = MOC.from_uniq_interval_set(uniq_interval) return moc
def get_polygon_moc(row): print('{} ({} {}) {}'.format(row['obs_id'], row['s_ra'], row['s_dec'], row['s_region'])) lon = u.Quantity(row['coords']['ra'] * u.deg) lat = u.Quantity(row['coords']['dec'] * u.deg) temp_moc = MOC.from_polygon(lon, lat, max_depth=MAX_DEPTH) #, # inside=SkyCoord(ra=row['s_ra'] * u.deg, dec=row['s_dec'] * u.deg)) print(temp_moc.serialize('json')) return temp_moc
def create_moc(self): """Creating a MOC map from the contour_ipix table.""" import sys sys.path.append( '/anaconda3/lib/python3.6/site-packages/MOCPy-0.4.9-py3.6.egg') from mocpy import MOC import astropy.units as u self.moc = MOC.from_lonlat(self.contour_ipix['RA[deg]'].T * u.deg, self.contour_ipix['DEC[deg]'].T * u.deg, max_norder=self.moc_order) return self.moc
class ASKAPSurvey: ASKAP_ROTATION = 45 * u.deg # may not be an appropriate assumption! # full width (diameter) WIDTH = 2 * 4.1 * u.deg HEIGHT = WIDTH def __init__(self, field_list, max_depth=7): if not os.path.exists(field_list): raise IOError("Cannot find file %s" % field_list) self.fields_df = pd.read_csv(field_list) self.max_depth = max_depth self.region_list = regions.ShapeList() self.moc = MOC() for _, field in self.fields_df.iterrows(): center = SkyCoord(ra=field.RA, dec=field.Dec, unit="hourangle,deg") sep = np.hypot(self.WIDTH, self.HEIGHT) / 2.0 self.region_list.append( regions.RectangleSkyRegion( center, self.WIDTH, self.HEIGHT, self.ASKAP_ROTATION + (field.Rotation * u.deg), )) self.vertices = SkyCoord([ center.directional_offset_by( self.ASKAP_ROTATION + pa + (field.Rotation * u.deg), sep) for pa in [45, 135, 225, 315] * u.deg ]) self.moc = self.moc.union( MOC.from_polygon_skycoord(self.vertices, max_depth=self.max_depth)) def to_moc(self, filename): self.moc.write(filename, overwrite=True) def to_reg(self, filename): regions.write_ds9(self.region_list, filename, coordsys="fk5")
def test_randomise_withmoc(): from mocpy import MOC mocfile = get_pkg_data_filename('data/testcat_moc_1.moc') moc = MOC.from_fits(mocfile) datafile = get_pkg_data_filename('data/testcat_moc_1.fits') cat = Catalogue(datafile, area=moc, name='test') numrepeat = 3 rndcat = cat.randomise(numrepeat=numrepeat) assert len(rndcat) > len(cat) assert all(moc.contains(rndcat.coords.ra, rndcat.coords.dec))
def test_set_fromfile_areafrommoc_nomags(): from mocpy import MOC datafile = get_pkg_data_filename('data/testcat_moc_1.fits') mocfile = get_pkg_data_filename('data/testcat_moc_1.moc') moc = MOC.from_fits(mocfile) cat = Catalogue(datafile, area=moc, name='test') assert cat.name == 'test' assert cat.area > 0 assert cat.poserr_type == 'circle' assert isinstance(cat.coords, SkyCoord) assert isinstance(cat.poserr, SkyCoordErr) assert cat.mags is None
def from_polygon(cls, polygon, *args, **kwargs): """Create a new instance from a polygon. Parameters ---------- polygon : astropy.coordinates.SkyCoord The vertices of the polygon. Returns ------- list A list of Tile instances. """ moc = MOC.from_polygon_skycoord(polygon) return cls.from_moc(moc, *args, **kwargs)
def mocFilter(apiobjects, moc_path): # Use object table with only unique OIDs unique_df = apiobjects.drop_duplicates(subset=['oid']) # Stipulation if object table is empty if len(unique_df) == 0: return unique_df # Running mocpy filter mocLocation = moc_path moc = MOC.from_fits(mocLocation) mask_in_moc = moc.contains(unique_df['meanra'] * u.deg, unique_df['meandec'] * u.deg) ztfobjects = Table.from_pandas(unique_df[mask_in_moc]) return ztfobjects
def Fov2Moc(config_struct, ra_pointing, dec_pointing, nside): """Return a MOC in fits file of a fov footprint. The MOC fov is displayed in real time in an Aladin plan. Input: ra--> right ascention of fov center [deg] dec --> declination of fov center [deg] fov_width --> fov width [deg] fov_height --> fov height [deg] nside --> healpix resolution; by default """ moc_struct = {} if config_struct["FOV_type"] == "square": ipix, radecs, patch, area = gwemopt.utils.getSquarePixels(ra_pointing, dec_pointing, config_struct["FOV"], nside) elif config_struct["FOV_type"] == "circle": ipix, radecs, patch, area = gwemopt.utils.getCirclePixels(ra_pointing, dec_pointing, config_struct["FOV"], nside) moc_struct["ra"] = ra_pointing moc_struct["dec"] = dec_pointing moc_struct["ipix"] = ipix moc_struct["corners"] = radecs moc_struct["patch"] = patch moc_struct["area"] = area if False: #if len(ipix) > 0: # from index to polar coordinates theta, phi = hp.pix2ang(nside, ipix) # converting these to right ascension and declination in degrees ra = np.rad2deg(phi) dec = np.rad2deg(0.5 * np.pi - theta) box_ipix = Table([ra, dec], names = ('RA[deg]', 'DEC[deg]'), meta = {'ipix': 'ipix table'}) moc_order = int(np.log(nside)/ np.log(2)) moc = MOC.from_table( box_ipix, 'RA[deg]', 'DEC[deg]', moc_order ) moc_struct["moc"] = moc else: moc_struct["moc"] = [] return moc_struct
def test_polygon2_issue_44(): from astropy import units as u from mocpy import MOC import numpy as np ra = [ 174.75937396073138, 185.24062603926856, 184.63292896369916, 175.3670710363009 ] dec = [ -49.16744206799886, -49.16744206799887, -42.32049830486584, -42.32049830486584 ] moc = MOC.from_polygon(ra * u.deg, dec * u.deg) assert not moc.empty()
def _mockcat_area(**kwargs): geometry = kwargs['geometry'] if geometry == 'allsky': area = ALLSKY_AREA_DEG elif geometry == 'cone': r = kwargs['r'] * u.deg area = np.pi * r**2 elif geometry == 'moc': area = MOC.from_fits(kwargs['mocfile']) else: raise ValueError('Unknown geometry: {}'.format(geometry)) return area
def test_apply_moc(): from mocpy import MOC datafile = get_pkg_data_filename('data/testcat_moc_2.fits') mocfile = get_pkg_data_filename('data/testcat_moc_2.moc') cat = Catalogue(datafile, area=mocfile, name='test', poserr_cols=['raErr', 'decErr'], poserr_type='rcd_dec_ellipse') mocfile = get_pkg_data_filename('data/testcat_moc_1.moc') moc = MOC.from_fits(mocfile) newcat = cat.apply_moc(moc) assert len(cat) > len(newcat) assert moc.intersection(newcat.moc) is not None
def get_data(): query = "SELECT top 1000 * FROM obsPointing WHERE obs_collection='K2' AND dataproduct_type='image'" df = query_db(CAOM, query) if len(df) == 0: return None df['coords'] = df.apply(lambda x: parse_s_region(x['s_region']), axis=1) # Generate MOC results = [get_polygon_moc(row) for _, row in df.iterrows()] # Union of MOCs if len(results) > 1: moc = MOC.union(*results) else: moc = results return moc
def load_decam(): log.info('downloading and reading DECam field list') url = 'https://github.com/growth-astro/growth-too-marshal/raw/master/growth/too/input/DECam.tess' table = Table.read(url, names=['field_id', 'ra', 'dec'], format='ascii') log.info('building MOCs') mocs = [ MOC.from_cone(row['ra'] * u.deg, row['dec'] * u.deg, 1.1 * u.deg, 10) for row in table ] log.info('creating ORM records') telescope = Telescope(telescope_name='DECam', fields=[ Field.from_moc(moc, field_id=field_id) for field_id, moc in zip(table['field_id'], mocs) ]) log.info('saving') db.session.add(telescope) db.session.commit() log.info('done')
def get_data(sector): query = "SELECT top 1000 * FROM obsPointing WHERE obs_collection='TESS' AND dataproduct_type='image' " \ "AND sequence_number={}".format(sector) df = query_db(CAOM_OPS, query) df['coords'] = df.apply(lambda x: parse_s_region(x['s_region']), axis=1) # Generate MOC start_time = time.time() pool = ThreadPoolExecutor(max_workers=4) results = list(pool.map(get_polygon_moc, [row for _, row in df.iterrows()])) end_time = time.time() print('Total time : {} seconds'.format(end_time - start_time)) # Union of MOCs start_time = time.time() moc = MOC.union(*results) end_time = time.time() print('Total time : {} seconds'.format(end_time - start_time)) return moc
def from_ipixs_to_moc(self, time_input): """Return ipix table with the associated airmass""" prob = self.moc.read_prob(self.user.get_skymap()) percentage = float(self.entry_percentage.get()) / 100.0 ipixs = self.moc.ipixs_in_percentage(prob, percentage) nside = int(self.user.get_nside()) ra, dec = self.moc.sky_coords(ipixs, nside) sky_coord = SkyCoord(ra=ra * u.deg, dec=dec * u.deg, frame='icrs') altaz = sky_coord.transform_to( AltAz(obstime=time_input, location=self.observatory)) airmass_values = altaz.secz contour_ipix = Table([ra, dec, airmass_values, ipixs], names=('RA[deg]', 'DEC[deg]', 'airmass', 'ipix'), meta={'ipix': 'ipix table'}) # astropy table mask = (contour_ipix['airmass']) >= 1 # clearing obs1 = contour_ipix[mask] mask2 = (obs1['airmass']) <= float( self.entry_airmass.get()) # airmass user values obs = obs1[mask2] # test print obs nside = self.user.get_nside() if len(obs) == 0: tkMessageBox.showinfo('MOC visibility', 'No region for the selected airmass') else: moc_order = self.moc.moc_order(nside) moc = MOC.from_table(obs, 'RA[deg]', 'DEC[deg]', moc_order) # moc creation moc.write('obs_airmass_', format='fits') # fit file return aladin.send_file('obs_airmass_')
def from_ipixs_to_moc(self, time_input): """Return ipix table with the associated airmass""" prob = self.moc.read_prob(self.user.get_skymap()) percentage = float(self.entry_percentage.get())/100.0 ipixs = self.moc.ipixs_in_percentage(prob, percentage ) nside = int(self.user.get_nside()) ra, dec = self.moc.sky_coords(ipixs, nside) sky_coord = SkyCoord(ra = ra*u.deg,dec=dec*u.deg, frame='icrs') altaz = sky_coord.transform_to(AltAz(obstime=time_input, location=self.observatory)) airmass_values = altaz.secz contour_ipix = Table([ ra, dec, airmass_values, ipixs ], names = ('RA[deg]', 'DEC[deg]', 'airmass', 'ipix'), meta = {'ipix': 'ipix table'}) # astropy table mask = (contour_ipix['airmass']) >= 1 # clearing obs1 = contour_ipix[mask] mask2 = (obs1['airmass']) <= float(self.entry_airmass.get()) # airmass user values obs = obs1[mask2] # test print obs nside = self.user.get_nside() if len(obs)==0: tkMessageBox.showinfo('MOC visibility', 'No region for the selected airmass') else: moc_order = self.moc.moc_order(nside) moc = MOC.from_table( obs, 'RA[deg]', 'DEC[deg]', moc_order ) # moc creation moc.write( 'obs_airmass_', format = 'fits' ) # fit file return aladin.send_file('obs_airmass_')
from mocpy import MOC, WCS from astropy.coordinates import Angle, SkyCoord import astropy.units as u # Load a MOC filename = './../../resources/P-SDSS9-r.fits' moc = MOC.from_fits(filename) # Plot the MOC using matplotlib import matplotlib.pyplot as plt fig = plt.figure(111, figsize=(15, 10)) # Define a astropy WCS easily with WCS(fig, fov=200 * u.deg, center=SkyCoord(0, 20, unit='deg', frame='icrs'), coordsys="icrs", rotation=Angle(0, u.degree), projection="AIT") as wcs: ax = fig.add_subplot(1, 1, 1, projection=wcs) # Call fill with a matplotlib axe and the `~astropy.wcs.WCS` wcs object. moc.fill(ax=ax, wcs=wcs, alpha=0.5, fill=True, color="green") moc.border(ax=ax, wcs=wcs, alpha=0.5, color="black") plt.xlabel('ra') plt.ylabel('dec') plt.title('Coverage of P-SDSS9-r') plt.grid(color="black", linestyle="dotted") plt.show()
[ 7.32238541, 6.44905255], [ 0.807265 , 6.53399616], [ 1.08855146, 3.51294225], [ 2.07615384, 0.7118289 ], [ 3.90690158, -1.61886929], [ 9.03727956, 2.80521847], [ 9.22274427, -4.38008174], [10.23563378, 4.06950324], [10.79931601, 3.77655576], [14.16533992, 1.7579858 ], [19.36243491, 1.78587203], [15.31732084, 5. ]]) skycoord = SkyCoord(vertices, unit="deg", frame="icrs") # A point that we say it belongs to the inside of the MOC inside = SkyCoord(ra=10, dec=5, unit="deg", frame="icrs") moc = MOC.from_polygon_skycoord(skycoord, max_depth=9, inside=inside) moc.write('polygon_moc.fits', format='fits', overwrite=True) # Plot the MOC using matplotlib import matplotlib.pyplot as plt fig = plt.figure(111, figsize=(10, 10)) # Define a astropy WCS easily with WCS(fig, fov=20 * u.deg, center=SkyCoord(10, 5, unit='deg', frame='icrs'), coordsys="icrs", rotation=Angle(0, u.degree), # The gnomonic projection transforms great circles into straight lines. projection="TAN") as wcs: ax = fig.add_subplot(1, 1, 1, projection=wcs) # Call fill with a matplotlib axe and the `~astropy.wcs.WCS` wcs object. moc.fill(ax=ax, wcs=wcs, alpha=0.5, fill=True, color="red", linewidth=1)
from mocpy import MOC, WCS from astropy.coordinates import Angle, SkyCoord import astropy.units as u # Load Galex and SDSS sdss = MOC.from_fits('./../../resources/P-SDSS9-r.fits') galex = MOC.from_fits('./../../resources/P-GALEXGR6-AIS-FUV.fits') # Compute their intersection inter = sdss.intersection(galex) union = sdss.union(galex) # Plot the MOC using matplotlib import matplotlib.pyplot as plt fig = plt.figure(111, figsize=(10, 10)) # Define a astropy WCS easily with WCS(fig, fov=160 * u.deg, center=SkyCoord(0, 0, unit='deg', frame='icrs'), coordsys="icrs", rotation=Angle(0, u.degree), projection="AIT") as wcs: ax = fig.add_subplot(1, 1, 1, projection=wcs) # Call fill with a matplotlib axe and the `~astropy.wcs.WCS` wcs object. union.fill(ax=ax, wcs=wcs, alpha=0.5, fill=True, color="red", linewidth=0, label="Union") union.border(ax=ax, wcs=wcs, alpha=1, color="red") inter.fill(ax=ax, wcs=wcs, alpha=0.5, fill=True, color="green", linewidth=0, label="Intersection") inter.border(ax=ax, wcs=wcs, alpha=1, color="green") ax.legend() plt.xlabel('ra') plt.ylabel('dec') plt.title('Logical operations between SDSS and GALEX')
def moc_obs(self): """Creating a MOC region in which the airmass is less than a value defined by users.""" percentage = float(self.entry_percentage.get())/100.0 hpx = hp.read_map(self.user.get_skymap(), verbose = False) sort = sorted(hpx, reverse = True) cumsum = np.cumsum(sort) index, value = min(enumerate(cumsum), key = lambda x: abs(x[1] - percentage)) value = round(value, 1) # value --> threshold print percentage print index, value # finding ipix indices confined in a given percentage index_hpx = range(0, len(hpx)) hpx_index = np.c_[hpx, index_hpx] sort_2array = sorted(hpx_index, key = lambda x: x[0], reverse = True) value_contour = sort_2array[0:index] j = 1 table_ipix_contour = [ ] for i in range (0, len(value_contour)): ipix_contour = int(value_contour[i][j]) table_ipix_contour.append(ipix_contour) # from index to polar coordinates theta, phi = hp.pix2ang(self.user.get_nside(), table_ipix_contour) # converting these to right ascension and declination in degrees ra = np.rad2deg(phi) dec = np.rad2deg(0.5 * np.pi - theta) #print ra # airmass calculation obs_time = Time(self.user.get_obs_time()) observatory = astropy.coordinates.EarthLocation( lat=self.user.get_latitude()*u.deg, lon=self.user.get_longitude()*u.deg,height=self.user.get_altitude()*u.m) sky_coord = SkyCoord(ra = ra*u.deg,dec=dec*u.deg, frame='icrs') altaz = sky_coord.transform_to(AltAz(obstime=self.user.get_obs_time(), location=observatory)) airmass_values = altaz.secz print airmass_values # creating an astropy.table with RA[deg] and DEC[deg] ipix positions contour_ipix = Table([ ra, dec, airmass_values ], names = ( 'RA[deg]', 'DEC[deg]', 'airmass'), meta = {'ipix': 'ipix table'}) mask = (contour_ipix['airmass']) >1 # clear obs1=contour_ipix[mask] mask2 = (obs1['airmass']) <= float(self.entry_airmass.get()) # user values obs = obs1[mask2] # setting MOC order from math import log moc_order = int(log( self.user.get_nside(), 2)) # creating a MOC map from the contour_ipix table moc = MOC.from_table( obs, 'RA[deg]', 'DEC[deg]', moc_order ) # writing MOC file in fits moc.write( 'obs_airmass_'+self.entry_airmass.get()+'MOC_'+str(percentage), format = 'fits' ) print type(self.entry_airmass.get())
def _parse_result(self, response, verbose=False): """ Parsing of the response returned by the MOCServer. Parameters ---------- response : `~requests.Response` The HTTP response returned by the MOCServer. verbose : bool, optional False by default. Returns ------- result : `astropy.table.Table` or `mocpy.MOC` By default an astropy table of the data-sets matching the query. If ``return_moc`` is set to True, it gives a MOC object corresponding to the union of the MOCs from all the matched data-sets. """ if not verbose: commons.suppress_vo_warnings() result = response.json() if not self.return_moc: """ The user will get `astropy.table.Table` object whose columns refer to the returned data-set meta-datas. """ # cast the data-sets meta-datas values to their correct Python type. typed_result = [] for d in result: typed_d = {k: self._cast_to_float(v) for k, v in d.items()} typed_result.append(typed_d) # looping over all the record's keys to find all the existing keys column_names_l = [] for d in typed_result: column_names_l.extend(d.keys()) # remove all the doubles column_names_l = list(set(column_names_l)) # init a dict mapping all the meta-data's name to an empty list table_d = {key: [] for key in column_names_l} type_d = {key: None for key in column_names_l} masked_array_d = {key: [] for key in column_names_l} # fill the dict with the value of each returned data-set one by one. for d in typed_result: row_table_d = {key: None for key in column_names_l} row_table_d.update(d) for k, mask_l in masked_array_d.items(): entry_masked = False if k in d.keys() else True mask_l.append(entry_masked) for k, v in row_table_d.items(): if v: type_d[k] = type(v) table_d[k].append(v) # define all the columns using astropy.table.MaskedColumn objects columns_l = [] for k, v in table_d.items(): try: if k != '#': columns_l.append(MaskedColumn(v, name=k, mask=masked_array_d[k], dtype=type_d[k])) except ValueError: # some metadata can be of multiple types when looking on all the datasets. # this can be due to internal typing errors of the metadatas. columns_l.append(MaskedColumn(v, name=k, mask=masked_array_d[k], dtype=object)) pass # return an `astropy.table.Table` object created from columns_l return Table(columns_l) """ The user will get `mocpy.MOC` object. """ # remove empty_order_removed_d = {} for order, ipix_l in result.items(): if len(ipix_l) > 0: empty_order_removed_d.update({order: ipix_l}) # return a `mocpy.MOC` object. See https://github.com/cds-astro/mocpy and the MOCPy's doc return MOC.from_json(empty_order_removed_d)
from mocpy import MOC, WCS from astropy.coordinates import SkyCoord, Angle from matplotlib.path import Path from matplotlib.patches import PathPatch import astropy.units as u moc = MOC.from_fits('polygon_moc.fits') skycoords = moc.get_boundaries() # Plot the MOC using matplotlib import matplotlib.pyplot as plt fig = plt.figure(111, figsize=(10, 10)) # Define a astropy WCS easily with WCS(fig, fov=20 * u.deg, center=SkyCoord(10, 5, unit='deg', frame='icrs'), coordsys="icrs", rotation=Angle(0, u.degree), # The gnomonic projection transforms great circles into straight lines. projection="TAN") as wcs: ax = fig.add_subplot(1, 1, 1, projection=wcs) # Call fill with a matplotlib axe and the `~astropy.wcs.WCS` wcs object. moc.fill(ax=ax, wcs=wcs, alpha=0.5, fill=True, color="red", linewidth=1) moc.border(ax=ax, wcs=wcs, alpha=1, color="red") # Plot the border from astropy.wcs.utils import skycoord_to_pixel x, y = skycoord_to_pixel(skycoords[0], wcs) p = Path(np.vstack((x, y)).T)