Ejemplo n.º 1
0
def load_tle_data(data_dir):
    data = []
    for tle_fn in glob(os.path.join(data_dir, '*.txt')):
        group_name, _ = os.path.splitext(os.path.basename(tle_fn))
        with open(tle_fn, 'r') as fh:
            while True:
                try:
                    platform = next(fh)
                    line1 = next(fh)
                    line2 = next(fh)
                    x = tlefile.read(platform, line1=line1, line2=line2)
                    data.append({
                        'group' : group_name,
                        'arg_perigee' : x.arg_perigee,
                        'bstar' : x.bstar,
                        'excentricity' : x.excentricity,
                        'inclination' : x.inclination,
                        'mean_anomaly' : x.mean_anomaly,
                        'mean_motion' : x.mean_motion,
                        'mean_motion_derivative' : x.mean_motion_derivative,
                        #'mean_motion_sec_derivative' : x.mean_motion_sec_derivative,
                        'orbit' : x.orbit,
                        'right_ascension' : x.right_ascension
                    })
                except StopIteration:
                    break       
    df = pd.DataFrame(data)
    return df
Ejemplo n.º 2
0
def loadSatellites(val):
    satellites = load.tle_file(constellationToLink[val]["link"],
                               filename="%s.txt" % val)

    redisServer = constellationRedis[val]

    for satellite in satellites:
        data = {}
        tle = tlefile.read(satellite.name, "%s.txt" % val)
        data['platform'] = tle.platform
        data['line1'] = tle.line1
        data['line2'] = tle.line2
        json_data = json.dumps(data)
        redisServer.set(tle.platform, json_data)

    os.remove("%s.txt" % val)

    message = "Loaded " + str(
        len(satellites)) + " satellites to " + str(val) + " database"
    print(message)
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=rabbitMQHost))
    logChannel = connection.channel()
    logChannel.exchange_declare(exchange='logs', exchange_type='topic')
    logChannel.basic_publish(exchange='logs',
                             routing_key='databaseUpdater.info',
                             body=message)
    def geo_sat_position(self, satellite: str):
        """


        Args:
            satellite (str): Name of the satellite

        Returns:
            np.array: Array containing the ra and dec of the satellite
        """
        # TODO improve the function
        try:
            # Get the filename
            url = self.cfg_data.get_tle_url()  # Get the URL from the settings file
            file_dir = os.path.abspath("TLE/" + url.split("/")[-1])  # Directory for the saved file

            tle_data = tlefile.read(satellite, file_dir)

            sat = ephem.readtle(tle_data.platform, tle_data.line1, tle_data.line2)
            self.observer.date = self.current_time()
            sat.compute(self.observer)

            c_time = self.current_time()  # Get the current time
            ha_sat = np.round(self.hour_angle(math.degrees(sat.ra), math.degrees(sat.dec), c_time), 4)  # Get the hour
            # angle of the satellite

            return np.array([np.round(np.degrees((sat.alt, sat.az,)), 4),
                             np.round((ha_sat, np.degrees(sat.dec),), 4)]).tolist()
        except KeyError:
            self.logger.exception("No satellite found. See traceback.")
Ejemplo n.º 4
0
 def __init__(self, satellite, tle_file=None, line1=None, line2=None):
     satellite = satellite.upper()
     self.satellite_name = satellite
     self.tle = tlefile.read(satellite, tle_file=tle_file,
                             line1=line1, line2=line2)
     self.orbit_elements = OrbitElements(self.tle)
     self._sgdp4 = _SGDP4(self.orbit_elements)
Ejemplo n.º 5
0
 def __init__(self, satellite, tle_file=None, line1=None, line2=None, use_NEAR_for_DEEP_space=False):
     satellite = satellite.upper()
     self.satellite_name = satellite
     self.tle = tlefile.read(satellite, tle_file=tle_file,
                             line1=line1, line2=line2)
     self.orbit_elements = OrbitElements(self.tle)
     self._sgdp4 = _SGDP4(self.orbit_elements, use_NEAR_for_DEEP_space=use_NEAR_for_DEEP_space)
Ejemplo n.º 6
0
 def deploy(self,
            category,
            deployer,
            dplyr_mass,
            dplyd_mass,
            name,
            vel,
            date=None):
     self.calcPosAndVel(deployer, vel)
     #tle = tlefile.read(deployer.name, "TLE/cubesat.txt")
     deployer_name, line1, line2 = deployer.createTLE()
     tle = tlefile.read(deployer_name, line1=line1, line2=line2)
     newSat = Sat(name=name, tle=tle, cat=category)
     #newSat = Sat(name=name, cat=category)
     self.updateSat(newSat, date)
     B = (2 *
          (0.034 * 0.084 + 0.034 * 0.028 + 0.084 * 0.028)) / 6 / dplyd_mass
     newSat.setBallisticCoeff(B)
     newSat.createTLE()
     dplyr_mass = dplyr_mass - dplyd_mass
     dplyr_vel = [
         -vel[0] * dplyd_mass / dplyr_mass,
         -vel[1] * dplyd_mass / dplyr_mass,
         -vel[2] * dplyd_mass / dplyr_mass
     ]
     self.calcPosAndVel(deployer, dplyr_vel)
     self.updateSat(deployer, date)
     B = (0.1 * 0.1 * 2 + 4 * 0.3 * 0.1) / 6 / dplyr_mass
     deployer.setBallisticCoeff(B)
     deployer.createTLE()
     return newSat
Ejemplo n.º 7
0
 def __init__(self, satellite, tle_file=None, line1=None, line2=None):
     satellite = satellite.upper()
     self.satellite_name = satellite
     self.tle = tlefile.read(satellite, tle_file=tle_file,
                             line1=line1, line2=line2)
     self.orbit_elements = OrbitElements(self.tle)
     self._sgdp4 = _SGDP4(self.orbit_elements)
Ejemplo n.º 8
0
def decode_TLE():

#here we can find more explanations about the module pyorbital here : https://pyorbital.readthedocs.io/en/latest/

    sat = tlefile.read('INMARSAT 3-F1'	,'C:\Users\Student-CIC-05\Desktop\Meuven\code\TLE.txt')
# we can use the command "Orbital", thanks to whom (with the name of the sat) we get directly on the internet the sat's TLE
    now = datetime.utcnow()
    coor_sat= sat.get_lonlatalt(now)
    return (coor_sat)         # gives a tuples with long, lat , alt 
Ejemplo n.º 9
0
 def __init__(self, satellite, tle_file=None, line1=None, line2=None):
     satellite = satellite.upper()
     self.satellite_name = satellite
     self.tle = tlefile.read(satellite, tle_file=tle_file, 
                             line1=line1, line2=line2)
     self.orbit_elements = OrbitElements(self.tle)
     self._sgdp4 = _SGDP4(self.orbit_elements)
     
     pos_epoch, vel_epoch = self.get_position(self.tle.epoch, 
                                              normalize=False)
     if np.abs(pos_epoch[2]) > 1 or not vel_epoch[2] > 0:
         # Epoch not at ascending node
         self.orbit_elements.an_time = self.get_last_an_time(self.tle.epoch)
     else:
         # Epoch at ascending node (z < 1 km) and positive v_z
         self.orbit_elements.an_time = self.tle.epoch
         
     self.orbit_elements.an_period = self.orbit_elements.an_time - \
                     self.get_last_an_time(self.orbit_elements.an_time 
                                           - timedelta(minutes=10))    
Ejemplo n.º 10
0
def getdata(satnum):
    c.execute('SELECT EPOCH,TLE_LINE0,TLE_LINE1,TLE_LINE2,FILE FROM DATA WHERE NORAD_CAT_ID = {satnum} ORDER BY EPOCH'.format(satnum=satnum));
    all_rows= c.fetchall()

    if len(all_rows)==0:
        print "Sat ",satname," not found"
        exit(1)
    data=[]
    print "[%5d] %s (%s-%s) latest=%s"%(satnum,all_rows[0][1][2:],all_rows[0][0],all_rows[-1][0],all_rows[-1][4])
    for line in all_rows:
        ep,l0,l1,l2,file=line
        tle=tlefile.read(ep, line1=l1,line2=l2)
        dt=datetime.strptime(ep,"%Y-%m-%d %H:%M:%S")
        inc=tle.inclination
        raan=tle.right_ascension # Right Ascension of the Ascending Node [deg]
        e=tle.excentricity       # (Ra-Rp)/(Ra+Rp)
        w=tle.arg_perigee        # Argument of periapsis [deg]
        n=tle.mean_motion        # Mean motion [Revs per day]
        Sm=(mu/(n*2*math.pi/(24*3600))**2)**(1./3) # Semi-major axis [km]
        Ra=e*Sm+Sm               # Apogee (farthest point)
        Rp=-e*Sm+Sm              # Perigree (nearest point)
        raan_off= (tle.epoch-datetime.strptime("1996", "%Y")).total_seconds()*1
        plane=(raan-raan_off*omega_p/math.pi*180)%360

        if verbose:
            print "time:",ep
            print "Sm  [km]:",Sm
            print "Ra  [km]:",Ra-R0
            print "Rp  [km]:",Rp-R0
            print "e       :",e
            print "inc  [°]:",inc
            print "RAAN [°]:",raan
            print "w    [°]:",w
            print "B*      :",tle.bstar
            print "plane[°]:",plane
            print ""
        if raan>180: raan-=360
        if plane>180: plane-=360
        data.append((dt, inc, Sm-R0, plane, e, w, raan, Ra-R0, Rp-R0, tle.bstar))
    return data
Ejemplo n.º 11
0
    def __init__(self, satellite, tle_file=None, line1=None, line2=None):
        satellite = satellite.upper()
        self.satellite_name = satellite
        self.tle = tlefile.read(satellite,
                                tle_file=tle_file,
                                line1=line1,
                                line2=line2)
        self.orbit_elements = OrbitElements(self.tle)
        self._sgdp4 = _SGDP4(self.orbit_elements)

        pos_epoch, vel_epoch = self.get_position(self.tle.epoch,
                                                 normalize=False)
        if np.abs(pos_epoch[2]) > 1 or not vel_epoch[2] > 0:
            # Epoch not at ascending node
            self.orbit_elements.an_time = self.get_last_an_time(self.tle.epoch)
        else:
            # Epoch at ascending node (z < 1 km) and positive v_z
            self.orbit_elements.an_time = self.tle.epoch

        self.orbit_elements.an_period = self.orbit_elements.an_time - \
                        self.get_last_an_time(self.orbit_elements.an_time
                                              - timedelta(minutes=10))
Ejemplo n.º 12
0
def import_satellites_from_file(path_to_file):
    """Импортирует данные из файла в формате tle в базу данных.

    @param: path_to_file Путь к файлу с tle наборами.

    """

    with open(path_to_file) as f:

        lines = f.read()[:-1].split('\n')
        tles = [lines[i:i+3] for i in range(0, len(lines),3)]

        for tle in tles:

            s = tlefile.read('', line1 = tle[1], line2 = tle[2])

            sat = Satellite(name=tle[0].strip(),
                            number=int(s.satnumber),
                            classification=s.classification,
                            id_launch_year=int(s.id_launch_year),
                            id_launch_number=int(s.id_launch_number),
                            id_launch_piece=s.id_launch_piece,
                            epoch=s.epoch,
                            excentricity=s.excentricity,
                            inclination=s.inclination,
                            right_ascension=s.right_ascension,
                            arg_perigee=s.arg_perigee,
                            mean_anomaly=s.mean_anomaly,
                            mean_motion=s.mean_motion,
                            mean_motion_derivative=s.mean_motion_derivative,
                            mean_motion_sec_derivative=s.mean_motion_sec_derivative,
                            bstar=s.bstar,
                            version=s.element_number,
                            revolutions=s.orbit)

            shared.session.save(sat)
def cubesat_t(cubesat, x):
    TCP_IP = '127.0.0.1'
    TCP_PORT = 5005
    BUFFER_SIZE = 1024
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if x == 1:
        s.connect((TCP_IP, TCP_PORT))
    response = urllib2.urlopen(
        'http://celestrak.com/NORAD/elements/cubesat.txt')
    html = response.read()
    f = open('tle1.txt', 'r+')
    f.write(html)
    f.close()
    tle = tlefile.read(cubesat, 'tle1.txt')
    inc = tle.inclination
    print(inc)
    lon, lat = -1.394, 50.9354
    alt = 41
    utc_time = datetime.datetime.utcnow()

    passhrs = 20
    o = orbital.Orbital('tisat 1', 'tle1.txt')
    print(o)
    p = o.get_next_passes(utc_time, passhrs, lon, lat, alt)
    print(p)
    for i in range(0, len(p)):
        d1 = o.get_observer_look(p[i][0], lon, lat, alt)
        d2 = o.get_observer_look(p[i][1], lon, lat, alt)
        d3 = o.get_observer_look(p[i][2], lon, lat, alt)
        print(i + 1)
        print 'start time:', p[i][0]
        print 'AOS azimuth, elevation:', d1[0], d1[1]
        print 'maximum elevation time:', p[i][2]
        print 'Max azimuth, elevation:', d3[0], d3[1]
        print 'end time:', p[i][1]
        print 'LOS azimuth, elevation:', d2[0], d2[1]
    ip = 0
    t = [1]
    for i in range(len(t)):
        l = p[i][0]
        dt = 2
        if l.minute != 0 and l.minute != 1:
            utctime2 = datetime.datetime(l.year, l.month, l.day, l.hour,
                                         l.minute - 2, l.second)
        else:
            utctime2 = datetime.datetime(l.year, l.month, l.day, l.hour - 1,
                                         59, l.second)
        if (utctime2.second % 2 == 0):
            utctime1 = utctime2
        else:
            utctime2 = datetime.datetime(l.year, l.month, l.day, l.hour - 1,
                                         59, l.second - 1)
            utctime1 = utctime2
        while p[i][1] >= utctime1:
            if utctime1.second < 58:
                utctime1 = datetime.datetime(utctime1.year, utctime1.month,
                                             utctime1.day, utctime1.hour,
                                             utctime1.minute,
                                             utctime1.second + dt)
            elif utctime1.second == 58:
                if utctime1.minute < 59:
                    utctime1 = datetime.datetime(utctime1.year, utctime1.month,
                                                 utctime1.day, utctime1.hour,
                                                 utctime1.minute + 1, 0)
                elif utctime1.minute == 59:
                    if utctime1.hour < 23:
                        utctime1 = datetime.datetime(utctime1.year,
                                                     utctime1.month,
                                                     utctime1.day,
                                                     utctime1.hour + 1, 0, 0)
                    elif utctime1.hour == 23:
                        if utctime1.month in [1, 3, 5, 7, 8, 10, 12
                                              ] and utctime1.day < 31:
                            utctime1 = datetime.datetime(
                                utctime1.year, utctime1.month,
                                utctime1.day + 1, 0, 0, 0)
                        elif utctime1.month in [1, 3, 5, 7, 8, 10, 12
                                                ] and utctime1.day == 31:
                            utctime1 = datetime.datetime(
                                utctime1.year, utctime1.month + 1, 1, 0, 0, 0)
                        elif utctime1.month in [4, 6, 9, 11
                                                ] and utctime1.month < 30:
                            utctime1 = datetime.datetime(
                                utctime1.year, utctime1.day, utctime1.day + 1,
                                0, 0, 0)
                        elif utctime1.month in [4, 6, 9, 11
                                                ] and utctime1.month == 30:
                            utctime1 = datetime.datetime(
                                utctime1.year, utctime1.day + 1, 1, 0, 0, 0)
            if p[i][0] <= utctime1:
                look = o.get_observer_look(utctime1, lon, lat, alt)
                "print look,utctime1"
                angle = ["%.3G" % (look[0]), "%.3G" % (look[1])]
                msg1 = str(angle[0]) + ',' + str(angle[1])
                if x == 1:
                    s.send(msg1)
                print msg1
                time.sleep(2)
            ip = ip + 1
    return ()
def cubesat_t(cubesat,x):   
     TCP_IP = '127.0.0.1'
     TCP_PORT = 5005
     BUFFER_SIZE = 1024
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     if x==1:
         s.connect((TCP_IP, TCP_PORT))
     response = urllib2.urlopen('http://celestrak.com/NORAD/elements/cubesat.txt')
     html = response.read()
     f = open('tle1.txt', 'r+')
     f.write(html)
     f.close()  
     tle=tlefile.read(cubesat,'tle1.txt')
     inc = tle.inclination
     print(inc)
     lon,lat = -1.394,50.9354
     alt=41
     utc_time = datetime.datetime.utcnow()
     
     passhrs=20
     o=orbital.Orbital('tisat 1','tle1.txt')
     print(o)
     p=o.get_next_passes(utc_time,passhrs,lon,lat,alt)
     print(p) 
     for i in range(0,len(p)):
         d1=o.get_observer_look(p[i][0], lon, lat, alt)
         d2=o.get_observer_look(p[i][1], lon, lat, alt)
         d3=o.get_observer_look(p[i][2], lon, lat, alt)
         print(i+1)         
         print 'start time:', p[i][0]
         print'AOS azimuth, elevation:' ,d1[0],d1[1]
         print'maximum elevation time:', p[i][2]
         print'Max azimuth, elevation:' ,d3[0],d3[1]
         print'end time:', p[i][1]
         print'LOS azimuth, elevation:' ,d2[0],d2[1]
     ip=0
     t=[1]
     for i in range(len(t)):
         l=p[i][0]
         dt=2
         if l.minute!=0 and l.minute!=1:
             utctime2=datetime.datetime(l.year,l.month,l.day,l.hour,l.minute-2,l.second)
         else:
             utctime2=datetime.datetime(l.year,l.month,l.day,l.hour-1,59,l.second) 
         if (utctime2.second%2==0) :
             utctime1=utctime2
         else:
            utctime2=datetime.datetime(l.year,l.month,l.day,l.hour-1,59,l.second-1)
            utctime1=utctime2
         while p[i][1]>=utctime1:
             if utctime1.second<58:
                 utctime1=datetime.datetime(utctime1.year,utctime1.month,utctime1.day,utctime1.hour,utctime1.minute,utctime1.second+dt) 
             elif utctime1.second==58:
                 if utctime1.minute<59:
                     utctime1=datetime.datetime(utctime1.year,utctime1.month,utctime1.day,utctime1.hour,utctime1.minute+1,0) 
                 elif utctime1.minute==59:
                     if utctime1.hour<23:
                         utctime1=datetime.datetime(utctime1.year,utctime1.month,utctime1.day,utctime1.hour+1,0,0) 
                     elif utctime1.hour==23:
                         if utctime1.month in [1,3,5,7,8,10,12] and utctime1.day<31:
                             utctime1=datetime.datetime(utctime1.year,utctime1.month,utctime1.day+1,0,0,0) 
                         elif utctime1.month in [1,3,5,7,8,10,12] and utctime1.day==31:
                             utctime1=datetime.datetime(utctime1.year,utctime1.month+1,1,0,0,0) 
                         elif utctime1.month in [4,6,9,11] and utctime1.month<30:
                             utctime1=datetime.datetime(utctime1.year,utctime1.day,utctime1.day+1,0,0,0) 
                         elif utctime1.month in [4,6,9,11] and utctime1.month==30:                             
                             utctime1=datetime.datetime(utctime1.year,utctime1.day+1,1,0,0,0)
             if p[i][0]<=utctime1:
                 look=o.get_observer_look(utctime1,lon,lat,alt)
                 "print look,utctime1"
                 angle=["%.3G" % (look[0]),"%.3G" % (look[1])]
                 msg1= str(angle[0])+','+str(angle[1])
                 if x==1:
                     s.send(msg1)
                 print msg1
                 time.sleep(2)
             ip=ip+1        
     return()
Ejemplo n.º 15
0
    return(z, nlat, nlon)


def parallax_shift(map):
    """ Shift for a given map object and corresponding height information 
        high clouds due to the parallax effect.

    Keyword arguments:

    """
    

# Create TLE file for MSG 10
line1 = "1 38552U 12035B   16165.27110250 -.00000007  00000-0  00000+0 0  9998"
line2 = "2 38552   0.7862  86.5431 0001426 165.7440 107.6925  1.00282029 14565"
msgtle = tlefile.read('meteosat 10', line1=line1, line2=line2)
msgorb = Orbital('meteosat 10', line1=msgtle.line1, line2=msgtle.line2)

# Offenbach test location
t = datetime.datetime(2016, 4, 29, 12, 00)
lat = 50.0956
lon = 8.7761
alt = 109.
h = 8000.
get_parallaxed_coor('meteosat 10', msgtle, t, lat, lon, alt, h)

# Algeria test location
t = datetime.datetime(2016, 4, 29, 12, 00)
lat = 0.00
lon = 25.00
alt = 0.
Ejemplo n.º 16
0
from pyorbital.orbital import Orbital
from datetime import datetime, timedelta
import time
import calendar

SIDERAL_DAY_SEC = 86164.0905
MU = 398600 # Earth standard gravitational parameter

satellite = sys.argv[1]
userLat = float(sys.argv[2])
userLng = float(sys.argv[3])
userAlt = float(sys.argv[4])
line1 = sys.argv[5]
line2 = sys.argv[6]

tle = tlefile.read(satellite, None, line1, line2)

orb = Orbital(satellite, None, line1, line2)

now = datetime.utcnow()
# Get normalized position and velocity of the satellite:
pos, vel = orb.get_position(now)
# Get longitude, latitude and altitude of the satellite:
position = orb.get_lonlatalt(now)

data = {}

timestamp = calendar.timegm(now.utctimetuple())


az, el = orb.get_observer_look(now, userLng, userLat, userAlt);
Ejemplo n.º 17
0
from math import pow, degrees, radians, pi, sin, cos, sqrt
from scipy import mat, arctan, arctan2, integrate  #pi, cos, sin,

# graphics modules
from mayavi import mlab
import matplotlib.pyplot as plt
from pylab import ion  #, plots
from tvtk.tools import visual

# $python setup.py install for first time
#import geomag

# -----------------------------------------------------------------------------
# Load the ISS TLE
#tle = tlefile.read('ISS (ZARYA)') # reads TLE from the celestrack website
tle = tlefile.read('ISS (ZARYA)', tle_folder + 'stations.txt')
#print tle.epoch

orb = Orbital("ISS (ZARYA)", tle_folder + 'stations.txt')
#now = datetime.utcnow() # for real time
now = datetime(2013, 05, 31, 22, 0, 0)
pos0 = orb.get_position(now, normalize=False)
lon, lat, alt = orb.get_lonlatalt(now)
print "\nSatellite Lat Lon Alt: ", lat, lon, alt, "\n"
print "\nSatellite Position (normalized):", pos0[0], "\n"
vector_zero = osl.vector_zero

###############################################################################
r_earth = 6371.0  # km
r = r_earth
Ejemplo n.º 18
0
def SatStats():

    #tle = r"C:\Users\Jake\Python\TLE Files\stations-tle.txt"

    # Download TLE file
    #downloadUrl = "http://www.celestrak.com/NORAD/elements/stations.txt"
    #urllib.request.urlretrieve(downloadUrl, tle)

    tle = GetTLEFile()

    stationList = GetStationList(tle)

    try:
        while (True):
            stationNumber = input("Enter Station Number: ")
            print()

            if stationNumber == 'n':
                for name in enumerate(stationList):
                    print(name[0], ':', name[1].replace('\n', ''))

                print()

            else:
                break

        stationNumber = int(stationNumber)

        if stationNumber < len(stationList):
            # Get Platform Object

            station = stationList[stationNumber]
            stationObject = tlefile.read(station, tle)

            GoogleSearch(station)

            # Print Platform Info
            PrintTLEInfo(stationObject, station)

            lon, lat, alt, now = GetGPSPosition(station, tle,
                                                datetime.utcnow())
            dmLon, dmLat = DegreeMinutes(lon, lat)

            print("Current GPS location:\n",
                  "Latitude: ",
                  lat,
                  " Longitude: ",
                  lon,
                  " Altitude (km): ",
                  alt,
                  sep='')
            print("Current GPS location:\n",
                  "Latitude: ",
                  dmLat,
                  " Longitude: ",
                  dmLon,
                  " Altitude (km): ",
                  alt,
                  sep='')
            satOrb = Orbital(station, tle)

            print()

            PrintFreqData(
                GetFreqData(
                    station,
                    "C:/Users/Jake/Python/Satellite Tracker/frequencies/satfreqlist.csv"
                ))

            passes = satOrb.get_next_passes(datetime.utcnow(), 120,
                                            -90.5546910, 38.6475290, 180.85)

            print("Next passes in 5 days (Max Elevation Above 20 deg):")

            for eachPass in passes:
                rise = eachPass[0]
                fall = eachPass[1]
                apex = eachPass[2]

                # Lon, Lat
                obsRiseAngle, obsRiseElv = satOrb.get_observer_look(
                    rise, -90.5546910, 38.6475290, 180.85)
                obsFallAngle, obsFallElv = satOrb.get_observer_look(
                    fall, -90.5546910, 38.6475290, 180.85)
                obsApexAngle, obsApexElv = satOrb.get_observer_look(
                    apex, -90.5546910, 38.6475290, 180.85)

                if obsApexElv >= 20.0:
                    print("Rise Time:", rise, "Azimuth:",
                          round(obsRiseAngle, 2), '(',
                          AzimuthDirection(obsRiseAngle), ')', "Elevation:",
                          abs(round(obsRiseElv, 2)))

                    print("Apex Time:", apex, "Azimuth:",
                          round(obsApexAngle, 2), '(',
                          AzimuthDirection(obsApexAngle), ')', "Elevation:",
                          abs(round(obsApexElv, 2)))

                    print("Fall Time:", fall, "Azimuth:",
                          round(obsFallAngle, 2), '(',
                          AzimuthDirection(obsFallAngle), ')', "Elevation:",
                          abs(round(obsFallElv, 2)))
                    print()
    except:
        pass
def getUpcomingPasses(satellite_name, tle_information, passes_begin_time, passes_period):


    observer = ephem.Observer()
    observer.lat = ground_station[0]
    observer.long = ground_station[1]
    #updatetime = 0
    period = passes_period
    #Get most recent TLE for determining upcoming passes from now
    tles = tle_information

    # make a list of dicts to hold the upcoming pass information for the selected satellites
    schedule = []
    observer.date = passes_begin_time

    while 1:

        print "---------------------------------------"
        for tle in tles:
            if tle[0] == satellite_name:
                #TODO clean up the use of pyephem versus orbital. Orbital can give a orbit number and does many of the pyephem functions
                #TODO add the individual acquisitions as layers in the same ogr output
                #TODO use an appropriate google earth icon for satellites at a visible display resolution with a name tag and minutesaway
                #TODO print output to logging
                satname = str(tle[0]).replace(" ","_")
                sat = ephem.readtle(tle[0],tle[1],tle[2])


                twole = tlefile.read(tle[0],'tles.txt')
                now = datetime.utcnow()
                #TODO check age of TLE - if older than x days get_tle()
                print "TLE EPOCH:",twole.epoch
                #if twole.epoch < now - timedelta(days=5):
                #    get_tles()
                #    satname = str(tle[0]).replace(" ","_")
                #    sat = ephem.readtle(tle[0],tle[1],tle[2])
                #    twole = tlefile.read(tle[0],'tles.txt')

                print "---------------------------------------"
                print tle[0]

                oi = float(str.split(tle[2],' ')[3])
                orb = Orbital(tle[0])

                attributes = []

                rt, ra, tt, ta, st, sa = observer.next_pass(sat)

                # Determine is pass descending or ascending
                sat.compute(rt)
                aos_lat = sat.sublat.real*(180/math.pi)
                sat.compute(st)
                los_lat = sat.sublat.real*(180/math.pi)

                if (aos_lat > los_lat):
                    print "PASS                 = descending"
                    node = "descending"
                else:
                    print "PASS                 = ascending"
                    node = "ascending"
                    oi = 360 - oi

                AOStime = datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S")
                minutesaway = (AOStime-now).seconds/60.0

                print "Minutes to horizon   = ", minutesaway
                print "AOStime              = ", rt
                print "LOStime              = ", st
                print "Transit time         = ", tt

                orad = orb.get_lonlatalt(datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S"))[2]

                attributes = {'Satellite name': satname, 'Orbit height': orad, 'Orbit': orb.get_orbit_number(datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S")), \
                              'Current time': str(now),'Minutes to horizon': minutesaway, 'AOS time': str(rt), \
                              'LOS time': str(st), 'Transit time': str(tt), 'Node': node}

                # Append the attributes to the list of acquisitions for the acquisition period
                if not any ((x['Satellite name'] == satname and x['Orbit'] == orb.get_orbit_number(datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S")))for x in schedule):
                    schedule.append(attributes)

                # Step from AOS to LOS in 100 second intervals
                delta = timedelta(seconds=100)
                deltatime = datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S")

                geoeastpoint = []
                geowestpoint = []
                geotrack = []


                print "DELTATIME", deltatime
                print "SETTING TIME", datetime.strptime(str(st), "%Y/%m/%d %H:%M:%S")

                while deltatime < datetime.strptime(str(st), "%Y/%m/%d %H:%M:%S"):

                    sat.compute(deltatime)
                    geotrack.append({'lat2': sat.sublat.real*(180/math.pi), \
                                     'lon2': sat.sublong.real*(180/math.pi), \
                                     'alt2': orb.get_lonlatalt(datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S"))[2]*1000})

                    eastaz = getEffectiveHeading(sat,oi,sat.sublat.real*(180/math.pi), sat.sublong.real*(180/math.pi), orad, sat._n)+90
                    westaz = getEffectiveHeading(sat,oi,sat.sublat.real*(180/math.pi), sat.sublong.real*(180/math.pi), orad, sat._n)+270

                    #Set ground swath per satellite sensor
                    #TODO use view angle check to refine step from satellite track see IFOV
                    if tle[0] in ("LANDSAT 8","LANDSAT 7"):
                        swath = 185000/2
                    if tle[0] in ("TERRA","AQUA"):
                        swath = 2330000/2
                    if tle[0] in ("NOAA 15", "NOAA 18", "NOAA 19"):
                        swath = 1100000/2
                    if tle[0] == "SUOMI NPP":
                        swath = 2200000/2

                    geoeastpoint.append(Geodesic.WGS84.Direct(sat.sublat.real*180/math.pi, sat.sublong.real*180/math.pi, eastaz, swath))
                    geowestpoint.append(Geodesic.WGS84.Direct(sat.sublat.real*180/math.pi, sat.sublong.real*180/math.pi, westaz, swath))

                    deltatime = deltatime+delta

                # Create current location ogr output
                nowpoint = [{'lat2':orb.get_lonlatalt(datetime.utcnow())[1],'lon2':orb.get_lonlatalt(datetime.utcnow())[0],'alt2':orb.get_lonlatalt(datetime.utcnow())[2]*1000}]
                #TODO ensure the now attributes are actually attributes for the current position of the satellite and include relevant next pass information...tricky?
                #if ((attributes['Orbit']==orb.get_orbit_number(datetime.utcnow()))and(AOStime<now)):
                now_attributes = {'Satellite name': satname, 'Orbit height': orb.get_lonlatalt(datetime.utcnow())[2], 'Orbit': orb.get_orbit_number(datetime.utcnow()), \
                          'Current time': str(now),'Minutes to horizon': "N/A", 'AOS time': "N/A", \
                          'LOS time': "N/A", 'Transit time': "N/A", 'Node': "N/A"}
                    #now_attributes=attributes
                CURRENT_POSITION_FILENAME = satname+"_current_position.kml"

                #TODO draw the current orbit forward for the passes period time from the satellite position as a long stepped ogr line

                getVectorFile(now_attributes,nowpoint,'point', CURRENT_POSITION_FILENAME, 'KML')

                polypoints = []

                for x in geowestpoint:
                    polypoints.append({'lat2':x['lat2'],'lon2':x['lon2']})
                for x in reversed(geoeastpoint):
                    polypoints.append({'lat2':x['lat2'],'lon2':x['lon2']})
                if len(polypoints)>0:
                    polypoints.append({'lat2':geowestpoint[0]['lat2'],'lon2':geowestpoint[0]['lon2']})

                # Create swath footprint ogr output
                SWATH_FILENAME = os.path.join(output_path,satname+"."+str(orb.get_orbit_number(datetime.strptime(str(rt),"%Y/%m/%d %H:%M:%S")))+".ALICE.orbit_swath.kml")
                ORBIT_FILENAME = os.path.join(output_path,satname+"."+str(orb.get_orbit_number(datetime.strptime(str(rt),"%Y/%m/%d %H:%M:%S")))+".ALICE.orbit_track.kml")
                TRACKING_SWATH_FILENAME = os.path.join(output_path,satname+"_tracking_now.kml")

                # Create currently acquiring polygon
                #TODO def this
                # Step from AOS to current time second intervals

                observer.date=datetime.utcnow()
                sat.compute(observer)
                tkdelta = timedelta(seconds=100)
                tkrt, tkra, tktt, tkta, tkst, tksa = observer.next_pass(sat)
                tkdeltatime = datetime.utcnow()
                tkgeoeastpoint = []
                tkgeowestpoint = []
                tkgeotrack = []

                while tkdeltatime < (datetime.utcnow() or datetime.strptime(str(tkst),"%Y/%m/%d %H:%M:%S")):

                    sat.compute(tkdeltatime)
                    tkgeotrack.append({'lat2':sat.sublat.real*(180/math.pi),'lon2':sat.sublong.real*(180/math.pi),'alt2':orb.get_lonlatalt(datetime.strptime(str(rt),"%Y/%m/%d %H:%M:%S"))[2]})

                    tkeastaz = getEffectiveHeading(sat,oi,sat.sublat.real*(180/math.pi), sat.sublong.real*(180/math.pi),orad,sat._n)+90
                    tkwestaz = getEffectiveHeading(sat,oi,sat.sublat.real*(180/math.pi), sat.sublong.real*(180/math.pi),orad,sat._n)+270
                    #TODO use view angle check to refine step from satellite track see IFOV
                    if tle[0] in ("LANDSAT 8","LANDSAT 7"):
                        tkswath = 185000/2
                    if tle[0] in ("TERRA","AQUA"):
                        tkswath = 2330000/2
                    if tle[0] in ("NOAA 15", "NOAA 18", "NOAA 19"):
                        tkswath = 1100000/2
                    if tle[0] == "SUOMI NPP":
                        tkswath = 2200000/2
                    tkgeoeastpoint.append(Geodesic.WGS84.Direct(sat.sublat.real*180/math.pi, sat.sublong.real*180/math.pi, tkeastaz, tkswath))
                    tkgeowestpoint.append(Geodesic.WGS84.Direct(sat.sublat.real*180/math.pi, sat.sublong.real*180/math.pi, tkwestaz, tkswath))

                    tkdeltatime = tkdeltatime+tkdelta

                tkpolypoints = []

                for x in tkgeowestpoint:
                    tkpolypoints.append({'lat2':x['lat2'],'lon2':x['lon2']})
                for x in reversed(tkgeoeastpoint):
                    tkpolypoints.append({'lat2':x['lat2'],'lon2':x['lon2']})
                if len(tkpolypoints)>0:
                    tkpolypoints.append({'lat2':tkgeowestpoint[0]['lat2'],'lon2':tkgeowestpoint[0]['lon2']})

                if not ((attributes['Node']=="ascending")and(satname not in ("AQUA"))):
                    # Create swath ogr output
                    getVectorFile(attributes,polypoints,'polygon', SWATH_FILENAME, 'KML')
                    # Create orbit track ogr output
                    getVectorFile(attributes,geotrack,'line', ORBIT_FILENAME, 'KML')
                    # Create currently acquiring ogr output
                    if ((now >= datetime.strptime(str(tkrt),"%Y/%m/%d %H:%M:%S")) and (now <= datetime.strptime(str(tkst),"%Y/%m/%d %H:%M:%S"))):
                        getVectorFile(now_attributes,tkpolypoints,'polygon', TRACKING_SWATH_FILENAME, 'KML')

                if minutesaway <= period:

                    print "---------------------------------------"
                    print tle[0], 'WILL BE MAKING A PASS IN ', minutesaway, " MINUTES"
                    print ' Rise Azimuth: ', ra
                    print ' Transit Time: ', tt
                    print ' Transit Altitude: ', ta
                    print ' Set Time: ', st
                    print ' Set Azimuth: ', sa

                    for x in sorted(schedule, key=lambda k: k['AOS time']):
                        print x
                        # For dictionary entries with 'LOS time' older than now time - remove
                        if ((datetime.strptime(str(x['LOS time']),"%Y/%m/%d %H:%M:%S"))<(datetime.utcnow())):
                            # Delete output ogr
                            if os.path.exists(os.path.join(output_path,satname+"."+str(x['Orbit'])+".ALICE.orbit_swath.kml")):
                                os.remove(os.path.join(output_path,satname+"."+str(x['Orbit'])+".ALICE.orbit_swath.kml"))
                            if os.path.exists(os.path.join(output_path,satname+"."+str(x['Orbit'])+".ALICE.orbit_track.kml")):
                                os.remove(os.path.join(output_path,satname+"."+str(x['Orbit'])+".ALICE.orbit_track.kml"))
                            # Delete dictionary entry for pass
                            schedule.remove(x)

                    # Unlikely - if no entries in the schedule don't try to print it
                    if len(schedule)>0:
                        print (datetime.strptime(str(schedule[0]['AOS time']),"%Y/%m/%d %H:%M:%S"))

                    # If the AOS time is less than now + the time delta, shift the time to the latest recorded pass LOS time
                    if ((datetime.strptime(str(schedule[len(schedule)-1]['AOS time']),"%Y/%m/%d %H:%M:%S")<(datetime.utcnow()+timedelta(minutes=period)))):
                        observer.date = (datetime.strptime(str(schedule[len(schedule)-1]['LOS time']),"%Y/%m/%d %H:%M:%S")+timedelta(minutes=5))
                        # Recompute the satellite position for the update time
                        sat.compute(observer)
                        print "MODIFIED OBSERVER DATE",observer.date
                    else:
                        print "--------NOTHING TO MODIFY MOVING TO NEXT SATELLITE IN LIST------"
                        #TODO - write to html

                        # Exit the def if the schedule isn't able to update because there are no passes in the acquisition window
                        return ()

        time.sleep(1*sleep_status)
    return ()
Ejemplo n.º 20
0
def SatStats():
    
    #tle = r"C:\Users\Jake\Python\TLE Files\stations-tle.txt"
    
    # Download TLE file
    #downloadUrl = "http://www.celestrak.com/NORAD/elements/stations.txt"
    #urllib.request.urlretrieve(downloadUrl, tle)

    tle = GetTLEFile()
    
    stationList = GetStationList(tle)
    
        
    try:
        while(True):
            stationNumber = input("Enter Station Number: ")
            print()
            
            if stationNumber == 'n':
                for name in enumerate(stationList):
                    print(name[0], ':', name[1].replace('\n', ''))
                
                print()
                    
            else:
                break
    
        stationNumber = int(stationNumber)
        
        if stationNumber < len(stationList):
            # Get Platform Object
        
            station = stationList[stationNumber]
            stationObject = tlefile.read(station, tle)
                    
            GoogleSearch(station)

            # Print Platform Info
            PrintTLEInfo(stationObject, station)
            
            lon, lat, alt, now = GetGPSPosition(station, tle, datetime.utcnow())                    
            dmLon, dmLat = DegreeMinutes(lon, lat)
                    
            print("Current GPS location:\n", "Latitude: ", lat, " Longitude: ", lon, " Altitude (km): ", alt, sep='')
            print("Current GPS location:\n", "Latitude: ", dmLat, " Longitude: ", dmLon, " Altitude (km): ", alt, sep='')
            satOrb = Orbital(station, tle)
            
            print()
        
            PrintFreqData(GetFreqData(station, "C:/Users/Jake/Python/Satellite Tracker/frequencies/satfreqlist.csv"))
            
            
            passes = satOrb.get_next_passes(datetime.utcnow(), 120, -90.5546910, 38.6475290, 180.85)
            
            
            print("Next passes in 5 days (Max Elevation Above 20 deg):")
            
            for eachPass in passes:
                rise = eachPass[0]
                fall = eachPass[1]
                apex = eachPass[2]
                
                # Lon, Lat
                obsRiseAngle, obsRiseElv = satOrb.get_observer_look(rise, -90.5546910, 38.6475290, 180.85)
                obsFallAngle, obsFallElv = satOrb.get_observer_look(fall, -90.5546910, 38.6475290, 180.85)
                obsApexAngle, obsApexElv = satOrb.get_observer_look(apex, -90.5546910, 38.6475290, 180.85)
                
                if obsApexElv >= 20.0:
                    print("Rise Time:", rise, "Azimuth:", round(obsRiseAngle, 2), 
                          '(', AzimuthDirection(obsRiseAngle), ')', "Elevation:", abs(round(obsRiseElv, 2)))
                    
                    print("Apex Time:", apex, "Azimuth:", round(obsApexAngle, 2),
                          '(', AzimuthDirection(obsApexAngle), ')', "Elevation:", abs(round(obsApexElv, 2)))
                          
                    print("Fall Time:", fall, "Azimuth:", round(obsFallAngle, 2), 
                          '(', AzimuthDirection(obsFallAngle), ')', "Elevation:", abs(round(obsFallElv, 2)))
                    print()
    except: 
        pass    
Ejemplo n.º 21
0
    description="Compute ISS orbit geometry vs time")
parser.add_argument("sourcename", help="Source name to look up coordinates")
parser.add_argument("--ra ",
                    dest='ra',
                    help="Source RA  [default: lookup]",
                    default=None)
parser.add_argument("--dec",
                    dest='dec',
                    help="Source DEC [default: lookup]",
                    default=None)
parser.add_argument("--vis", help="Visibility file from Wayne", default=None)
args = parser.parse_args()

# Set up two TLEs so we can compute the precession rate from the
# change of RA of ascending node with time
tle1 = tlefile.read(platform, line1=tle160lines[0], line2=tle160lines[1])
tle2 = tlefile.read(platform, line1=tle167lines[0], line2=tle167lines[1])

print(platform)
ISSInclination = tle2.inclination * u.deg
print("Inclination = {0:.3f}".format(ISSInclination))

StarboardPoleDec0 = -1 * (90.0 * u.deg - ISSInclination)
PortPoleDec0 = -1 * StarboardPoleDec0

print("Starboard Orbit Pole Declination {0:.2f}".format(StarboardPoleDec0))
print("Port Orbit Pole Declination {0:.2f}".format(PortPoleDec0))

# Compute ISS precession rate in degrees per day
ISSPrecessionRate = (tle2.right_ascension - tle1.right_ascension) / (
    tle2.epoch_day - tle1.epoch_day) * u.deg / u.d
def getUpcomingPasses(satellite_name,satellite_swath,tle_information, passes_begin_time, passes_period):


    observer       = ephem.Observer()
    observer.lat   = GROUND_STATION[0]
    observer.long  = GROUND_STATION[1]
    #updatetime = 0
    period = passes_period
    #Get most recent TLE for determining upcoming passes from now
    tles = tle_information

    # make a list of dicts to hold the upcoming pass information for the selected satellites
    SCHEDULE = []
    observer.date = passes_begin_time

    while 1:

        for tle in tles:

            if tle[0].strip()== satellite_name:

                #TODO clean up the use of pyephem versus orbital. Orbital can give a orbit number and does many of the pyephem functions
                #TODO add the individual acquisitions as layers in the same ogr output
                #TODO use an appropriate google earth icon for satellites at a visible display resolution with a name tag and minutesaway
                #TODO print output to logging
                satname = str(tle[0]).replace(" ","_")
                sat = ephem.readtle(tle[0],tle[1],tle[2])

                twole = tlefile.read(tle[0],DATA_IN_DIR+'tles.txt')
                now = datetime.utcnow()
                #TODO check age of TLE - if older than x days get_tle()
#                print "TLE EPOCH:",twole.epoch
                
                oi = float(str.split(tle[2],' ')[3])
                orb = Orbital(tle[0])
                attributes = []
                rt, ra, tt, ta, st, sa = observer.next_pass(sat)

                # Determine is pass descending or ascending
                sat.compute(rt)
                aos_lat = sat.sublat.real*(180/math.pi)
                sat.compute(st)
                los_lat = sat.sublat.real*(180/math.pi)

                if (aos_lat > los_lat):
#                    print "PASS                 = descending"
                    node = "descending"
                else:
#                    print "PASS                 = ascending"
                    node = "ascending"
                    oi = 360 - oi

                AOStime = datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S")
                minutesaway = (AOStime-now).seconds/60.0

#		print "Satellie             = ", satname
#               print "Minutes to horizon   = ", minutesaway
#               print "AOStime              = ", rt
#               print "LOStime              = ", st
#               print "Transit time         = ", tt
#	-----------------------------------------------------------------------------
#		This is a test routine for calculating Az, El angles
#	-----------------------------------------------------------------------------



                orad = orb.get_lonlatalt(datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S"))[2]

#               print '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'
		test_az_el_cal(orb,observer, rt, ra, tt, ta, st, sa,orad)
#               print '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'



#		
                attributes = {'Satellite name': satname, 'Orbit height': orad, 'Orbit': orb.get_orbit_number(datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S")), \
#                attributes = {'Satellite name': satname, 'Orbit height': orad, 'Orbit': orb.get_orbit_number(datetime.strptime(str(tt), "%Y/%m/%d %H:%M:%S")), \
                              'Current time': str(now),'Minutes to horizon': minutesaway, 'AOS time': str(rt), \
                              'LOS time': str(st), 'Transit time': str(tt), 'Node': node}

                # Append the attributes to the list of acquisitions for the acquisition period
                if not any ((x['Satellite name'] == satname and x['Orbit'] == orb.get_orbit_number(datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S")))for x in SCHEDULE):
#                if not any ((x['Satellite name'] == satname and x['Orbit'] == orb.get_orbit_number(datetime.strptime(str(tt), "%Y/%m/%d %H:%M:%S")))for x in SCHEDULE):
                    SCHEDULE.append(attributes)

                # Step from AOS to LOS in 100 second intervals
#                delta = timedelta(seconds=100)
                delta = timedelta(seconds=DELTA_TIME_STEP)
                deltatime = datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S")
                geoeastpoint = []
                geowestpoint = []
                geotrack = []


#                print "DELTATIME", deltatime
#                print "SETTING TIME", datetime.strptime(str(st), "%Y/%m/%d %H:%M:%S")


#		Tesing for next satellite



#	--------------------------------------------------------------------------------------------
#	--------------------------------------------------------------------------------------------
#		The following set of lines have been for testing while making comparision in seconds 
#		instead of string comparisiom
#	--------------------------------------------------------------------------------------------
#	--------------------------------------------------------------------------------------------

#		print '================ Testing Loop starts ==========================================='
#		print 'deltatime       = ',deltatime
#		print 'Secs Time       = ', get_time_secs(str(deltatime).replace("-","/"))
#		print 'st              = ',str(datetime.strptime(str(st), "%Y/%m/%d %H:%M:%S"))
#		print 'st in Secs Time = ',get_time_secs(str(datetime.strptime(str(st), "%Y/%m/%d %H:%M:%S")).replace('-','/'))
#		print '================ Testing Loop Ends   ==========================================='
#		The following if statement has ben included on the basis of dpoch seconds
#

		if get_time_secs(str(deltatime).replace("-","/")) >= \
			get_time_secs(str(datetime.strptime(str(st), "%Y/%m/%d %H:%M:%S")).replace('-','/')):
			return()

		print 'Delta Time = ',deltatime
		print 'date time  = ',datetime.strptime(str(st), "%Y/%m/%d %H:%M:%S")		
		print '---------------------------'

#		if deltatime >= datetime.strptime(str(st), "%Y/%m/%d %H:%M:%S"):
#			return()

                while deltatime < datetime.strptime(str(st), "%Y/%m/%d %H:%M:%S"):

                    sat.compute(deltatime)
                    geotrack.append({'lat2': sat.sublat.real*(180/math.pi), \
                                     'lon2': sat.sublong.real*(180/math.pi), \
                                     'alt2': orb.get_lonlatalt(datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S"))[2]*1000})

                    eastaz = getEffectiveHeading(sat,oi,sat.sublat.real*(180/math.pi), sat.sublong.real*(180/math.pi), orad, sat._n)+90
                    westaz = getEffectiveHeading(sat,oi,sat.sublat.real*(180/math.pi), sat.sublong.real*(180/math.pi), orad, sat._n)+270

                    #Set ground swath per satellite sensor
                    #TODO use view angle check to refine step from satellite track see IFOV
                    
		    swath = float(satellite_swath)/2.
		    
                    geoeastpoint.append(Geodesic.WGS84.Direct(sat.sublat.real*180/math.pi, sat.sublong.real*180/math.pi, eastaz, swath))
                    geowestpoint.append(Geodesic.WGS84.Direct(sat.sublat.real*180/math.pi, sat.sublong.real*180/math.pi, westaz, swath))

                    deltatime = deltatime+delta

                # Create current location ogr output
                nowpoint = [{'lat2':orb.get_lonlatalt(datetime.utcnow())[1],'lon2':orb.get_lonlatalt(datetime.utcnow())[0],'alt2':orb.get_lonlatalt(datetime.utcnow())[2]*1000}]
                #TODO ensure the now attributes are actually attributes for the current position of the satellite and include relevant next pass information...tricky?
                #if ((attributes['Orbit']==orb.get_orbit_number(datetime.utcnow()))and(AOStime<now)):
                now_attributes = {'Satellite name': satname, 'Orbit height': orb.get_lonlatalt(datetime.utcnow())[2], 'Orbit': orb.get_orbit_number(datetime.utcnow()), \
                          'Current time': str(now),'Minutes to horizon': "N/A", 'AOS time': "N/A", \
                          'LOS time': "N/A", 'Transit time': "N/A", 'Node': "N/A"}
                    #now_attributes=attributes
                #CURRENT_POSITION_FILENAME = satname+"_current_position.kml"

                CURRENT_POSITION_FILENAME = OUTPUT_DIR+satname+"_current_position.kml"

                #TODO draw the current orbit forward for the passes period time from the satellite position as a long stepped ogr line

                getVectorFile(now_attributes,nowpoint,'point', CURRENT_POSITION_FILENAME, 'KML')

                polypoints = []

                for x in geowestpoint:
                    polypoints.append({'lat2':x['lat2'],'lon2':x['lon2']})
                for x in reversed(geoeastpoint):
                    polypoints.append({'lat2':x['lat2'],'lon2':x['lon2']})
                if len(polypoints)>0:
                    polypoints.append({'lat2':geowestpoint[0]['lat2'],'lon2':geowestpoint[0]['lon2']})

                # Create swath footprint ogr output
                SWATH_FILENAME = os.path.join(output_path,satname+"."+str(orb.get_orbit_number(datetime.strptime(str(rt),"%Y/%m/%d %H:%M:%S")))+".ALICE.orbit_swath.kml")
                ORBIT_FILENAME = os.path.join(output_path,satname+"."+str(orb.get_orbit_number(datetime.strptime(str(rt),"%Y/%m/%d %H:%M:%S")))+".ALICE.orbit_track.kml")
                TRACKING_SWATH_FILENAME = os.path.join(output_path,satname+"_tracking_now.kml")

                # Create currently acquiring polygon
                #TODO def this
                # Step from AOS to current time second intervals

                observer.date=datetime.utcnow()
                sat.compute(observer)

#               tkdelta = timedelta(seconds=100)

                tkdelta = timedelta(seconds=DELTA_TIME_STEP)

                tkrt, tkra, tktt, tkta, tkst, tksa = observer.next_pass(sat)
                tkdeltatime = datetime.utcnow()
                tkgeoeastpoint = []
                tkgeowestpoint = []
                tkgeotrack = []

                while tkdeltatime < (datetime.utcnow() or datetime.strptime(str(tkst),"%Y/%m/%d %H:%M:%S")):

                    sat.compute(tkdeltatime)
                    tkgeotrack.append({'lat2':sat.sublat.real*(180/math.pi),'lon2':sat.sublong.real*(180/math.pi),'alt2':orb.get_lonlatalt(datetime.strptime(str(rt),"%Y/%m/%d %H:%M:%S"))[2]})

                    tkeastaz = getEffectiveHeading(sat,oi,sat.sublat.real*(180/math.pi), sat.sublong.real*(180/math.pi),orad,sat._n)+90
                    tkwestaz = getEffectiveHeading(sat,oi,sat.sublat.real*(180/math.pi), sat.sublong.real*(180/math.pi),orad,sat._n)+270
                    #TODO use view angle check to refine step from satellite track see IFOV

		    tkswath = float(satellite_swath)/2.
		    
                    tkgeoeastpoint.append(Geodesic.WGS84.Direct(sat.sublat.real*180/math.pi, sat.sublong.real*180/math.pi, tkeastaz, tkswath))
                    tkgeowestpoint.append(Geodesic.WGS84.Direct(sat.sublat.real*180/math.pi, sat.sublong.real*180/math.pi, tkwestaz, tkswath))

                    tkdeltatime = tkdeltatime+tkdelta

                tkpolypoints = []

                for x in tkgeowestpoint:
                    tkpolypoints.append({'lat2':x['lat2'],'lon2':x['lon2']})
                for x in reversed(tkgeoeastpoint):
                    tkpolypoints.append({'lat2':x['lat2'],'lon2':x['lon2']})
                if len(tkpolypoints)>0:
                    tkpolypoints.append({'lat2':tkgeowestpoint[0]['lat2'],'lon2':tkgeowestpoint[0]['lon2']})

                if not ((attributes['Node']=="ascending")and(satname not in ("AQUA"))):
                    # Create swath ogr output
                    getVectorFile(attributes,polypoints,'polygon', SWATH_FILENAME, 'KML')
                    # Create orbit track ogr output
                    getVectorFile(attributes,geotrack,'line', ORBIT_FILENAME, 'KML')
                    # Create currently acquiring ogr output
                    if ((now >= datetime.strptime(str(tkrt),"%Y/%m/%d %H:%M:%S")) and (now <= datetime.strptime(str(tkst),"%Y/%m/%d %H:%M:%S"))):
                        getVectorFile(now_attributes,tkpolypoints,'polygon', TRACKING_SWATH_FILENAME, 'KML')

                if minutesaway <= period:

#                    print tle[0], 'WILL BE MAKING A PASS IN ', minutesaway, " MINUTES"
#                    print ' Rise Azimuth: ', ra
#                    print ' Transit Time: ', tt
#                    print ' Transit Altitude: ', ta
#                    print ' Set Time: ', st
#                    print ' Set Azimuth: ', sa
#                    print '================================================='
#		    print 'Satellite Name = ',satellite_name
                    for x in sorted(SCHEDULE, key=lambda k: k['AOS time']):
#			print x
			output_orbit_parameters(x)
                        # For dictionary entries with 'LOS time' older than now time - remove
                        if ((datetime.strptime(str(x['LOS time']),"%Y/%m/%d %H:%M:%S"))<(datetime.utcnow())):
                            # Delete output ogr
                            if os.path.exists(os.path.join(output_path,satname+"."+str(x['Orbit'])+".ALICE.orbit_swath.kml")):
                                os.remove(os.path.join(output_path,satname+"."+str(x['Orbit'])+".ALICE.orbit_swath.kml"))
                            if os.path.exists(os.path.join(output_path,satname+"."+str(x['Orbit'])+".ALICE.orbit_track.kml")):
                                os.remove(os.path.join(output_path,satname+"."+str(x['Orbit'])+".ALICE.orbit_track.kml"))
                            # Delete dictionary entry for pass
                            SCHEDULE.remove(x)

                    # Unlikely - if no entries in the SCHEDULE don't try to print it

                    if len(SCHEDULE)>0:
			print (datetime.strptime(str(SCHEDULE[0]['AOS time']),"%Y/%m/%d %H:%M:%S"))

                    # If the AOS time is less than now + the time delta, shift the time to the latest recorded pass LOS time

                    if ((datetime.strptime(str(SCHEDULE[len(SCHEDULE)-1]['AOS time']),"%Y/%m/%d %H:%M:%S")<(datetime.utcnow()+timedelta(minutes=period)))):
                        observer.date = (datetime.strptime(str(SCHEDULE[len(SCHEDULE)-1]['LOS time']),"%Y/%m/%d %H:%M:%S")+timedelta(minutes=5))
                        # Recompute the satellite position for the update time
                        sat.compute(observer)
#                        print "MODIFIED OBSERVER DATE",observer.date
                    else:
#                       print "--------NOTHING TO MODIFY MOVING TO NEXT SATELLITE IN LIST------"
                        #TODO - write to html

                        # Exit the def if the SCHEDULE isn't able to update because there are no passes in the acquisition window
                        return ()

#	print 'Before Time Sleep ......'
#	print 'Loop for While .........'
	print '============================================================================='

        time.sleep(1*SLEEP_STATUS)
    return ()
Ejemplo n.º 23
0
 def addSat(self):
     add_sat = self.avail_sats_lst.get(self.avail_sats_lst.curselection())
     self.ax_cov.append(
         self.ax.fill([0, 0], [0, 0],
                      transform=Geodetic(),
                      color='white',
                      alpha=self.cov_alpha)[0])
     self.sat_txt.append(
         self.ax.text([], [],
                      "",
                      color='yellow',
                      size=8,
                      transform=Geodetic(),
                      ha="center"))
     if (add_sat in self.argos):
         self.createSatFromFile(add_sat, "TLE/argos.txt",
                                "Argos Data Collection System")
     elif (add_sat in self.cubesat):
         self.createSatFromFile(add_sat, "TLE/cubesat.txt", "CubeSat")
     elif (add_sat in self.dmc):
         self.createSatFromFile(add_sat, "TLE/dmc.txt",
                                "Disaster Monitoring")
     elif (add_sat in self.goes):
         self.createSatFromFile(add_sat, "TLE/goes.txt", "GOES")
     elif (add_sat in self.intelsat):
         self.createSatFromFile(add_sat, "TLE/intelsat.txt", "Intelsat")
     elif (add_sat in self.iridium):
         self.createSatFromFile(add_sat, "TLE/iridium.txt", "Iridium")
     elif (add_sat in self.iridium_next):
         self.createSatFromFile(add_sat, "TLE/iridium-NEXT.txt",
                                "Iridium Next")
     elif (add_sat in self.molniya):
         self.createSatFromFile(add_sat, "TLE/molniya.txt", "Molniya")
     elif (add_sat in self.noaa):
         self.createSatFromFile(add_sat, "TLE/noaa.txt", "NOAA")
     elif (add_sat in self.planet):
         self.createSatFromFile(add_sat, "TLE/planet.txt", "Planet")
     elif (add_sat in self.resource):
         self.createSatFromFile(add_sat, "TLE/resource.txt",
                                "Earth Resources")
     elif (add_sat in self.sarsat):
         self.createSatFromFile(add_sat, "TLE/sarsat.txt",
                                "Search & Rescue")
     elif (add_sat in self.spire):
         self.createSatFromFile(add_sat, "TLE/spire.txt", "Spire")
     elif (add_sat in self.tdrss):
         self.createSatFromFile(add_sat, "TLE/tdrss.txt",
                                "Tracking and Data Relay")
     elif (add_sat in self.tle_new):
         self.createSatFromFile(add_sat, "TLE/tle-new.txt",
                                "Last 30 Days' Launches")
     elif (add_sat in self.weather):
         self.createSatFromFile(add_sat, "TLE/weather.txt", "Weather")
     else:
         self.Sats.append(Sat(add_sat, tle=tlefile.read(add_sat)))
     self.curr_sats_lst.insert(END, add_sat)
     self.sortSats()
     self.srch_box.focus()
     for i, sat in enumerate(self.Sats):
         self.curr_sats_lst.delete(i)
         self.curr_sats_lst.insert(i, sat.name)
Ejemplo n.º 24
0
def PulsarVis(sourcename, times):

    if sourcename in {'PSRJ0030+0451', 'PSRJ0437-4715'}:
        SunAvoidance = 55.0 * u.deg
    else:
        SunAvoidance = 45.0 * u.deg
    print("Sun Avoidance: {0:.3f}".format(SunAvoidance))
    MoonAvoidance = 15.0 * u.deg
    # Each pulsar's feasible observation range based on ISS hardware data
    if sourcename in 'PSRB1821-24':  #Analysis ticket 890
        HardwareUpperAvoidance = 120 * u.deg  #360*u.deg
        HardwareLowerAvoidance = 88 * u.deg  #0*u.deg
    elif sourcename in 'PSRB1937+21':
        HardwareUpperAvoidance = 142.0 * u.deg  #360*u.deg
        HardwareLowerAvoidance = 91.0 * u.deg  #0*u.deg
    elif sourcename in 'PSRJ0218+4232':
        HardwareUpperAvoidance = 156.0 * u.deg  #360*u.deg
        HardwareLowerAvoidance = 88.0 * u.deg  #0*u.deg
    elif sourcename in 'PSRJ0030+0451':
        HardwareUpperAvoidance = 148.0 * u.deg  #360*u.deg
        HardwareLowerAvoidance = 95.0 * u.deg  #0*u.deg
    elif sourcename in 'PSRJ0437-4715':
        HardwareUpperAvoidance = 95.0 * u.deg  #360*u.deg
        HardwareLowerAvoidance = 35.0 * u.deg  #0*u.deg
    else:
        HardwareUpperAvoidance = 360.0 * u.deg  #360*u.deg
        HardwareLowerAvoidance = 0.0 * u.deg  #0*u.deg

    print("ISS Upper:", HardwareUpperAvoidance, "Lower:",
          HardwareLowerAvoidance, "\n".format(HardwareLowerAvoidance,
                                              HardwareUpperAvoidance))

    tle160lines = [
        '1 25544U 98067A   17160.91338884 +.00001442 +00000-0 +29152-4 0  9993',
        '2 25544 051.6425 074.5823 0004493 253.3640 193.9362 15.54003243060621'
    ]

    tle167lines = [
        '1 25544U 98067A   17167.53403196 +.00002711 +00000-0 +48329-4 0  9994',
        '2 25544 051.6431 041.5846 0004445 283.0899 147.8207 15.54043876061656'
    ]

    platform = 'ISS (ZARYA)'

    # Set up two TLEs so we can compute the precession rate from the
    # change of RA of ascending node with time
    tle1 = tlefile.read(platform, line1=tle160lines[0], line2=tle160lines[1])
    tle2 = tlefile.read(platform, line1=tle167lines[0], line2=tle167lines[1])

    #    print(platform)
    ISSInclination = tle2.inclination * u.deg
    #    print("Inclination = {0:.3f}".format(ISSInclination))

    StarboardPoleDec0 = -1 * (90.0 * u.deg - ISSInclination)
    PortPoleDec0 = -1 * StarboardPoleDec0

    #print("Starboard Orbit Pole Declination {0:.2f}".format(StarboardPoleDec0))
    #    print("Port Orbit Pole Declination {0:.2f}".format(PortPoleDec0))

    # Compute ISS precession rate in degrees per day
    ISSPrecessionRate = (tle2.right_ascension - tle1.right_ascension) / (
        tle2.epoch_day - tle1.epoch_day) * u.deg / u.d
    #    print("ISS Precession Rate {0:.3f} ({1:.3f} period)".format(ISSPrecessionRate,
    #                                                               np.abs(360.0*u.deg/ISSPrecessionRate)))

    ttle2 = Time("{0:4d}-01-01T00:00:00".format(int(tle2.epoch_year) + 2000),
                 format='isot',
                 scale='utc') + tle2.epoch_day * u.d
    #    print("ttle2 = ",ttle2.isot)
    StarboardPoleRA0 = np.fmod(tle2.right_ascension + 90.0, 360.0) * u.deg
    PortPoleRA0 = np.fmod(StarboardPoleRA0 + 180.0 * u.deg, 360.0 * u.deg)

    #   print("Starboard Pole RA @ ttle2 = {0:.3f}".format(StarboardPoleRA0))
    #   print("Port Pole RA @ ttle2 = {0:.3f}".format(PortPoleRA0))

    def StarboardPoleDec(t):
        return np.ones_like(t) * StarboardPoleDec0

    def PortPoleDec(t):
        return np.ones_like(t) * StarboardPoleDec0

    def StarboardPoleRA(t):
        return np.fmod(
            StarboardPoleRA0 + (t - ttle2).to(u.d) * ISSPrecessionRate,
            360.0 * u.deg)

    def PortPoleRA(t):
        return np.fmod(StarboardPoleRA(t) + 180.0 * u.deg, 360.0 * u.deg)

    def StarboardPoleCoord(t):
        return SkyCoord(StarboardPoleRA(t).value,
                        StarboardPoleDec(t).value,
                        unit=u.deg,
                        frame="icrs")

    def PortPoleCoord(t):
        return SkyCoord(PortPoleRA(t).value,
                        PortPoleDec(t).value,
                        unit=u.deg,
                        frame="icrs")

    now = Time.now()
    doy_now = np.float(now.yday.split(':')[1])
    #   print("Current DOY = {0}".format(np.int(doy_now)))
    #print("StarboardPoleRA (now) = {0:.3f}".format(StarboardPoleRA(now)))
    #print("PortPoleRA (now) = {0:.3f}".format(PortPoleRA(now)))

    if sourcename[0:2] != 'PSR':
        SourcePos = get_icrs_coordinates(sourcename)
    else:
        splitstr = sourcename.split(',')
        SourcePos = ICRS(ra=Angle(double(splitstr[0])),
                         dec=Angle(double(splitstr[1])))
    #print("\nSource: {0} at {1}, {2}".format(sourcename,SourcePos.ra, SourcePos.dec))
    #print("Separation from Starboard Pole = {0:.3f}".format(SourcePos.separation(StarboardPoleCoord(now))))
    #print("Separation from Port Pole = {0:.3f}".format(SourcePos.separation(PortPoleCoord(now))))

    #Calculate terms and references to do check
    #doy2XXX = np.arange(365.0)
    #times = doy2XXX*u.d + startepoch

    issseps = SourcePos.separation(StarboardPoleCoord(times)).to(u.deg)

    # The Sun and Moon positions are returned in the GCRS frame
    # Convert them to ICRS so .separation doesn't go insane when
    # comparing different frames with different obstimes.
    SunPos = get_sun(times)
    SunPos = SkyCoord(SunPos.ra, SunPos.dec, frame='icrs')
    MoonPos = get_moon(times)
    MoonPos = SkyCoord(MoonPos.ra, MoonPos.dec, frame='icrs')
    # Hold indicies when Sun and Moon cause constraint violation
    sunseps = SourcePos.separation(SunPos).to(u.deg)
    idxsun = sunseps < SunAvoidance
    moonseps = SourcePos.separation(MoonPos).to(u.deg)
    idxmoon = moonseps < MoonAvoidance
    # Hold indicies when sep is outside of 91 to 142 deg due to hardware violation (KWood analysis 10/27/2017)
    idxang = ~((issseps > HardwareLowerAvoidance) &
               (issseps < HardwareUpperAvoidance))
    # Apply all vis constraints
    indxall = idxsun | idxmoon | idxang  #true when constraint is violated
    # Generate and populate signal output
    vis = np.ones(len(doy2XXX))
    vis[indxall] = float('NaN')

    #Return result
    return vis
Ejemplo n.º 25
0
#print()

#after that for the satellite id, return all the tle parameters
#stationName = input("Enter Station Name: ")  
satNameUser = input("Enter Station Name: ")  
stationList=getStationList(tleFile)

for satelitename in stationList:
    if satelitename.rstrip() == satNameUser:
        satName = satNameUser
        
#satNumber = int(stationNumber)
#satName = stationList[satNumber]

try:
    stationObject = tlefile.read(satName, tleFile)
except:
    print("No satelite name matched, look at the following list and select the satelite number")
    print("\n List of satelites for this TLE are :  \n")
    stationList=getStationList(tleFile)
    for i in range(len(stationList)):
        print("Station Number",i, "Station Name", stationList[i])
    stationNumber = input("\n Enter Station Name: ")  
    satNumber = int(stationNumber)
    satName = stationList[satNumber]

# Print Platform Info
print("\n For the station number entered the TLE information are : \n")
stationObject = tlefile.read(satName, tleFile)
satTLENumber = printTLEInfo(stationObject, satName)
print()
Ejemplo n.º 26
0
#                12 OCT 2018                 #
#                                            #
##############################################
#
# To install PyOrbital on Linux:
# $ sudo apt_get install python_pyorbital
#
from pyorbital import tlefile
from pyorbital.orbital import Orbital
from datetime import datetime

# There are two ways we can track orbital elements using PyOrbital

# First we will use the TLE files created using tle_web_scraper.py
# Dont forget to change the file path to the actual location of the saved TLE files
tle = tlefile.read('NOAA 20 [+]', '/path/to/tle/files/noaa_tle_file.txt')
print tle

# The second method uses current TLEs from the internet, which we do not need to download
orb = Orbital(
    "NOAA 20"
)  # For additional satellites, subsitute "NOAA 20" with other NOAA satellites (numbered 1 - 20)
now = datetime.utcnow()

# Get normalized position and velocity of the satellite
current_position = orb.get_position(now)
print(current_position)

# Get the longitude, latitude and altitude of the satellite
current_lonlatalt = orb.get_lonlatalt(now)
print(current_lonlatalt)
Ejemplo n.º 27
0
    def tle(self):
        # using an archive; select appropriate TLE from file
        if self.tle_file:
            tle_data = self.read_tle_file(self.tle_file)
            dates = self.tle2datetime64(
                np.array([float(line[18:32]) for line in tle_data[::2]]))

            #  set utctime to arbitrary value inside archive if object init
            if self.utctime is None:
                sdate = dates[-1]
            else:
                sdate = np.datetime64(
                    self.utctime)  # .timestamp() #self.utcs[0]
            # Find index "iindex" such that dates[iindex-1] < sdate <= dates[iindex]
            # Notes:
            #     1. If sdate < dates[0] then iindex = 0
            #     2. If sdate > dates[-1] then iindex = len(dates), beyond the right boundary!
            iindex = np.searchsorted(dates, sdate)

            if iindex in (0, len(dates)):
                if iindex == len(dates):
                    # Reset index if beyond the right boundary (see note 2. above)
                    iindex -= 1
            elif abs(sdate - dates[iindex - 1]) < abs(sdate - dates[iindex]):
                # Choose the closest of the two surrounding dates
                iindex -= 1

            # Make sure the TLE we found is within the threshold
            delta_days = abs(sdate - dates[iindex]) / np.timedelta64(1, 'D')
            tle_thresh = 7
            if delta_days > tle_thresh:
                raise IndexError(
                    "Can't find tle data for %s within +/- %d days around %s" %
                    (self.satellite_name, tle_thresh, sdate))

            # if delta_days > 3:
            #     LOG.warning("Found TLE data for %s that is %f days appart",
            #                 sdate, delta_days)
            # else:
            #     LOG.debug("Found TLE data for %s that is %f days appart",
            #               sdate, delta_days)

            # Select TLE data
            tle1 = tle_data[iindex * 2]
            tle2 = tle_data[iindex * 2 + 1]
            self._tle = tlefile.read(self.satellite_name,
                                     tle_file=None,
                                     line1=tle1,
                                     line2=tle2)

        # Not using TLE archive;
        # Either using current celestrek TLE,
        # or using user supplied Line 1 and line 2
        else:
            sat_time = self.tle2datetime64(float(self._tle.line1[18:32]))
            # Object just created
            if not self.utctime:
                self.utctime = datetime.now()
            mismatch = sat_time.astype(datetime) - self.utctime
            if abs(mismatch.days) > 7:
                raise IndexError("""
                    Current TLE from celestrek is %d days newer than
                    requested orbital parameter. Please use TLE archive
                    for accurate results""" % (mismatch.days))

        return self._tle
Ejemplo n.º 28
0
def get_upcoming_passes(satellite_name, passes_begin_time, passes_period):
    """Returns potential satellite pass information for input satellite and Two Line Elements over temporal period"""
    kml = simplekml.Kml()
    observer = ephem.Observer()
    observer.lat = ground_station[0]
    observer.long = ground_station[1]
    observer.horizon = observer_horizon
    swathincrement = 1
    # make a list to hold dicts of attributes for the upcoming pass information for the selected satellites
    schedule = []
    observer.date = passes_begin_time

    print("---------------------------------------")

    for tle in tles:

        if tle[0] == satellite_name:

            # Update satellite names for use in filename
            satname = get_satellite_name(tle)
            sat = ephem.readtle(tle[0], tle[1], tle[2])

            # Report currency of TLE
            twole = tlefile.read(tle[0], 'tles.txt')
            now = datetime.utcnow()
            timesinceepoch = now - twole.epoch.astype(datetime)

            print("TLE EPOCH:", twole.epoch.astype(datetime))
            print("TLE age:", timesinceepoch)
            print("---------------------------------------")

            # While lostime of next pass is less than or equal to pass_begin_time + period do something
            lostime = start  # passes_begin_time + passes_period

            while lostime <= (passes_begin_time +
                              timedelta(minutes=passes_period)):
                oi = float(str.split(tle[2], ' ')[3])
                orb = Orbital(tle[0], "tles.txt", tle[1], tle[2])

                rt, ra, tt, ta, st, sa = observer.next_pass(sat)

                # Confirm that observer details have been computed i.e. are not 'Null'

                if rt is None:
                    print(rt + "is none")
                    logging.info(
                        "Rise time of satellite not calculated - pass currently under way"
                    )
                    observer.date = (lostime + timedelta(minutes=90))

                    return ()
                sat.compute(rt)
                aos_lat = sat.sublat.real * (180 / math.pi)

                sat.compute(st)
                los_lat = sat.sublat.real * (180 / math.pi)

                # Determine if pass descending or ascending
                oi, node = get_orbit_node(aos_lat, los_lat, oi)

                aostime = datetime.strptime(str(rt), "%Y/%m/%d %H:%M:%S")

                loctime = local_time(aostime, 'Australia/Sydney')
                minutesaway = ((aostime - start).seconds / 60.0) + (
                    (aostime - start).days * 1440.0)
                orad = orb.get_lonlatalt(to_datetime(rt))[2]
                orbitnumber = orb.get_orbit_number(
                    to_datetime(rt)) + orbitoffset

                # Get code version for provenance - TODO embed this in HTML
                try:
                    repo = git.Repo(os.getcwd())
                    tag = repo.tags[
                        len(repo.tags) -
                        1].tag.tag  # TODO work out if git repo, if not skip TRY
                except:
                    tag = '0.0.0'
                print("code tag             = ", tag)
                print("------------------------------------------")
                print("Satellite            = ", satname)
                print("Orbit                = ", orbitnumber)
                print("Minutes to horizon   = ", minutesaway)
                print("AOStime local        = ", loctime)
                print("AOStime UTC          = ", to_datetime(rt))
                print("LOStime UTC          = ", to_datetime(st))
                print("Transit time UTC     = ", to_datetime(tt))

                SWATH_FILENAME = os.path.join(
                    output_path, satname + "." + str(orbitnumber) + "." +
                    ground_station_name + ".orbit_swath.geojson")
                ORBIT_FILENAME = os.path.join(
                    output_path, satname + "." + str(orbitnumber) + "." +
                    ground_station_name + ".orbit_track.geojson")

                # Step from AOS to LOS by configuration timestep interval
                deltatime = to_datetime(rt)

                geoeastpoint = []
                geowestpoint = []
                geotrack = []
                # TODO - 1/10 steps out to east and west limbs of pass from track
                startpoint = True

                # TODO - confirm nextpass method works when satellite within horizon
                subsatlat1 = None
                while deltatime < to_datetime(st):
                    #if subsatlat1 is None:
                    #    subsatlat1 = sat.sublat.real * (180 / math.pi)
                    #    subsatlon1 = sat.sublong.real * (180 / math.pi)
                    #    print("got to here")

                    sat.compute(deltatime)

                    subsatlat = sat.sublat.real * (180 / math.pi)
                    subsatlon = sat.sublong.real * (180 / math.pi)

                    orbaltitude = orb.get_lonlatalt(to_datetime(rt))[2] * 1000

                    geotrack.append({
                        'lat2': subsatlat,
                        'lon2': subsatlon,
                        'alt2': orbaltitude,
                        'time': str(deltatime)
                    })

                    # Original heading calculation
                    #effectiveheading = get_effective_heading(sat, oi, subsatlat,
                    #                                       subsatlon, orad, sat._n)

                    # TODO Alternate simple heading
                    subsatlat1, subsatlon1 = get_subsat_oneincrement(
                        sat, deltatime, timestep)

                    effectiveheading = Geodesic.WGS84.Inverse(
                        subsatlat1, subsatlon1, subsatlat, subsatlon)['azi1']

                    eastaz = effectiveheading + 90
                    westaz = effectiveheading + 270

                    # 1/10 swath steps out to east and west limbs of pass from track start and end
                    #          <-- 1| 2 --> reverse
                    #   |   .................   |
                    #   V   .       .       .   V  reverse
                    #       .       .       .
                    #       .................
                    #          <-- 3| 4 -->
                    #  (reverse 3 append to 1) append (append 4 to reversed 2)

                    incrementtoswath = swathincrement
                    if startpoint is True:
                        # Step from sub satellite point to limb of swath with increasing step size
                        while math.pow(incrementtoswath, 5) < swath:

                            geoeastpointdict = Geodesic.WGS84.Direct(
                                subsatlat, subsatlon, eastaz,
                                math.pow(incrementtoswath, 5))
                            geoeastpointdict['time'] = str(deltatime)
                            geoeastpoint.append(geoeastpointdict)

                            geowestpointdict = Geodesic.WGS84.Direct(
                                subsatlat, subsatlon, westaz,
                                math.pow(incrementtoswath, 5))
                            geowestpointdict['time'] = str(deltatime)
                            geowestpoint.append(geowestpointdict)
                            incrementtoswath = incrementtoswath + 1
                            startpoint = False
                    # Trace the eastern limb of the swath
                    geoeastpointdict = Geodesic.WGS84.Direct(
                        subsatlat, subsatlon, eastaz, swath)
                    geoeastpointdict['time'] = str(deltatime)
                    geoeastpoint.append(geoeastpointdict)

                    # Trace the western limb of the swath

                    geowestpointdict = Geodesic.WGS84.Direct(
                        subsatlat, subsatlon, westaz, swath)
                    geowestpointdict['time'] = str(deltatime)
                    geowestpoint.append(geowestpointdict)

                    deltatime = deltatime + timestep

                    time.sleep(0.01)
                # When the end of the track is reached
                # Step from sub satellite point to limb of swath with increasing step size

                geoloseastpoint = []
                geoloswestpoint = []
                incrementtoswath = swathincrement

                while math.pow(incrementtoswath, 5) < swath:

                    geodesiceastazdict = Geodesic.WGS84.Direct(
                        subsatlat, subsatlon, eastaz,
                        math.pow(incrementtoswath, 5))
                    geodesiceastazdict['time'] = str(deltatime)
                    geoloseastpoint.append(geodesiceastazdict)

                    geodesicwestazdict = Geodesic.WGS84.Direct(
                        subsatlat, subsatlon, westaz,
                        math.pow(incrementtoswath, 5))
                    geodesicwestazdict['time'] = str(deltatime)
                    geoloswestpoint.append(geodesicwestazdict)

                    incrementtoswath = incrementtoswath + 1

                # Append reversed geoloswestpoint to geoloseastpoint
                reversedwest = []
                for x in reversed(geoloswestpoint):
                    reversedwest.append(x)

                for x in geoloseastpoint:
                    reversedwest.append(x)
                for x in reversedwest:
                    geowestpoint.append(x)

                polypoints = []

                for x in geowestpoint:
                    polypoints.append({
                        'lat2': x['lat2'],
                        'lon2': x['lon2'],
                        'time': x['time']
                    })

                for x in reversed(geoeastpoint):
                    polypoints.append({
                        'lat2': x['lat2'],
                        'lon2': x['lon2'],
                        'time': x['time']
                    })

                if len(polypoints) > 0:
                    polypoints.append({
                        'lat2': geowestpoint[0]['lat2'],
                        'lon2': geowestpoint[0]['lon2'],
                        'time': geowestpoint[0]['time']
                    })

                # TODO add local solar time for AOSTime Lat Lon
                attributes = {
                    'Satellite name':
                    satname,
                    'Sensor code':
                    sensor,
                    'Orbit height':
                    orad,
                    'Orbit':
                    orbitnumber,
                    #'Current time': str(now),
                    'Minutes to horizon':
                    minutesaway,
                    'Local time':
                    str(loctime),
                    'AOS time':
                    str(rt),
                    'LOS time':
                    str(st),
                    'Transit time':
                    str(tt),
                    'Node':
                    node,
                    'SWATH_FILENAME':
                    (satname + "." + str(orbitnumber) + "." +
                     ground_station_name + ".orbit_swath.geojson"),
                    'Orbit filename':
                    ORBIT_FILENAME,
                    'Orbit line':
                    geotrack,
                    'Swath filename':
                    SWATH_FILENAME,
                    'Swath polygon':
                    polypoints
                }

                # Append the attributes to the list of acquisitions for the acquisition period
                #print('ATTRIBUTES:', attributes)
                #print('SCHEDULE:', schedule)
                if not any(d['SWATH_FILENAME'] == attributes['SWATH_FILENAME']
                           for d in schedule):
                    #if not attributes in schedule:
                    # if not any((x['Satellite name'] == satname and x['Orbit'] == orbitnumber) for x in schedule):
                    if imagingnode == 'both' or imagingnode == attributes[
                            'Node']:
                        schedule.append(attributes)

                        # Create swath footprint ogr output

                        get_vector_file(attributes, polypoints, 'polygon',
                                        SWATH_FILENAME, 'GeoJSON')
                        get_vector_file(attributes, geotrack, 'line',
                                        ORBIT_FILENAME, 'GeoJSON')

                        add_layer_to_map(
                            SWATH_FILENAME,
                            satname + "." + str(orbitnumber) + ".swath",
                            'blue')
                        add_layer_to_map(
                            ORBIT_FILENAME,
                            satname + "." + str(orbitnumber) + ".orbit", 'red')

                        # Create a temporal KML
                        pol = kml.newpolygon(name=satname + '_' +
                                             str(orbitnumber),
                                             description=SWATH_FILENAME)
                        kml_polypoints = []

                        for i in polypoints:
                            kml_polypoints.append((i['lon2'], i['lat2']))
                        rt_kml = datetime.strptime(str(rt),
                                                   "%Y/%m/%d %H:%M:%S")
                        st_kml = datetime.strptime(str(st),
                                                   "%Y/%m/%d %H:%M:%S")
                        pol.outerboundaryis = kml_polypoints
                        pol.style.linestyle.color = simplekml.Color.green
                        pol.style.linestyle.width = 5
                        pol.style.polystyle.color = simplekml.Color.changealphaint(
                            100, simplekml.Color.green)
                        pol.timespan.begin = rt_kml.strftime(
                            "%Y-%m-%dT%H:%M:%SZ")
                        pol.timespan.end = st_kml.strftime(
                            "%Y-%m-%dT%H:%M:%SZ")

                observer.date = (lostime + timedelta(minutes=90))
                lostime = (datetime.strptime(str(observer.date),
                                             "%Y/%m/%d %H:%M:%S"))

    kml.save(
        os.path.join(output_path,
                     satname + "." + ground_station_name + ".kml"))

    ## plot folium map
    folium.LayerControl().add_to(satellite_map)
    foliumhtml = os.path.join(
        output_path, satname + "." + ground_station_name + ".map.html")
    satellite_map.save(foliumhtml)
    folium_timespan_geojson_html(schedule, satname)

    # render the html schedule and write to file
    attributeshtml = []

    for acquisition in schedule:
        attributeshtml.append('<td>' + acquisition['Satellite name'] + '</td>'\
        '<td><a href="' + str(os.path.relpath(acquisition['Swath filename'],os.path.dirname(foliumhtml)))+ '">' + str(acquisition['Sensor code']) + '</a></td>'\
        '<td><a href="' + str(os.path.relpath(acquisition['Orbit filename'],os.path.dirname(foliumhtml))) + '">' + str(acquisition['Orbit']) + '</a></td>'\
        '<td>' + str(acquisition['Node']) + '</td>'\
        '<td>' + str(acquisition['AOS time']) + '</td>'\
        '<td>' + str(acquisition['LOS time']) + '</td>')

    satelliteslist = []
    for x in satellites:
        schedule_url = get_satellite_name(
            [x]) + "." + ground_station_name + ".schedule.html"
        satelliteslist.append([x, schedule_url])
        satelliteslist.append(',')

    renderedoutput = template.render(content=attributeshtml,
                                     foliumhtml=os.path.relpath(
                                         foliumhtml, output_path),
                                     satelliteslist=satelliteslist)

    with open(
            os.path.join(
                output_path,
                satname + "." + ground_station_name + ".schedule.html"),
            "w") as fh:
        fh.write(renderedoutput)

    return ()
Ejemplo n.º 29
0
 def createSatFromFile(self, sat_name, file_name, category):
     newSat = Sat(sat_name,
                  tle=tlefile.read(sat_name, file_name),
                  cat=category)
     newSat.updateOrbitalParameters3(self.date)
     self.Sats.append(newSat)
Ejemplo n.º 30
0
    def setUp(self):
        # Load test data
        inputs = np.dsplit(testdata_night, 14)
        self.ir108 = inputs[0]
        self.ir039 = inputs[1]
        self.vis008 = inputs[2]
        self.nir016 = inputs[3]
        self.vis006 = inputs[4]
        self.ir087 = inputs[5]
        self.ir120 = inputs[6]
        self.elev = inputs[7]
        self.cot = inputs[8]
        self.reff = inputs[9]
        self.lwp = inputs[10]
        self.lat = inputs[11]
        self.lon = inputs[12]
        self.cth = inputs[13]

        self.time = datetime(2013, 11, 12, 6, 00, 00)
        # METEOSAT-10 (MSG-3) TLE file from 01.08.2017
        # http://celestrak.com/NORAD/elements/weather.txt
        line1 = "1 38552U 12035B   17212.14216600 -.00000019  00000-0  00000-0 0  9998"
        line2 = "2 38552   0.8450 357.8180 0002245 136.4998 225.6885  1.00275354 18379"
        # Import TLE file
        self.tle = tlefile.read('meteosat 10', line1=line1, line2=line2)
        self.orbital = Orbital('meteosat 10',
                               line1=self.tle.line1,
                               line2=self.tle.line2)
        # Compute satellite zenith angle
        azi, ele = self.orbital.get_observer_look(self.time, self.lon,
                                                  self.lat, self.elev)
        self.sza = ele

        self.input = {
            'ir108': self.ir108,
            'ir039': self.ir039,
            'lat': self.lat,
            'lon': self.lon,
            'time': self.time,
            'plot': True,
            'save': True,
            'dir': '/tmp/FLS',
            'resize': '5',
            'sza': self.sza
        }

        inputs = np.dsplit(testdata_night2, 14)
        self.ir108 = inputs[0]
        self.ir039 = inputs[1]
        self.vis008 = inputs[2]
        self.nir016 = inputs[3]
        self.vis006 = inputs[4]
        self.ir087 = inputs[5]
        self.ir120 = inputs[6]
        self.elev = inputs[7]
        self.cot = inputs[8]
        self.reff = inputs[9]
        self.lwp = inputs[10]
        self.lat = inputs[11]
        self.lon = inputs[12]
        self.cth = inputs[13]

        self.time = datetime(2013, 12, 1, 4, 00, 00)

        self.input2 = {
            'ir108': self.ir108,
            'ir039': self.ir039,
            'lat': self.lat,
            'lon': self.lon,
            'time': self.time,
            'plot': True,
            'save': True,
            'dir': '/tmp/FLS',
            'resize': '5',
            'sza': self.sza
        }