In [3]:
import callhorizons2 #add some new fields!
import datetime
import os
import subprocess
import time
from astropy import units as u
from astropy.coordinates import Angle
import logging
from logging.handlers import RotatingFileHandler
import unicodedata
import string
import re
import pytz
import time

In [4]:
#the datetimes
#Aug.  7 Mo  02:30 06:15         X  023 Nowinski             SpeX/MORIS           SJB First Night
#Oct.  9 Mo  00:05 05:55         X  023 Nowinski             SpeX/MORIS           SJB 
#Nov. 25 Sa  00:35 05:55         X  023 Nowinski             SpeX/MORIS           SJB
#Nov. 26 Su  18:35 01:05         X  023 Nowinski             SpeX/MORIS           SJB 
#Dec. 29 Fr  18:45 23:20         X  023 Nowinski             SpeX/MORIS           ACB
#convert to UTC (+10)
dts = [ [datetime.datetime(2017, 8, 7, 12, 30, 0), datetime.datetime(2017, 8, 7, 16, 15, 0)],
        [datetime.datetime(2017, 10, 9, 10, 5, 0), datetime.datetime(2017, 10, 9, 15, 55, 0)],
        [datetime.datetime(2017, 11, 25, 10, 35, 0), datetime.datetime(2017, 11, 25, 15, 55, 0)],
        [datetime.datetime(2017, 11, 27, 4, 35, 0), datetime.datetime(2017, 11, 27, 11, 5, 0)],
        [datetime.datetime(2017, 12, 30, 4, 45, 0), datetime.datetime(2017, 12, 30, 9, 20, 0)]       
      ]

In [5]:
fname_targets = 'targets2.txt'
fname_observables = 'observables2.csv'

#the target using spkid
#targets = ['2009633']
targets = open(fname_targets, "r").readlines()

#output file
f = open(fname_observables, "w")
f.write("spkid,name")
for i in range(0,len(dts)):
    f.write(",start%d,duration%d,ra%d,dec%d,appmag%d,phase%d,glxlat%d,moonphase%d,moonphase%d"%(i,i,i,i,i,i,i,i,i))
f.write("\n")
f.close()

In [6]:
#the observatory
observatory = '568'

In [7]:
#min elevation in degrees
min_elev = 30;

#min minutes observable per night
min_minutes = 90;

#faintest apparent magnitude of target
faintest_apmag = 18;

In [8]:
#get ephemerides for targets in JPL Horizons from start to end times
#for spkid, use DES=spkid; for target name
#loop thru all targets
for target in targets:
    days_available = 0
    total_minutes = 0
    ch=callhorizons2.query('DES='+target.strip()+";", smallbody=True)
    print 'Processing %s...'%(target.strip())
    #f = open(fname_observables, "a")	
    #f.write('#Processing %s...\n'%(target.strip()))
    #f.close()
    #loop thru all datetimes
    count = 0
    minutes = [0] * len(dts)
    phase = [0.0] * len(dts)
    startdt = [''] * len(dts)
    enddt = [''] * len(dts)
    apmag = [0.0] * len(dts)    
    glxlat = [''] * len(dts)
    phase_moon = [0.0] * len(dts) 
    illum_moon = [0.0] * len(dts)
    ra = [0.0] * len(dts)
    dec = [0.0] * len(dts)    
    for dt in dts:
        #get ephemerides for specified observation windows in 1m increments
        ch.set_epochrange(dt[0].strftime("%Y/%m/%d %H:%M:%S"), dt[1].strftime("%Y/%m/%d %H:%M:%S"), '1m')
        ch.get_ephemerides(observatory)
        #count minutes where targets is at an elevation > min_elev
        for i in range(0,len(ch)):
            if ch['EL'][i] >= min_elev and ch['V'][i] <= faintest_apmag:
                minutes[count] += 1
        #if there is an hour of observing time for this target, mark it!
        if minutes >= min_minutes:
            startdt[count] = pytz.utc.localize(dt[0]).astimezone(pytz.timezone("US/Hawaii"))
            enddt[count] = pytz.utc.localize(dt[1]).astimezone(pytz.timezone("US/Hawaii"))
            #print '%s to %s'%(start_hst.strftime("%Y/%m/%d %H:%M:%S"), end_hst.strftime("%Y/%m/%d %H:%M:%S"))
            days_available += 1
            total_minutes += minutes[count]
            phase[count] = ch['alpha'][0]
            apmag[count] = ch['V'][0]
            glxlat[count] = ch['GlxLat'][0]
            phase_moon[count] = ch['tom'][0]
            illum_moon[count] = ch['moonillum'][0]
            ra[count] = ch['RA'][0]
            dec[count] = ch['DEC'][0]
            #print '%s to %s'%(startdt[count].strftime("%Y/%m/%d %H:%M:%S"), enddt[count].strftime("%Y/%m/%d %H:%M:%S"))
            #print 'RA=%f deg, DEC=%f deg'%(ra[count], dec[count])
            #print 'Phase = %f deg'%(phase[count])
            #print 'Minutes = %d min'%minutes[count]
            #print 'ApMag = %f'%(apmag[count])
            #print 'GlxLat = %s'%(glxlat[count])
            #print 'MoonPhase = %f deg'%(phase_moon[count])
            #print 'MoonIllum = %f%%'%(illum_moon[count])
        count += 1
        ##give the server a little rest
        #time.sleep(1)
    #is it available for each of the observation windows? record it!
    #print '%s is observable for %d of the %d available sessions.'%(ch['targetname'][0], days_available, len(dts))
    #if days_available == len(dts):
        #print '\tspkid=%s name=%s avemin=%f'%(target.strip(), ch['targetname'][0], total_minutes/len(dts))
        #if = open(fname_observables, "a")
        #if.write('"%s","%s",%f\n'%(target.strip(), ch['targetname'][0], total_minutes/len(dts)))
        #if.close()
    #write to output file
    #f.write("spkid,name")
    f = open(fname_observables, "a")
    f.write('%s,%s'%(target.strip(), ch['targetname'][0]))
    print '%s:'%(ch['targetname'][0])
    for i in range(0, len(dts)):
        #f.write(",start%d,duration%d,ra%d,dec%d,appmag%d,phase%d,glxlat%d,moonphase%d,moonphase%d"%(i,i,i,i,i,i,i,i,i))
        f.write(',%s,%d,%f,%f,%f,%f,%f,%f,%f'%(startdt[i].strftime("%Y/%m/%d %H:%M:%S"),minutes[i],ra[i],dec[i],apmag[i],phase[i],glxlat[i],phase_moon[i],illum_moon[i]))
    f.write("\n")
    f.close()
print 'Complete!'


Processing 2000460...
2000460 (460 Scania (1900 FN))
Processing 2000628...
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-8-c749a1382b9f> in <module>()
     25         #get ephemerides for specified observation windows in 1m increments
     26         ch.set_epochrange(dt[0].strftime("%Y/%m/%d %H:%M:%S"), dt[1].strftime("%Y/%m/%d %H:%M:%S"), '1m')
---> 27         ch.get_ephemerides(observatory)
     28         #count minutes where targets is at an elevation > min_elev
     29         for i in range(0,len(ch)):

C:\owncloud\code\giterdone\asteroids\callhorizons2\callhorizons.pyc in get_ephemerides(self, observatory_code, airmass_lessthan, solar_elongation, skip_daylight)
    486         while True:
    487             try:
--> 488                 src = urllib.urlopen(url).readlines()
    489                 break
    490             except urllib.URLError:

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    152     else:
    153         opener = _opener
--> 154     return opener.open(url, data, timeout)
    155 
    156 def install_opener(opener):

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in open(self, fullurl, data, timeout)
    433         for processor in self.process_response.get(protocol, []):
    434             meth = getattr(processor, meth_name)
--> 435             response = meth(req, response)
    436 
    437         return response

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in http_response(self, request, response)
    546         if not (200 <= code < 300):
    547             response = self.parent.error(
--> 548                 'http', request, response, code, msg, hdrs)
    549 
    550         return response

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in error(self, proto, *args)
    465             http_err = 0
    466         args = (dict, proto, meth_name) + args
--> 467         result = self._call_chain(*args)
    468         if result:
    469             return result

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
    405             func = getattr(handler, meth_name)
    406 
--> 407             result = func(*args)
    408             if result is not None:
    409                 return result

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in http_error_302(self, req, fp, code, msg, headers)
    652         fp.close()
    653 
--> 654         return self.parent.open(new, timeout=req.timeout)
    655 
    656     http_error_301 = http_error_303 = http_error_307 = http_error_302

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in open(self, fullurl, data, timeout)
    427             req = meth(req)
    428 
--> 429         response = self._open(req, data)
    430 
    431         # post-process response

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in _open(self, req, data)
    445         protocol = req.get_type()
    446         result = self._call_chain(self.handle_open, protocol, protocol +
--> 447                                   '_open', req)
    448         if result:
    449             return result

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
    405             func = getattr(handler, meth_name)
    406 
--> 407             result = func(*args)
    408             if result is not None:
    409                 return result

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in https_open(self, req)
   1239         def https_open(self, req):
   1240             return self.do_open(httplib.HTTPSConnection, req,
-> 1241                 context=self._context)
   1242 
   1243         https_request = AbstractHTTPHandler.do_request_

C:\Users\mcnow\Anaconda2\lib\urllib2.pyc in do_open(self, http_class, req, **http_conn_args)
   1193 
   1194         try:
-> 1195             h.request(req.get_method(), req.get_selector(), req.data, headers)
   1196         except socket.error, err: # XXX what error?
   1197             h.close()

C:\Users\mcnow\Anaconda2\lib\httplib.pyc in request(self, method, url, body, headers)
   1040     def request(self, method, url, body=None, headers={}):
   1041         """Send a complete request to the server."""
-> 1042         self._send_request(method, url, body, headers)
   1043 
   1044     def _set_content_length(self, body, method):

C:\Users\mcnow\Anaconda2\lib\httplib.pyc in _send_request(self, method, url, body, headers)
   1080         for hdr, value in headers.iteritems():
   1081             self.putheader(hdr, value)
-> 1082         self.endheaders(body)
   1083 
   1084     def getresponse(self, buffering=False):

C:\Users\mcnow\Anaconda2\lib\httplib.pyc in endheaders(self, message_body)
   1036         else:
   1037             raise CannotSendHeader()
-> 1038         self._send_output(message_body)
   1039 
   1040     def request(self, method, url, body=None, headers={}):

C:\Users\mcnow\Anaconda2\lib\httplib.pyc in _send_output(self, message_body)
    880             msg += message_body
    881             message_body = None
--> 882         self.send(msg)
    883         if message_body is not None:
    884             #message_body was not a string (i.e. it is a file) and

C:\Users\mcnow\Anaconda2\lib\httplib.pyc in send(self, data)
    842         if self.sock is None:
    843             if self.auto_open:
--> 844                 self.connect()
    845             else:
    846                 raise NotConnected()

C:\Users\mcnow\Anaconda2\lib\httplib.pyc in connect(self)
   1253             "Connect to a host on a given (SSL) port."
   1254 
-> 1255             HTTPConnection.connect(self)
   1256 
   1257             if self._tunnel_host:

C:\Users\mcnow\Anaconda2\lib\httplib.pyc in connect(self)
    819         """Connect to the host and port specified in __init__."""
    820         self.sock = self._create_connection((self.host,self.port),
--> 821                                            self.timeout, self.source_address)
    822 
    823         if self._tunnel_host:

C:\Users\mcnow\Anaconda2\lib\socket.pyc in create_connection(address, timeout, source_address)
    564             if source_address:
    565                 sock.bind(source_address)
--> 566             sock.connect(sa)
    567             return sock
    568 

C:\Users\mcnow\Anaconda2\lib\socket.pyc in meth(name, self, *args)
    226 
    227 def meth(name,self,*args):
--> 228     return getattr(self._sock,name)(*args)
    229 
    230 for _m in _socketmethods:

KeyboardInterrupt: 

In [ ]: