Run a cone search of the Gaia DR2.
770436
def coneSearch(self, center, radius=3*u.arcmin, magnitudelimit=20):
        '''
        
        '''


        self.magnitudelimit = magnitudelimit

        # define a query for cone search surrounding this center
        conequery = """SELECT designation, ra, dec, j_m, h_m, ks_m, j_date FROM gaiadr1.tmass_original_valid WHERE CONTAINS(POINT('ICRS',ra,dec),CIRCLE('ICRS',{},{},{}))=1 and j_m < {}""".format(center.ra.deg, center.dec.deg, radius.to(u.deg).value, magnitudelimit)


        # run the query
        self.speak('querying 2MASS, centered on {} with radius {}, for J<{}'.format(center, radius, magnitudelimit))
        table = self.query(conequery)




        # create skycoord objects
        self.coordinates = coord.SkyCoord(  ra=table['ra'].data*u.deg,
                                        dec=table['dec'].data*u.deg,
                                        obstime=Time(table['j_date'].data, format='jd'))

        self.magnitudes = dict(         J=table['j_m'].data,
                                        H=table['h_m'].data,
                                        Ks=table['ks_m'].data)
        self.magnitude = self.magnitudes['J']
752866
def _search_result(self, name, tipo, obsres, resultid):
        """"""

        instrument = obsres.instrument

        conf = obsres.configuration.uuid

        drp = self.drps.query_by_name(instrument)
        label = drp.product_label(tipo)

        # search results of these OBs
        for prod in self.prod_table[instrument]:
            pid = prod['id']
            if pid == resultid:
                # this is a valid product
                # We have found the result, no more checks
                # Make a copy
                rprod = dict(prod)

                if 'content' in prod:
                    path = prod['content']
                else:
                    # Build path
                    path = build_product_path(drp, self.rootdir, conf, name, tipo, obsres)
                _logger.debug("path is %s", path)
                rprod['content'] = self.product_loader(tipo, name, path)
                return StoredProduct(**rprod)
        else:
            msg = 'result with id %s not found' % (resultid, )
            raise NoResultFound(msg)
914798
def a_star_search(start, successors, state_value, is_goal):
    
    if is_goal(start):
        return [start]
    explored = []
    g = 1
    h = state_value(start)
    f = g + h
    p = [start]
    frontier = [(f, g, h, p)]
    while frontier:
        f, g, h, path = frontier.pop(0)
        s = path[-1]
        for (action, state) in successors(s, path_actions(path)[-1] if len(path) != 1 else []):
            if state not in explored:
                explored.append(state)
                path2 = path + [action, state]
                h2 = state_value(state)
                g2 = g + 1
                f2 = h2 + g2
                if is_goal(state):
                    return path2
                else:
                    frontier.append((f2, g2, h2, path2))
                    frontier.sort(key=lambda x:x[:3])
    return []
888855
def geo_search(self, radius, node=None, center=False, **kwargs):
        ''''''
        node = as_node(node if node is not None else self)

        G = self.subgraph(**kwargs)

        pos = nx.get_node_attributes(G, 'pos')
        if not pos:
            return []
        nodes, coords = list(zip(*pos.items()))
        kdtree = KDTree(coords)  # Cannot provide generator.
        indices = kdtree.query_ball_point(pos[node], radius)
        return [nodes[i] for i in indices if center or (nodes[i] != node)]
538242
def explorev2(self, datasource_type, datasource_id):
        """"""
        return redirect(url_for(
            'Superset.explore',
            datasource_type=datasource_type,
            datasource_id=datasource_id,
            **request.args))
1253441
def calcdelay(self, ant1, ant2, skyfreq, pol):
        

        select = self.select[n.where( (self.skyfreq[self.select] == skyfreq) & (self.polarization[self.select] == pol) )[0]]

        ind1 = n.where(ant1 == self.antnum[select])
        ind2 = n.where(ant2 == self.antnum[select])
        d1 = self.delay[select][ind1]
        d2 = self.delay[select][ind2]
        if len(d1-d2) > 0:
            return d1-d2
        else:
            return n.array([0])
648903
def get(self):
        
        self.log.info('starting the ``get`` method')

        # sort results by angular separation
        from operator import itemgetter
        results = list(self.squareResults)
        results = sorted(
            results, key=itemgetter('separation_arcsec'), reverse=True)

        # order of results
        headers = ["sdss_name", "type", "ra", "dec", "specz", "specz_err", "photoz",
                   "photoz_err", "separation_arcsec", "separation_north_arcsec", "separation_east_arcsec"]

        import collections
        orderDict = collections.OrderedDict(sorted({}.items()))

        # filter out results greater than the search radius
        filteredResults = []
        for row in results:
            if float(row["separation_arcsec"]) < self.searchRadius:
                orderDict = collections.OrderedDict(sorted({}.items()))
                for h in headers:
                    if h in row.keys():
                        orderDict[h] = row[h]
                filteredResults.append(orderDict)
            else:
                pass

        if self.nearest and len(filteredResults):
            orderDict = collections.OrderedDict(sorted({}.items()))
            for h in headers:
                if h in filteredResults[0].keys():
                    orderDict[h] = row[h]
            filteredResults = [orderDict]
            # filteredResults = [filteredResults[0]]

        if not len(filteredResults):
            orderDict = collections.OrderedDict(sorted({}.items()))
            for h in headers:
                if self.galaxyType == "all" or self.galaxyType == False or (self.galaxyType == "specz" and h not in ["photoz_err", "photoz"]) or (self.galaxyType == "photoz" and h not in ["specz", "specz_err"]):
                    orderDict[h] = ""
            filteredResults = [orderDict]

        # pretty format print
        dataSet = list_of_dictionaries(
            log=self.log,
            listOfDictionaries=list(reversed(filteredResults))
        )
        if self.outputFormat == "csv":
            results = dataSet.csv()
        else:
            results = dataSet.table()

        # sdss only allows 60 hits per minute
        sleep(1)

        self.log.info('completed the ``get`` method')
        return results
1335915
def ang2pix(nside, theta, phi):
    
    """
    nside, theta, phi = numpy.lib.stride_tricks.broadcast_arrays(nside, theta, phi)

    def equatorial(nside, tt, z):
        t1 = nside * (0.5 + tt)
        t2 = nside * z * 0.75
        jp = (t1 - t2).astype('i8')
        jm = (t1 + t2).astype('i8')
        ir = nside + 1 + jp - jm # in {1, 2n + 1}
        kshift = 1 - (ir & 1) # kshift=1 if ir even, 0 odd

        ip = (jp + jm - nside + kshift + 1) // 2 # in {0, 4n - 1}

        ip = ip % (4 * nside)
        return nside * (nside - 1) * 2 + (ir - 1) * 4 * nside + ip

    def polecaps(nside, tt, z, s):
        tp = tt - numpy.floor(tt)
        za = numpy.abs(z)
        tmp = nside * s / ((1 + za) / 3) ** 0.5
        mp = za > 0.99
        tmp[mp] = nside[mp] * (3 *(1-za[mp])) ** 0.5
        jp = (tp * tmp).astype('i8')
        jm = ((1 - tp) * tmp).astype('i8')
        ir = jp + jm + 1
        ip = (tt * ir).astype('i8')
        ip = ip % (4 * ir)

        r1 = 2 * ir * (ir - 1)
        r2 = 2 * ir * (ir + 1)

        r = numpy.empty_like(r1)

        r[z > 0] = r1[z > 0] + ip[z > 0]
        r[z < 0] = 12 * nside[z < 0] * nside[z < 0] - r2[z < 0] + ip[z < 0]
        return r

    z = numpy.cos(theta)
    s = numpy.sin(theta)

    tt = (phi / (0.5 * numpy.pi) ) % 4 # in [0, 4]

    result = numpy.zeros(z.shape, dtype='i8')
    mask = (z < 2. / 3) & (z > -2. / 3)

    result[mask] = equatorial(nside[mask], tt[mask], z[mask])
    result[~mask] = polecaps(nside[~mask], tt[~mask], z[~mask], s[~mask])
    return result
827737
def allskyfinder(self, figsize=(14, 7), **kwargs):
        '''
        
        '''

        plt.figure(figsize=figsize)
        scatter = self.plot(**kwargs)
        plt.xlabel(r'Right Ascension ($^\circ$)'); plt.ylabel(r'Declination ($^\circ$)')
        #plt.title('{} in {:.1f}'.format(self.name, epoch))
        plt.xlim(0, 360)
        plt.ylim(-90,90)
        return scatter
778379
def run(self):
        
        import numpy as np

        # get all NUTS region IDs, for linking values to region objects
        query = self.session.query(models.NUTS2Region.key,
                                   models.NUTS2Region.id)
        region_ids = self.client.df_query(query).set_index('key')['id'].to_dict()

        # load climate data and NUTS2 polygons
        data = next(self.requires()).load()
        nuts = NUTS2GeoJSONInputFile().load()

        # generated indicator IDs, keyed by season
        indicator_ids = dict()

        # climate data by season
        t_data = dict()

        # create new indicator objects for summer and winter, create averaged climate data
        for season, suffix in CLIMATE_SEASON_SUFFIXES.items():
            # noinspection PyUnresolvedReferences
            indicator = models.ClimateIndicator(description=self.description + suffix)
            self.session.add(indicator)

            # commit, to get indicator ID filled
            self.session.commit()
            indicator_ids[season] = indicator.id

            # select winter or summer data by month index, average over time range
            if season == 'summer':
                t_data[season] = np.ma.average(data['data'][3:9, :, :], axis=0)
            else:
                # noinspection PyTypeChecker
                t_data[season] = np.ma.average(0.5 * (data['data'][0:3, :, :] + data['data'][9:12, :, :]), axis=0)

        # container for output objects, for bulk saving
        objects = []

        # start value for manual object id generation
        current_value_id = models.ClimateValue.get_max_id(self.session)

        # for each region, get a mask, average climate variable over the mask and store the indicator value;
        # loop over features first, then over seasons, because mask generation is expensive
        for feature in nuts:

            # draw region mask (doesn't matter for which season we take the map shape)
            mask = geojson_polygon_to_mask(feature=feature,
                                           shape=t_data['summer'].shape,
                                           lat_idx=data['lat_idx'],
                                           lon_idx=data['lon_idx'])

            # create indicator values for summer and winter
            for season in list(CLIMATE_SEASON_SUFFIXES.keys()):
                # weighted average from region mask
                value = np.ma.average(t_data[season], weights=mask)

                # region ID must be cast to int (DBs don't like numpy dtypes from pandas)
                region_id = region_ids.get(feature.properties['NUTS_ID'], None)
                if region_id is not None:
                    region_id = int(region_id)

                # append an indicator value, manually generate object IDs for bulk saving
                current_value_id += 1
                objects.append(models.ClimateValue(id=current_value_id,
                                                   value=value,
                                                   region_id=region_id,
                                                   indicator_id=indicator_ids[season]))

                # # print some debugging output
                # print self.variable_name + ' ' + season, feature.properties['NUTS_ID'], value

                # # generate some plots for debugging
                # from matplotlib import pyplot as plt
                # plt.subplot(211)
                # plt.imshow(0.02 * t_data + mask * t_data, interpolation='none')
                # plt.subplot(212)
                # plt.imshow(t_data, interpolation='none')
                # plt.savefig('/tmp/' + feature.properties['NUTS_ID'] + '.png')

        # bulk-save all objects
        self.session.bulk_save_objects(objects)
        self.session.commit()

        self.done()
156267
def search_star(star):
    '''
    
    '''

    base_url = "http://star-api.herokuapp.com/api/v1/stars/"

    if not isinstance(star, str):
        raise ValueError("The star arg you provided is not the type of str")
    else:
        base_url += star

    return dispatch_http_get(base_url)
260635
def calcgain(self, ant1, ant2, skyfreq, pol):
        

        select = self.select[n.where( (self.skyfreq[self.select] == skyfreq) & (self.polarization[self.select] == pol) )[0]]

        if len(select):  # for when telcal solutions don't exist
            ind1 = n.where(ant1 == self.antnum[select])
            ind2 = n.where(ant2 == self.antnum[select])
            g1 = self.amp[select][ind1]*n.exp(1j*n.radians(self.phase[select][ind1])) * (not self.flagged.astype(int)[select][ind1][0])
            g2 = self.amp[select][ind2]*n.exp(-1j*n.radians(self.phase[select][ind2])) * (not self.flagged.astype(int)[select][ind2][0])
        else:
            g1 = [0]; g2 = [0]

        try:
            assert (g1[0] != 0j) and (g2[0] != 0j)
            invg1g2 = 1./(g1[0]*g2[0])
        except (AssertionError, IndexError):
            invg1g2 = 0
        return invg1g2
1114905
def Search(ID, mission='k2'):
    """"""
    # Only K2 supported for now
    assert mission == 'k2', "Only the K2 mission is supported for now."
    print("Searching for target %d..." % ID)

    # First check if it is in the database
    season = missions.k2.Season(ID)
    if season in [91, 92, [91, 92]]:
        print("Campaign 9 is currently not part of the EVEREST catalog.")
        return
    elif season == 101:
        print("The first half of campaign 10 is not currently part of " +
              "the EVEREST catalog.")
        return
    elif season is not None:
        print("Target is in campaign %d of the EVEREST catalog." % season)
        return

    # Get the kplr object
    star = k2plr_client.k2_star(ID)

    # First check if this is a star
    if star.objtype.lower() != "star":
        print("Target is of type %s, not STAR, " % star.objtype +
              "and is therefore not included in the EVEREST catalog.")
        return

    # Let's try to download the pixel data and see what happens
    try:
        tpf = star.get_target_pixel_files()
    except:
        print("Unable to download the raw pixel files for this target.")
        return
    if len(tpf) == 0:
        print("Raw pixel files are not available for this target. Looks like " +
              "data may not have been collected for it.")
        return

    # Perhaps it's in a campaign we haven't gotten to yet
    if tpf[0].sci_campaign not in missions.k2.SEASONS:
        print("Targets for campaign %d are not yet available."
              % tpf[0].sci_campaign)
        return

    # Let's try to download the K2SFF data
    try:
        k2sff = k2plr.K2SFF(ID)
    except:
        print("Error downloading the K2SFF light curve for this target. " +
              "Currently, EVEREST uses the K2SFF apertures to perform " +
              "photometry. This is likely to change in the next version.")
        return

    # Let's try to get the aperture
    try:
        assert np.count_nonzero(k2sff.apertures[15]), "Invalid aperture."
    except:
        print("Unable to retrieve the K2SFF aperture for this target. " +
              "Currently, EVEREST uses the K2SFF apertures to perform " +
              "photometry. This is likely to change in the next version.")
        return

    # Perhaps the star is *super* saturated and we didn't bother
    # de-trending it?
    if star.kp < 8:
        print("Target has Kp = %.1f and is too saturated " +
              "for proper de-trending with EVEREST.")
        return

    # I'm out of ideas
    print("I'm not sure why this target isn't in the EVEREST catalog." +
          "You can try de-trending it yourself:")
    print("http://faculty.washington.edu/rodluger/everest/pipeline.html")
    return
830631
def within(self, x, ctrs, kdtree=None):
        """"""

        if kdtree is None:
            # If no K-D Tree is provided, execute a brute-force
            # search over all balls.
            idxs = np.where(lalg.norm(ctrs - x, axis=1) <= self.radius)[0]
        else:
            # If a K-D Tree is provided, find all points within `self.radius`.
            idxs = kdtree.query_ball_point(x, self.radius, p=2.0, eps=0)

        return idxs
915775
def search(self, dstpath, **params):
        

        self.logger.debug("search params=%s" % (str(params)))
        ra, dec = params['ra'], params['dec']
        if not (':' in ra):
            # Assume RA and DEC are in degrees
            ra_deg = float(ra)
            dec_deg = float(dec)
        else:
            # Assume RA and DEC are in standard string notation
            ra_deg = wcs.hmsStrToDeg(ra)
            dec_deg = wcs.dmsStrToDeg(dec)

        # Convert to degrees for search
        wd_deg = float(params['width']) / 60.0
        ht_deg = float(params['height']) / 60.0
        # wd_deg = float(params['width'])
        # ht_deg = float(params['height'])

        # initialize our query object with the service's base URL
        query = pyvo.sia.SIAQuery(self.url)
        query.ra = ra_deg
        query.dec = dec_deg
        query.size = (wd_deg, ht_deg)
        query.format = 'image/fits'
        self.logger.info("Will query: %s" % query.getqueryurl(True))

        results = query.execute()
        if len(results) > 0:
            self.logger.info("Found %d images" % len(results))
        else:
            self.logger.warning("Found no images in this area" % len(results))
            return None

        # For now, we pick the first one found

        # REQUIRES FIX IN PYVO:
        # imfile = results[0].cachedataset(dir="/tmp")
        #
        # Workaround:
        fitspath = results[0].make_dataset_filename(dir="/tmp")
        results[0].cachedataset(fitspath)

        # explicit return
        return fitspath
635502
def run(time: datetime, altkm: float,
        glat: Union[float, np.ndarray], glon: Union[float, np.ndarray], *,
        f107a: float = None, f107: float = None, Ap: int = None) -> xarray.Dataset:
    
    glat = np.atleast_2d(glat)
    glon = np.atleast_2d(glon)  # has to be here
# %% altitude 1-D
    if glat.size == 1 and glon.size == 1 and isinstance(time, (str, date, datetime, np.datetime64)):
        atmos = rungtd1d(time, altkm, glat.squeeze()[()], glon.squeeze()[()],
                         f107a=f107a, f107=f107, Ap=Ap)
# %% lat/lon grid at 1 altitude
    else:
        atmos = loopalt_gtd(time, glat, glon, altkm,
                            f107a=f107a, f107=f107, Ap=Ap)

    return atmos
1070465
def update(self):
        
        g = get_root(self).globals

        if g.astro is None or g.fpslide is None:
            self.after(100, self.update)
            return

        try:
            if g.cpars['tcs_on']:

                try:
                    # Poll TCS for ra,dec etc.
                    ra, dec, pa, focus = self.tcs_data_queue.get(block=False)

                    # format ra, dec as HMS
                    coo = coord.SkyCoord(ra, dec, unit=(u.deg, u.deg))
                    ratxt = coo.ra.to_string(sep=':', unit=u.hour, precision=0)
                    dectxt = coo.dec.to_string(sep=':', unit=u.deg,
                                               alwayssign=True,
                                               precision=0)
                    self.ra.configure(text=ratxt)
                    self.dec.configure(text=dectxt)

                    # wrap pa from 0 to 360
                    pa = coord.Longitude(pa*u.deg)
                    self.pa.configure(text='{0:6.2f}'.format(pa.value))

                    # set focus
                    self.focus.configure(text='{0:+5.2f}'.format(focus))

                    # Calculate most of the
                    # stuff that we don't get from the telescope
                    now = Time.now()
                    with warnings.catch_warnings():
                        warnings.simplefilter('ignore')
                        # ignore astropy deprecation warnings
                        lon = g.astro.obs.longitude
                    lst = now.sidereal_time(kind='mean',
                                            longitude=lon)
                    ha = coo.ra.hourangle*u.hourangle - lst
                    hatxt = ha.wrap_at(12*u.hourangle).to_string(sep=':', precision=0)
                    self.ha.configure(text=hatxt)

                    altaz_frame = coord.AltAz(obstime=now, location=g.astro.obs)
                    altaz = coo.transform_to(altaz_frame)
                    self.alt.configure(text='{0:<4.1f}'.format(altaz.alt.value))
                    self.az.configure(text='{0:<5.1f}'.format(altaz.az.value))
                    # set airmass
                    self.airmass.configure(text='{0:<4.2f}'.format(altaz.secz))

                    # distance to the moon. Warn if too close
                    # (configurable) to it.
                    md = coord.get_moon(now, g.astro.obs).separation(coo)
                    self.mdist.configure(text='{0:<7.2f}'.format(md.value))
                    if md < g.cpars['mdist_warn']*u.deg:
                        self.mdist.configure(bg=g.COL['warn'])
                    else:
                        self.mdist.configure(bg=g.COL['main'])
                except Empty:
                    # silently do nothing if queue is empty
                    pass
                except Exception as err:
                    self.ra.configure(text='UNDEF')
                    self.dec.configure(text='UNDEF')
                    self.pa.configure(text='UNDEF')
                    self.ha.configure(text='UNDEF')
                    self.alt.configure(text='UNDEF')
                    self.az.configure(text='UNDEF')
                    self.airmass.configure(text='UNDEF')
                    self.mdist.configure(text='UNDEF')
                    g.clog.warn('TCS error: ' + str(err))

            if g.cpars['hcam_server_on'] and \
               g.cpars['eso_server_online']:

                # get run number (set by the 'Start' button')
                try:
                    # get run number from hipercam server
                    run = getRunNumber(g)
                    self.run.configure(text='{0:03d}'.format(run))

                    # Find the number of frames in this run
                    try:
                        frame_no = getFrameNumber(g)
                        self.frame.configure(text='{0:04d}'.format(frame_no))
                    except Exception as err:
                        if err.code == 404:
                            self.frame.configure(text='0')
                        else:
                            g.clog.debug('Error occurred trying to set frame')
                            self.frame.configure(text='UNDEF')

                except Exception as err:
                    g.clog.debug('Error trying to set run: ' + str(err))

            # get the slide position
            # poll at 5x slower rate than the frame
            if self.count % 5 == 0 and g.cpars['focal_plane_slide_on']:
                try:
                    pos_ms, pos_mm, pos_px = self.slide_pos_queue.get(block=False)
                    self.fpslide.configure(text='{0:d}'.format(
                        int(round(pos_px))))
                    if pos_px < 1050.:
                        self.fpslide.configure(bg=g.COL['warn'])
                    else:
                        self.fpslide.configure(bg=g.COL['main'])
                except Exception as err:
                    pass

            # get the CCD temperature poll at 5x slower rate than the frame
            if self.count % 5 == 0:
                try:
                    if g.ccd_hw is not None and g.ccd_hw.ok:
                        self.ccd_temps.configure(text='OK')
                        self.ccd_temps.configure(bg=g.COL['main'])
                    else:
                        self.ccd_temps.configure(text='ERR')
                        self.ccd_temps.configure(bg=g.COL['warn'])
                except Exception as err:
                    g.clog.warn(str(err))
                    self.ccd_temps.configure(text='UNDEF')
                    self.ccd_temps.configure(bg=g.COL['warn'])

        except Exception as err:
            # this is a safety catchall trap as it is important
            # that this routine keeps going
            g.clog.warn('Unexpected error: ' + str(err))

        # run every 2 seconds
        self.count += 1
        self.after(2000, self.update)