Plot the sky coverage of pointing at event.x,event.y on the canavas
332251
def create_pointing(self,event):
        """"""

        import math
        (ra,dec)=self.c2p((self.canvasx(event.x),
                           self.canvasy(event.y)))
        this_camera=camera(camera=self.camera.get())
        ccds=this_camera.getGeometry(ra,dec)
        items=[]
        for ccd in ccds:
            (x1,y1)=self.p2c((ccd[0],ccd[1]))
            (x2,y2)=self.p2c((ccd[2],ccd[3]))
            item=self.create_rectangle(x1,y1,x2,y2)
            items.append(item)
	label={}
	label['text']=w.plabel.get()
	label['id']=self.label(this_camera.ra,this_camera.dec,label['text'])
        self.pointings.append({
		"label": label,
		"items": items,
		"camera": this_camera} )
        self.current_pointing(len(self.pointings)-1)
979267
def show(cmap, var, vmin=None, vmax=None):
    '''

    '''

    # get variable data
    lat, lon, z, data = read(var)

    fig = plt.figure(figsize=(16, 12))

    # Plot with grayscale
    ax = fig.add_subplot(3, 1, 1)
    map1 = ax.scatter(lon, -z, c=data, cmap='gray', s=10, linewidths=0., vmin=vmin, vmax=vmax)
    plt.colorbar(map1, ax=ax)

    # Plot with jet
    ax = fig.add_subplot(3, 1, 2)
    map1 = ax.scatter(lon, -z, c=data, cmap='jet', s=10, linewidths=0., vmin=vmin, vmax=vmax)
    plt.colorbar(map1, ax=ax)

    # Plot with cmap
    ax = fig.add_subplot(3, 1, 3)
    map1 = ax.scatter(lon, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=vmin, vmax=vmax)
    ax.set_xlabel('Longitude [degrees]')
    ax.set_ylabel('Depth [m]')
    plt.colorbar(map1, ax=ax)

    plt.suptitle(var)
368476
def plot_sphere(ax, center, radius, color='black', alpha=1., linspace_count=_LINSPACE_COUNT):
    

    u = np.linspace(0, 2 * np.pi, linspace_count)
    v = np.linspace(0, np.pi, linspace_count)
    sin_v = np.sin(v)
    x = center[0] + radius * np.outer(np.cos(u), sin_v)
    y = center[1] + radius * np.outer(np.sin(u), sin_v)
    z = center[2] + radius * np.outer(np.ones_like(u), np.cos(v))

    ax.plot_surface(x, y, z, linewidth=0.0, color=color, alpha=alpha)
1231653
def save_pointings(self):
        """"""
        i = 0
        if self.pointing_format.get() in ['GEMINI ET', 'CFHT ET', 'CFHT API']:
            logging.info('Beginning table pointing save.')
            for pointing in self.pointings:
                name = pointing["label"]["text"]
                camera = pointing["camera"]
                ccds = numpy.radians(camera.geometry)
                polygons = []
                for ccd in ccds:
                    polygon = Polygon.Polygon(((ccd[0], ccd[1]),
                                               (ccd[0], ccd[3]),
                                               (ccd[2], ccd[3]),
                                               (ccd[2], ccd[1]),
                                               (ccd[0], ccd[1])))
                    polygons.append(polygon)
                et = EphemTarget(name, ephem_format=self.pointing_format.get())
                # determine the mean motion of target KBOs in this field.
                field_kbos = []
                center_ra = 0
                center_dec = 0

                pointing_date = mpc.Time(self.date.get(), scale='utc')
                start_date = mpc.Time(self.date.get(), scale='utc') - TimeDelta(8.1*units.day)
                end_date = start_date + TimeDelta(17*units.day)
                time_step = TimeDelta(3.0*units.hour)

                # Compute the mean position of KBOs in the field on current date.
                for kbo_name, kbo in self.kbos.items():
                    if kbo_name in Neptune or kbo_name in tracking_termination:
                        print 'skipping', kbo_name
                        continue
                    kbo.predict(pointing_date)
                    ra = kbo.coordinate.ra
                    dec = kbo.coordinate.dec
                    if kbo_name in name:
                        print "{} matches pointing {} by name, adding to field.".format(kbo_name, name)
                        field_kbos.append(kbo)
                        center_ra += ra.radian
                        center_dec += dec.radian
                    else:
                        for polygon in polygons:
                            if polygon.isInside(ra.radian, dec.radian):
                                print "{} inside pointing {} polygon, adding to field.".format(kbo_name, name)
                                field_kbos.append(kbo)
                                center_ra += ra.radian
                                center_dec += dec.radian

                # logging.critical("KBOs in field {0}: {1}".format(name, ', '.join([n.name for n in field_kbos])))

                today = start_date
                while today < end_date:
                    today += time_step
                    mean_motion = (0, 0)
                    max_mag = 0.0
                    if len(field_kbos) > 0:
                        current_ra = 0
                        current_dec = 0
                        for kbo in field_kbos:
                            kbo.predict(today)
                            max_mag = max(max_mag, kbo.mag)
                            current_ra += kbo.coordinate.ra.radian
                            current_dec += kbo.coordinate.dec.radian
                        mean_motion = ((current_ra - center_ra) / len(field_kbos),
                                       (current_dec - center_dec) / len(field_kbos))
                    ra = pointing['camera'].coordinate.ra.radian + mean_motion[0]
                    dec = pointing['camera'].coordinate.dec.radian + mean_motion[1]
                    cc = SkyCoord(ra=ra,
                                  dec=dec,
                                  unit=(units.radian, units.radian),
                                  obstime=today)
                    dt = pointing_date - today
                    cc.dra = (mean_motion[0] * units.radian / dt.to(units.hour)).to(units.arcsec/units.hour).value*math.cos(dec)
                    cc.ddec = (mean_motion[1] * units.radian / dt.to(units.hour)).to(units.arcsec/units.hour).value
                    cc.mag = max_mag
                    et.append(cc)

                et.save()
            return

        f = tkFileDialog.asksaveasfile()
        if self.pointing_format.get() == 'Subaru':
            for pointing in self.pointings:
                (sra, sdec) = str(pointing["camera"]).split()
                ra = sra.replace(":", "")
                dec = sdec.replace(":", "")
                name = pointing["label"]["text"]
                f.write("""{}=OBJECT="{}" RA={} DEC={} EQUINOX=2000.0 INSROT_PA=90\n""".format(name,
                                                                                               name,
                                                                                               ra,
                                                                                               dec))
            return
        if self.pointing_format.get() == 'CFHT PH':
            f.write("""<?xml version = "1.0"?>
<!DOCTYPE ASTRO SYSTEM "http://vizier.u-strasbg.fr/xml/astrores.dtd">
<ASTRO ID="v0.8" xmlns:ASTRO="http://vizier.u-strasbg.fr/doc/astrores.htx">
<TABLE ID="Table">
<NAME>Fixed Targets</NAME>
<TITLE>Fixed Targets for CFHT QSO</TITLE>
<!-- Definition of each field -->
<FIELD name="NAME" datatype="A" width="20">
   <DESCRIPTION>Name of target</DESCRIPTION>
</FIELD>
<FIELD name="RA" ref="" datatype="A" width="11" unit="&quot;h:m:s&quot;">
   <DESCRIPTION>Right ascension of target</DESCRIPTION>
</FIELD>     
<FIELD name="DEC" ref="" datatype="A" width="11" unit="&quot;d:m:s&quot;">
   <DESCRIPTION>Declination of target</DESCRIPTION>
</FIELD>     
<FIELD name="EPOCH" datatype="F" width="6">
    <DESCRIPTION>Epoch of coordinates</DESCRIPTION>
</FIELD>     
<FIELD name="POINT" datatype="A" width="5">
<DESCRIPTION>Pointing name</DESCRIPTION>
</FIELD>     
<!-- Data table --> 
<DATA><CSV headlines="4" colsep="|"><![CDATA[
NAME                |RA         |DEC        |EPOCH |POINT|
                    |hh:mm:ss.ss|+dd:mm:ss.s|      |     |
12345678901234567890|12345678901|12345678901|123456|12345|
--------------------|-----------|-----------|------|-----|\n""")
        if self.pointing_format.get() == 'Palomar':
            f.write("index\n")
        for pointing in self.pointings:
            i = i + 1
            name = pointing["label"]["text"]
            (sra, sdec) = str(pointing["camera"]).split()
            ra = sra.split(":")
            dec = sdec.split(":")
            dec[0] = str(int(dec[0]))
            if int(dec[0]) >= 0:
                dec[0] = '+' + dec[0]
            if self.pointing_format.get() == 'Palomar':
                f.write("%5d %16s %2s %2s %4s %3s %2s %4s 2000\n" % (i, name,
                                                                     ra[0].zfill(2),
                                                                     ra[1].zfill(2),
                                                                     ra[2].zfill(2),
                                                                     dec[0].zfill(3),
                                                                     dec[1].zfill(2),
                                                                     dec[2].zfill(2)))
            elif self.pointing_format.get() == 'CFHT PH':
                # f.write("%f %f\n" % (pointing["camera"].ra,pointing["camera"].dec))
                f.write("%-20s|%11s|%11s|%6.1f|%-5d|\n" % (name, sra, sdec, 2000.0, 1))
            elif self.pointing_format.get() == 'KPNO/CTIO':
                str1 = sra.replace(":", " ")
                str2 = sdec.replace(":", " ")
                f.write("%16s %16s %16s 2000\n" % ( name, str1, str2))
            elif self.pointing_format.get() == 'SSim':
                ra = []
                dec = []
                for ccd in pointing["camera"].geometry:
                    ra.append(ccd[0])
                    ra.append(ccd[2])
                    dec.append(ccd[1])
                    dec.append(ccd[3])

                dra = math.degrees(math.fabs(max(ra) - min(ra)))
                ddec = math.degrees(math.fabs(max(dec) - min(dec)))
                f.write("%f %f %16s %16s DATE 1.00 1.00 500 FILE\n" % (dra, ddec, sra, sdec ))
        if self.pointing_format.get() == 'CFHT PH':
            f.write("""]]</CSV></DATA>
</TABLE>
</ASTRO>
""")
        f.close()
422536
def _plot_stars(catalog, observer, project, ax, mag1, mag2, margin=1.25):
    """"""

    art = []

    # from astropy import wcs
    # w = wcs.WCS(naxis=2)
    # w.wcs.crpix = [-234.75, 8.3393]
    # w.wcs.cdelt = np.array([-0.066667, 0.066667])
    # w.wcs.crval = [0, -90]
    # w.wcs.ctype = ["RA---AIR", "DEC--AIR"]
    # w.wcs.set_pv([(2, 1, 45.0)])

    # import matplotlib.pyplot as plt

    # plt.subplot(projection=wcs)
    # #plt.imshow(hdu.data, vmin=-2.e-5, vmax=2.e-4, origin='lower')
    # plt.grid(color='white', ls='solid')
    # plt.xlabel('Galactic Longitude')
    # plt.ylabel('Galactic Latitude')

    xmin, xmax = ax.get_xlim()
    ymin, ymax = ax.get_xlim()
    lim = max(abs(xmin), abs(xmax), abs(ymin), abs(ymax)) * margin
    lims = (-lim, lim)
    ax.set_xlim(lims)
    ax.set_ylim(lims)
    ax.set_aspect('equal')

    o = observer[0]

    # Dim stars: points of with varying gray levels.

    c = catalog
    c = c[c['magnitude'] > mag1]
    c = c[c['magnitude'] <= mag2]
    #print('Second star group:', len(c))
    c = c.sort_values('magnitude', ascending=False)
    s = Star(ra_hours=c.ra_hours, dec_degrees=c.dec_degrees)
    spos = o.observe(s)
    x, y = project(spos)
    m = (mag2 - c['magnitude']) / (mag2 - mag1)
    # Note that "gray_r" is white for 0.0 and black for 1.0
    art.append(ax.scatter(
        x, y, s=1.0,
        c=1 - 0.8 * m, cmap='gray_r', vmin=0.0, vmax=1.0,
    ))

    # Bright stars: black circles of varying radius, surrounded by a
    # white gap in case stars are touching.  Draw the brightest stars
    # first to stop them from completely occluding smaller companions.

    def mag_to_radius(m):
        return (mag1 - m) * scale + 1.0

    c = catalog
    c = c[c['magnitude'] <= mag1]
    c = c.sort_values('magnitude', ascending=True)
    #print('First star group:', len(c))
    s = Star(ra_hours=c.ra_hours, dec_degrees=c.dec_degrees)
    spos = o.observe(s)
    x, y = project(spos)
    scale = 1.5
    radius = mag_to_radius(c['magnitude'])

    x2 = np.repeat(x, 2)
    y2 = np.repeat(y, 2)
    radius2 = (radius[:,None] + (3.0,0.0)).flatten()
    c2 = ('w', 'k')
    c2 = ('k', 'w')

    art.append(ax.scatter(x2, y2, s=radius2 ** 2.0, c=c2))

    return art, mag_to_radius
430943
def get_pointings(self):
        """"""
	import MOPdbaccess,ephem,math
        import tkSimpleDialog
        result = tkSimpleDialog.askstring("Block Load", "Which Block do you want to plot?")
        db = MOPdbaccess.connect('bucket','cfhls',dbSystem='MYSQL')
        SQL = """SELECT object,ra,`dec`,status,ccd FROM blocks b 
			JOIN cfeps.triple_members m ON m.expnum=b.expnum
			JOIN cfeps.discovery d ON d.triple=m.triple
			JOIN exposure e ON e.expnum=b.expnum
                        LEFT JOIN cfeps.processing p ON p.triple=m.triple
		WHERE p.process='plant' and b.block RLIKE '%s' GROUP BY m.triple,p.ccd """ % (result)
	points=[]
	c = db.cursor()
	r = c.execute(SQL)
	rows=c.fetchall()

        print len(rows)
        geo = camera.geometry['MEGACAM_36']
        main_pointing=''
	for row in rows:
            if main_pointing != row[0]:
                # put down the 'full MP FOV' here
                c=camera(camera='MEGACAM_1')
                if row[4]!= "NULL":
                    color='pale green'
                else:
                    color='gray'
                label={'text': row[0]}
                c.ra=ephem.hours(math.radians(float(row[1])))
                c.dec=ephem.degrees(math.radians(float(row[2])))
                self.pointings.append({"label": label,
                                       "camera": c,
                                       "color": color})
                main_pointing=row[0]
            if int(row[3]) < 0:
                # Create a 'red' box for this CCD
                c=camera(camera='MP_CCD')
                c.ra = ephem.hours(math.radians(float(row[1])-geo[int(row[4])]["ra"]/math.cos(math.radians(float(row[2])))))
                c.dec =ephem.degrees(math.radians(float(row[2])-geo[int(row[4])]["dec"]))
                color='red'
                label={'text': str(row[4])}
                self.pointings.append({"label": label, "camera": c,"color":color})
                                       
        self.plot_pointings()

        return
236841
def plotgwsrc(gwb):
    
    theta, phi, omega, polarization = gwb.gw_dist()

    rho = phi-N.pi
    eta = 0.5*N.pi - theta

    # I don't know how to get rid of the RuntimeWarning -- RvH, Oct 10, 2014:
    #     /Users/vhaaster/env/dev/lib/python2.7/site-packages/matplotlib/projections/geo.py:485:
    #     RuntimeWarning: invalid value encountered in arcsin theta = np.arcsin(y / np.sqrt(2))
    #old_settings = N.seterr(invalid='ignore')

    P.title("GWB source population")
    ax = P.axes(projection='mollweide')

    foo = P.scatter(rho, eta, marker='.', s=1)
    #bar = N.seterr(**old_settings)

    return foo
78532
def plot_gos(fout_png, goids, obo_dag, *args, **kws):
    """"""
    engine = kws['engine'] if 'engine' in kws else 'pydot'
    godagsmall = OboToGoDagSmall(goids=goids, obodag=obo_dag).godag
    godagplot = GODagSmallPlot(godagsmall, *args, **kws)
    godagplot.plt(fout_png, engine)
1104019
def plot(x, y, z, color=default_color, **kwargs):
    
    fig = gcf()
    _grow_limits(x, y, z)
    defaults = dict(
        visible_lines=True, color_selected=None, size_selected=1, size=1, connected=True, visible_markers=False
    )
    kwargs = dict(defaults, **kwargs)
    s = ipv.Scatter(x=x, y=y, z=z, color=color, **kwargs)
    s.material.visible = False
    fig.scatters = fig.scatters + [s]
    return s
851297
def sky(lon=None,lat=None,size=1):
    
    if lon is None:
        umin,umax = 0,1
    else:
        lon = np.asarray(lon)
        lon = np.radians(lon + 360.*(lon<0))
        if   lon.size==1: umin=umax=lon/(2*np.pi)
        elif lon.size==2: umin,umax=lon/(2*np.pi)
        else: raise Exception('...')
        
    if lat is None:
        vmin,vmax = -1,1
    else:
        lat = np.asarray(lat)
        lat = np.radians(90 - lat)
        if   lat.size==1: vmin=vmax=np.cos(lat)
        elif lat.size==2: vmin,vmax=np.cos(lat)
        else: raise Exception('...')

    phi = 2*np.pi*np.random.uniform(umin,umax,size=size)
    theta = np.arcsin(np.random.uniform(vmin,vmax,size=size))
    return np.degrees(phi),np.degrees(theta)
760669
def plot_data():
    '''

    '''

    var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM']
    # colorbar limits for each property
    lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2], [0, 9]])  # reasonable values
    # lims = np.array([[20,36], [26,33], [1.5,5.6], [0,4], [0,9], [0,1.5]]) # values to show colormaps

    for fname in fnames:
        fig, axes = plt.subplots(nrows=4, ncols=2)
        fig.set_size_inches(20, 10)
        fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.0, hspace=0.07)
        i = 0
        for ax, Var, cmap in zip(axes.flat, var, cmaps):  # loop through data to plot up

            # get variable data
            lat, lon, z, data = test.read(Var, fname)

            map1 = ax.scatter(lat, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=lims[i, 0], vmax=lims[i, 1])
            # no stupid offset
            y_formatter = mpl.ticker.ScalarFormatter(useOffset=False)
            ax.xaxis.set_major_formatter(y_formatter)
            if i == 6:
                ax.set_xlabel('Latitude [degrees]')
                ax.set_ylabel('Depth [m]')
            else:
                ax.set_xticklabels([])
                ax.set_yticklabels([])
            ax.set_ylim(-z.max(), 0)
            ax.set_xlim(lat.min(), lat.max())
            cb = plt.colorbar(map1, ax=ax, pad=0.02)
            cb.set_label(cmap.name + ' [' + '$' + cmap.units + '$]')
            i += 1

        fig.savefig('figures/' + fname.split('.')[0] + '.png', bbox_inches='tight')
857652
def sky_to_offset(skydir, lon, lat, coordsys='CEL', projection='AIT'):
    """"""

    w = create_wcs(skydir, coordsys, projection)
    skycrd = np.vstack((lon, lat)).T

    if len(skycrd) == 0:
        return skycrd

    return w.wcs_world2pix(skycrd, 0)
1217295
function draw() {
    const options = {
      start: timeframeStartNode.value,
      end: timeframeEndNode.value,
      latitude: latNode.value,
      longitude: lngNode.value,
      radius: GEO.miles,
      zoom: GEO.zoom
    };

    const end = (options['end']) ? new Date(Date.parse(options['end'])) : new Date();
    const start = (options['start']) ? new Date(Date.parse(options['start'])) : new Date(end.getFullYear(), end.getMonth(), end.getDate() - 14);

    const rad = (options['radius']) ? parseFloat(options['radius']) : false;
    const lat = (options['latitude']) ? parseFloat(options['latitude']) : false;
    const lng = (options['longitude']) ? parseFloat(options['longitude']) : false;

    let geoFilter = [];
    if (lat && lng && rad) {
      geoFilter.push({
        property_name: 'keen.location.coordinates',
        operator: 'within',
        property_value: {
          coordinates: [parseFloat(options['longitude']), parseFloat(options['latitude'])],
          max_distance_miles: parseFloat(options['radius'])
        }
      });
    };

    const baseParams = {
      timeframe: {
        start: start.toISOString(),
        end: end.toISOString()
      },
      filters: geoFilter
    };

    // Fetch events within geo target
    const scoped_events = client.query('select_unique', {
      event_collection: 'user_action',
      target_property: 'keen.location.coordinates',
      timeframe: baseParams.timeframe,
      filters: baseParams.filters
    });
    client.run(scoped_events, (err, res) => {
      activeMapData.clearLayers();
      Keen.utils.each(res.result, coord => {
        const em = L.marker(new L.LatLng(coord[1], coord[0]), {
          icon: L.mapbox.marker.icon({
            'marker-color': '#00bbde'
          })
        }).addTo(activeMapData);;
      });
    });



    // Sample queries
    // groupBy not supported for Geo Filters

    const hearts = client.query('median', {
      event_collection: 'user_action',
      interval: 'daily',
      target_property: 'bio_sensors.heart_rate',
      timeframe: baseParams.timeframe,
      filters: baseParams.filters
    });

    const daily_median_heartrate = new KeenDataviz({
      container: '#chart-01',
      title: 'Daily Median Heart Rate',
      type: 'area',
      colors: ['#fe6672'],
    })

    client
      .run(hearts)
      .then(res => {
        daily_median_heartrate
          .data(res)
          .render()
      });


    const activations = client.query('count', {
      event_collection: 'activations',
      interval: 'daily',
      target_property: 'bio_sensors.heart_rate',
      timeframe: baseParams.timeframe,
      filters: baseParams.filters
    });

    const daily_activations = new KeenDataviz({
      container: '#chart-02',
      title: 'Daily Activations',
      type: 'area',
      colors: ['#fe6672'],
    });

    client
      .run(activations)
      .then(res => {
        daily_activations
          .data(res)
          .render()
      });


    const purchases = client.query('sum', {
      event_collection: 'purchases',
      target_property: 'order_price',
      interval: 'daily',
      timeframe: baseParams.timeframe,
      filters: baseParams.filters
    });

    const daily_purchases = new KeenDataviz({
      container: '#chart-03',
      title: 'Daily Purchases',
      type: 'area',
      colors: ['#eeb058'],
    });

    client
      .run(purchases)
      .then(res => {
        daily_purchases
          .data(res)
          .render()
      });

  }
285440
def do_objs(kbos):
    """"""

    import orbfit, ephem, math
    import re
    re_string=w.FilterVar.get()
    vlist=[]
    for name in kbos:
        if not re.search(re_string,name):
            continue
        vlist.append(name)
        if type(kbos[name])==type(ephem.EllipticalBody()):
	    kbos[name].compute(w.date.get())
	    ra=kbos[name].ra
	    dec=kbos[name].dec
	    a=math.radians(10.0/3600.0)
	    b=a
	    ang=0.0
	    color='blue'
            yoffset=+10
	    xoffset=+10
        else:
            yoffset=-10
            xoffset=-10
            file=kbos[name]
	    jdate=ephem.julian_date(w.date.get())
	    obs=568
 	    try:
	        position=orbfit.predict(file,jdate,obs)
	    except:
		continue
	    ra=math.radians(position[0])
	    dec=math.radians(position[1])
	    a=math.radians(position[2]/3600.0)
	    b=math.radians(position[3]/3600.0)
	    ang=math.radians(position[4])
	    if ( a> math.radians(1.0) ):
	        color='green'
            else:
	        color='black'
	if w.show_ellipse.get()==1 :
            if ( a < math.radians(5.0) ): 
	        w.create_ellipse(ra,dec,a,b,ang)
        if ( a < math.radians(1.0) ): 
            w.create_point(ra,dec,size=2,color=color)
	if w.show_labels.get()==1:
	    w.label(ra,dec,name,offset=[xoffset,yoffset])
    vlist.sort()
    for v in vlist:
        w.objList.insert(END,v)
    w.plot_pointings()
170276
def plot(self, phi, r, **kwargs):
        
        if self.use_radians:
            phi = np.degrees(phi)
        super(PolarPlot, self).plot(phi, r, **kwargs)
1144134
def oplot(self, x, y, **kw):
        
        self.panel.oplot(x, y, **kw)
346827
def from_sky(cls, distancelimit=15, magnitudelimit=18):
        '''
        

        '''

        # define a query for cone search surrounding this center
        criteria = []
        if distancelimit is not None:
            criteria.append('parallax >= {}'.format(1000.0/distancelimit))
        if magnitudelimit is not None:
            criteria.append('phot_g_mean_mag <= {}'.format(magnitudelimit))

        allskyquery = """{} WHERE {}""".format(cls.basequery, ' and '.join(criteria))
        print(allskyquery)

        # run the query
        print('querying Gaia DR2, for distance<{} and G<{}'.format(distancelimit, magnitudelimit))
        table = query(allskyquery)

        # store the search parameters in this object
        c = cls(cls.standardize_table(table))

        c.standardized.meta['query'] = allskyquery
        c.standardized.meta['magnitudelimit'] = magnitudelimit
        c.standardized.meta['distancelimit'] = distancelimit

        #c.distancelimit = distancelimit
        #c.magnitudelimit = magnitudelimit or c.magnitudelimit
        return c