Beispiel #1
0
    def test_bad_second_line(self):
        with self.assertRaisesRegexp(ValueError, re.escape("""TLE format error

The Two-Line Element (TLE) format was designed for punch cards, and so
is very strict about the position of every period, space, and digit.
Your line does not quite match.  Here is the official format for line 2
with an N where each digit should go, followed by the line you provided:

2 NNNNN NNN.NNNN NNN.NNNN NNNNNNN NNN.NNNN NNN.NNNN NN.NNNNNNNNNNNNNN
2 00005 34 .268234 8.7242 1859667 331.7664  19.3264 10.82419157413667""")):
            io.twoline2rv(good1, good2.replace(' 34', '34 '), wgs72)
Beispiel #2
0
    def test_bad_first_line(self):
        with self.assertRaisesRegexp(ValueError, re.escape("""TLE format error

The Two-Line Element (TLE) format was designed for punch cards, and so
is very strict about the position of every period, space, and digit.
Your line does not quite match.  Here is the official format for line 1
with an N where each digit should go, followed by the line you provided:

1 NNNNNC NNNNNAAA NNNNN.NNNNNNNN +.NNNNNNNN +NNNNN-N +NNNNN-N N NNNNN
1 00005U 58002B   00179.78495062  .000000234 00000-0  28098-4 0  4753""")):
            io.twoline2rv(good1.replace('23 ', '234'), good2, wgs72)
    def propagate(self, date_from, date_to, sample=300):
        '''Предсказывает положение спутника в заданный промежуток времени и с
        заданной периодичностью

        @param: date_from Дата начала расчета.

        @param: date_to Дата окончания расчета.

        @param: sample Период вычислений в секундах (по умолчанию: 300 сек).

        '''

        assert (date_from >= self.epoch), 'Дата начала расчета произошла раньше эпохи'
        assert (date_to > date_from), 'Дата окончания произошла раньше даты начала'

        line1, line2 = self.to_tle().split('\n')[1:]
        satmodel = twoline2rv(line1, line2, wgs84)

        ts_locations = []
        for sec in range(0, int((date_to-date_from).total_seconds()), sample):
            ts_locations.append(
                tuple([sec] +
                      [1000*x for x in satmodel.propagate(*tuple((
                          date_from +
                          timedelta(seconds=sec)).timetuple()[:-3]))[0]]))

        return ts_locations
def main():
    lines = open('../sat23839.txt','r').read().splitlines()

    satellite = twoline2rv(lines[7], lines[8], wgs72)

    times = []
    report = csv.DictReader(open('atsb-report.csv', 'r'))
    for r in report:
	time = r['Time']
	hours = int(time[0:2])
	minutes = int(time[3:5])
	seconds = int(time[6:8])
	day = 7 if (hours > 12) else 8
        times.append([2014, 3, day, hours, minutes, seconds])

    w = csv.writer(open('sgp4-positions.csv', 'w'), lineterminator='\n')
    w.writerow(['x', 'y','z', 'dx','dy', 'dz'])

    for time in times:
	position, velocity = satellite.propagate(*time)

	jd = julian_date(*time)
	velocity = numpy.asarray(velocity) * 24.0 * 60.0 * 60.0
	p,v = TEME_to_ITRF(jd, position, velocity.tolist())
	v = v / (24.0 * 60.0 * 60.0)
	p = ["%0.1f" % i for i in p]
	v = ["%0.5f" % i for i in v]
	w.writerow([ p[0],p[1],p[2],v[0],v[1],v[2] ])
def state_satellite(dateTime,tle):
    year, month, day, hour, minute, second = dateTime
    #ISS
    #line1 = ('1 25544U 98067A   08264.51782528  .00002182  00000-0 -11606-4 0  2927')
    #line2 = ('2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537')
    
    #line1 = ('1 00005U 58002B   00179.78495062  .00000023  00000-0  28098-4 0  4753')
    #line2 = ('2 00005  34.2682 348.7242 1859667 331.7664  19.3264 10.82419157413667')
    
    # similar to hiakasat orbit
    #line1 = ('1 39143U 13016B   13112.53874487 -.00003669  11601-4  00000+0 0    49')
    #line2 = ('2 39143 091.6094 306.9444 0018244 348.7202  11.3600 16.10627010   119')
    
    #2 39143  91.6094 306.9444 0018244 348.7202  11.3600 16.10627010   119  
    #2 25544  51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537
      
    satellite = twoline2rv(tle.line1, tle.line2, wgs72)
    
    #position and velocity are given in ECI True Equator Mean Equinox (TEME) frame
    position, velocity = satellite.propagate(year, month, day, hour, minute, second)
    
    # convert TEME to a standard frame, 
    # suggestion: rotate to Pseudo Earth Fixed (PEF) using 
    # Greenwich Mean Sideral Time (GMST) and then rotate to other standard frame
    # reference: http://www.centerforspace.com/downloads/files/pubs/AIAA-2008-6770.pdf Appendix B
    return position, velocity
def api_calculate():
    if request.headers['Content-Type'] == 'application/json':
    	satellite = twoline2rv(request.json['line1'], request.json['line2'], wgs72)
    	result = satellite.propagate(request.json['year'], request.json['month'], request.json['day'], request.json['hour'], request.json['minute'], request.json['second'])
        return jsonify(position=result[0],velocity=result[1]);
    else:
        return "415 Unsupported Media Type ;)"
 def Position_and_Velocity(self, time):
   '''This function generates the barycentric position and velocity of
   the orbital body at a specified time with the use of the
   SGP4 propogator.'''
   #The time to find the position and velocity at
   t = time
   #The first line of the orbital body's TLE
   line1 = self.TLE_line1
   #The second line of the orbital body's TLE
   line2 = self.TLE_line2
   #Fictitiously instantiate a SGP4 satellite object
   sat = twoline2rv(line1, line2, gravity_constant)
   #Convert Julian date to conventional
   time_conv = invjday(time)
   #Compute the geocentric position and velocity of the orbital body
   p, v = sat.propagate(*time_conv)
   #Turn the tuples into arrays
   p = np.asarray(p)
   v = np.asarray(v)
   #Convert km to m
   p = p * 1e3
   #Convert km/s to m/s
   v = v * 1e3
   #Compute the barycentric position and velocity of the attracting body
   P, V = self.attracting_body.Position_and_Velocity(time)
   #Compute the barycentric position of the orbital body
   p = p + P
   #compute the barycentric velocity of the orbital body
   v = v + V
   return p, v
Beispiel #8
0
def generate_test_output(whichconst):
    """Generate lines like those in the test file tcppver.out.

    This iterates through the satellites in "SGP4-VER.TLE", which are
    each supplemented with a time start/stop/step over which we are
    supposed to print results.

    """
    whichconst = wgs72
    tlepath = os.path.join(thisdir, 'SGP4-VER.TLE')
    with open(tlepath) as tlefile:
        tlelines = iter(tlefile.readlines())

    for line1 in tlelines:

        if not line1.startswith('1'):
            continue

        line2 = next(tlelines)
        satrec = twoline2rv(line1, line2, whichconst)

        yield '%ld xx\n' % (satrec.satnum,)

        for line in generate_satellite_output(satrec, line2):
            yield line
Beispiel #9
0
 def __init__(self, lines, earth):
     sat = twoline2rv(*lines[-2:], whichconst=wgs72)
     self._sgp4_satellite = sat
     self._earth = earth
     # TODO: Drat. Where should this Timescale come from?
     # Should they have to pass it in?
     self.epoch = Timescale().utc((sat.epochyr, 1, sat.epochdays))
Beispiel #10
0
def main():
    lines = open('../sat23839.txt','r').read().splitlines()

    satellite = twoline2rv(lines[7], lines[8], wgs72)

    times = []
    report = csv.DictReader(open('../inmarsat-su-log-redacted.csv', 'r'))
    for r in report:
        if r['Frequency Offset (Hz)'] != '':
            t = datetime.datetime.now().strptime(r['Time'],"%d/%m/%Y %H:%M:%S.%f")
            times.append(t)

    w = csv.writer(open('python.csv', 'w'), lineterminator='\n')
    w.writerow(['Time','x', 'y','z', 'dx','dy', 'dz'])

    for t in times:
        time = [t.year, t.month, t.day, t.hour, t.minute, t.second]
	position, velocity = satellite.propagate(*time)

	jd = julian_date(*time)
	velocity = numpy.asarray(velocity) * 24.0 * 60.0 * 60.0
	p,v = TEME_to_ITRF(jd, position, velocity.tolist())
	v = v / (24.0 * 60.0 * 60.0)
#	p = ["%0.1f" % i for i in p]
#	v = ["%0.5f" % i for i in v]
	w.writerow([ t,p[0],p[1],p[2],v[0],v[1],v[2] ])
Beispiel #11
0
 def __init__(self, lines, earth):
     sat = twoline2rv(*lines[-2:], whichconst=wgs72)
     self._sgp4_satellite = sat
     self._earth = earth
     if EarthSatellite.timescale is None:
         from skyfield import api
         EarthSatellite.timescale = api.load.timescale()
     self.epoch = EarthSatellite.timescale.utc(sat.epochyr, 1, sat.epochdays)
Beispiel #12
0
    def _getPositionX(self, date):
        """
        experimental: uses sgp4 library
        
        NOTE: returns TEME coordinates (true equator mean equinox)

        :param datetime date:
        :rtype: GCRSCoordinates
        """
        from sgp4.earth_gravity import wgs72
        from sgp4.io import twoline2rv
        from sgp4.ext import jday

        jdate = jday(date.year, date.month, date.day, date.hour, date.minute, date.second)

        tleCount = len(self.tles) // 2
        lo = 0
        hi = tleCount
        while lo < hi: # equals bisect.bisect_left
            mid = (lo+hi)//2
            tle = twoline2rv(self.tles[mid*2], self.tles[mid*2 + 1], wgs72)
            if tle.jdsatepoch < jdate:
                lo = mid+1
            else:
                hi = mid
        
        tleIdx = lo-1 # equals find_lt (rightmost TLE with epoch less than given date)
        tle = twoline2rv(self.tles[tleIdx*2], self.tles[tleIdx*2 + 1], wgs72)

        if tle.jdsatepoch > jdate:
            raise Exception("The epoch of the earliest available TLE is AFTER the requested date. " +
                            "Are you missing historic TLE data?")
        
        if (jdate - tle.jdsatepoch > 10*ephem.hour):
            warnings.warn('closest TLE epoch is ' + str((date - tle.jdsatepoch)*24) + 'h away from photo time')
        
        position, _ = tle.propagate(date.year, date.month, date.day, date.hour, date.minute, date.second)

        x,y,z = units.km.to(units.pc, position)
        
        # FIXME this is wrong, conversion TEME-J2000 is missing
        # -> need skyfield library for that, but too heavy currently
        #   see https://github.com/brandon-rhodes/python-skyfield/issues/31
        return np.array([x,y,z]) 
def UpdateTLE():
    
    #Solo me traigo el tle si hace un dia que no me lo traigo
    
    try:
        param = Parameter.objects.get(_Key="LastTLEDownload")
    except Parameter.DoesNotExist:
        param = None
        
    if param==None:
        param = Parameter()
        param._Key = "LastTLEDownload"
        param._Value = (datetime.utcnow() - timedelta(days=1)).strftime("%B %d, %Y")
        param._Module = "OrbitDynamic"
        param.save()
        
    
    
    lastTLEDownload = datetime.strptime(param._Value, "%B %d, %Y")
    dg = lastTLEDownload.date()
    da = datetime.utcnow().date()
    if dg<da: 
        print("Actualizando TLE...")
            
        
        loginURL = Parameter.objects.get(_Key="NoradLoginURL")
        username = Parameter.objects.get(_Key="NoradUserName")
        password = Parameter.objects.get(_Key="NoradPassword")   
        
        data = {'identity': username._Value , 'password': password._Value}
        
        
        s = session()
        rp = s.post(loginURL._Value, data)
        
        satellites = list(Satellite.objects.all()) 
        
        for sat  in satellites:
            fquery = "https://www.space-track.org/basicspacedata/query/class/tle_latest/ORDINAL/1/NORAD_CAT_ID/" + str(sat._noradId) + "/orderby/TLE_LINE1 ASC/format/tle"
            # print(s.cookies)
            rg = s.get(fquery)
            
            
            TLE = rg.text.split("\n")
            sgp4sat = twoline2rv(TLE[0], TLE[1], wgs72)  # es un objeto de clase (satelite)
            
            
            tle = Tle()
            tle._satellite = sat
            tle._datetime = datetime.utcnow()
            tle._tleDateTime = sgp4sat.epoch
            tle._tle = rg.text
            print("Salvando TLE")
            tle.save()
            param._Value = (datetime.utcnow()).strftime("%B %d, %Y")
            param.save()
Beispiel #14
0
 def init(self,*args,**kwargs):
     super(KeplerOrbit,self).init(*args,**kwargs)
     
     line0,line1,line2 = kwargs.get("tle").split("\n")
     
     name = self._data_graph.node[("name",)]["obj"]
     name.value = line0
     
     body = self._data_graph.node[("body",)]["obj"]
     self.value = twoline2rv(line1,line2,body.gravity)
Beispiel #15
0
def geojson():
    # Test TLE for Hubble Space Telescope
    line1 = ('1 20580U 90037B   14101.16170949  '
             '.00002879  00000-0  18535-3 0  4781')
    line2 = ('2 20580 028.4694 117.6639 0002957 '
             '290.9180 143.6730 15.05140277114603')

    satellite = twoline2rv(line1, line2, wgs72)

    date = datetime(2000, 6, 29, 12, 46, 19)

    delta = timedelta(minutes=1)

# empty array for GeoJSON LineString for groundtrack plotting
    points = []

# Loop in one-minute steps to calculate track
    for n in range(0, 90):

    #print date

        position, velocity = satellite.propagate(date.year, date.month, date.day,
                                                 date.hour, date.minute, date.second)

    #print position

    #print velocity

        lat, gmra, alt = groundtrack(position)

    #print str(lat)
    #print str(gmra)
    #print str(alt)

        gmst = utcDatetime2gmst(date)

    #print gmst

        lon = (gmst * 15.0) - gmra

        lon = ((lon + 180.0) % 360.0) - 180.0

    #print lon

        # add current point coordinates to GeoJSON LineString array

        points.append([lon, lat])

        date = date+delta

    # Generate GeoJSON LineString for groundtrack
    line = {"type": "LineString", "coordinates": points}

    # Bottle function returns dict as JSON
    return line
Beispiel #16
0
    def __init__(self, line1, line2, name=None, ts=None):
        ts = ts or _ts

        self.name = None if name is None else name.strip()
        sat = twoline2rv(line1, line2, whichconst=wgs72)
        self.model = sat
        self.epoch = ts.utc(sat.epochyr, 1, sat.epochdays)

        self.target = object()  # TODO: make this more interesting
        self.target_name = 'Satellite{0} {1}'.format(
            self.model.satnum,
            ' ' + repr(self.name) if self.name else '',
        )
Beispiel #17
0
def L_para(T_E):
    
    L1 = parser.get('mission_parameters', 'TLE_Line1')
    L2 = parser.get('mission_parameters', 'TLE_Line2')
    satellite = twoline2rv(L1, L2, wgs72)
    position, velocity = satellite.propagate(T_E[0],T_E[1],T_E[2],T_E[3],T_E[4],T_E[5])  
    Re= [(x/6371.2) for x in position] 
    spaco = spc.Coords(Re, 'GEI', 'car')
    spaco.ticks=spt.Ticktock([T_E[6]], 'ISO')
    q=[90]
#    q=spaco.convert('SM','sph') #default value of 90 is used as it returns the most data-points, other values of q have more instances when the value returned is NaN
#    q=q.data[0][1]
    L=ir.get_Lm(spaco.ticks,spaco,q,extMag='T01STORM',intMag='IGRF')
    return satellite.alta*6371,satellite.altp*6371,math.degrees(satellite.inclo),L.items()[2][1][0][0]
def test_december_32():
    # ISS [Orbit 606], whose date is 2019 plus 366.82137887 days.
    # The core SGP4 routines handled this fine, but my hamfisted
    # attempt to provide a Python datetime for "convenience" ran
    # into an overflow.
    sat = io.twoline2rv(
        '1 25544U 98067A   19366.82137887  .00016717  00000-0  10270-3 0  9129',
        '2 25544  51.6392  96.6358 0005156  88.7140 271.4601 15.49497216  6061',
        wgs72,
    )
    assertEqual(
        dt.datetime(2020, 1, 1, 19, 42, 47, 134367),
        sat.epoch,
    )
Beispiel #19
0
    def twoline2rv(cls, line1, line2, whichconst=WGS72):
        whichconst = gravity_constants[whichconst]
        self = cls()
        twoline2rv(line1, line2, whichconst, 'i', self)

        # Expose the same attribute types as the C++ code.
        self.ephtype = int(self.ephtype.strip() or '0')
        self.revnum = int(self.revnum)

        # Install a fancy split JD of the kind the C++ natively supports.
        # We rebuild it from the TLE year and day to maintain precision.
        year = self.epochyr
        days, fraction = divmod(self.epochdays, 1.0)
        self.jdsatepoch = year * 365 + (year - 1) // 4 + days + 1721044.5
        self.jdsatepochF = round(fraction, 8)  # exact number of digits in TLE

        # Remove the legacy datetime "epoch", which is not provided by
        # the C++ version of the object.
        del self.epoch

        # Undo my non-standard 4-digit year
        self.epochyr %= 100
        return self
Beispiel #20
0
    def _createSatByID(self, identifier, file=None):
        ''' creates a satellite by its ID
            code provided by david vallado (twoline2rv) '''

        n, l1, l2 = getSatTLE(identifier, file)

        if (l1 == None):
            # If no TLE with that ID is found
            self._successID = False
            return None
        else:
            sat = sgp4_io.twoline2rv(l1, l2, sgp4_earth_gravity.wgs72)
            sat.satname = n
        return sat
Beispiel #21
0
def TLE_propagation_TEME(line1, line2, jd_ut1, wgs='72'):
    '''Convert Two-line element to TEME coordinates at a specific Julian date.
    
    :param str line1: TLE line 1
    :param str line2: TLE line 2
    :param float/numpy.ndarray jd_ut1: Julian Date UT1 to propagate TLE to.
    :param str wgs: The used WGS standard, options are :code:`'72'` or :code:`'84'`.

    :return: (6,len(jd_ut1)) numpy.ndarray of Cartesian states [SI units]
    '''

    if wgs == '72':
        from sgp4.earth_gravity import wgs72 as wgs_sys
    elif wgs == '84':
        from sgp4.earth_gravity import wgs84 as wgs_sys
    else:
        raise Exception('WGS standard "{}" not recognized.'.format(wgs))

    satellite = twoline2rv(line1, line2, wgs_sys)

    if isinstance(jd_ut1, np.ndarray):
        if len(jd_ut1.shape) > 1:
            raise Exception(
                'Only 1-D date array allowed: jd_ut1.shape = {}'.format(
                    jd_ut1.shape))
    else:
        if isinstance(jd_ut1, float):
            jd_ut1 = np.array([jd_ut1], dtype=np.float)

    states = np.empty((6, jd_ut1.size), dtype=np.float)

    for jdi in range(jd_ut1.size):
        year, month, day, hour, minute, second, usec = dpt.npdt2date(
            dpt.mjd2npdt(dpt.jd_to_mjd(jd_ut1[jdi])))

        position, velocity = satellite.propagate(
            year=year,
            month=month,
            day=day,
            hour=hour,
            minute=minute,
            second=second + usec * 1e-6,
        )

        state = np.array(position + velocity, dtype=np.float)
        state *= 1e3  #km to m

        states[:, jdi] = state

    return states
Beispiel #22
0
def test_tle_export():
    """Check `export_tle()` round-trip using all the TLEs in the test file.

    This iterates through the satellites in "SGP4-VER.TLE",
    generates `Satrec` objects and exports the TLEs.  These exported
    TLEs are then compared to the original TLE, closing the loop (or
    the round-trip).

    """
    data = get_data(__name__, 'SGP4-VER.TLE')
    tle_lines = iter(data.decode('ascii').splitlines())

    # Skip these lines, known errors
    # Resulting TLEs are equivalent (same values in the Satrec object), but they are not the same
    # 25954: BSTAR = 0 results in a negative exp, not positive
    # 29141: BSTAR = 0.13519 results in a negative exp, not positive
    # 33333: Checksum error as expected on both lines
    # 33334: Checksum error as expected on line 1
    # 33335: Checksum error as expected on line 1
    expected_errs_line1 = set([25954, 29141, 33333, 33334, 33335])
    expected_errs_line2 = set([33333, 33335])

    if accelerated:
        # Non-standard: omits the ephemeris type integer.
        expected_errs_line1.add(11801)

    for line1 in tle_lines:

        if not line1.startswith('1'):
            continue

        line2 = next(tle_lines)

        # trim lines to normal TLE string size
        line1 = line1[:69]
        line2 = line2[:69]
        satrec = Satrec.twoline2rv(line1, line2)
        satrec_old = io.twoline2rv(line1, line2, wgs72)

        # Generate TLE from satrec
        out_line1, out_line2 = export_tle(satrec)
        out_line1_old, out_line2_old = export_tle(satrec_old)

        if satrec.satnum not in expected_errs_line1:
            assertEqual(out_line1, line1)
            assertEqual(out_line1_old, line1)
        if satrec.satnum not in expected_errs_line2:
            assertEqual(out_line2, line2)
            assertEqual(out_line2_old, line2)
Beispiel #23
0
    def calc(self):

        line1 = ('1 00005U 58002B   00179.78495062  '
                 '.00000023  00000-0  28098-4 0  4753')
        line2 = ('2 00005  34.2682 348.7242 1859667 '
                 '331.7664  19.3264 10.82419157413667')

        satellite = twoline2rv(line1, line2, wgs84)
        position, velocity = satellite.propagate(2000, 6, 29, 12, 50, 19)

        print(satellite.error)  # nonzero on error 0
        print(satellite.error_message)  # None
        print(position)
        #print('5576.056952..., -3999.371134..., -1521.957159...')
        print(velocity)
Beispiel #24
0
def read_tles(tles: str, rgbs):
    raw_tle = []
    sats = []

    i = 1
    for line in tles.splitlines():
        raw_tle.append(line)

        if i % 3 == 0:
            tle_object = twoline2rv(raw_tle[1], raw_tle[2], wgs72)
            sats.append(Satellite(raw_tle, tle_object, rgbs.get_next_color()))
            raw_tle = []
        i += 1

    return sats
Beispiel #25
0
    def __init__(self, lines):
        self.name = None if len(lines) < 3 else lines[0].strip()
        sat = twoline2rv(*lines[-2:], whichconst=wgs72)
        self._sgp4_satellite = sat
        if EarthSatellite.timescale is None:
            from skyfield import api
            EarthSatellite.timescale = api.load.timescale()
        self.epoch = EarthSatellite.timescale.utc(sat.epochyr, 1,
                                                  sat.epochdays)

        self.target = object()  # TODO: make this more interesting
        self.target_name = 'Satellite{0} {1}'.format(
            self._sgp4_satellite.satnum,
            ' ' + repr(self.name) if self.name else '',
        )
def envicosmos(tle1,tle2):
    whichconst = 'wgs72'
    #whichconst = wgs72

    f1=open(tle1+'.tle')
    f2=open(tle2+'.tle')
    out1=open('envi.sal','w+')
    out2=open('cosmos.sal','w+')

    archivos=[f1,f2]
    

    var=0
    for tlefile in archivos:
        var = var + 1
        tlelines = iter(tlefile.readlines())
        for line1 in tlelines:
            if not line1.startswith('1'):
                continue 
            line2 = next(tlelines) 
            satrec = twoline2rv(line1, line2, whichconst) # es un objeto de clase (satelite)
            mu = satrec.whichconst.mu
            epocatle=satrec.jdsatepoch
            print 'epoca del tle [jd] = ', epocatle
            jdini=jday(2008,1,9,18,0,0.0) 
            tini=(jdini-epocatle)*1440.0
            print(tini)
            tintervalo=np.arange(0,7200,1) 
            for t1 in tintervalo:
                t=tini+t1/60.0 
                r, v = sgp4(satrec, t)
                tjd=epocatle+t/1440.0 # dia juliano correspondiente al t en min.

            
                """Impresion de salida"""
                year, mon, day, hr, minute, sec = invjday(tjd)
                fecha = str(year)+'/'+str(mon)+'/'+str(day)+' '+str(hr)+':'+\
                    str(minute)+':'+str(sec)+' '+str(tjd)+' '+str(r[0])+' '+\
                    str(r[1])+' '+str(r[2])+' '+str(v[0])+' '+\
                    str(v[1])+' '+str(v[2])+'\n'
                if var == 1: 
                    out1.write(fecha)
                else:
                    out2.write(fecha)

#    year2,mon2,day2,hr2,minu2,sec2=invjday(2454475.29201)
#    print year2,mon2,day2,hr2,minu2,sec2
        """
Beispiel #27
0
def states_to_lightcurve(times, states, pass_obj, quats=False):

    lightcurve = []
    spacecraft = twoline2rv(pass_obj['TLE'][0], pass_obj['TLE'][1], wgs84)
    telescope_ecef = AF.lla_to_ecef(LAT, LON, ALT, geodetic=True)
    utc0 = pass_obj['EPOCH']

    for time, state in zip(times, states):

        now = utc0 + datetime.timedelta(seconds=time)

        sun_vec = AF.vect_earth_to_sun(now)

        sc_eci, _ = spacecraft.propagate(now.year, now.month, now.day,
                                         now.hour, now.minute, now.second)
        sc_eci = asarray(sc_eci)

        # if AF.shadow(sc_eci,sun_vec):
        #     #if the spacecraft is in shadow its brightness is zero
        #     print("IN SHADOW")
        #     lightcurve.append(0)
        #     continue

        lst = AF.local_sidereal_time(now, LON)

        telescope_eci = AF.Cz(lst) @ telescope_ecef
        obs_vec = telescope_eci - sc_eci

        if quats:
            eta = state[0]
            eps = state[1:4]
            dcm_body2eci = R.from_quat(hstack([eps, eta])).as_dcm().T
        else:
            eulers = state[:3]
            dcm_body2eci = R.from_euler(ROTATION, eulers).as_dcm().T

        power = 0
        for facet, area in zip(FACETS, AREAS):
            normal = dcm_body2eci @ facet

            if dot(normal, sun_vec) > 0 and dot(normal, obs_vec) > 0:
                power += phong_brdf(obs_vec, sun_vec, normal, area)

        lightcurve.append(power)

    lightcurve = hstack(lightcurve)

    return lightcurve
Beispiel #28
0
def L_para(T_E):

    L1 = parser.get('mission_parameters', 'TLE_Line1')
    L2 = parser.get('mission_parameters', 'TLE_Line2')
    satellite = twoline2rv(L1, L2, wgs72)
    position, velocity = satellite.propagate(T_E[0], T_E[1], T_E[2], T_E[3],
                                             T_E[4], T_E[5])
    Re = [(x / 6371.2) for x in position]
    spaco = spc.Coords(Re, 'GEI', 'car')
    spaco.ticks = spt.Ticktock([T_E[6]], 'ISO')
    q = [90]
    #    q=spaco.convert('SM','sph') #default value of 90 is used as it returns the most data-points, other values of q have more instances when the value returned is NaN
    #    q=q.data[0][1]
    L = ir.get_Lm(spaco.ticks, spaco, q, extMag='T01STORM', intMag='IGRF')
    return satellite.alta * 6371, satellite.altp * 6371, math.degrees(
        satellite.inclo), L.items()[2][1][0][0]
Beispiel #29
0
def read_tles(tle_file_name, rgbs):
    tle_src = open(tle_file_name, 'r')
    raw_tle = []
    sats = []

    i = 1
    for line in tle_src:
        raw_tle.append(line)

        if i % 3 == 0:
            tle_object = twoline2rv(raw_tle[1], raw_tle[2], wgs72)
            sats.append(Satellite(raw_tle, tle_object, rgbs.get_next_color()))
            raw_tle = []
        i += 1

    return sats
Beispiel #30
0
    def calc(self):
      
        line1 = ('1 00005U 58002B   00179.78495062  '
                 '.00000023  00000-0  28098-4 0  4753')
        line2 = ('2 00005  34.2682 348.7242 1859667 '
                  '331.7664  19.3264 10.82419157413667')

        satellite = twoline2rv(line1, line2, wgs84)
        position, velocity = satellite.propagate(2000, 6, 29, 12, 50, 19)

        print(satellite.error)    # nonzero on error 0
        print(satellite.error_message) # None
        print(position)
        #print('5576.056952..., -3999.371134..., -1521.957159...')
        print(velocity)
        #print('4.772627..., 5.119817..., 4.275553...')
Beispiel #31
0
    def __init__(self, line1, line2, name=None, ts=None):
        self.name = None if name is None else name.strip()
        sat = twoline2rv(line1, line2, whichconst=wgs72)
        self.model = sat
        if ts is None:
            if EarthSatellite.timescale is None:
                from skyfield.api import load
                EarthSatellite.timescale = load.timescale()
            ts = EarthSatellite.timescale
        self.epoch = ts.utc(sat.epochyr, 1, sat.epochdays)

        self.target = object()  # TODO: make this more interesting
        self.target_name = 'Satellite{0} {1}'.format(
            self.model.satnum,
            ' ' + repr(self.name) if self.name else '',
        )
def tle2eci(l1, l2, year, month, day, hour, minute, secunde):
    """
	Function takes first and second line of tle data and returns
	ECI position (x, y, z) of the satellite at current UTC time.
	For parsing TLE data and getting current location I am using
	spg4 library
	"""
    satellite = twoline2rv(l1, l2, wgs84)
    #a_date = ephem.now()
    #global y, mn, d, h, min, sec
    #(y, mn, d, h, min, sec) = a_date.tuple()
    position, velocity = satellite.propagate(year, month, day, hour, minute,
                                             secunde)
    #print "tle2eci", position
    #print position
    return position
Beispiel #33
0
def get_satellite_orbit(raw_tle, sim_start_time, sim_end_time, czml_file_name):
	sat_name = raw_tle[0]
	tle_sgp4 = twoline2rv(raw_tle[1], raw_tle[2], wgs72)

	sat = Satellite(raw_tle, tle_sgp4, DEFAUlead_times_RGBA)
	doc = create_czml_file(sim_start_time, sim_end_time)
	
	if DEBUGGING:
		print()
		print('Satellite Name: ', sat.satName)
		print('TLE Epoch: ', sat.tleEpoch)
		print('Orbit time in Minutes: ', sat.orbitalTimeInMinutes)	
		print()
	
	sat_packet = create_satellite_packet(sat.sat_name, sat.tle_object, sat.orbital_time_in_minutes, sim_start_time, sim_end_time, sat.rgba)
	doc.packets.append(sat_packet)
	doc.write(czml_file_name)		
Beispiel #34
0
    def orbit(self, orbit):
        """Initialize the propagator

        Args:
            orbit (Orbit)
        """

        self._orbit = orbit
        tle = Tle.from_orbit(orbit)
        lines = tle.text.splitlines()

        if len(lines) == 3:
            _, line1, line2 = lines
        else:
            line1, line2 = lines

        self.tle = twoline2rv(line1, line2, wgs72)
Beispiel #35
0
    def __init__(self,
                 gps_tle_file,
                 rx_sv_list=('PRN 03', 'PRN 09', 'PRN 22', 'PRN 26'),
                 ref_lla=(38.8454167, -104.7215556, 1903.0),
                 ts=1.0):
        """
        Parameters
        ----------
        gps_tle_file : A text file extracted from Celestrak Web Site
        ref_lla : A 3 element tuple of lat(deg), lon(deg), and ele(m)

        Returns
        -------
        None : This is the constructor method

        Notes
        -----
        Default lla is CosmicAES COS office
        """
        self.ref_lla = ref_lla
        self.GPS_TLE_file = gps_tle_file
        self.Rx_sv_list = rx_sv_list
        """
        Perform coordinate conversion
        """
        # convert from llh (or lla) to earth centric fixed
        self.ref_ecef = self.llh2ecef(self.ref_lla)
        """
        Read GPS TLEs into dictionary
        """
        self.GPS_sv_dict = self.get_gps_sv(self.GPS_TLE_file)
        """
        Initialize Four SGP4 satellite objects in tuple satellite 
        """
        self.satellite = []
        for k in range(4):
            PRN = self.Rx_sv_list[k]
            self.satellite.append(
                twoline2rv(self.GPS_sv_dict[PRN][0], self.GPS_sv_dict[PRN][1],
                           wgs84))
        """
        Time offset relative to satellite propagation start time
        """
        self.Ts = ts
        self.t_delta = np.array([0])
        self.N_sim_steps = 0
Beispiel #36
0
    def orbit(self, orbit):
        """Initialize the propagator

        Args:
            orbit (Orbit)
        """

        self._orbit = orbit
        tle = Tle.from_orbit(orbit)
        lines = tle.text.splitlines()

        if len(lines) == 3:
            _, line1, line2 = lines
        else:
            line1, line2 = lines

        self.tle = twoline2rv(line1, line2, wgs72)
Beispiel #37
0
def sgp4_tracs(request, *args, **kw):
    """Sat. orbit tracs by SGP4 module."""
    from sgp4.earth_gravity import wgs84
    from sgp4.io import twoline2rv
    import datetime, math

    tledata = [
        [
            'ISS (ZARYA)',
            '1 25544U 98067A   12138.83290882  .00011789  00000-0  17152-3 0  5727',
            '2 25544  51.6409 274.1861 0010682 328.0828 128.1508 15.56173799773289'
        ],
        [
            'MOLNIYA 1-90',
            '1 24960U 97054A   04104.60038411 -.00000148  00000-0  10000-3 0  8467',
            '2 24960  64.1699 306.8439 7209074 272.6281  14.3196  2.00635799 48072'
        ],
        [
            'COSMOS 158 R/B',
            '1 02802U 67045B   04105.12224913  .00000082  00000-0  32618-4 0  5785',
            '2 02802  74.0096 111.2339 0069038 241.3647 118.0552 14.42132256935013'
        ]
    ]
    utc = list(args)
    for i, arg in enumerate(utc):
        utc[i] = int(arg)
    # loop tledata
    ret = []
    for x in tledata:
        pos = []
        try:
            satellite = twoline2rv(x[1], x[2], wgs84)
            ps = 2.0 * math.pi * 1 / satellite.no * 60.0
            utc1 = utc2 = datetime.datetime(*utc)
            # by 2 mean motion ago
            delta = datetime.timedelta(0, ps)
            step = delta.total_seconds() / 10.0
            while (utc1 - utc2 < delta):
                p, v = satellite.propagate(*utc2.timetuple()[:6])
                utc2 = utc2 - datetime.timedelta(0, step)
                pos += [p]
                break
            ret += [[x[0], pos]]
        except:
            pass
    return HttpResponse(str(ret))
Beispiel #38
0
def main():
    tle_list = []
    with open('data/zarya_tle', 'rb') as tlefile:
        for _ in range(50):
            line1 = tlefile.readline()
            line2 = tlefile.readline()
            tle_list.append((line1, line2))

    x_file.write('dttm,value,label\n')
    y_file.write('dttm,value,label\n')
    z_file.write('dttm,value,label\n')

    prev_sat = None
    prev_tle = None
    prev_date = None

    for tle in tle_list:
        line1, line2 = tle

        # Initialize the satellite propagation model
        satellite = twoline2rv(line1, line2, wgs84)
        date = date_from_jds(satellite.jdsatepoch)

        if prev_tle is None:
            prev_tle = tle
            prev_sat = satellite
            prev_date = date
            continue

        time_delta_minutes = (date - prev_date).total_seconds()/60
        time_delta_half = time_delta_minutes / 2

        # First we catch the previous satellite up to the midway point
        propogate_over_range(prev_sat, prev_date, 0, int(time_delta_half))

        # Then we run the current satellite backwards to th halfway point
        propogate_over_range(satellite, date, -int(time_delta_half), 0)

        prev_tle = tle
        prev_sat = satellite
        prev_date = date

    x_file.close()
    y_file.close()
    z_file.close()
Beispiel #39
0
def get_satellite_orbit(raw_tle, sim_start_time, sim_end_time, czml_file_name):
    'returns orbit of the satellite'
    tle_sgp4 = twoline2rv(raw_tle[1], raw_tle[2], wgs72)

    sat = Satellite(raw_tle, tle_sgp4, DEFAULT_RGBA)
    doc = create_czml_file(sim_start_time, sim_end_time)

    if DEBUGGING:
        print()
        print('Satellite Name: ', sat.get_satellite_name)
        print('TLE Epoch: ', sat.tle_epoch)
        print('Orbit time in Minutes: ', sat.orbital_time_in_minutes)
        print()

    sat_packet = create_satellite_packet(sat, sim_start_time, sim_end_time)
    doc.packets.append(sat_packet)
    with open(czml_file_name, 'w') as file:
        file.write(str(doc))
Beispiel #40
0
def Position_and_Velocity_Satellite(satellite, time):
    # The first line of the TLE
    line1 = satellite.line1
    # The second line
    line2 = satellite.line2
    # Fictitious SGP4 satellite object
    sat = twoline2rv(line1, line2, grav_const)
    # Convert Julian date to conventional
    time_conv = invjday(time)
    # The position and velocity of the satellite
    pv = np.asarray(sat.propagate(*time_conv))
    # Convert km to m and km/s to m/s
    pv = np.multiply(pv, 1e3)
    # The attracting body ephemeris
    PV = satellite.attracting_body.Position_and_Velocity(time)
    # Convert from geocentric to barycentric frame
    pv = np.add(pv, PV)
    return pv
Beispiel #41
0
def test_december_32():
    # ISS [Orbit 606], whose date is 2019 plus 366.82137887 days.
    # The core SGP4 routines handled this fine, but my hamfisted
    # attempt to provide a Python datetime for "convenience" ran
    # into an overflow.
    a = '1 25544U 98067A   19366.82137887  .00016717  00000-0  10270-3 0  9129'
    b = '2 25544  51.6392  96.6358 0005156  88.7140 271.4601 15.49497216  6061'
    correct_epoch = dt.datetime(2020, 1, 1, 19, 42, 47, 134368)

    # Legacy API.
    sat = io.twoline2rv(a, b, wgs72)
    assertEqual(sat.epoch, correct_epoch)

    correct_epoch = correct_epoch.replace(tzinfo=conveniences.UTC)

    # Modern API.
    sat = Satrec.twoline2rv(a, b)
    assertEqual(conveniences.sat_epoch_datetime(sat), correct_epoch)
Beispiel #42
0
def load_tle_data():
    now = datetime.now()
    with open('tle.txt', 'r') as f:
        while True:
            try:
                line1 = f.readline()
                line2 = f.readline()
                debris = twoline2rv(line1, line2, wgs84)
                position, velocity = debris.propagate(now.year, now.month,
                                                      now.day, now.hour + 1)
                d = {
                    'satellite': debris,
                    'position': position,
                    'velocity': velocity
                }
                satellites.append(d)
            except:
                return
Beispiel #43
0
def sgp4_step(line1, line2, mjd, model=wgs84):
    """
    Function: sgp4_step
        Returns position and velocity in ECI from SGP4 propagation.

    Inputs:
        line1:  first line of TLE (string)
        line2:  second line of TLE (string)
        mjd     time to propagate to (mjd)
        model:  Earth gravity model to use (default=wgs84)
    Outputs:
        rECI:   position in ECI
        vECI:   velocity in ECI
    """
    sgp4 = twoline2rv(line1, line2, model)
    dt = julian.from_jd(mjd, fmt='mjd')
    sec = dt.second + dt.microsecond / 1e6
    return sgp4.propagate(dt.year, dt.month, dt.day, dt.hour, dt.minute, sec)
Beispiel #44
0
def TLE_read(sat, TLEfile1in=False):
    norad_id = norad(sat)
    if norad_id == 0: return 0
    if TLEfile1in:
        TLEfile1 = TLEfile1in
    else:
        TLEfile1 = "sarsat.txt"
    with open(TLEfile1) as TLE:
        for line in TLE:
            #print(sats)
            if norad_id in line[2:7]:
                TLEout = []
                if int(line[0]) == 1:
                    TLEout1 = line[:]
                elif int(line[0]) == 2:
                    TLEout2 = line[:]
    if TLEout1 == None: return 0
    satellite = twoline2rv(TLEout1, TLEout2, wgs72)
    return satellite
Beispiel #45
0
 def propagaTLE(self, date=None):
     """
     Devuelve las coordenadas cartesianas x,y,z. !! EN TEME!!
     Si no se introduce una fecha, devuelve las coordenadas correspondientes
     a la fecha y hora del TLE.
     Si se le introduce una fecha y hora, propaga hasta ese momento y devuelve
     las coordenadas de la propagacion. 
     """
     whichconst = wgs84
     satrec = twoline2rv(self.linea1, self.linea2, whichconst)
     if date == None:
         ffin = satrec.epoch
         r, v = satrec.propagate(ffin.year, ffin.month, ffin.day, ffin.hour,
                                 ffin.minute, ffin.second)
     else:
         segundos = date.second + date.microsecond / 1000000.0
         r, v = satrec.propagate(date.year, date.month, date.day, date.hour,
                                 date.minute, segundos)  #date.second
     return r, v
Beispiel #46
0
def get_sat(tle_string):
    '''
    Construct a satellite instance (`sgp4.io.Satellite`) from TLE string.

    Parameters
    ----------
    tle_string : str
        Two-line elements (TLE) as 3-line string

    Returns
    -------
    satname : str
        Name (identifier) of satellite
    satellite : `sgp4.io.Satellite` instance
        Satellite object filled from TLE

    Notes
    -----
    TLE string must be of the form:

    .. code-block:: none

        ISS (ZARYA)
        1 25544U 98067A   13165.59097222  .00004759  00000-0  88814-4 0    47
        2 25544  51.6478 121.2152 0011003  68.5125 263.9959 15.50783143834295
    '''

    try:
        import sgp4
        from sgp4.earth_gravity import wgs72
        from sgp4.io import twoline2rv, Satellite
    except ImportError:
        raise ImportError(
            'The "sgp4" package is necessary to use this function.'
            )

    tle_string_list = tle_string.split('\n')
    satname = tle_string_list[0]
    if satname[0:2] == '0 ':  # remove leading 0 if present
        satname = satname[2:]
    satellite = twoline2rv(tle_string_list[1], tle_string_list[2], wgs72)

    return satname, satellite
Beispiel #47
0
    def test_eci_position_vs_sgp4(self):

        from sgp4.earth_gravity import wgs72
        from sgp4.io import twoline2rv

        sat2 = twoline2rv(self.tle_tup[1], self.tle_tup[2], wgs72)
        pos2, vel2 = sat2.propagate(*self.dt_tup[:-2],
                                    self.dt_tup[-2] + self.dt_tup[-1] / 1e6)

        sat = Satellite(self.tle, self.effbg_observer, self.pydt)
        eci_pos = sat.eci_pos()

        print(eci_pos.loc)
        print(pos2)
        print(eci_pos.vel)
        print(vel2)

        assert_allclose(eci_pos.loc, pos2, atol=1e-2)
        assert_allclose(eci_pos.vel, vel2, atol=1e-5)
Beispiel #48
0
    def createTLE(self, date):
        """
        Creates a new TLE for the received date.

        Parameters
        ----------
        date : datetime
               Date used to obtain the epoch of the TLE.
        """
        rad2deg = 180/pi
        self.updateEpoch(date)
        aux="{:+.9f}".format(self.ndot)
        ndot = "{}{}".format(aux[0],aux[2:-1])
        #aux = "{:+.6f}".format(self.bstar*10000)
        #BSTAR = "{}{}-4".format(aux[0],aux[3:-1])
        aux="{:+.6f}".format(self.B*2.461*10**(-5)*6378.135*0.5*100)
        BSTAR = "{}{}-2".format(aux[0],aux[3:-1])
        aux="{:.8f}".format(self.e)
        e = "{}".format(aux[2:-1])
        tle_num = "{:4d}".format(self.element_number)
        epoch_year = self.epoch_year - 2000
        line1 = "1 {}U {:9}{}{:012.8f} {} +{} {} 0 {}7".format(self.satnumber,
                                                           self.id_launch_data,
                                                           epoch_year,
                                                           self.epoch_day,
                                                           ndot,
                                                           "00000-0",
                                                           BSTAR,
                                                           tle_num)
        line2 = "2 {} {:8.4f} {:8.4f} {} {:8.4f} {:08.4f} {:02.8f}{}7".format(self.satnumber,
                                                             self.incl*rad2deg,
                                                             self.RAAN*rad2deg,
                                                             e,
                                                             self.w*rad2deg,
                                                             self.MA*rad2deg,
                                                             86400/self.getPeriod(),
                                                             "    0")
        checksum1 = self.checksum(line1)
        checksum2 = self.checksum(line2)
        line1 = "{}{}".format(line1[0:-1], checksum1)
        line2 = "{}{}".format(line2[0:-1], checksum2)
        self.sat_model = twoline2rv(line1, line2, wgs72)
        return self.name, line1, line2
Beispiel #49
0
def tle2eci(l1, l2):
    """
	Function takes first and second line of tle data and returns
	ECI position (x, y, z) of the satellite at current UTC time.
	For parsing TLE data and getting current location I am using
	spg4 library
	"""
    satellite = twoline2rv(l1, l2, wgs84)
    ljubljana = timezone('Europe/Ljubljana')
    lj_time = datetime.datetime.now(ljubljana)
    a_date = ephem.Date(lj_time.strftime('%Y/%m/%d %H:%M:%S'))
    #print "Time in Ljubljana: ", a_date

    (year, month, day, hour, minute, secunde) = a_date.tuple()
    position, velocity = satellite.propagate(year, month, day, hour - 2,
                                             minute, secunde)
    #print "ECI position: ", position

    return position
Beispiel #50
0
def TLE_to_TEME(line1, line2, wgs='72'):
    '''Convert Two-line element to TEME coordinates and a Julian date epoch.

    Here it is assumed that the TEME frame uses:
    The Cartesian coordinates produced by the SGP4/SDP4 model have their z
    axis aligned with the true (instantaneous) North pole and the x axis
    aligned with the mean direction of the vernal equinox (accounting for
    precession but not nutation). This actually makes sense since the
    observations are collected from a network of sensors fixed to the
    earth's surface (and referenced to the true equator) but the position
    of the earth in inertial space (relative to the vernal equinox) must
    be estimated.
    
    :param str line1: TLE line 1
    :param str line2: TLE line 2
    :param str wgs: The used WGS standard, options are :code:`'72'` or :code:`'84'`.

    :return: tuple of (6-D numpy.ndarray Cartesian state [SI units], epoch in Julian Date UT1)
    '''

    year, month, day, hour, minute, second, usec = tle_date(line1)

    if wgs == '72':
        from sgp4.earth_gravity import wgs72 as wgs_sys
    elif wgs == '84':
        from sgp4.earth_gravity import wgs84 as wgs_sys
    else:
        raise Exception('WGS standard "{}" not recognized.'.format(wgs))

    satellite = twoline2rv(line1, line2, wgs_sys)
    position, velocity = satellite.propagate(
        year=year,
        month=month,
        day=day,
        hour=hour,
        minute=minute,
        second=second,
    )

    state = np.array(position + velocity, dtype=np.float)
    state *= 1e3  #km to m

    return state, tle_jd(line1)
Beispiel #51
0
def get_sat(tle_string):
    '''
    Construct a satellite instance (`sgp4.io.Satellite`) from TLE string.

    Parameters
    ----------
    tle_string : str
        Two-line elements (TLE) as 3-line string

    Returns
    -------
    satname : str
        Name (identifier) of satellite
    satellite : `sgp4.io.Satellite` instance
        Satellite object filled from TLE

    Notes
    -----
    TLE string must be of the form:

    .. code-block:: none

        ISS (ZARYA)
        1 25544U 98067A   13165.59097222  .00004759  00000-0  88814-4 0    47
        2 25544  51.6478 121.2152 0011003  68.5125 263.9959 15.50783143834295
    '''

    try:
        import sgp4
        from sgp4.earth_gravity import wgs72
        from sgp4.io import twoline2rv, Satellite
    except ImportError:
        raise ImportError(
            'The "sgp4" package is necessary to use this function.')

    tle_string_list = tle_string.split('\n')
    satname = tle_string_list[0]
    if satname[0:2] == '0 ':  # remove leading 0 if present
        satname = satname[2:]
    satellite = twoline2rv(tle_string_list[1], tle_string_list[2], wgs72)

    return satname, satellite
Beispiel #52
0
def get_nustar_location(checktime, line1, line2):
    ''' 
    
    Code to determine the spacecraft location from the TLE.
    
    Inputs are a datetime object and the two lines of the TLE you want to use.
    
    Returns a tuple that has the X, Y, and Z geocentric coordinates (in km).
    
    '''
    
    from sgp4.earth_gravity import wgs72
    from sgp4.io import twoline2rv
    from astropy.coordinates import EarthLocation
    
    satellite = twoline2rv(line1, line2, wgs72)
    position, velocity = satellite.propagate(
        checktime.year, checktime.month, checktime.day,
        checktime.hour, checktime.minute, checktime.second)

    return position
Beispiel #53
0
def sgp4_tracs(request, *args, **kw):
    """Sat. orbit tracs by SGP4 module."""
    from sgp4.earth_gravity import wgs84
    from sgp4.io import twoline2rv
    import datetime, math
    
    tledata = [[ 'ISS (ZARYA)',
                 '1 25544U 98067A   12138.83290882  .00011789  00000-0  17152-3 0  5727',
                 '2 25544  51.6409 274.1861 0010682 328.0828 128.1508 15.56173799773289' ],
               [ 'MOLNIYA 1-90',
                 '1 24960U 97054A   04104.60038411 -.00000148  00000-0  10000-3 0  8467',
                 '2 24960  64.1699 306.8439 7209074 272.6281  14.3196  2.00635799 48072' ],
               [ 'COSMOS 158 R/B',
                 '1 02802U 67045B   04105.12224913  .00000082  00000-0  32618-4 0  5785',
                 '2 02802  74.0096 111.2339 0069038 241.3647 118.0552 14.42132256935013' ]]
    utc = list(args)
    for i, arg in enumerate(utc):
        utc[i] = int(arg)
    # loop tledata
    ret = []
    for x in tledata:
        pos = []
        try:
            satellite = twoline2rv(x[1], x[2], wgs84)
            ps = 2.0 * math.pi * 1/satellite.no * 60.0
            utc1 = utc2 = datetime.datetime(*utc)
            # by 2 mean motion ago
            delta = datetime.timedelta(0, ps)
            step = delta.total_seconds() / 10.0
            while (utc1 - utc2 < delta):
                p, v = satellite.propagate(*utc2.timetuple()[:6])
                utc2 = utc2 - datetime.timedelta(0, step)
                pos += [p]
                break
            ret += [[x[0], pos]]
        except:
            pass
    return HttpResponse(str(ret))
Beispiel #54
0
 def __init__(self, local_path, jansky, name_list=None):
     self.jansky = jansky
     self.satellites = []
     f = open(local_path, "r")
     lines = f.readlines()
     for i, l in enumerate(lines):
         #print(i, l)
         if (i % 3 == 0):
             name = l.strip()
         
         if (i % 3 == 1):
             line1 = l.strip()
         
         if (i % 3 == 2):
             line2 = l.strip()
             sv = twoline2rv(line1, line2, wgs84)
             if name_list is None:
                 self.satellites.append(Sp4Ephemeris(name, sv))
             else:
                 # Check that name is in the list.
                 for n in name_list:
                     if n in name:
                         self.satellites.append(Sp4Ephemeris(name, sv))
    def getPosition(self, mnow = datetime.utcnow()):
        """
        Retorna la posicion actual del satelite en funcion del ultimo TLE, no utiliza las
        propagaciones previamente armadas aunque seria una buena alternativa
        Retorna x, y, z y velocity
        Utiliza SGP4 para propagar
        """

        
        #Como busco dentro de los tles del satelite????
        try:
            tleo = self.tle_set.all().filter(_tleDateTime__range=[mnow-timedelta(days=30), mnow])
            tleo = tleo[0]
                
            
            TLE = tleo._tle.split("\n") 
                
            
            
               
            #sgp4sat = twoline2rv(TLE[0], TLE[1], wgs72)  # es un objeto de clase (satelite)
            sat = twoline2rv(TLE[0], TLE[1], wgs72) # es un objeto de clase (satelite)
            position, velocity = sat.propagate( mnow.year, mnow.month, mnow.day, mnow.hour , mnow.minute, mnow.second)
            
            
            
        
        except Tle.DoesNotExists:
            #Lanzar excepcion
            position = None
            velocity = None
            
        
        return position, velocity
        
        
Beispiel #56
0
    lat = atan2((z+ep*ep*b*pow(sin(th),3)), (p-e*e*a*pow(cos(th),3)))
    n = a/sqrt(1-e*e*pow(sin(lat),2))

    alt = p/cos(lat)-n
    lat = (lat*180)/pi
    lon = (lon*180)/pi

    return (lat, lon, alt)

# Test TLE for Hubble Space Telescope
line1 = ('1 20580U 90037B   14101.16170949  '
         '.00002879  00000-0  18535-3 0  4781')
line2 = ('2 20580 028.4694 117.6639 0002957 '
         '290.9180 143.6730 15.05140277114603')

satellite = twoline2rv(line1, line2, wgs72)

date = datetime(2000, 6, 29, 12, 46, 19)

delta = timedelta(minutes=1)

position, velocity = satellite.propagate(date.year, date.month, date.day, date.hour, date.minute, date.second)

print position

print velocity

lat, gmra, alt = groundtrack(position)

print str(lat)
print str(gmra)
Beispiel #57
0
# Read and store TLE catalog
###################################################################################################

# Read in catalog and store lines in list.
fileHandle = open(tleCatalogFilePath)
catalogLines = fileHandle.readlines()
fileHandle.close()

# Strip newline and return carriage characters.
for i in xrange(len(catalogLines)):
    catalogLines[i] = catalogLines[i].strip('\r\n')

# Parse TLE entries and store debris objects.
debrisObjects = []
for tleEntry in xrange(0, len(catalogLines), tleEntryNumberOfLines):
    debrisObjects.append(twoline2rv(catalogLines[tleEntry+1], catalogLines[tleEntry+2], wgs72))

###################################################################################################

###################################################################################################
# Compute pruned list and write to file.
###################################################################################################

# Convert altitude bounds [km] to mean motion [rad/min].
meanMotionMaximum = convertSemiMajorAxisToMeanMotion( \
    altitudeMinimum + getgravconst('wgs72')[2], getgravconst('wgs72')[1]) * 60.0
meanMotionMinimum = convertSemiMajorAxisToMeanMotion( \
    altitudeMaximum + getgravconst('wgs72')[2], getgravconst('wgs72')[1]) * 60.0

# Create pruned list based on bounds specified by user.
prunedList = [(objectIndex) for objectIndex, debrisObject in enumerate(debrisObjects) \
from sgp4.earth_gravity import wgs72
from sgp4.io import twoline2rv

from urllib import urlretrieve
from visual import *
from orbit import *
from time import sleep

new = twoline2rv("1 25544U 98067A   14102.55154002  .00018142  00000-0  31656-3 0   687","2 25544  51.6489  64.8360 0002245  19.9828  92.1413 15.50758489881146",wgs72)
year=2000
month=6
day=29
hour=12
minute=50
second=19

position, velocity = new.propagate(year, month, day, hour, minute, second)
#position = [x/1000.0 for x in position]
print position
ball= sphere(pos=tuple(position),radius=1000,make_trail=True,color=color.red)
earth = sphere(pos=(0,0,0),radius=6000)
#sleep(5)
#print("CHanged")
x=0
while True:
    sleep(.01)
    rate(30)
    x+=1
    position, velocity = new.propagate(year, month, day, hour, minute, second+x)
    
    print(position)
Beispiel #59
0
data = response.readlines()

sats = []
thc = 0  # three counter count three and set to zero again.
for d in data:
    if(thc < 3):
        if(thc == 0):
            tmp_sat_name = d.rstrip()
            thc = thc + 1
        elif(thc == 1):
            tmp_sat_tle1 = d.rstrip()
            thc = thc + 1
        else:
            tmp_sat_tle2 = d.rstrip()
            sat = Sat(tmp_sat_name, tmp_sat_tle1, tmp_sat_tle2)
            sats.append(sat)
            thc = 0


earth_radius = 6378.137
print "sat_name, sma, inclination,ecco"
for sat in sats:
    satellite = twoline2rv(sat.get_tle1(), sat.get_tle2(), wgs72)
    satellite.propagate(2015, 8, 1, 12, 50, 19)
    satllite_data = propagation._initl(satellite.satnum, satellite.whichconst,
                                       satellite.ecco,
                                       satellite.jdsatepoch, satellite.inclo,
                                       satellite.no, satellite.method, "a")
    print sat.get_name() + "," + str(satllite_data[3] * earth_radius) + "," +\
        str(math.degrees(satellite.inclo)) + "," + str(satellite.ecco)