SuperWASP Asteroids Archive

Number of asteroids:
Number of data points:

Example codes

Here are some example programs in python that use the api

Get asteroid name

This code will print the asteroid name using the summary api given the asteroid number.

#!/usr/bin/python

if __name__ == "__main__":
  
  try:
      import json
  except ImportError:
      import simplejson as json #the json library was only part of python after 2.6
      
  import urllib2
  import sys
  
  if (len(sys.argv) < 2): # Only work if asteroid number given
    print "Usage ./getName.py number"
    sys.exit()
    
  asteroid = sys.argv[1] 
    
  url = "http://asteroids.neilparley.com/asteroidsAPI/summary/number/%s " % (asteroid) # set up our url
  
  try: # catch 404 errors which tell us there is no data
    request = urllib2.Request(url,headers={"Accept" : "application/json"}) # Say we would like JSON
    result = json.load(urllib2.urlopen(request)) # Download the json
    print "%s" % (result['name']) # Print out the name
  except urllib2.HTTPError: # Report if number is not found
    print "No Asteroid with this number in table"
Example output:
$ ./getName.py 350
Ornamenta

Check asteroid data for given year

This code will check the data/query api and get the number of nights and rows for a given asteroid and a given year.

#!/usr/bin/python

if __name__ == "__main__":
  
  try:
      import json
  except ImportError:
      import simplejson as json #the json library was only part of python after 2.6
      
  import urllib2
  import sys
  
  if (len(sys.argv) < 3): # Only work if asteroid number and year given
    print "Usage ./checkAsteroid.py number year"
    sys.exit()
    
  asteroid = sys.argv[1] 
  year = sys.argv[2]
  
  url = "http://asteroids.neilparley.com/asteroidsAPI/data/query/number/%s?startDate=%s-01-01&endDate=%s-12-31 " 
        % (asteroid,year,year) # set up our url
  
  try: # catch 404 errors which tell us there is no data
    request = urllib2.Request(url,headers={"Accept" : "application/json"}) # Say we would like JSON
    result = json.load(urllib2.urlopen(request)) # Download the json
    print "Asteroid %s data for %s" % (asteroid,year) # Print out the results
    print "%d rows and %d nights" % (result['rows'], result['nights'])
  except urllib2.HTTPError: # Report a nice no data message
    print "No Asteroid data found for this year"
Example output:
$ ./checkAsteroid.py 350 2006
Asteroid 350 data for 2006
2149 rows and 46 nights

Find Asteroids that past search tests

This code lets the user find asteroids which pass number of nights, diameter and absolute magnitude tests

#!/usr/bin/python

if __name__ == "__main__":
      
  import requests
  import sys
  
  # Test 1: search for minimum nights
  
  minNights = raw_input("Enter minimum number of nights needed:") # Get min nights from user
  payload = {'nights_min':minNights} # set up url parameters
  headers = {'Accept': 'application/json'} # say we accept json
  # send get request to the stats api
  r = requests.get("http://asteroids.neilparley.com/asteroidsAPI/stats/number", params=payload, headers=headers)
  # make sure we don't get a failed error code
  if (r.status_code == requests.codes.ok):
    pastTest1 = (r.json())['numbers'] # save the array of matched asteroid numbers
  else:
    print "No asteroids where found with that many nights"
    sys.exit(1)
  
  # Test 2: search for diameter and h
  
  dia = raw_input("Enter minimum diameter (km):") # Get minimum diameter
  h = raw_input("Enter maximum absolute magnitude:") # Get maximum absolute magnitude
  payload = {'diam_min':dia,'h_max':h} # set up url parameters
  headers = {'Accept': 'application/json'} # say we accept json
  # send get request to the diam cat api
  r = requests.get("http://asteroids.neilparley.com/asteroidsAPI/cats/diam/number", params=payload, headers=headers)
  # make sure we don't get a failed error code
  if (r.status_code == requests.codes.ok):
    pastTest2 = (r.json())['numbers']
  else:
    print "No asteroids where found with diameter and absolute magnitude which match requests"
    sys.exit(1)
    
  # find asteroid numbers which are common to both sets and return sorted list  
  past = sorted(set(pastTest1) & set(pastTest2))
  print "Asteroids which past the tests:"
  print past
Example output:
./asteroidTests.py
Enter minimum number of nights needed:60
Enter minimum diameter (km):300
Enter maximum absolute magnitude:8
Asteroids which past the tests:
[10, 52, 511, 704]

Output my way

This code downloads the asteroid data for a given year and prints out the julian data and magnitude columns separated by tabs

#!/usr/bin/python

if __name__ == "__main__":
  
  try:
      import json
  except ImportError:
      import simplejson as json #the json library was only part of python after 2.6
      
  import urllib2
  import sys
  
  if (len(sys.argv) < 3): # Only work if asteroid number and year given
    print "Usage ./getAsteroid.py number year"
    sys.exit()
    
  asteroid = sys.argv[1] 
  year = sys.argv[2]
  
  url = "http://asteroids.neilparley.com/asteroidsAPI/data/number/%s?startDate=%s-01-01&endDate=%s-12-31 " % (asteroid,year,year) # set up our url
  
  try: # catch 404 errors which tell us there is no data
    request = urllib2.Request(url,headers={"Accept" : "application/json"}) # Say we would like JSON
    result = json.load(urllib2.urlopen(request)) # Download the json
    data = result['data'] # get the data array
    
    for rows in data: # for each of the rows in our data array 
      print "%13.6f\t%9.5f\t%8.5f" % (rows['jd_lc'],rows['c_mag'],rows['c_mag_err']) # print in whatever format
    
  except urllib2.HTTPError: # Report a nice no data message
    print "No Asteroid data found for this year"
Example output:
$ ./getAsteroid.py 350 2004
2453130.355672 9.342100 0.054703
2453130.357998 9.298140 0.047795

Lightcurve using plot API

This code produces a lightcurve plot using matplotlib and the plot API output

#!/usr/bin/python

if __name__ == "__main__":
      
  import requests
  import sys
  import matplotlib.pyplot as plt
  
  # Get the asteroid number / lcId
  number = int(raw_input("Enter number of the asteroid:"))
  lcId = int(raw_input("Enter lightcurve ID:"))
  # check input
  if (lcId > 0) and (number > 0):
    print "Loading plot data..."
    # Setup URL
    url = "http://asteroids.neilparley.com/asteroidsAPI/periods/plot/number/%d/%d" % (number,lcId)
    # Make get request 
    r = requests.get(url)
    # Check server response
    if (r.status_code == requests.codes.ok):
      plotData = r.json() # Save data
    else:
       print "No plot data for asteroid (%d) and lightcurve ID %d"  % (number,lcId)
       sys.exit(1)
  else:
    print "Number and lightcurve ID must both be numbers greater than 0"
    sys.exit(1)
    
  # Get the datasets from the plot data dictionary  
  dataSets = plotData['datasets']
  # Load up our plot object
  fig = plt.figure(num=1, figsize=(12, 10), dpi=80, facecolor='w', edgecolor='k')
  # Loop over all the nights where we have data to plot
  # Sort the dictionary so the labels appear in date order
  for night, values in sorted(dataSets.items()):
    # Split the x,y,error values into their own lists
    x = [item[0] for item in values['data']]
    y = [item[1] for item in values['data']]
    e = [item[2] for item in values['data']]
    # Add them to the plot
    plt.errorbar(x, y,label=night,yerr=e,fmt=',')
  
  # Do the same for the fitted series
  fit = plotData['fit']
  x = [item[0] for item in fit['data']]
  y = [item[1] for item in fit['data']]
  plt.plot(x,y,'-k',label="Fit")
  
  # Find the min and max and add 10% for the legend
  yMin = min(y) * 1.2
  yMax = max(y) * 1.2
  yMin -= (yMax - yMin) * 0.1
  # Add limits to the plot
  plt.ylim( (yMin,yMax ) )
  # Invert the axis because -ve magnitude = brighter
  plt.gca().invert_yaxis()
  # Add labels
  plt.xlabel("Phase")
  plt.ylabel(r"$\Delta$ Magnitude")
  plt.title("Lightcurve %d for asteroid (%d)" %  (lcId,number))
  plt.legend(loc='upper center',ncol=5,prop={'size':12})
  # Show the plot
  plt.show() 
Example output:
$ python plot.py
Enter number of the asteroid:20
Enter lightcurve ID:2
Loading plot data...

Lightcurve using lc info, fit, data and means APIs

This code produces a lightcurve plot using matplotlib and the raw photometric data. The data is phase folded and offset using information collected from the other rotation curve APIs

#!/usr/bin/python

if __name__ == "__main__":
      
  import requests
  import sys
  import matplotlib.pyplot as plt
  import numpy
  
  # Get the asteroid number / lcId
  number = int(raw_input("Enter number of the asteroid:"))
  lcId = int(raw_input("Enter lightcurve ID:"))
  # check input
  if (lcId > 0) and (number > 0):
    print "Loading plot data..."
    # Setup URL
    url = "http://asteroids.neilparley.com/asteroidsAPI/periods/data/number/%d/%d" % (number,lcId)
    # Make get request 
    r = requests.get(url)
    # Check server response
    if (r.status_code == requests.codes.ok):
      plotData = r.json() # Save data
    else:
       print "No plot data for asteroid (%d) and lightcurve ID %d"  % (number,lcId)
       sys.exit(1)
  else:
    print "Number and lightcurve ID must both be numbers greater than 0"
    sys.exit(1)
    
  # Get lightcurve information for the period and epoch of the rotation curve
  url = "http://asteroids.neilparley.com/asteroidsAPI/periods/lc/number/%d" % (number)
  r = requests.get(url)
  if (r.status_code == requests.codes.ok):
    lcInfo = r.json() # Save data
  else: 
    print "Error getting lightcurve info"
    sys.exit(1)
    
  links = lcInfo["lightcurves"][str(lcId)]["_links"]  
    
  # Get nightly means to offset the photometric values
  url = "http://asteroids.neilparley.com" + (links["means"]["href"])
  r = requests.get(url)
  if (r.status_code == requests.codes.ok):
    means = r.json() # Save data
  else: 
    print "Error getting nightly means"
    sys.exit(1)
    
  # Get fit data to overlay the fourier series fit on the data
  url = "http://asteroids.neilparley.com" + (links["fit"]["href"])
  r = requests.get(url)
  if (r.status_code == requests.codes.ok):
    fit = r.json() # Save data
  else: 
    print "Error getting fit data"
    sys.exit(1)
    
  # Get the period, epoch and amplitude from the lcInfo object  
  period = lcInfo["lightcurves"][str(lcId)]["period"]
  epoch = lcInfo["lightcurves"][str(lcId)]["epoch"]
  amplitude = lcInfo["lightcurves"][str(lcId)]["amplitude"]
  
  # Print the values for the user to see
  print "Period (hours) = %f" % period
  print "Epoch (jd) = %f" % epoch
  print "Amplitude (magnitude) = %f" % amplitude
  # Convert the period into days to make phase folding easier
  period /= 24.0
  # Create empty list to hold our x,y and error data
  x = []
  y = []
  e = []
  lastNight = None # Remember the last night so we know when the night has changed
    
  # Load up our plot object
  fig = plt.figure(num=1, figsize=(12, 10), dpi=80, facecolor='w', edgecolor='k')
  
  for dataPoint in plotData['data']: # Loop over all the data points
    if dataPoint["c_mag"] > 0.0: # Only do work if the photometry is not zero
      night = dataPoint["night"] # Get the current night of the data point
      if night != lastNight and lastNight != None: # If the night has changed 
        plt.errorbar(x, y,label=lastNight,yerr=e,fmt=',') # plot the last nights data
        del x[:] # Clear our lists ready for the new night
        del y[:]
        del e[:]
      
      lastNight = night # Save the night 
      rotPhase = ((dataPoint["jd_lc"] - epoch) / period) % 1.0 # Calculate the rotation phase
      delMag = dataPoint["c_mag"] - means["means"][night]["meanMag"] # Calculate the delta Mag
      x.append(rotPhase) # Append the values to our data lists
      y.append(delMag)
      e.append(dataPoint["c_mag_err"])
  else: # This plots the last night of the loop to the graph 
    if lastNight != None:
      plt.errorbar(x, y,label=lastNight,yerr=e,fmt=',')
      del x[:]
      del y[:]
      del e[:]  
  
  # calculate our fitted data, because we have phase folded and offset the data
  # Our fit is y = sum_{i=1}^{order} A_i * sin (2*pi*i*x) + B_i * cos(2*pi*i*x)
  # calculate an array of the i's
  order = numpy.array([item['order'] for item in fit["fit"]])
  # calculate an array of the As and Bs
  A = numpy.array([item['sin'] for item in fit["fit"]])
  B = numpy.array([item['cos'] for item in fit["fit"]])
  order = (2 * numpy.pi * order) # work out 2*pi*i
  xPoints = (numpy.arange(100) / 100.0) # create a list of x values from 0 to 1
  yPoints = [] # create an empty list to hold the y values
          
  for x in xPoints: # Loop over all the x points
    sum = A * numpy.sin(order*x) + B * numpy.cos(order*x) # calc an array of the fourier series  
    y = (sum.sum()) # sum that array to get the y value
    yPoints.append(y) # append that to the list
  
  plt.plot(xPoints,yPoints,'-k',label="Fit") # Plot the fitted data
    
  # Set the min and max and add 10% for the legend
  yMin = amplitude * -1.2
  yMax = amplitude * 1.2
  yMin -= (yMax - yMin) * 0.1
  # Add limits to the plot
  plt.ylim( (yMin,yMax ) )
  # Invert the axis because -ve magnitude = brighter
  plt.gca().invert_yaxis()
  # Add labels
  plt.xlabel("Phase (Period = %.3f hours)" %  (period*24.0))
  plt.ylabel(r"$\Delta$ Magnitude (Amplitude = %.3f)" % (amplitude))
  plt.title("Lightcurve %d for asteroid (%d)" %  (lcId,number))
  plt.legend(loc='upper center',ncol=5,prop={'size':12})
  # Show the plot
  plt.show() 
Example output:
$ python plotRaw.py
Enter number of the asteroid:63
Enter lightcurve ID:1
Loading plot data...
Period (hours) = 9.296900
Epoch (jd) = 2453896.500000
Amplitude (magnitude) = 0.802490