def test_iss_against_horizons():
    ts = api.load.timescale()
    s = EarthSatellite(*iss_tle0.splitlines())

    hp = array([
        [2.633404251158200E-5, 1.015087620439817E-5, 3.544778677556393E-5],
        [-2.136440257814821E-5, -2.084170814514480E-5, -3.415494123796893E-5],
    ]).T
    hv = array([
        [-1.751248694205384E-3, 4.065407557020968E-3, 1.363540232307603E-4],
        [2.143876266215405E-3, -3.752167957502106E-3, 9.484159290242074E-4],
    ]).T

    two_meters = 2.0 / AU_M
    three_km_per_hour = 3.0 * 24.0 / AU_KM

    t = ts.tdb(2018, 7, 4)
    p = s.at(t)
    assert (abs(p.position.au - hp[:,0]) < two_meters).all()
    assert (abs(p.velocity.au_per_d - hv[:,0]) < three_km_per_hour).all()

    t = ts.tdb(2018, 7, [4, 5])
    p = s.at(t)
    assert (abs(p.position.au - hp) < two_meters).all()
    assert (abs(p.velocity.au_per_d - hv) < three_km_per_hour).all()
Esempio n. 2
0
def test_is_sunlit():
    # Yes, a positionlib method; but it made sense to test it here.
    ts = api.load.timescale()
    t = ts.utc(2018, 7, 3, 0, range(0, 60, 10))
    s = EarthSatellite(line1, line2)
    eph = load('de421.bsp')
    expected = [True, False, False, False, True, True]
    assert list(s.at(t).is_sunlit(eph)) == expected

    # What if we observe from a topos rather than the geocenter?
    topos = api.Topos('40.8939 N', '83.8917 W')
    assert list((s - topos).at(t).is_sunlit(eph)) == expected
	def sat_pos(self):
		# Create timescale
		ts = load.timescale()

		# Satellite
		satellite = EarthSatellite(self.TLE[0],self.TLE[1],self.name,ts)

		# Find t
		t = ts.utc(self.date[0],self.date[1],self.date[2],self.date[3],self.date[4],self.date[5])
		geocentric = satellite.at(t)
		# Generate Longitude and Latitude of satellite
		y = geocentric.subpoint().latitude
		x = geocentric.subpoint().longitude
		return x,y
Esempio n. 4
0
def find_satelite(x, y, z, tmt, ts):

    with open("stations.txt") as active:

        sat_name = active.readline()
        while sat_name:
            line1 = active.readline()
            line2 = active.readline()
            #print(sat_name,line1,line2)

            satellite = EarthSatellite(line1, line2, sat_name, ts)
            geocentric = satellite.at(tmt)

            sat_pos = geocentric.position.km

            if (sat_pos[0] == x and sat_pos[1] == y and sat_pos[2] == z):
                return satellite

            sat_name = active.readline().rstrip()
Esempio n. 5
0
class SatData:

    no = 0

    def __init__(self, name, l1, l2):
        self.name = name
        self.l1 = l1
        self.l2 = l2

        self.ts = load.timescale()
        self.sat = EarthSatellite(self.l1, self.l2, self.name, self.ts)

        self.no = SatData.no
        SatData.no += 1

    def posAtT(self, time):
        geocentric = self.sat.at(time)
        print(geocentric.position.km)

        return geocentric.position.km
Esempio n. 6
0
def get_adcs_vectors(time_data, tle_data):
    sun = JPL_EPH['sun']
    earth = JPL_EPH['earth']
    ts = load.timescale()
    label="Satellite"
    satellite = EarthSatellite(tle_data["line_1"], tle_data["line_2"], label, ts)
    time_instant = ts.utc(
        time_data["year"],
        time_data["month"],
        time_data["day"],
        time_data["hour"],
        time_data["min"],
        time_data["sec"],
    )
    tru_pos = earth + satellite
    sun_vector1 = tru_pos.at(time_instant).observe(sun).apparent().position.km
    sun_vector2 = satellite.at(time_instant).position.km
    # sun_vector = satellite.at(time_instant).observe(earth).apparent()
    # print(tru_pos.at(time_instant).position.km)
    # print(earth.at(time_instant).position.km)
    return [sun_vector1 - sun_vector2]
Esempio n. 7
0
def processTle():
    calculated_lat_long_tle = []
    with open("../datastore/tle_data.json") as tle_data:
        data = json.load(tle_data)
        ts = load.timescale()
        calc_time = ts.now()
        for tle in data:
            temp_tle = tle
            tle_line1 = temp_tle["TLE_LINE1"]
            tle_line2 = temp_tle["TLE_LINE2"]
            name = temp_tle["OBJECT_NAME"]
            satellite = EarthSatellite(tle_line1,tle_line2,name,ts)
            geocentric = satellite.at(calc_time)
            subpoint = geocentric.subpoint()
            # print('Latitude:', subpoint.latitude.degrees)
            # print('Longitude:', subpoint.longitude.degrees)
            # print(satellite)
            temp_tle["Latitude"] = str(subpoint.latitude.degrees)
            temp_tle["Longitude"] = str(subpoint.longitude.degrees)
            # print(temp_tle)
            calculated_lat_long_tle.append(temp_tle)
        with open("../datastore/proc_tle_load.json",'w') as proc_tle:
            proc_tle.write(json.dumps(calculated_lat_long_tle))
Esempio n. 8
0
    def __init__(self, Q, name=None, coords=None, t=0, v_cart=None, line1=None,
                 line2=None, cartesian=True, **kwargs):
        """
        Intialises the satellite class. If cartesian == True, satellite coordinates will be cartesian and  it will
        travel in a fixed plane.
        Else the satellite will be initalised with the given TLEs with geodesic coordinates.
        If either TLE is invalid or None, the satellite defaults to ISS Zarya with geodesic coordinates

        Parameters
        ----------
        name : String
            Name of the satellite. The default is None.
        coords : Array of floats
            Coords of satellite, usage [x,y,z]. The default is [0,0,0].
        e : float
            Efficiancy. The default is 1.
        p : float
            Proportion of surviving photons that haven't changed state. The default is 1.
        px : float
            Probability of x-flip (Bitflip). The default is 0.
        py : float
            Probability of y-flip. The default is 0.
        pz : float
            Probability of z-flip (Dephasing). The default is 0.
        t : float
            Time (in seconds) ahead of the current time from which the satellite is started being tracked. The default is 0.
        v_cart: Array of floats
            Cartesian velocity of Satellite.
        line1 : String
            Line 1 of TLE of the satellite to be added in the network. The default is ''.
        line2 : String
            Line 2 of TLE of the satellite to be added in the network. The default is ''.
        **kwargs : TYPE
            Other costs or qualifying attributes.

        Returns
        -------
        None.

        """
        # Initialise coordinate type
        self.cartesian = cartesian
        
        super().__init__(Q, name, coords, **kwargs)


        if cartesian is True:
            if v_cart is None:
                v_cart = [0]*2
            else:
                assert len(v_cart) == 2
            self.velocity = v_cart
            super().__init__(Q, name, coords, **kwargs)

        else:
            ## Define the time at which the satellite is being tracked ##
            ts = load.timescale()
            t_now = ts.now()
            t_startTime = ts.utc(t_now.utc[0], t_now.utc[1], t_now.utc[2], t_now.utc[3], t_now.utc[4], t_now.utc[5] + t)
            t_new = t_startTime

            ## Initialise which satellite to track. Default is ISS Zarya ##
            try:
                satellite = EarthSatellite(line1, line2, self.name, ts)
                geometry = satellite.at(t_new)
                subpoint = geometry.subpoint()
                self.coords = [int(subpoint.latitude.degrees), int(subpoint.longitude.degrees),
                               int(subpoint.elevation.km)]
            except:
                # Add ISS Zarya to the network by default if the given TLE is invalid
                # l1 and l2 are TLE of ISS Zarya
                l1 = '1 25544U 98067A   20154.85125762  .00002004  00000-0  43906-4 0  9990'
                l2 = '2 25544  51.6443  59.4222 0002071  22.0017  92.6243 15.49416742229799'
                satellite = EarthSatellite(l1, l2, self.name, ts)
                geometry = satellite.at(t_new)
                subpoint = geometry.subpoint()
                geo_coords = [int(subpoint.latitude.degrees), int(subpoint.longitude.degrees),
                              int(subpoint.elevation.km)]
                super().__init__(Q, name, geo_coords, **kwargs)

            # TODO: Write descriptions for these variables here
            self.ts = ts
            self.t_now = t_now
            self.t_startTime = t_startTime
            self.t_new = t_new
            self.satellite = satellite

            print(t_now.utc)
def main(args):

    ## load metafits
    hdu = fits.open(args.metafits)
    duration = hdu[0].header["EXPOSURE"]
    quack = 3  ## to overcome the hardcoded behaviour of cotter

    try:
        start_utc = datetime.strptime(hdu[0].header["DATE-OBS"],
                                      '%Y-%m-%dT%H:%M:%S.%f')
    except:
        start_utc = datetime.strptime(hdu[0].header["DATE-OBS"],
                                      '%Y-%m-%dT%H:%M:%S')

    start_utc = start_utc + timedelta(
        seconds=quack)  ## update start time for quack time

    line1, line2 = getTLE(args, start_utc)
    print("found TLEs\nline1\n{}\nline2\n{}".format(line1, line2))
    ts = load.timescale(builtin=True)
    mwa = Topos("26.701276778 S", "116.670846137 E", elevation_m=377.827)
    sat = EarthSatellite(line1, line2, "sat", ts)
    pointing_ra = float(hdu[0].header["RA"])
    pointing_dec = float(hdu[0].header["DEC"])

    ## create delta array (in seconds)
    search_timeSteps, search_ra, search_dec = [], [], [
    ]  ## contains the timesteps with satellite signal
    baseline_cutoff = []
    time_array = []
    for timeStep in range(int(duration / args.integration)):
        ### skip the first 2 timeSteps and the last timeStep
        if timeStep in [0, 1, int(duration / args.integration) - 1]:
            continue

        local_utc = start_utc + timedelta(seconds=timeStep * args.integration)

        local_ts = ts.utc(local_utc.year, local_utc.month, local_utc.day,
                          local_utc.hour, local_utc.minute,
                          local_utc.second + local_utc.microsecond / 1000000.0)

        sat.at(local_ts)
        difference = sat - mwa
        topocentric = difference.at(local_ts)
        ra, dec, distance = topocentric.radec()
        ra_deg, dec_deg = np.degrees(ra.radians), np.degrees(dec.radians)
        dist = np.sqrt((ra_deg - pointing_ra)**2 + (dec_deg - pointing_dec)**2)
        cutOff = getCutOff(distance.m)
        print("ra {} dec {} timeStep {} dist {} los dist {} cutoff {}".format(
            ra, dec, timeStep, dist, distance.m, cutOff))

        ## update ra and dec in chgcentre format
        ra = str(ra).replace(" ", "")
        dec = str(dec).replace(" ", "").replace('"',
                                                's').replace("'", "m").replace(
                                                    "deg", "d")
        search_timeSteps.append(timeStep)
        search_ra.append(ra)
        search_dec.append(dec)
        baseline_cutoff.append(cutOff)
        time_array.append(str(local_utc))

    with open("lightCurve" + str(args.obs) + "-" + str(args.noradid) + ".csv",
              "w") as vsc:
        thewriter = csv.writer(vsc)
        for t, ra, dec, c, ut in zip(search_timeSteps, search_ra, search_dec,
                                     baseline_cutoff, time_array):
            ut1, ut2 = str(ut).split(" ")
            ut = ut1 + "T" + ut2
            line = [t, ra, dec, c, ut, "dummy"]
            thewriter.writerow(line)
Esempio n. 10
0
# Variable Declaration / Definition
earth_radius = 6378.0
hours = np.arange(0, 3, 0.01)
radians_to_degrees, degrees_to_radians = 180 / np.pi, np.pi / 180
time_scale = load.timescale()
time = time_scale.utc(2018, 2, 7, hours)
TLE = """1 43205U 18017A   18038.05572532 +.00020608 -51169-6 +11058-3 0  9993
2 43205 029.0165 287.1006 3403068 180.4827 179.1544 08.75117793000017"""
line1, line2 = TLE.splitlines()
roadster = EarthSatellite(line1, line2)

# Plot 3D
fig = plt.figure(figsize=[10, 8])
axes1: Axes3D = fig.gca(projection='3d')
x, y, z = roadster.at(time).position.km

# Plot the orbit of the roadster
axes1.plot3D(x, y, z, '-r')

# Plot the globe
x_earth, y_earth, z_earth, img = map_on_sphere(earth_radius,
                                               'land_ocean_ice_2048.jpg')
axes1.plot_wireframe(x_earth, y_earth, z_earth, rstride=10, cstride=10)
# axes1.plot_surface(x_earth.T, y_earth.T, z_earth.T, facecolors=img/255, cstride=1, rstride=1)

# # Plot globe as wireframe
# # Calculate lines of longitude
# for phi in degrees_to_radians * np.arange(0, 180, 15):
#     cos_phi, sin_phi = [f(phi) for f in (np.cos, np.sin)]
#     lon = np.vstack((earth_radius * (np.cos(theta) * cos_phi - np.zeros_like(theta) * sin_phi),
sat = EarthSatellite(
    '1 34602U 09013A   13314.96046236  .14220718  20669-5  50412-4 0   930',
    '2 34602 096.5717 344.5256 0009826 296.2811 064.0942 16.58673376272979',
    'GOCE',
)

# Build the time range `t` over which to plot, plus other values.

ts = load.timescale()
t = ts.tt_jd(np.arange(sat.epoch.tt - 2.0, sat.epoch.tt + 2.0, 0.005))
reentry = ts.utc(2013, 11, 11, 0, 16)
earth_radius_km = 6371.0

# Compute geocentric positions for the satellite.

g = sat.at(t)
valid = [m is None for m in g.message]

# Start a new figure.

fig, ax = plt.subplots()

# Draw the blue curve.

x = t.utc_datetime()
y = np.where(valid, g.distance().km - earth_radius_km, np.nan)
ax.plot(x, y)

# Label the TLE epoch.

x = sat.epoch.utc_datetime()

if __name__ == "__main__":
    from astropy import coordinates as coords
    from astropy.time import Time
    from astropy import units as u
    from skyfield.api import load, EarthSatellite, utc
    from datetime import datetime

    line1 = '1 44031U 98067PX  19083.14584174  .00005852  00000-0  94382-4 0  9997'
    line2 = '2 44031  51.6393  63.5548 0003193 165.0023 195.1063 15.54481029  8074'
    satellite = EarthSatellite(line1, line2)
    ts = load.timescale()
    time_track = datetime(2019, 3, 24, 18, 35, 1, tzinfo=utc)
    t = ts.utc(time_track)
    geo = satellite.at(t)
    subpoint = geo.subpoint()

    now = Time(time_track)
    mag_ecef = magnetic_field(time_track, subpoint.latitude.degrees,
                              subpoint.longitude.degrees, subpoint.elevation.m)
    mag_inertial = magnetic_field(time_track,
                                  subpoint.latitude.degrees,
                                  subpoint.longitude.degrees,
                                  subpoint.elevation.m,
                                  output_format='inertial')

    mag_ecef_obj = coords.EarthLocation.from_geocentric(mag_ecef[0],
                                                        mag_ecef[1],
                                                        mag_ecef[2],
                                                        unit=u.meter)
Esempio n. 13
0
load = Loader('~/Documents/fishing/SkyData')
data = load('de421.bsp')
ts = load.timescale()

planets = load('de421.bsp')
earth = planets['earth']

Roadster = EarthSatellite(L1, L2)

#print(Roadster.epoch.tt)
hours = np.arange(0, 3, 0.01)

time = ts.utc(2018, 2, 7, hours)

Rpos = Roadster.at(time).position.km
Rposecl = Roadster.at(time).ecliptic_position().km

#print(Rpos.shape)

re = 6378

theta = np.linspace(0, twopi, 201)

import matplotlib.pyplot as plt
from scipy.integrate import quad
import numpy as np
from scipy.constants import e, k, pi, epsilon_0
import math

# mass number
Esempio n. 14
0
from skyfield.api import EarthSatellite, load, Topos
import time, math

line1 = "1 37348U 11002A   20053.50800700  .00010600  00000-0  95354-4 0    09"
line2 = "2 37348  97.9000 166.7120 0540467 271.5258 235.8003 14.76330431    04"

satellite = EarthSatellite(line1, line2, 'SAT')
t = load.timescale().utc(2020, 4, 22, 0, 0, 0)
subpoint = satellite.at(t).subpoint()

print('Latitude:', subpoint.latitude)
print('Longitude:', subpoint.longitude)
Esempio n. 15
0
class Orbit:
    def __init__(self):
        self.tle = None
        self.id = None
        self.line1 = None
        self.line2 = None
        self.url = None
        self.satellites = None
        self.observer = None
        self.ts = load.timescale()
        self.alt = None
        self.az = None
        self.distance = None

    def __str__(self):
        temp = "TLE\n"
        temp += 69 * "-"
        temp += self.id
        temp += self.line1
        temp += self.line2
        return temp

    def loadTLE(self, tle):
        '''

        :param tle:
        :return:
        '''
        self.tle = tle
        self.id = self.tle[0]
        self.line1 = self.tle[1]
        self.line2 = self.tle[2]
        return self.id, self.line1, self.line2

    def loadSatellites(self):
        '''

        :return:
        '''
        self.satellites = load.tle_file(self.url)
        return

    def loadSatfromTLE(self, tle):
        '''

        :param tle:
        TLE EXAMPLE
        tle = """
        GOCE
        1 34602U 09013A   13314.96046236  .14220718  20669-5  50412-4 0   930
        2 34602 096.5717 344.5256 0009826 296.2811 064.0942 16.58673376272979
        """

        :return:
        '''

        lines = tle.strip().splitlines()
        self.satellites = EarthSatellite(lines[1], lines[2], lines[0])
        return

    def loadObserver(self, lat, long):
        '''

        :param lat:
        :param long:
        :return:
        '''
        self.observer = wgs84.latlon(lat, long)
        return

    def setURL(self, url):
        '''

        :param url:
        :return:
        '''
        self.url = url
        return

    def currentTime(self):
        '''

        :return:
        '''
        return self.ts.now()

    def showSatellite(self):
        '''

        :return:
        '''
        print(self.satellite)
        return

    def setTime(self, year, month, day):
        '''

        :param year:
        :param month:
        :param day:
        :return:
        '''
        t = self.ts.utc(year, month, day)
        return t

    def findRiseSets(self, timedate_init, timedate_final, altitude_degrees):
        '''

        :param timedate_init:
        :param timedate_final:
        :param altitude_degrees:
        :return:
        '''
        t0 = self.setTime(timedate_init)
        t1 = self.setTime(timedate_final)
        t, events = self.satellites.find_events(self.observer, t0, t1,
                                                altitude_degrees)
        for ti, event in zip(t, events):
            name = ('rise above' + str(altitude_degrees), 'culminate',
                    'set below' + str(altitude_degrees))[event]
            print(ti.utc_strftime('%Y %b %d %H:%M:%S'), name)
        return

    def checkSatEpoch(self):
        '''

        :return:
        '''
        self.epoch = self.satellites.epoch.utc_jpl()
        print(self.epoch)
        return

    def checkSatellitePosition(self):
        '''

        :return:
        '''
        return self.satellites.at(self.currentTime())

    def getSatfromYours(self):
        '''

        :return:
        '''
        return print(self.satellites - self.observer)

    def getObservation(self):
        '''

        :return:
        '''
        self.alt, self.az, self.distance = self.getSatfromYours()

        if self.alt.degrees > 0:
            print(str(self.satellites.name) + " is above the horizon")

        print(self.alt)
        print(self.az)
        print(self.int(self.distance.km), 'km')
        return
Esempio n. 16
0
    lines = tles.readlines()

sats = []

ts = load.timescale()
candidate_sat = None
norm = 1e99

# Load sat names and find closest sat
for i in range(0, len(lines), 3):
    name = lines[i].strip()
    sats.append(name)
    t = datetime.datetime(*initial_time, tzinfo=utc)  # From, prompt
    try:
        satellite = EarthSatellite(lines[i + 1], lines[i + 2], lines[i], ts)
        position = satellite.at(ts.utc(t)).position.km

        diff = position - target_pos
        curr_norm = np.linalg.norm(diff)
        if curr_norm < norm:
            candidate_sat = satellite
            norm = curr_norm
            # print(name, position, target_pos)
    except NotImplementedError:
        pass

print("Selected sat", candidate_sat)
t = datetime.datetime(*check_time, tzinfo=utc)  # Change this from challenge
position = candidate_sat.at(ts.utc(t)).position.km
print(position)
class SimulateX2(object):
    """A class to simulate a satellite with SGP4 propagation model"""
    def __init__(self, catnr, xdays):
        """Initialize the catalog number and number of days attributes."""

        self.catnr = catnr
        self.xdays = xdays

    def getTLEs(self):
        """Get TLEs of a given satellite from Internet and save into a file"""

        url = 'https://celestrak.com/satcat/tle.php?CATNR={}'.format(
            self.catnr)
        self.filename = 'tle-CATNR-{}.txt'.format(self.catnr)

        try:
            # TODO: Use logger for logging
            print("Fetching TLEs for satellite with catalog number {}.".format(
                self.catnr))
            tle = load.tle_file(url, filename=self.filename, reload=True)
        except OSError:
            print("An error occurred while fetching the TLEs")
            print("Are you connected to Internet?")
        else:
            print("TLEs are saved in {}".format(self.filename))

    def loadTLEs(self):
        """Load line 1 and 2 of TLEs"""

        try:
            with open(self.filename) as fobj:
                lines = fobj.readlines()
        except FileNotFoundError:
            print("Sorry, the file {} does not exist.".format(self.filename))
        else:
            length = len(lines)
            if length != 3:
                print("The file {} is not in a standard NORAD TLEs format.".
                      format(self.filename))
                print("Cannot continue.")
                sys.exit()
            temp = []
            for line in lines:
                temp.append(line.strip())
            self.line0, self.line1, self.line2 = temp[0], temp[1], temp[2]

    def getEpoch(self):
        """Get epoch from TLEs"""

        self.ts = load.timescale()
        self.satellite = EarthSatellite(self.line1, self.line2, self.line0,
                                        self.ts)
        print("TLE epoch: {}".format(self.satellite.epoch.utc_jpl()))

    def getNewEpoch(self):
        """Calculate new epoch based on the number of days"""

        c_epoch = self.satellite.epoch.utc_datetime()
        offset = rd(days=+self.xdays)
        new_epoch = c_epoch + offset
        print("New epoch: {}".format(new_epoch))
        t1 = self.ts.utc(new_epoch)
        return t1

    def getPV(self):
        """Get satellite position(geocentric coordinates) and velocity at new epoch"""

        n_epoch = self.getNewEpoch()

        geocentric = self.satellite.at(n_epoch)
        speed = self.satellite.at(n_epoch).velocity.km_per_s
        return [geocentric, speed]

    def getLonLatAlt(self):
        """Get longitude, latitude, and altitude """

        pv_list = self.getPV()
        subpoint = wgs84.subpoint(pv_list[0])
        print("Longitude: {}".format(subpoint.longitude))
        print("Latitude: {}".format(subpoint.latitude))
        print("Altitude (in kilometers): {}".format(subpoint.elevation.km))

    def getOrbitalElements(self):
        """Get orbital and dynamic elements"""

        pv_list = self.getPV()
        elements = osculating_elements_of(pv_list[0])

        # line 2 of new TLEs
        self.inclination = elements.inclination.degrees
        self.raan = elements.longitude_of_ascending_node
        self.eccentricity = elements.eccentricity
        self.aop = elements.argument_of_periapsis
        self.ma = elements.mean_anomaly
        self.mm = elements.mean_motion_per_day
        return [self.inclination, self.raan, self.eccentricity, \
                self.aop, self.ma, self.mm]

    def printResults(self):
        """Print results obtained from various methods"""

        pv_list = self.getPV()
        print("Geocentric x,y,z in GCRS: {}".format(pv_list[0].position.km))

        print("Velocity (km/s): {}".format(pv_list[1]))

        orbit_elements = self.getOrbitalElements()
        print()
        print(" ========== Line 0 of New TLEs ========== ")
        print("Satellite name: {}".format(self.satellite.name))
        print()
        print(" ========== Line 1 of New TLEs ========== ")
        print("Satellite number: {}".format(self.catnr))
        print("Satellite classification: {}".format(
            self.satellite.model.classification))
        print("International designator: {}".format(
            self.satellite.model.intldesg))
        print("Epoch year: {}".format(
            self.satellite.model.epochyr))  # put updated epoch
        print("Epoch days: {}".format(self.satellite.model.epochdays +
                                      self.xdays))
        print("Ballistic drag coefficient: <placeholder>")
        print(
            "2nd Derivative of the mean motion (ignored by SGP4): <placeholder>"
        )
        print("Drag term: <placeholder>")
        print("Ephemeris Type: 0")
        print("Element number: {}".format(self.satellite.model.elnum))

        print()
        print(" ========== Line 2 of New TLEs ========== ")
        print("Satellite number: {}".format(self.catnr))
        print("Inclination (in degrees): {}".format(orbit_elements[0]))
        print("RAAN: {}".format(orbit_elements[1]))
        print("Eccentricity: {}".format(orbit_elements[2]))
        print("Argument of perigee: {}".format(orbit_elements[3]))
        print("Mean Anomaly: {}".format(orbit_elements[4]))
        print("Mean motion: {}".format(orbit_elements[5]))

    def generateTLEs(self):
        """Generate a new set of TLEs based on the new epoch"""

        # TODO: wrap the static and dynamic elements into a new TLEs
        #satrec = satrec()
        #satrec.sgp4init(
        #            WGS84,              # gravity model
        #            'i',                # 'i' = improved mode
        #            self.catnr,         # satnum: Satellite number

        #        )
        pass
Esempio n. 18
0
halfpi, pi, twopi = [f * np.pi for f in [0.5, 1, 2]]
degs, rads = 180 / pi, pi / 180
lines = text.strip().splitlines()
ts = load.timescale()
t = ts.now()
try:
    EarthSatellite(lines[0], lines[1])
except:
    print("TLE not found")
    sys.exit(1)

Roadster = EarthSatellite(lines[0], lines[1])
hours = np.arange(0, 3, 0.01)
time = ts.utc(2018, 2, 7, hours)
Rpos = Roadster.at(time).position.km
re = 6378.
theta = np.linspace(0, twopi, 201)
cth, sth, zth = [f(theta) for f in [np.cos, np.sin, np.zeros_like]]
lon0 = re * np.vstack((cth, zth, sth))
lons = []
for phi in rads * np.arange(0, 180, 15):
    cph, sph = [f(phi) for f in [np.cos, np.sin]]
    lon = np.vstack((lon0[0] * cph - lon0[1] * sph,
                     lon0[1] * cph + lon0[0] * sph, lon0[2]))
    lons.append(lon)

lat0 = re * np.vstack((cth, sth, zth))
lats = []
for phi in rads * np.arange(-75, 90, 15):
    cph, sph = [f(phi) for f in [np.cos, np.sin]]
Esempio n. 19
0
def get_next_satellite_pass_for_latlon(
    latitude: float,
    longitude: float,
    requested_date: datetime.datetime,
    tle_satellite_name: str,
    elevation: float = 0.0,
    number_of_results: int = 1,
    visible_passes_only: bool = False,
    altitude_degrees: float = 10.0,
    units: str = "metric",
):
    """
    Determine the next pass of the ISS for a given set
    of coordinates for a certain date

    Parameters
    ==========
    latitude : 'float'
        Latitude value
    longitude : 'float'
        Longitude value
    requested_date: class 'datetime'
        Start-datestamp for the given calculation
    tle_satellite_name: 'str'
        Name of the satellite whose pass we want to
        calculate (see http://www.celestrak.com/NORAD/elements/amateur.txt)
    elevation : 'float'
        Elevation in meters above sea levels
        Default is 0 (sea level)
    number_of_results: int
        default: 1, supports up to 5 max results
    visible_passes_only: bool
        If True, then show only visible passes to the user
    altitude_degrees: float
        default: 10.0 degrees
    units: str
        units of measure, either metric or imperial

    Returns
    =======
    success: bool
        False in case an error has occurred

    """

    assert 1 <= number_of_results <= 5
    assert units in ["metric", "imperial"]

    satellite_response_data = {}

    rise_time = (
        rise_azimuth
    ) = maximum_time = maximum_altitude = set_time = set_azimuth = None

    # Try to get the satellite information from the dictionary
    # Return error settings if not found
    success, tle_satellite, tle_data_line1, tle_data_line2 = get_tle_data(
        satellite_id=tle_satellite_name)
    if success:
        ts = api.load.timescale()
        eph = api.load("de421.bsp")

        satellite = EarthSatellite(tle_data_line1, tle_data_line2,
                                   tle_satellite, ts)

        pos = api.Topos(
            latitude_degrees=latitude,
            longitude_degrees=longitude,
            elevation_m=elevation,
        )

        today = requested_date
        tomorrow = requested_date + datetime.timedelta(days=10)

        #
        # t = ts.utc(
        #    year=today.year,
        #    month=today.month,
        #    day=today.day,
        #    hour=today.hour,
        #    minute=today.minute,
        #    second=today.second,
        # )
        # days = t - satellite.epoch
        # logger.info(msg="{:.3f} days away from epoch".format(days))

        t0 = ts.utc(today.year, today.month, today.day, today.hour,
                    today.minute, today.second)
        t1 = ts.utc(
            tomorrow.year,
            tomorrow.month,
            tomorrow.day,
            tomorrow.hour,
            tomorrow.minute,
            tomorrow.second,
        )

        t, events = satellite.find_events(pos,
                                          t0,
                                          t1,
                                          altitude_degrees=altitude_degrees)

        events_dictionary = {}

        found_rise = False
        for ti, event in zip(t, events):
            #            name = ("rise above 10°", "culminate", "set below 10°")[event]
            #            print(ti.utc_strftime("%Y %b %d %H:%M:%S"), name)

            # create a datetime object out of the skyfield date/time-stamp
            # we don't really need the microsecond information but keeping this data
            # should make our dictionary key unique :-)
            timestamp = datetime.datetime(
                year=ti.utc.year,
                month=ti.utc.month,
                day=ti.utc.day,
                hour=ti.utc.hour,
                minute=ti.utc.minute,
                second=floor(ti.utc.second),
                microsecond=floor(1000000 *
                                  (ti.utc.second - floor(ti.utc.second))),
            )
            is_sunlit = satellite.at(ti).is_sunlit(eph)
            difference = satellite - pos
            topocentric = difference.at(ti)
            alt, az, distance = topocentric.altaz()
            above_horizon = True if alt.degrees > 0 else False

            # (re)calculate km distance in miles if the user has requested imperial units
            _div = 1.0
            if units == "imperial":
                _div = 1.609  # change km to miles

            # 'event' values: '0' = rise above, '1' = culminate, '2' = set below
            # at the point in time for which the user has requested the data
            # there might happen a flyby (meaning that we receive a '1'/'2'
            # even as first event). We are going to skip those until we receive
            # the first '0' event
            if event == 0 or found_rise:
                events_dictionary[timestamp] = {
                    "event": event,
                    "above_horizon": above_horizon,
                    "altitude": ceil(altitude_degrees),
                    "azimuth": ceil(az.degrees),
                    "distance": floor(distance.km /
                                      _div),  # Change km to miles if necessary
                    "is_sunlit": is_sunlit,
                }
                found_rise = True

        # We now have a dictionary that is a) in the correct order and b) starts with a '0' event
        # Try to process the data and build the dictionary that will contain
        # the blended data

        is_visible = False
        rise_date = culmination_date = set_date = datetime.datetime.min
        alt = az = dst = 0.0

        count = 0

        for event_datetime in events_dictionary:
            event_item = events_dictionary[event_datetime]
            event = event_item["event"]
            above_horizon = event_item["above_horizon"]
            altitude = event_item["altitude"]
            azimuth = event_item["azimuth"]
            distance = event_item["distance"]
            is_sunlit = event_item["is_sunlit"]

            if event == 0:  # rise
                rise_date = event_datetime
                if is_sunlit:
                    is_visible = True
            elif event == 1:  # culmination
                culmination_date = event_datetime
                alt = altitude
                az = azimuth
                dst = distance
                if is_sunlit:
                    is_visible = True
            elif event == 2:  # set
                set_date = event_datetime
                if is_sunlit:
                    is_visible = True
                # we should now have all of the required data for creating
                # a full entry. Now check if we need to add it
                if is_visible or not visible_passes_only:
                    satellite_response_data[rise_date] = {
                        "culmination_date": culmination_date,
                        "set_date": set_date,
                        "altitude": alt,
                        "azimuth": az,
                        "distance": dst,
                        "is_visible": is_visible,
                    }
                    # Increase entry counter and end for loop
                    # if we have enough results
                    count = count + 1
                    if count >= number_of_results:
                        break
                # Otherwise, we are going to reset our work variables for
                # the next loop that we are going to enter
                is_visible = False
                rise_date = culmination_date = set_date = datetime.datetime.min
                alt = az = dst = 0.0
    return success, satellite_response_data
Esempio n. 20
0
from skyfield.api import EarthSatellite, N, W, wgs84, load

ts = load.timescale()
t = ts.now()

line1 = '1 25544U 98067A   14020.93268519  .00009878  00000-0  18200-3 0  5082'
line2 = '2 25544  51.6498 109.4756 0003572  55.9686 274.8005 15.49815350868473'

boston = wgs84.latlon(42.3583 * N, 71.0603 * W, elevation_m=43)
satellite = EarthSatellite(line1, line2, name='ISS (ZARYA)')

# Geocentric

geometry = satellite.at(t)

# Geographic point beneath satellite

subpoint = wgs84.subpoint(geometry)
latitude = subpoint.latitude
longitude = subpoint.longitude
elevation = subpoint.elevation

# Topocentric

difference = satellite - boston
geometry = difference.at(t)
Esempio n. 21
0
def orbit(TLE):
    L1 = row['TLE_LINE1']
    L2 = row['TLE_LINE2']
    Roadster = EarthSatellite(L1, L2)
    print(Roadster.epoch.tt)
    return Roadster.at(time).position.km
Esempio n. 22
0
def calculatePasses(params):
    try:
        ephem = load(params[13])
        sun = ephem['sun']
        earth = ephem['earth']
        CityElevation = int(params[15])
        Location = Topos(params[12].split(',')[0],
                         params[12].split(',')[1],
                         elevation_m=CityElevation)

        tle0 = params[0]
        tle1 = params[1]
        tle2 = params[2]
        NORADID = params[3]
        tleEpoch = params[4]
        City = params[5]
        YearFrom = params[6]
        MonthFrom = params[7]
        DayFrom = params[8]
        YearTo = params[9]
        MonthTo = params[10]
        DayTo = params[11]
        stdmag = params[14]
        ts = load.timescale()
        E_TLEEEPOCH = tleEpoch
        E_SATID = NORADID
        E_CITY = City
        E_UTCCALCDATE = ts.now()
        E_TLEEEPOCH = tleEpoch
        satellite = EarthSatellite(tle1, tle2, tle0, ts)
        difference = satellite - Location
        EarthLoc = (earth + Location)
        SunEarth = (sun - earth)
        obj = []
        t0 = ts.utc(YearFrom, MonthFrom, DayFrom)
        t1 = ts.utc(YearTo, MonthTo, DayTo)

        lastevent = -1
        times, events = satellite.find_events(Location,
                                              t0,
                                              t1,
                                              altitude_degrees=0)

        if len(events) == 0:
            return obj

        if events[len(events) - 1] != 2:
            t1 = ts.utc(YearTo, MonthTo, DayTo, 0, 40, 0)
            times, events = satellite.find_events(Location,
                                                  t0,
                                                  t1,
                                                  altitude_degrees=0)

        for ti, event in zip(times, events):
            if lastevent == -1 and event > 0:
                continue
            else:
                lastevent = event
            if event == 0:
                E_UTC0R = None
                E_UTC0S = None
                E_UTC15R = None
                E_UTC15S = None
                E_UTC30R = None
                E_UTC30S = None
                E_UTCMAX = None
                E_MAXELEV = None
                E_SUNELEVAT0R = None
                E_SUNELEVAT0S = None
                E_SUNELEVAT15R = None
                E_SUNELEVAT15S = None
                E_SUNELEVAT30R = None
                E_SUNELEVAT30S = None
                E_SUNELEVATMAX = None
                E_ISSUNLIT0R = None
                E_ISSUNLIT0S = None
                E_ISSUNLIT15R = None
                E_ISSUNLIT15S = None
                E_ISSUNLIT30R = None
                E_ISSUNLIT30S = None
                E_ISSUNLITMAX = None
                E_UTCSHADOW = None
                E_ELEVATSHADOW = None
                E_MAG0R = None
                E_MAG0S = None
                E_MAG15R = None
                E_MAG15S = None
                E_MAG30R = None
                E_MAG30S = None
                E_MAGMAX = None
                E_MAGPRESHADOW = None
                E_AZ0R = None
                E_AZ15R = None
                E_AZ30R = None
                E_AZMAX = None
                E_AZ30S = None
                E_AZ15S = None
                E_AZ0S = None

                E_UTC0R = ti
                topocentric = difference.at(E_UTC0R)
                alt, az, distance = topocentric.altaz()
                E_AZ0R = az.degrees
                E_ISSUNLIT0R = satellite.at(E_UTC0R).is_sunlit(ephem)
                EarthLocSun = EarthLoc.at(E_UTC0R).observe(sun)
                altSun, azSun, distanceSun = EarthLocSun.apparent().altaz()
                E_SUNELEVAT0R = altSun.degrees
                if E_ISSUNLIT0R:
                    E_MAG0R = calculateMag(E_UTC0R, difference, SunEarth,
                                           EarthLocSun, stdmag)
            if event == 1:
                E_UTCMAX = ti
                topocentric = difference.at(E_UTCMAX)
                alt, az, distance = topocentric.altaz()
                E_MAXELEV = alt.degrees
                E_AZMAX = az.degrees
                E_ISSUNLITMAX = satellite.at(E_UTCMAX).is_sunlit(ephem)
                EarthLocSun = EarthLoc.at(E_UTCMAX).observe(sun)
                altSun, azSun, distanceSun = EarthLocSun.apparent().altaz()
                E_SUNELEVATMAX = altSun.degrees
                if E_ISSUNLITMAX:
                    E_MAGMAX = calculateMag(E_UTCMAX, difference, SunEarth,
                                            EarthLocSun, stdmag)
            if event == 2:
                E_UTC0S = ti
                topocentric = difference.at(E_UTC0S)
                alt, az, distance = topocentric.altaz()
                E_AZ0S = az.degrees
                E_ISSUNLIT0S = satellite.at(E_UTC0S).is_sunlit(ephem)
                EarthLocSun = EarthLoc.at(E_UTC0S).observe(sun)
                altSun, azSun, distanceSun = EarthLocSun.apparent().altaz()
                E_SUNELEVAT0S = altSun.degrees
                if E_ISSUNLIT0S:
                    E_MAG0S = calculateMag(E_UTC0S, difference, SunEarth,
                                           EarthLocSun, stdmag)
                if E_MAXELEV > 15:
                    times15, events15 = satellite.find_events(
                        Location, E_UTC0R, E_UTC0S, altitude_degrees=15)
                    for ti15, event15 in zip(times15, events15):
                        if event15 == 0:
                            E_UTC15R = ti15
                            topocentric = difference.at(E_UTC15R)
                            alt, az, distance = topocentric.altaz()
                            E_AZ15R = az.degrees
                            E_ISSUNLIT15R = satellite.at(E_UTC15R).is_sunlit(
                                ephem)
                            EarthLocSun = EarthLoc.at(E_UTC15R).observe(sun)
                            altSun, azSun, distanceSun = EarthLocSun.apparent(
                            ).altaz()
                            E_SUNELEVAT15R = altSun.degrees
                            if E_ISSUNLIT15R:
                                E_MAG15R = calculateMag(
                                    E_UTC15R, difference, SunEarth,
                                    EarthLocSun, stdmag)
                        if event15 == 2:
                            E_UTC15S = ti15
                            topocentric = difference.at(E_UTC15S)
                            alt, az, distance = topocentric.altaz()
                            E_AZ15S = az.degrees
                            E_ISSUNLIT15S = satellite.at(E_UTC15S).is_sunlit(
                                ephem)
                            EarthLocSun = EarthLoc.at(E_UTC15S).observe(sun)
                            altSun, azSun, distanceSun = EarthLocSun.apparent(
                            ).altaz()
                            E_SUNELEVAT15S = altSun.degrees
                            if E_ISSUNLIT15S:
                                E_MAG15S = calculateMag(
                                    E_UTC15S, difference, SunEarth,
                                    EarthLocSun, stdmag)
                if E_MAXELEV > 30:
                    times30, events30 = satellite.find_events(
                        Location, E_UTC15R, E_UTC15S, altitude_degrees=30)
                    for ti30, event30 in zip(times30, events30):
                        if event30 == 0:
                            E_UTC30R = ti30
                            topocentric = difference.at(E_UTC30R)
                            alt, az, distance = topocentric.altaz()
                            E_AZ30R = az.degrees
                            E_ISSUNLIT30R = satellite.at(E_UTC30R).is_sunlit(
                                ephem)
                            EarthLocSun = EarthLoc.at(E_UTC30R).observe(sun)
                            altSun, azSun, distanceSun = EarthLocSun.apparent(
                            ).altaz()
                            E_SUNELEVAT30R = altSun.degrees
                            if E_ISSUNLIT30R:
                                E_MAG30R = calculateMag(
                                    E_UTC30R, difference, SunEarth,
                                    EarthLocSun, stdmag)
                        if event30 == 2:
                            E_UTC30S = ti30
                            topocentric = difference.at(E_UTC30S)
                            alt, az, distance = topocentric.altaz()
                            E_AZ30S = az.degrees
                            E_ISSUNLIT30S = satellite.at(E_UTC30S).is_sunlit(
                                ephem)
                            EarthLocSun = EarthLoc.at(E_UTC30S).observe(sun)
                            altSun, azSun, distanceSun = EarthLocSun.apparent(
                            ).altaz()
                            E_SUNELEVAT30S = altSun.degrees
                            if E_ISSUNLIT30S:
                                E_MAG30S = calculateMag(
                                    E_UTC30S, difference, SunEarth,
                                    EarthLocSun, stdmag)

                SHADOWDIRECTION = 0
                if (E_ISSUNLIT0R and (not E_ISSUNLITMAX or not E_ISSUNLIT0S)):
                    SHADOWDIRECTION = 1

                if (not E_ISSUNLIT0R and (E_ISSUNLITMAX or E_ISSUNLIT0S)):
                    SHADOWDIRECTION = -1

                if SHADOWDIRECTION != 0:
                    SatRiseTime = datetime.datetime.strptime(
                        E_UTC0R.utc_iso(' '), '%Y-%m-%d %H:%M:%SZ')
                    SatSetTime = datetime.datetime.strptime(
                        E_UTC0S.utc_iso(' '), '%Y-%m-%d %H:%M:%SZ')
                    SatTimeDiff = (SatSetTime - SatRiseTime).total_seconds()
                    TimeIncrease = 1

                    if SHADOWDIRECTION > 0:
                        MinLitTime = SatRiseTime
                        MaxLitTime = SatSetTime
                        TTC1 = SatRiseTime
                    if SHADOWDIRECTION < 0:
                        MinLitTime = SatRiseTime
                        MaxLitTime = SatSetTime
                        TTC1 = SatSetTime

                    while TimeIncrease > 0:
                        TimeIncrease = math.ceil(SatTimeDiff / 2)
                        TTC1 = TTC1 + datetime.timedelta(
                            seconds=SHADOWDIRECTION * TimeIncrease)
                        TTC2 = TTC1 + datetime.timedelta(
                            seconds=SHADOWDIRECTION)
                        tsunlit1 = ts.utc(TTC1.year, TTC1.month, TTC1.day,
                                          TTC1.hour, TTC1.minute, TTC1.second)
                        tsunlit2 = ts.utc(TTC2.year, TTC2.month, TTC2.day,
                                          TTC2.hour, TTC2.minute, TTC2.second)
                        ShadowSunLit1 = satellite.at(tsunlit1).is_sunlit(ephem)
                        ShadowSunLit2 = satellite.at(tsunlit2).is_sunlit(ephem)
                        if ShadowSunLit1 != ShadowSunLit2:
                            TimeIncrease = -1
                        else:
                            if ShadowSunLit1 and SHADOWDIRECTION > 0:
                                MinLitTime = TTC1

                            elif not ShadowSunLit1 and SHADOWDIRECTION > 0:
                                MaxLitTime = TTC1
                                SHADOWDIRECTION = -1

                            elif ShadowSunLit1 and SHADOWDIRECTION < 0:
                                MinLitTime = TTC1
                                SHADOWDIRECTION = 1

                            elif not ShadowSunLit1 and SHADOWDIRECTION < 0:
                                MinLitTime = TTC1

                            SatTimeDiff = (MaxLitTime -
                                           MinLitTime).total_seconds()
                            if SatTimeDiff <= 1:
                                TimeIncrease = -1

                    topocentric = difference.at(tsunlit1)
                    alt, az, distance = topocentric.altaz()
                    E_ELEVATSHADOW = alt.degrees
                    E_UTCSHADOW = tsunlit1
                    E_MAGPRESHADOW = calculateMag(E_UTCSHADOW, difference,
                                                  SunEarth, EarthLocSun,
                                                  stdmag)

                obj.append(
                    fillValues(P_SATID=E_SATID,
                               P_CITY=E_CITY,
                               P_UTCCALCDATE=E_UTCCALCDATE,
                               P_TLEEEPOCH=E_TLEEEPOCH,
                               P_UTC0R=E_UTC0R,
                               P_UTC0S=E_UTC0S,
                               P_UTC15R=E_UTC15R,
                               P_UTC15S=E_UTC15S,
                               P_UTC30R=E_UTC30R,
                               P_UTC30S=E_UTC30S,
                               P_UTCMAX=E_UTCMAX,
                               P_MAXELEV=E_MAXELEV,
                               P_SUNELEVAT0R=E_SUNELEVAT0R,
                               P_SUNELEVAT0S=E_SUNELEVAT0S,
                               P_SUNELEVAT15R=E_SUNELEVAT15R,
                               P_SUNELEVAT15S=E_SUNELEVAT15S,
                               P_SUNELEVAT30R=E_SUNELEVAT30R,
                               P_SUNELEVAT30S=E_SUNELEVAT30S,
                               P_SUNELEVATMAX=E_SUNELEVATMAX,
                               P_ISSUNLIT0R=E_ISSUNLIT0R,
                               P_ISSUNLIT0S=E_ISSUNLIT0S,
                               P_ISSUNLIT15R=E_ISSUNLIT15R,
                               P_ISSUNLIT15S=E_ISSUNLIT15S,
                               P_ISSUNLIT30R=E_ISSUNLIT30R,
                               P_ISSUNLIT30S=E_ISSUNLIT30S,
                               P_ISSUNLITMAX=E_ISSUNLITMAX,
                               P_UTCSHADOW=E_UTCSHADOW,
                               P_ELEVATSHADOW=E_ELEVATSHADOW,
                               P_MAG0R=E_MAG0R,
                               P_MAG0S=E_MAG0S,
                               P_MAG15R=E_MAG15R,
                               P_MAG15S=E_MAG15S,
                               P_MAG30R=E_MAG30R,
                               P_MAG30S=E_MAG30S,
                               P_MAGMAX=E_MAGMAX,
                               P_MAGPRESHADOW=E_MAGPRESHADOW,
                               P_AZ0R=E_AZ0R,
                               P_AZ15R=E_AZ15R,
                               P_AZ30R=E_AZ30R,
                               P_AZMAX=E_AZMAX,
                               P_AZ30S=E_AZ30S,
                               P_AZ15S=E_AZ15S,
                               P_AZ0S=E_AZ0S))
        return obj
    except Exception as e:
        if hasattr(e, 'message'):
            return "Error {0} processing values: {1}".format(
                e.message, ",".join(str(x) for x in params))
        else:
            return "Error {0} processing values: {1}".format(
                str(e), ",".join(str(x) for x in params))
Esempio n. 23
0
# --------- fullsat.py --------- Apr.27-May.07, 2019 --------------------
from skyfield.api import EarthSatellite, Topos, load
from numpy import around

ts = load.timescale()
timestring= '2020, 3, 26, 21, 53, 30'
t = ts.utc(2020,3,26,21,53,30)
# TLE twoline dbase
line1 = '1 13337U 98067A   20087.38052801 -.00000452  00000-0  00000+0 0  9995'
line2 = '2 13337  51.6460  33.2488 0005270  61.9928  83.3154 15.48919755219337'
#
loc = Topos(38.8892771, -77.0353628)
satellite = EarthSatellite(line1, line2)

# Geocentric
geometry = satellite.at(t)

# Geographic point beneath satellite
subpoint = geometry.subpoint()
latitude = subpoint.latitude
longitude = subpoint.longitude
elevation = subpoint.elevation

# Topocentric
difference = satellite - loc
geometry = difference.at(t)
topoc= loc.at(t)
#
topocentric = difference.at(t)
geocentric = satellite.at(t)
# ------ Start outputs -----------
Esempio n. 24
0
def localisation():
    ts = load.timescale()
    yearstring = yearentry.get() + "/" + monthentry.get() + "/" + dayentry.get(
    )
    daystring = hoursentry.get() + "h" + minutentry.get(
    ) + "m" + secondentry.get() + "s"
    timestring = yearstring + " " + daystring
    print(timestring)
    t = ts.utc(int(yearentry.get()), int(monthentry.get()),
               float(dayentry.get()), float(hoursentry.get()),
               float(minutentry.get()),
               float(secondentry.get()))  # datetime selection
    # TLE twoline dbase
    line1, line2 = parsedData[satelliteselector.get()]
    loc = wgs84.latlon(float(latentry.get()),
                       float(logentry.get()),
                       elevation_m=float(altentry.get()))  # location coords
    satellite = EarthSatellite(line1, line2)

    # Geocentric
    geometry = satellite.at(t)

    # Geographic point beneath satellite
    subpoint = geometry.subpoint()
    latitude = subpoint.latitude
    longitude = subpoint.longitude
    elevation = subpoint.elevation

    # Topocentric
    difference = satellite - loc
    geometry = difference.at(t)
    topoc = loc.at(t)
    #
    topocentric = difference.at(t)
    geocentric = satellite.at(t)
    # ------ Start outputs -----------
    print('\n Heures locale :', timestring)
    # print (' Temps Solaire : ',t) pb
    print('', loc)
    print('\n Subpoint Longitude= ', longitude)
    print(' Subpoint Latitude = ', latitude)
    print(' Subpoint Elevation=  {0:.3f}'.format(elevation.km), 'km')
    # ------ Step 1: compute sat horizontal coords ------
    alt, az, distance = topocentric.altaz()
    # print(alt.degree)
    if alt.degrees > 0:
        print('\n', satellite, "\n est au dessus de l'horizon")
    print('\n Altitude= ', alt)
    print(' Azimute = ', az)
    print(' Distance=  {0:.3f}km'.format(distance.km))
    #
    # ------ Step 2: compute sat RA,Dec [equinox of date] ------
    ra, dec, distance = topocentric.radec(epoch='date')
    print('\n Ascention droite= ', ra)
    print(' Déclinaison =', dec)
    #
    # ------ Step 3: compute sat equatorial coordinates  --------
    print('\n Vecteur définissant la position du satellite: r = R + rho')
    print('    Obs. posit.(R): ', topoc.position.km, 'km')
    print(' topocentrique (rho): ', topocentric.position.km, 'km')
    print(' -----------------')
    print('    Geocentrique (r): ', geocentric.position.km, 'km')
Esempio n. 25
0
sensor = Topos('0.0 N', '0.0 W')
difference = satellite - sensor
print(difference)

# Start and end times
topocentric = difference.at(tBreakup)
alt, az, distance = topocentric.altaz()

# Simulate a number of pieces that are ejected randomly from the main body
nPieces = 4
nTimeSteps = 10
timeStep = 100
ejectionVelocity = 0.4  # km/sec

geocentric = satellite.at(tBreakup)
r = geocentric.position
v = geocentric.velocity
print('Breakup state vector', r, v)
print('Satnum:          ', satellite.model.satnum)
print('Epoch year:      ', satellite.model.epochyr
      )  # Full four-digit year of this element set’s epoch moment.
print('Epoch days:      ', satellite.model.epochdays
      )  # Fractional days into the year of the epoch moment.
print('JD sat epoch:    ', satellite.model.jdsatepoch)
print('NDot:            ', satellite.model.ndot)
print('NDDot:           ', satellite.model.nddot)
print('BStar:           ', satellite.model.bstar
      )  # Ballistic drag coefficient B* in inverse earth radii.
print('Inclination:     ', satellite.model.inclo)  # Inclination in radians.
print('Right Ascension: ',
Esempio n. 26
0
    import time

    line1 = "1 47856U 21020C   21331.00000000 -.00000072  00000-0  30707-4 0  9998"
    line2 = "2 47856  63.4086 209.7279 0025693 342.6358  17.3780 13.45215752 34829"

    inclination = 63.4086
    raan = 209.7279
    eccentricity = 0.0025693
    AoP = 342.6358
    mean_anomaly = 17.3780
    n_mean_motion_perday = 13.45215752

    epoch = 21331.00000000  #2021-11-27T00:00:00

    observing_time = Time("2021-11-27T00:00:00", format="isot", scale="utc")
    ts = load.timescale()
    t = ts.from_astropy(observing_time)
    satellite = EarthSatellite(line1, line2, 'TEST', ts)
    R1 = satellite.at(t).position.km
    print(R1, np.linalg.norm(R1))

    oe = orbital_parameters()
    oe.get_statevector_from_orbital_elemts(inclination, raan, eccentricity,
                                           AoP, mean_anomaly,
                                           n_mean_motion_perday)

    R2 = oe.R
    V2 = oe.V

    print(R2, np.linalg.norm(R2))
    print(np.linalg.norm(R2 - R1))
records = cursor.fetchall()

while True:
    ts = load.timescale()
    t = ts.now()

    time = datetime.utcnow()
    jd, fr = jday(time.year, time.month, time.day, time.hour, time.minute,
                  time.second)

    for row in records:
        id = row[0]
        name = row[1]
        line1, line2 = row[2].splitlines()
        satellite = EarthSatellite(line1, line2, name, ts)
        geocentric = satellite.at(t)
        subpoint = geocentric.subpoint()
        # Latitude and Longitude in degrees
        latitude = subpoint.latitude.degrees
        longitude = subpoint.longitude.degrees
        # Elevation in meters
        elevation = int(subpoint.elevation.m)
        sat = Satrec.twoline2rv(line1, line2)
        # e  Non zero error code if the satellite position could not be computed
        e, r, v = sat.sgp4(jd, fr)
        # rx, ry,rz   satellite position in kilometers
        rx, ry, rz = r
        # vx, vy,vz  satelite velocity in km/s
        vx, vy, vz = v
        # Velocity km/s
        velocity = math.sqrt(vx**2 + vy**2 + vz**2)
Esempio n. 28
0
def main(args):
    ### create large wcs
    hdu_metafits = fits.open(str(args.obs) + ".metafits")
    pointing_ra = float(hdu_metafits[0].header["RA"])
    pointing_dec = float(hdu_metafits[0].header["DEC"])
    big_wcs = WCS(naxis=2)
    big_wcs.wcs.ctype = ['RA---SIN','DEC--SIN']
    big_wcs.wcs.crval = [pointing_ra, pointing_dec]
    big_wcs.wcs.crpix = [701.0, 701.0]
    big_wcs.wcs.cdelt = [-0.0833333333333333, 0.0833333333333333]
  
    ## make timeSteps by reading csv file
    
    timeSteps = np.arange(args.t1, args.t2 + 1)

    font = {'family' : 'normal','size'   : 1}
    hfont = {'fontname':'Helvetica', 'size':15, 'color': "white"}
    if debug:
        print("the selected timeSteps are " + str(timeSteps))

    line1, line2, line3 = obtainTLE(args.noradid)
    ts = load.timescale(builtin=True)
    sat = EarthSatellite(line2, line3, line1, ts)
    mwa = Topos("26.701276778 S", "116.670846137 E", elevation_m= 377.827)
    trackGlobalData = np.zeros((imgSize, imgSize))
    fullSkyGlobalData = np.zeros((1400, 1400))
    sat_x_array, sat_y_array = [], []
    for t in timeSteps:
        hdu = fits.open(args.prefix + "SigmaRFIBinaryMapSeed-t" + str(t).zfill(4) + ".fits")
        wcs = WCS(hdu[0].header, naxis=2)
        time = datetime.strptime(hdu[0].header['DATE-OBS'], '%Y-%m-%dT%H:%M:%S.%f')
        ts_time = ts.utc(time.year, time.month, time.day, time.hour, time.minute, time.second + time.microsecond/1000000)
        ### determine satellite position
        sat.at(ts_time)
        difference = sat - mwa
        topocentric = difference.at(ts_time)
        ra, dec, distance = topocentric.radec()
        ra = np.degrees(ra.radians)
        dec = np.degrees(dec.radians)
        sat_x, sat_y = big_wcs.all_world2pix(np.array([[ra], [dec]]).T, 1).T
        sat_x_array.append(sat_x)
        sat_y_array.append(sat_y)



    for t in tqdm(timeSteps):
        if debug:
            print("plotting data for timeStep {}".format(t))

        hdu = fits.open(args.prefix + "SigmaRFIBinaryMapSeed-t" + str(t).zfill(4) + ".fits")
        data = hdu[0].data
        wcs = WCS(hdu[0].header, naxis=2)
        time = datetime.strptime(hdu[0].header['DATE-OBS'], '%Y-%m-%dT%H:%M:%S.%f')
        ts_time = ts.utc(time.year, time.month, time.day, time.hour, time.minute, time.second + time.microsecond/1000000)
        ## determine satellite position
        #sat.at(ts_time)
        #difference = sat - mwa
        #topocentric = difference.at(ts_time)
        #ra, dec, distance = topocentric.radec()
        #ra = np.degrees(ra.radians)
        #dec = np.degrees(dec.radians)
        #sat_x, sat_y = big_wcs.all_world2pix(np.array([[ra], [dec]]).T, 1).T
        #sat_x_array.append(sat_x)
        #sat_y_array.append(sat_y)
        
     
        trackGlobalData += hdu[0].data
        wcs = WCS(hdu[0].header, naxis=2)
        fig = plt.figure(figsize = (10,5))
        st = fig.suptitle("UTC {}".format(time), fontsize="x-large")

        ax = plt.subplot(1,2,1, projection=wcs)

        plt.imshow(data, origin="lower",vmax=1,vmin=-1,cmap=plt.cm.seismic)
        plt.xlabel("RA", **hfont)
        plt.ylabel("DEC", **hfont)
        plt.grid(color="black",linestyle="dotted")

        ax = plt.subplot(1,2,2, projection=big_wcs)
        ## translate points from local fov to sky
        points = np.array(np.where(data > 0)).T
        #print(points)
        row_points, col_points = points.T
        #print(np.array([col_points, row_points]).T)
        points = np.array([col_points, row_points]).T
        
        world = wcs.wcs_pix2world(points, 0)
        px, py = big_wcs.wcs_world2pix(world,0 ).T
        for x, y in zip(px, py):
            fullSkyGlobalData[int(y), int(x)] = 1
        
        

   
        plt.imshow(fullSkyGlobalData, origin="lower", vmax=1, vmin=-1, cmap=plt.cm.seismic)
        scatter_row, scatter_col = np.where(fullSkyGlobalData == 1)
        plt.scatter(scatter_col, scatter_row, marker=".", color="red", s=1)
        plt.xlabel("RA")
        plt.ylabel("DEC")
        ### plot fov
        pixcrd = np.array([[0, 0], [0, 199], [199, 0], [199, 199]], dtype=np.float64)
        world = wcs.wcs_pix2world(pixcrd, 0)

        x, y = big_wcs.wcs_world2pix(world, 0).T
       
        #print(borders)
        plt.scatter(sat_x_array, sat_y_array, marker=".",color="green",alpha=0.8, s=0.5)
        plt.scatter(x, y, marker="x", c ="black")
        plt.grid(color="black",linestyle="dotted")
        plt.savefig("timeLapseObs" + str(args.obs)+ "norad" + str(args.noradid) + "t" + str(t).zfill(4) + ".png")