Exemplo n.º 1
0
def test():

    #print "test!"

    part4 = """2009 005A 30983 043018207204 150212002613102 1483008
     01019933 01020490 00138796 16134808 35269969 09897525
     19882771 07228311 P071848002 M009204348 P000000001
     M00158196 M01145249 P07324206 003883805 155154007 9449
     0000500000 M00277416 P00100028 P00508269  20439887           
     020809 M00148 052112 M00885 072709 P00000 000000                    
     APT 137.9125 MHZ, HRPT 1698.0 MHZ, BCN DSB 137.77 MHZ.              
     APT DAY/NIGHT 2,4. VIS CH 2 /0.725 TO 1.0/ AND IR CH 4              
     /10.5 TO 11.5/ XMTD DURING S/C DAY. IR CH3 /3ND IR CH 4             
     /10.5 TO 11.5/ XMTD DURING S/C NIGHT.  DCS CLK TIME                 
     YR/DA/TIM 1995 021 79186.656 LAST TIP CLK CORR 02/08/09.            
     CLK ERR AFTER CORR MINUS 0148 MSEC.  CLK ERR AS OF 05/21/12         
     MINUS 885 MSEC.  ERR RATE AS OF 07/27/09  PLUS 0.0 MS/DAY.          
     NEXT CLK CORR UNKNOWN. N19 APT SWITCH TO VTX1 137.1 MHZ             
     ON 23 JUN 2009 AT 1825Z.                                               
    NNNN"""



    ref_line1 = "1 33591U 09005A   15043.53970792  .00000119  00000-0  89587-4 0  9992"
    ref_line2 = "2 33591  98.9763 353.2216 0014536 157.9967 331.3486 14.11873647309901"

    import numpy as np
    from pyorbital.orbital import Orbital

    orb_ref = Orbital("NOAA 19", line1=ref_line1, line2=ref_line2)
    line1, line2 = generate_tle(part4)
    #print line1
    #print line2
    orb_test = Orbital("NOAA 19", line1=line1, line2=line2)


    from datetime import timedelta
    delta = timedelta(minutes=120)
    epoch = datetime(2015, 2, 12, 0, 26, 13, 102000)
    time = epoch
    cnt = 0
    errors = []
    while cnt < 30:

        #print time
        ref_pos = orb_ref.get_position(time, False)
        test_pos = orb_test.get_position(time, False)

        error = np.sqrt((ref_pos[0][0] - test_pos[0][0])**2 +
                        (ref_pos[0][1] - test_pos[0][1])**2 +
                        (ref_pos[0][2] - test_pos[0][2])**2)
        errors.append(error)


        time = time + delta
        cnt += 1

    #print "max error", np.max(errors), "mean error", np.mean(errors)
    assert(np.max(errors) < 5) #km
Exemplo n.º 2
0
def propagate_orbits(TLE_path, days):
    num_mins = int(days * 24 * 60)
    time_list = [
        datetime.datetime(2020, 1, 1, 0, 0, 0, 0) +
        datetime.timedelta(seconds=60 * x) for x in range(0, num_mins)
    ]
    num = 0

    table = pd.DataFrame(time_list, columns=["Time"])
    file = open(TLE_path, "r")

    a = file.readline()
    b = file.readline()

    # Iterate over TLE file
    while a != '' and b != '':
        orb = Orbital("sat{}".format(num), line1=a, line2=b)
        pos_list = []
        for time in time_list:
            pos = orb.get_position(time, normalize=False)
            pos_list.append(pos)
        table[str(num)] = pos_list
        num += 1

        a = file.readline()
        b = file.readline()
    file.close()

    return table
Exemplo n.º 3
0
def compute_pixels(orb, sgeom, times, rpy=(0.0, 0.0, 0.0)):
    """Compute cartesian coordinates of the pixels in instrument scan."""
    if isinstance(orb, (list, tuple)):
        tle1, tle2 = orb
        orb = Orbital("mysatellite", line1=tle1, line2=tle2)

    # get position and velocity for each time of each pixel
    pos, vel = orb.get_position(times, normalize=False)

    # now, get the vectors pointing to each pixel
    vectors = sgeom.vectors(pos, vel, *rpy)

    # compute intersection of lines (directed by vectors and passing through
    # (0, 0, 0)) and ellipsoid. Derived from:
    # http://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection

    # do the computation between line and ellipsoid (WGS 84)
    # NB: AAPP uses GRS 80...
    centre = -pos
    a__ = 6378.137  # km
    # b__ = 6356.75231414 # km, GRS80
    b__ = 6356.752314245  # km, WGS84
    radius = np.array([[1 / a__, 1 / a__, 1 / b__]]).T
    shape = vectors.shape

    xr_ = vectors.reshape([3, -1]) * radius
    cr_ = centre.reshape([3, -1]) * radius
    ldotc = np.einsum("ij,ij->j", xr_, cr_)
    lsq = np.einsum("ij,ij->j", xr_, xr_)
    csq = np.einsum("ij,ij->j", cr_, cr_)

    d1_ = (ldotc - np.sqrt(ldotc ** 2 - csq * lsq + lsq)) / lsq

    # return the actual pixel positions
    return vectors * d1_.reshape(shape[1:]) - centre
Exemplo n.º 4
0
def get_xyz(t):
    orb = Orbital("TJREVERB",
                  tle_file=(Path(__file__).parent.resolve() /
                            "tjreverb_tle.txt"))
    return ({
        'xyz_pos': orb.get_position(t)[0],
        'xyz_vel': orb.get_position(t)[1]
    })
Exemplo n.º 5
0
class Orbit:
    def __init__(self,name,file):
        self.file = file
        self.orbital = Orbital(name,file)
        self.xyz=[[],[],[]]
        self.now = datetime.now()
        self.position = self.orbital.get_position(self.now,False)
        for i in range(0,2000):
            self.now += timedelta(seconds=4)
            position = self.orbital.get_position(self.now,False)
            for i in range(0,3):
                self.xyz[i].append(position[0][i])
                
    def get_x(self):
        return self.xyz[0]
    def get_y(self):
        return self.xyz[1]
    def get_z(self):
        return self.xyz[2]
Exemplo n.º 6
0
def track():
    # tle = tlefile.read('ISS', 'orbit.txt')
    orbit = Orbital('ISS', 'Telescope/orbit.txt')
    while True:
        now = datetime.utcnow()
        # print(now)
        coords = (orbit.get_position(now)[0])
        # print(orbit.get_lonlatalt(now))
        # print(coords)
        print(convertCartesianToRaDec(coords[0], coords[1], coords[2]))

        time.sleep(1)
Exemplo n.º 7
0
    def orbitpos(file_name, names, date):
        orbit = []
        cont = 0
        for nam in names:
            try:
                orb = Orbital(nam, file_name)
                orbit.append(
                    [nam, orb.get_lonlatalt(date),
                     orb.get_position(date)])
                #altitudine in km da terra  #pos normalizata r_sat/r_terra
            except:
                cont += 1
                print(nam, cont)

        return orbit
Exemplo n.º 8
0
def get_parallaxed_coor(sat, tle, t, lat, lon, alt, h):
    """

    """
    # Setup orbital class with TLE file
    orbit = Orbital(sat, line1=tle.line1, line2=tle.line2)
    pos = orbit.get_position(t)
    # Calculate observer azimuth and elevation
    azi, ele = orbit.get_observer_look(t, lon, lat, alt)
    # Apply parallax correction for given heights
    x, y, z = parallax_corr(h, azi, ele)
    # WGS84 parameters
    f = 1 / 298.257223563
    a = 6378137.
    # Convert coordinates and azimuth to radians
    radlat = np.deg2rad(lat)
    radlon = np.deg2rad(lon)
    radazi = np.deg2rad(azi)
    # Calculate shifted point coordinates
    nlat, nlon, nazi = vinc_pt(f, a, radlat, radlon, radazi, z)
    # Reconvert to degree
    nlat = np.rad2deg(nlat)
    nlon = np.rad2deg(nlon)
    nazi = np.rad2deg(nazi)

    info = "\n--------------------------------------------------------" + \
           "\n      ----- Parallax correction summary -----" +\
           "\n--------------------------------------------------------" + \
           "\n Satellite Name: " + sat + \
           "\n Observation Time: " + \
           datetime.datetime.strftime(t, "%Y-%m-%d %H:%M:%S") + \
           "\n Satellite Position: " + str(pos[0]) + \
           "\n Satellite Velocity: " + str(pos[1]) + \
           "\n-----------------------------------" + \
           "\n Latitude: " + str(lat) + \
           "\n Longitude: " + str(lon) + \
           "\n Altitude: " + \
           str(alt) + "\n Height: " + str(h) + \
           "\n-----------------------------------" +\
           "\n Azimuth: " + str(azi) + \
           "\n Elevation: " + str(ele) + \
           "\n Parallax Distance: " + str(z) + \
           "\n New Latitude: " + str(nlat) + \
           "\n New Longitude: " + str(nlon) + \
           "\n--------------------------------------------------------"
    logger.debug(info)

    return(z, nlat, nlon)
    def extractDataset(self,
                       satelliteName='ISS (ZARYA)',
                       sourceDirectory=generateFilename(description = "stations",
                                                        extension = ".txt",
                                                        dateToday = False),
                       referenceDate = (2015,10,28,0,0,0),
                       numberOfSamples = 1440,
                       numberOfInputs = 4,
                       incrementSeconds = 60):

        self.satelliteName = satelliteName
        self.sourceDirectory = sourceDirectory
        self.referenceDate = referenceDate
        self.numberOfSamples = numberOfSamples
        self.numberOfInputs = numberOfInputs
        self.dataset = np.zeros(shape=[1,self.numberOfInputs])
        self.incrementSeconds = incrementSeconds
        self.min = 0
        self.max = 0
        self.min_dataset = 0
        self.max_dataset = 0

        try:
            # reading input data
            input_data = Orbital(self.satelliteName, self.sourceDirectory)

            # calculate date
            date = datetime.datetime(*self.referenceDate)

            #1440 for the number of minutes in a day
            for point_n in xrange(self.numberOfSamples):
                #each point will be collected with a specified difference of seconds
                date += datetime.timedelta(0,incrementSeconds)
                output_data = input_data.get_position(date,normalize=False)
                self.dataset = np.vstack([self.dataset, np.append(output_data[0],[point_n + referenceDate[4]])])

            self.dataset = np.delete(self.dataset,0,0)

            return 0

        except:

            return 1
Exemplo n.º 10
0
def propagate(TLE_path, length, year):
    '''
    Reads TLE file, propagates satellites based on sim length and epoch year
    Returns a position table of every node at every time step
    '''

    time_list = [
        datetime.datetime(year, 1, 1, 0, 0, 0, 0) +
        datetime.timedelta(seconds=60 * x) for x in range(length + 3)
    ]
    node_num = 0

    table = pd.DataFrame(time_list, columns=["Time"])
    file = open(TLE_path, "r")

    # corrected = open(r"C:\Users\JK31434\Desktop\Packet\code_source\TLEs\correct_TLEs.txt",'w')

    a = file.readline()
    b = file.readline()

    # Iterate over TLE file
    while a != '' and b != '':
        # try:
        orb = Orbital("sat{}".format(node_num), line1=a, line2=b)
        pos_list = []
        for time in time_list:
            pos = orb.get_position(time, normalize=False)
            pos_list.append(pos[0])  # pos[1] has xyz velocity
        table[str(node_num)] = pos_list
        node_num += 1

        # corrected.write(a)
        # corrected.write(b)
        # except:
        #     pass

        a = file.readline()
        b = file.readline()
    file.close()

    return table
vertMat = [[0 for x in range(8)] for y in range(100)]

now = datetime.utcnow()

i = 0

for x in range(0, 100):
    if x == 0:
        string = 'COSMOS 2251'
    if x >= 1:
        string = 'COSMOS 2251 DEB' + str(x)
    orbX = Orbital(string, 'cosmos-2251-debris.txt')
    orbY = Orbital(string, 'cosmos-2251-debris.txt')
    orbZ = Orbital(string, 'cosmos-2251-debris.txt')

    orbMat[i][0] = 0.49 * orbX.get_position(now)[0][0]
    orbMat[i][1] = 0.49 * orbY.get_position(now)[0][1]
    orbMat[i][2] = 0.49 * orbZ.get_position(now)[0][2]

    i += 1

i = 0

for eachOrb in orbMat:
    vertMat[i][0] = [orbMat[i][0], orbMat[i][1], orbMat[i][2]]
    vertMat[i][1] = [orbMat[i][0] + 0.01, orbMat[i][1], orbMat[i][2]]
    vertMat[i][2] = [orbMat[i][0] + 0.01, orbMat[i][1] - 0.01, orbMat[i][2]]
    vertMat[i][3] = [orbMat[i][0], orbMat[i][1] - 0.01, orbMat[i][2]]
    vertMat[i][4] = [orbMat[i][0], orbMat[i][1], orbMat[i][2] + 0.01]
    vertMat[i][5] = [orbMat[i][0] + 0.01, orbMat[i][1], orbMat[i][2] + 0.01]
    vertMat[i][6] = [
Exemplo n.º 12
0
import numpy as np
from pyorbital.orbital import Orbital

orb_ref = Orbital("NOAA 19", line1=ref_line1, line2=ref_line2)
orb_test = Orbital("NOAA 19", line1=line1, line2=line2)

from datetime import timedelta
delta = timedelta(minutes=120)

time = epoch
cnt = 0
errors = []
while cnt < 30:

    print time
    ref_pos = orb_ref.get_position(time, False)
    test_pos = orb_test.get_position(time, False)
    print ref_pos
    print test_pos
    error = np.sqrt((ref_pos[0][0] - test_pos[0][0])**2 +
                    (ref_pos[0][1] - test_pos[0][1])**2 +
                    (ref_pos[0][2] - test_pos[0][2])**2)
    errors.append(error)
    print error

    time = time + delta
    cnt += 1

print np.max(errors), np.mean(errors)
Exemplo n.º 13
0
        if np.all(abs(lat - lat2) < 1e-10):
            break
    alt = r / np.cos(lat) - c
    alt *= A
    return np.rad2deg(lon), np.rad2deg(lat), alt

# END OF DIRTY STUFF


def compute_pixels((tle1, tle2), sgeom, times, rpy=(0.0, 0.0, 0.0)):
    """Compute cartesian coordinates of the pixels in instrument scan.
    """
    orb = Orbital("mysatellite", line1=tle1, line2=tle2)

    # get position and velocity for each time of each pixel
    pos, vel = orb.get_position(times, normalize=False)

    # now, get the vectors pointing to each pixel
    vectors = sgeom.vectors(pos, vel, *rpy)

    # compute intersection of lines (directed by vectors and passing through
    # (0, 0, 0)) and ellipsoid. Derived from:
    # http://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection

    # do the computation between line and ellipsoid (WGS 84)
    # NB: AAPP uses GRS 80...
    centre = -pos
    a__ = 6378.137  # km
    # b__ = 6356.75231414 # km, GRS80
    b__ = 6356.752314245  # km, WGS84
    radius = np.array([[1 / a__, 1 / a__, 1 / b__]]).T
Exemplo n.º 14
0
import folium
# PYORBITAL DOCUMENTATION
# https://pyorbital.readthedocs.io/en/latest/
# PyOrbital get_position and get_lonlatalt cases
# Use current TLEs from Celestrak: http://celestrak.com/NORAD/elements/

# SATELLITE
sat = "SENTINEL-3A"

#orb = Orbital('SENTINEL-3A', tle_file='./EO_Sat.txt')
orb = Orbital(sat)

now = datetime.utcnow()

# Get position and velocity of the satellite:
print(orb.get_position(now, normalize=False))

# Get longitude, latitude and altitude of the satellite:
print(orb.get_lonlatalt(now))

# Create a new Map centered on position [0,0]
m = folium.Map(location=[10, 0],zoom_start = 1)

# Function to get position with a deltatime from now(). (Default deltatime is 0)
def getsatpos(DeltaTiming=0):
    now = datetime.utcnow() + timedelta(seconds = DeltaTiming)

    # Get longitude, latitude and altitude of the satellite:
    lon,lat,alt = orb.get_lonlatalt(now)
    return(lat,lon)
    
Exemplo n.º 15
0
#now = datetime.utcnow()
local_tz = pytz.timezone("America/Montevideo")
UTC_dif = 3
dtobj = datetime(year, month, day, hour + UTC_dif, minute, second)
dtobj2 = dtobj + timedelta(seconds=duracion_s)

lon, lat, alt = orb.get_lonlatalt(dtobj)
lon2, lat2, alt2 = orb.get_lonlatalt(dtobj2)

coords_1 = (lat, lon)
coords_2 = (lat2, lon2)

distancia = geopy.distance.vincenty(coords_1, coords_2).km

print("Posición inicio:", orb.get_position(dtobj))
print("Longitud:", lon)
print("Latitud:", lat)
print("Altura (km):", alt)

print("\nPosición final:", orb.get_position(dtobj2))
print("Longitud:", lon2)
print("Latitud:", lat2)
print("Altura (km):", alt2)

print("\nDistancia recorrida (km): ", distancia)
"""# Visualización"""

# create new figure, axes instances.
fig = plt.figure(figsize=(8, 6), dpi=150)
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
Exemplo n.º 16
0
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);

data['user_view'] = {}
data['user_view']['azimuth'] = az
data['user_view']['elevation'] = el

data['timestamp'] = timestamp
Exemplo n.º 17
0
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

# start epoch
year = 2013
month = 11
day = 1
hour = 0
minute = 30
Exemplo n.º 18
0
# $ 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)

# Get the orbit number of the satellite
current_orbit_number = orb.get_orbit_number(now, tbus_style=False)
print("Current orbit:", current_orbit_number)
    'Sentinel 1A',
    'SMOS',
    'SPOT 5',
    'SPOT 6',
    'SPOT 7',
    'Suomi NPP',
    'TanDEM X',
    'TerraSAR X',
]

for name in SAT_NAME:
    try:
        orb = Orbital(name)
        now = datetime.utcnow()
        # Get normalized position and velocity of the satellite:
        normal_position = orb.get_position(now)
        # Get longitude, latitude and altitude of the satellite:
        geo_position = orb.get_lonlatalt(now)
        print("{} - {}".format(name, geo_position))
    except (KeyError, NotImplementedError):
        print('No satellite name: {}'.format(name))

        #
        #
        #
        #
        #
        # r_string = requests.get('http://celestrak.com/NORAD/elements/noaa.txt')
        # r_filtered = r_string.text.split(str="", num=r_string.count(str))
        #
        # # every third element - satellite names in TLE
class InviewCalculator:
    """Class to compute inviews above a specified elevation angle from a latitude, longitude, elevation to a satellite (number) """

    # Constructor
    def __init__(self, ground_station, satellite_tle):
        """Constructor:  ground station as GroundStation, satellite TLE as TleManipulator"""
        self.__ground_station = ground_station
        self.__satellite_tle = satellite_tle
        self.__orb = Orbital(str(self.__satellite_tle.get_satellite_number()), \
                             line1=self.__satellite_tle.get_line1(), \
                             line2=self.__satellite_tle.get_line2())

    # Member functions

    def __repr__(self):
        """Returns a string representing an instance of this class."""
        out = 'Inview Calculator:\n' \
              'latitude=%f, longitude=%f, elevation=%f, ' \
              'minimum elevation angle=%s, satellite TLE=\n%s' % \
              (self.__ground_station.get_latitude(), self.__ground_station.get_longitude(), self.__ground_station.get_minimum_elevation_angle(), \
               self.__ground_station.get_minimum_elevation_angle(), self.__satellite_tle)
        return out

    def compute_inviews(self, in_start_time, in_end_time):
        """Method to compute inviews (in UTC) for the initialized location, elevation angle, and satellite over a specified time period.  Returns a list of inview start/stop times, accurate to the nearest second and using the latest available TLE when the method is called."""
        # NOTE:  pyorbital EXPECTS naive date/times and interprets them
        # as UTC... so we need to satisfy it; however, we are making this
        # module DATETIME AWARE, so RETURN VALUES are DATETIME AWARE!!
        # Also, all naive inputs are assumed to be UTC and all aware inputs
        # are converted to UTC (and then made naive)
        if (in_start_time.tzinfo is not None):
            temp = in_start_time.astimezone(UTC)
            start_time = datetime(temp.year, temp.month, temp.day, \
                                  temp.hour, temp.minute, temp.second)
        else:
            start_time = in_start_time
        if (in_end_time.tzinfo is not None):
            temp = in_end_time.astimezone(UTC)
            end_time = datetime(temp.year, temp.month, temp.day, \
                                temp.hour, temp.minute, temp.second)
        else:
            end_time = in_end_time
        # start_time, end_time are now naive
        inviews = []
        time = start_time
        up = 0
        el_increasing = 0
        maxel = 0
        try:
            (az, el) = self.__orb.get_observer_look(time, self.__ground_station.get_longitude(), \
                                                    self.__ground_station.get_latitude(), \
                                                    self.__ground_station.get_minimum_elevation_angle())
            if (el > self.__ground_station.get_minimum_elevation_angle()):
                # start the first inview at the input start_time
                up = 1
                el_increasing = 1
                rising = time
            # Step through time, looking for inview starts and ends
            while (time < end_time):
                (az, el) = self.__orb.get_observer_look(time, self.__ground_station.get_longitude(), \
                                                        self.__ground_station.get_latitude(), \
                                                        self.__ground_station.get_minimum_elevation_angle())
                if (el > self.__ground_station.get_minimum_elevation_angle()
                    ) and (up == 0):
                    rising = self.__find_exact_crossing(time, up)
                    el_increasing = 1
                    up = 1
                if (el < self.__ground_station.get_minimum_elevation_angle()
                    ) and (up == 1):
                    # make sure to append AWARE datetimes
                    crossing = self.__find_exact_crossing(time, up)
                    inviews.append((rising.replace(tzinfo=UTC), \
                                    crossing.replace(tzinfo=UTC), \
                                    maxel))
                    el_increasing = 0
                    up = 0
                    maxel = 0
                if (el > self.__ground_station.get_minimum_elevation_angle()):
                    if (el > maxel):
                        maxel = el
                    elif (
                            el_increasing
                    ):  # First point after el starts decreasing... find the exact max el
                        el_increasing = 0
                        maxel = self.__find_exact_maxel(time, maxel)
                time += self.__oneminute
            if (up == 1):
                # end the last inview at the input end_time
                # make sure to append AWARE datetimes
                inviews.append((rising.replace(tzinfo=UTC), \
                                end_time.replace(tzinfo=UTC), \
                                maxel))

            return inviews
        except NotImplementedError:  # Does not seem to work?
            print("NotImplementedError computing inviews.  Date/time = %s-%s-%sT%s:%s:%s, satellite number = %s" % \
                (time.year, time.month, time.day, time.hour, time.minute, time.second, self.__satellite_tle.get_satellite_number()))
            sys.stdout.flush()
            raise
        except:  # Does not seem to work?
            print("Unknown exception computing inviews.  Date/time = %s-%s-%sT%s:%s:%s, satellite number = %s" % \
                (time.year, time.month, time.day, time.hour, time.minute, time.second, self.__satellite_tle.get_satellite_number()))
            sys.stdout.flush()
            raise

    def print_inviews(self, inviews):
        """Method to print a table of inviews... assumes that inviews contains the data for such a table"""
        for iv in inviews:
            print("Rise: %s, Set: %s, Maximum Elevation: %f" %
                  (iv[0], iv[1], iv[2]))

    def compute_azels(self, in_start_time, in_end_time, time_step_seconds):
        """Method to compute az/el angles at time_step intervals during the input time period, INDEPENDENT of whether the satellite is actually in view """
        # NOTE:  pyorbital EXPECTS naive date/times and interprets them
        # as UTC... so we need to satisfy it; however, we are making this
        # module DATETIME AWARE, so RETURN VALUES are DATETIME AWARE!!
        # Also, all naive inputs are assumed to be UTC and all aware inputs
        # are converted to UTC (and then made naive)
        if (in_start_time.tzinfo is not None):
            temp = in_start_time.astimezone(UTC)
            start_time = datetime(temp.year, temp.month, temp.day, \
                                  temp.hour, temp.minute, temp.second)
        else:
            start_time = in_start_time
        if (in_end_time.tzinfo is not None):
            temp = in_end_time.astimezone(UTC)
            end_time = datetime(temp.year, temp.month, temp.day, \
                                temp.hour, temp.minute, temp.second)
        else:
            end_time = in_end_time
        # start_time, end_time are now naive
        try:
            delta = timedelta(seconds=time_step_seconds)
        except:
            delta = timedelta(seconds=60)
        azels = []
        time = start_time
        # Naively compute the table... i.e. compute time, az, el for the
        # input duration at each time step... no matter whether the satellite
        # is really inview or not!
        while (time < end_time + delta):
            (az, el) = self.__orb.get_observer_look(time, self.__ground_station.get_longitude(), \
                                                    self.__ground_station.get_latitude(), \
                                                    self.__ground_station.get_minimum_elevation_angle())
            range_km = self.__compute_range(time)
            outtime = time.replace(tzinfo=UTC)  # time is unmodified!
            azels.append((outtime, az, el, range_km))
            time += delta

        return azels

    def __compute_range(self, utc_time):
        """Method to compute range in kilometers from observer to satellite at *naive* UTC time utc_time"""
        # N.B. pyorbital works in kilometers
        (pos_x, pos_y,
         pos_z), (vel_x, vel_y,
                  vel_z) = self.__orb.get_position(utc_time, normalize=False)
        (opos_x, opos_y, opos_z), (ovel_x, ovel_y, ovel_z) = astronomy.observer_position(utc_time, \
                self.__ground_station.get_longitude(), self.__ground_station.get_latitude(), self.__ground_station.get_elevation_in_meters()/1000.0)
        dx = pos_x - opos_x
        dy = pos_y - opos_y
        dz = pos_z - opos_z
        return math.sqrt(dx * dx + dy * dy + dz * dz)  # km

    # up is what it is **before** the crossing
    def __find_exact_crossing(self, time, up):
        """Private method to refine an in view/out of view crossing time from the nearest minute to the nearest second."""
        exacttime = time
        # The crossing occurred in the minute before now... search backwards
        # for the exact second of crossing
        for j in range(0, 60):
            exacttime -= self.__onesecond
            (az, el) = self.__orb.get_observer_look(exacttime, \
                                                    self.__ground_station.get_longitude(), \
                                                    self.__ground_station.get_latitude(), \
                                                    self.__ground_station.get_minimum_elevation_angle())
            if ((el > self.__ground_station.get_minimum_elevation_angle()) and (up == 1)) or \
               ((el < self.__ground_station.get_minimum_elevation_angle()) and (up == 0)):
                break
        return exacttime

    def __find_exact_maxel(self, time, maxel):
        """Private method to refine the maximum elevation from occuring at the nearest minute to the nearest second."""
        exacttime = time
        # The maximum elevation occurred in the **two** minutes before now... search backwards
        # for the exact second of maximum elevation
        for j in range(0, 120):
            exacttime -= self.__onesecond
            (az, el) = self.__orb.get_observer_look(exacttime, \
                                                    self.__ground_station.get_longitude(), \
                                                    self.__ground_station.get_latitude(), \
                                                    self.__ground_station.get_minimum_elevation_angle())
            if (el > maxel):
                maxel = el
        return maxel

    # Class member constants
    __onesecond = timedelta(seconds=1)
    __oneminute = timedelta(minutes=1)
Exemplo n.º 21
0
duracion = 10.01 * 60
satelite = "noaa 19"
orb = Orbital(satelite)

#now = datetime.utcnow()
local_tz = pytz.timezone("America/Montevideo")
UTC_dif = 3
dtobj = datetime(2019, 1, 5, 18 + UTC_dif, 19, 18)
dtobj2 = dtobj + timedelta(seconds=duracion)

#aget_latlon_corners(direction, satellite, duracion, dtobj):

lon, lat, alt = orb.get_lonlatalt(dtobj)
lon2, lat2, alt2 = orb.get_lonlatalt(dtobj2)

print "Position:", orb.get_position(dtobj)
print "Print lon:", lon
print "Print lon:", lat
print "Print lon:", alt
print "Print lon:", lon2
print "Print lon:", lat2
print "Print lon:", alt2

from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
# create new figure, axes instances.
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
# setup mercator map projection.
#m = Basemap(width=12000000,height=9000000, projection='mill',
Exemplo n.º 22
0
        lat = np.arctan2(pos_z + c * e2 * np.sin(lat2), r)
        if np.all(abs(lat - lat2) < 1e-10):
            break
    alt = r / np.cos(lat) - c
    alt *= A
    return np.rad2deg(lon), np.rad2deg(lat), alt


### END OF DIRTY STUFF
def compute_pixels((tle1, tle2), sgeom, times, rpy=(0.0, 0.0, 0.0)):
    """Compute cartesian coordinates of the pixels in instrument scan.
    """
    orb = Orbital("mysatellite", line1=tle1, line2=tle2)

    # get position and velocity for each time of each pixel
    pos, vel = orb.get_position(times, normalize=False)

    # now, get the vectors pointing to each pixel
    vectors = sgeom.vectors(pos, vel, *rpy)

    ## compute intersection of lines (directed by vectors and passing through
    ## (0, 0, 0)) and ellipsoid. Derived from:
    ## http://en.wikipedia.org/wiki/Line%E2%80%93sphere_intersection

    # do the computation between line and ellipsoid (WGS 84)
    # NB: AAPP uses GRS 80...
    centre = -pos
    a__ = 6378.137  # km
    #b__ = 6356.75231414 # km, GRS80
    b__ = 6356.752314245  # km, WGS84
    radius = np.array([[1 / a__, 1 / a__, 1 / b__]]).T
Exemplo n.º 23
0
from pyorbital.orbital import Orbital
from datetime import datetime, timedelta
from pyorbital import tlefile
'''
tle = tlefile.read('noaa 18', '../tle/noaa18_June_14_2018.txt')
print(tle.inclination)
'''
# Use current TLEs from the internet:
orb = Orbital("NOAA 19")

#sup_SDRSharp_20180614_202010Z_137850000Hz_IQ_f1
#m1_SDRSharp_20180615_141220Z_137300000Hz_IQ_f1.png
tc = datetime(2018, 6, 15, 14, 12, 20)
tc = tc + timedelta(seconds=int(925 / 4))
now = datetime.utcnow()
# Get normalized position and velocity of the satellite:
print(orb.get_position(tc))
print(orb.get_lonlatalt(tc))