示例#1
0
def calcLong_3(catalog, number=0):
    ''' Возвращает три массива орбитальных ошибок "длинных интервалов"
    '''

    time = []
    sig1 = []
    sig2 = []
    sig3 = []

    line1 = catalog.line1[number]
    line2 = catalog.line2[number]
    sat1 = twoline2rv(line1, line2, wgs72)

    for numsat in range(0, len(catalog.line1)):
        line1 = catalog.line1[numsat]
        line2 = catalog.line2[numsat]
        sat2 = twoline2rv(line1, line2, wgs72)

        dT = (catalog.JD[numsat] - catalog.JD[number]) * 24 * 60

        x1, v1 = sgp4(sat1, dT)
        x2, v2 = sgp4(sat2, 0)

        s1, s2, s3 = orbitSigma(x1, v1, x2, v2)

        time.append((catalog.JD[numsat] - catalog.JD[number]))
        sig1.append(s1)
        sig2.append(s2)
        sig3.append(s3)

    return sig1, sig2, sig3, time
示例#2
0
def generate_satellite_output(satrec, line2):
    """Print a data line for each time in line2's start/stop/step field."""

    mu = satrec.whichconst.mu

    r, v = sgp4(satrec, 0.0)
    if r is None:
        yield '(Use previous data line)'
        return
    yield format_short_line(satrec, r, v)

    tstart, tend, tstep = (float(field) for field in line2[69:].split())

    tsince = tstart
    while tsince <= tend:
        if tsince == tstart == 0.0:
            tsince += tstep
            continue  # avoid duplicating the first line

        r, v = sgp4(satrec, tsince)

        if r is None:
            return
        yield format_long_line(satrec, mu, r, v)

        tsince += tstep

    if tsince - tend < tstep - 1e-6:  # do not miss last line!
        r, v = sgp4(satrec, tend)
        if r is None:
            return
        yield format_long_line(satrec, mu, r, v)
示例#3
0
def calcShort_ephem(catalog, ephem):
    '''  Возвращает масиив ошибок по конкретному элементу орбиты
    '''

    time = []
    sig = []
    for numsat in range(0, len(catalog.line1) - 1):
        # формирование массива данных рассчётов

        line1 = catalog.line1[numsat]
        line2 = catalog.line2[numsat]
        sat1 = twoline2rv(line1, line2, wgs72)

        line1 = catalog.line1[numsat + 1]
        line2 = catalog.line2[numsat + 1]
        sat2 = twoline2rv(line1, line2, wgs72)

        dT = (catalog.JD[numsat + 1] - catalog.JD[numsat]) * 24 * 60

        x1, v1 = sgp4(sat1, dT)
        x2, v2 = sgp4(sat2, 0)

        s = ephemSigma(x1, v1, x2, v2, ephem)

        time.append((catalog.JD[numsat] - catalog.JD[0]))
        sig.append(s)

    return sig, time
示例#4
0
def calcShort_R(catalog):
    '''  Возвращает массив полных ошибок "коротких интервалов"
    '''

    time = []
    sig = []
    for numsat in range(0, len(catalog.line1) - 1):
        # формирование массива данных рассчётов

        line1 = catalog.line1[numsat]
        line2 = catalog.line2[numsat]
        sat1 = twoline2rv(line1, line2, wgs72)

        line1 = catalog.line1[numsat + 1]
        line2 = catalog.line2[numsat + 1]
        sat2 = twoline2rv(line1, line2, wgs72)

        dT = (catalog.JD[numsat + 1] - catalog.JD[numsat]) * 24 * 60

        x1, v1 = sgp4(sat1, dT)
        x2, v2 = sgp4(sat2, 0)

        time.append((catalog.JD[numsat] - catalog.JD[0]))
        sig.append(fullSigma(x1, x2))
    return sig, time
示例#5
0
def generate_satellite_output(satrec, line2, error_list):
    """Print a data line for each time in line2's start/stop/step field."""

    mu = satrec.whichconst.mu

    r, v = sgp4(satrec, 0.0)
    if isnan(r[0]) and isnan(r[1]) and isnan(r[2]):
        error_list.append((satrec.error, satrec.error_message))
        yield '(Use previous data line)'
        return
    yield format_short_line(satrec, r, v)

    tstart, tend, tstep = (float(field) for field in line2[69:].split())

    tsince = tstart
    while tsince <= tend:
        if tsince == tstart == 0.0:
            tsince += tstep
            continue  # avoid duplicating the first line

        r, v = sgp4(satrec, tsince)

        if satrec.error:
            error_list.append((satrec.error, satrec.error_message))
            return
        yield format_long_line(satrec, mu, r, v)

        tsince += tstep

    if tsince - tend < tstep - 1e-6:  # do not miss last line!
        r, v = sgp4(satrec, tend)
        if satrec.error:
            error_list.append((satrec.error, satrec.error_message))
            return
        yield format_long_line(satrec, mu, r, v)
示例#6
0
def calcShort_3(catalog):
    '''    Возвращает три массива орбитальных ошибок "коротких интервалов"
    '''

    time = []
    sig1 = []
    sig2 = []
    sig3 = []

    for numsat in range(0, len(catalog.line1) - 1):
        # формирование массива данных рассчётов

        line1 = catalog.line1[numsat]
        line2 = catalog.line2[numsat]
        sat1 = twoline2rv(line1, line2, wgs72)

        line1 = catalog.line1[numsat + 1]
        line2 = catalog.line2[numsat + 1]
        sat2 = twoline2rv(line1, line2, wgs72)

        dT = (catalog.JD[numsat + 1] - catalog.JD[numsat]) * 24 * 60

        x1, v1 = sgp4(sat1, dT)
        x2, v2 = sgp4(sat2, 0)

        s1, s2, s3 = orbitSigma(x1, v1, x2, v2)

        time.append((catalog.JD[numsat] - catalog.JD[0]))
        sig1.append(s1)
        sig2.append(s2)
        sig3.append(s3)

    return sig1, sig2, sig3, time
示例#7
0
def calcLong_ephem(catalog, ephem, number=0):
    '''  Возвращает массив ошибок по конкретному элементу орбиты
    '''

    line1 = catalog.line1[number]
    line2 = catalog.line2[number]
    sat1 = twoline2rv(line1, line2, wgs72)

    time = []
    sig = []
    for numsat in range(0, len(catalog.line1)):
        line1 = catalog.line1[numsat]
        line2 = catalog.line2[numsat]
        sat2 = twoline2rv(line1, line2, wgs72)

        dT = (catalog.JD[numsat] - catalog.JD[number]) * 24 * 60

        x1, v1 = sgp4(sat1, dT)
        x2, v2 = sgp4(sat2, 0)

        s = ephemSigma(x1, v1, x2, v2, ephem)

        time.append((catalog.JD[numsat] - catalog.JD[number]))
        sig.append(s)

    return sig, time
示例#8
0
    def propagate(self, year, month=1, day=1, hour=0, minute=0, second=0.0):
        """Return a position and velocity vector for a given date and time."""

        j = jday(year, month, day, hour, minute, second)
        m = (j - self.jdsatepoch) * minutes_per_day
        r, v = sgp4(self, m)
        return r, v
示例#9
0
def generate_satellite_output_vectorial(satrec, line2, error_list):
    """Print a data line for each time in line2's start/stop/step field."""

    if satrec.method == 'd':
        yield from generate_satellite_output(satrec, line2, error_list)
        return

    import numpy as np

    mu = satrec.whichconst.mu

    tstart, tend, tstep = (float(field) for field in line2[69:].split())
    times = np.arange(tstart, tend, tstep)

    if times[-1] - tend < tstep - 1e-6:  # do not miss last line!
        times = np.append(times, tend)

    _r, _v = np.array(sgp4(satrec, times))

    if _r.shape == (3, ):
        if isnan(_r[0]) and isnan(_r[1]) and isnan(_r[2]):
            error_list.append((satrec.error, satrec.error_message))
            print(error_list)
            return

    for i in range(_r.shape[1]):
        r = list(_r[:, i])
        v = list(_v[:, i])
        t = satrec.t[i]

        if i == 0:
            yield format_short_line(t, r, v)
        else:
            yield format_long_line(satrec, t, mu, r, v)
示例#10
0
    def propagate(self, year, month=1, day=1, hour=0, minute=0, second=0.0):
        """Return a position and velocity vector for a given date and time."""

        j = jday(year, month, day, hour, minute, second)
        m = (j - self.jdsatepoch) * minutes_per_day
        r, v = sgp4(self, m)
        return r, v
示例#11
0
    def calcXYZ(self, name, time):
        '''  Вычисление прямоугольных координат.
             на выходе:
             -- кординаты аппарата
             -- скорости
             -- номер использованных эфемерид в каталоге
             -- длительность экстраполяции (в минутах)
        '''

        # поиск ближайшего ИСЗ к этому моменту времени
        d_since = 1e+10
        num = -1
        for i in range(0, len(self.time)):

            if self.name[i].find(name) == -1:  # не тот спутник, пропускаем
                continue

            d_day = time - self.time[i]
            d_sinceNew = d_day.days * 24 * 60 + d_day.seconds / 60

            if (abs(d_sinceNew) < abs(d_since)):  # более свежие эфемериды
                num = i
                d_since = d_sinceNew

        line1 = self.line1[num]
        line2 = self.line2[num]

        satellite = twoline2rv(line1, line2, wgs72)
        #    position, velocity = satellite.propagate(2016, 6, 30, 12, 0, 0)
        position, velocity = sgp4(satellite, d_since)

        return position, velocity, num, d_since
示例#12
0
def _testSGP():
    ''' Тестируем чтение информации по ИСЗ + вычисление координат
    '''
    print('  ')
    print('Тест SGP.')

    catalog = CatalogTLE()
    catalog.readTLEsat('catalogs/catalog_2016_06_30.txt', 'ISS')

    catalog.status()

    line1 = catalog.getLine1('ISS')
    line2 = catalog.getLine2('ISS')

    satellite = twoline2rv(line1, line2, wgs72)

    #    position, velocity = satellite.propagate(2016, 6, 30, 12, 0, 0)

    position, velocity = sgp4(satellite, 10.001)

    print('---   error   ---')
    print(satellite.error)  # nonzero on error

    print('---   error_message   ---:')
    print(satellite.error_message)

    print('---   position   ---')
    print(position)

    print('---   velocity   ---')
    print(velocity)
示例#13
0
def drawEphem_allcatalog(catalog, ephem):
    ''' Создание графиков эволюции эфемериды на протяжении полученного каталога
    
    catalog -- каталог ТЛЕ
    ephem --   название той эфемериды, что нам надо
    number --  номер данных в каталоге (по умолчанию 0)
    '''

    time = []
    val = []
    for numsat in range(0, len(catalog.line1)):
        line1 = catalog.line1[numsat]
        line2 = catalog.line2[numsat]
        sat = twoline2rv(line1, line2, wgs72)

        dT = (catalog.JD[numsat] - catalog.JD[0]) * 24 * 60

        x1, v1 = sgp4(sat, dT)

        orbit = KeplerOrbit()
        orbit.xyz2ephem(x1[0], x1[1], x1[2], v1[0], v1[1], v1[2])

        time.append(catalog.JD[numsat] - catalog.JD[0])

        val.append(orbit.get_ephem(ephem))

    plt.plot(time, val, 'r-')
    plt.plot(time, val, 'k+')

    plt.xlabel('Epoсh')
    plt.ylabel('Ephemeris')
    plt.title(catalog.name[1])
    plt.grid(True)
    plt.show()
示例#14
0
def drawEphem_oneSat(catalog, ephem, dT, number=0):
    ''' Создание графиков эволюции эфемериды в пронозе SGP
    
    catalog -- каталог ТЛЕ
    ephem --   название той эфемериды, что нам надо
    dT --      массив времён, на который строим график (в сутках)
    number --  номер данных в каталоге (по умолчанию 0)
    '''

    line1 = catalog.line1[number]
    line2 = catalog.line2[number]
    sat1 = twoline2rv(line1, line2, wgs72)

    time = []
    val = []
    for t in dT:
        x1, v1 = sgp4(sat1, t / 24 / 60)

        orbit = KeplerOrbit()
        orbit.xyz2ephem(x1[0], x1[1], x1[2], v1[0], v1[1], v1[2])

        time.append(t)
        val.append(orbit.get_ephem(ephem))

    sig = calcLong_ephem(catalog, ephem, number)

    plt.plot(time, val, 'c-')
    plt.plot(time, val, 'k+')

    plt.xlabel('Epoсh (day)')
    plt.ylabel('Ephemeris')
    plt.title(catalog.name[1])
    plt.grid(True)
    plt.show()
示例#15
0
    def _position_and_velocity_TEME_km(self, jd):
        """Return the raw true equator mean equinox (TEME) vectors from SGP4.

        Returns a tuple of NumPy arrays ``([x y z], [xdot ydot zdot])``
        expressed in kilometers and kilometers per second.

        """
        minutes_past_epoch = (jd.ut1 - self._sgp4_satellite.jdsatepoch) * 1440.
        position, velocity = sgp4(self._sgp4_satellite, minutes_past_epoch)
        return (array(position), array(velocity))
示例#16
0
    def extrapolateShort(self):
        for numsat in range(0, len(self.catalog.line1) - 1):
            # формирование массива данных рассчётов

            line1 = self.catalog.line1[numsat]
            line2 = self.catalog.line2[numsat]
            sat1 = twoline2rv(line1, line2, wgs72)

            line1 = self.catalog.line1[numsat + 1]
            line2 = self.catalog.line2[numsat + 1]
            sat2 = twoline2rv(line1, line2, wgs72)

            dT = (self.catalog.JD[numsat + 1] -
                  self.catalog.JD[numsat]) * 24 * 60

            x1, v1 = sgp4(sat1, dT)
            x2, v2 = sgp4(sat2, 0)

            self._sig.append(FullSigma(x1, x2))
        return self._sig
示例#17
0
def test_sgp4(client):
    """ test the sgp4 device interface """
    tsince = np.linspace(0, 100, client.n, dtype=np.float64)

    sgp4.sgp4(tsince, client.whichconst_array, client.satrec_array)
    array = []
    for ts in tsince:
        r, v = prop.sgp4(client.Satrec(), ts, wgs72)
        array.append([r[0], r[1], r[2], v[0], v[1], v[2]])
    expected = np.array(array)
    assert np.allclose(expected, client.satrec_array[:, 94:])
示例#18
0
def propogate_over_range(satellite, date, min_time, max_time):
    # First we catch the previous satellite up to the midway point
    for tsince in range(min_time, max_time):
        # get current position and velocity in ECI
        position_eci, velocity_eci = sgp4(satellite, tsince)

        interval_date = increment_date_by_minutes(date, tsince)
        time_string = TIME_TEMPLATE.format(interval_date)

        x_csv_writer.writerow([time_string, position_eci[0], '0'])
        y_csv_writer.writerow([time_string, position_eci[1], '0'])
        z_csv_writer.writerow([time_string, position_eci[2], '0'])
示例#19
0
def calcLong_R(catalog, number=0):
    ''' Возвращает массив полных ошибок "длинных интервалов"
    '''
    line1 = catalog.line1[number]
    line2 = catalog.line2[number]
    sat1 = twoline2rv(line1, line2, wgs72)

    time = []
    sig = []
    for numsat in range(0, len(catalog.line1)):
        line1 = catalog.line1[numsat]
        line2 = catalog.line2[numsat]
        sat2 = twoline2rv(line1, line2, wgs72)

        dT = (catalog.JD[numsat] - catalog.JD[number]) * 24 * 60

        x1, v1 = sgp4(sat1, dT)
        x2, v2 = sgp4(sat2, 0)

        time.append((catalog.JD[numsat] - catalog.JD[number]))
        sig.append(fullSigma(x1, x2))
    return sig, time
示例#20
0
    def _position_and_velocity_TEME_km(self, t):
        """Return the raw true equator mean equinox (TEME) vectors from SGP4.

        Returns a tuple of NumPy arrays ``([x y z], [xdot ydot zdot])``
        expressed in kilometers and kilometers per second.  Note that we
        assume the TLE epoch to be a UTC date, per AIAA 2006-6753.

        """
        sat = self.model
        minutes_past_epoch = (t._utc_float() - sat.jdsatepoch) * 1440.0
        if getattr(minutes_past_epoch, 'shape', None):
            position = []
            velocity = []
            error = []
            for m in minutes_past_epoch:
                p, v = sgp4(sat, m)
                position.append(p)
                velocity.append(v)
                error.append(sat.error_message)
            return array(position).T, array(velocity).T, error
        else:
            position, velocity = sgp4(sat, minutes_past_epoch)
            return array(position), array(velocity), sat.error_message
示例#21
0
def propogate_over_range(satellite, date, min_time, max_time):
    # First we catch the previous satellite up to the midway point
    for tsince in range(min_time, max_time):
        # get current position and velocity in ECI
        position_eci, velocity_eci = sgp4(satellite, tsince)

        interval_date = increment_date_by_minutes(date, tsince)
        time_string = TIME_TEMPLATE.format(interval_date)

        # transform rectangular coordinates to spherical coordinates
        position_sp = spherical(position_eci)
        velocity_sp = spherical(velocity_eci)

        phi_csv_writer.writerow([time_string, position_sp[0], '0'])
        theta_csv_writer.writerow([time_string, position_sp[1], '0'])
示例#22
0
    def _position_and_velocity_TEME_km(self, t):
        """Return the raw true equator mean equinox (TEME) vectors from SGP4.

        Returns a tuple of NumPy arrays ``([x y z], [xdot ydot zdot])``
        expressed in kilometers and kilometers per second.  Note that we
        assume the TLE epoch to be a UTC date, per AIAA 2006-6753.

        """
        sat = self._sgp4_satellite
        epoch = sat.jdsatepoch
        minutes_past_epoch = (t._utc_float() - epoch) * 1440.
        if getattr(minutes_past_epoch, 'shape', None):
            position = []
            velocity = []
            error = []
            for m in minutes_past_epoch:
                p, v = sgp4(sat, m)
                position.append(p)
                velocity.append(v)
                error.append(sat.error_message)
            return array(position).T, array(velocity).T, error
        else:
            position, velocity = sgp4(sat, minutes_past_epoch)
            return array(position), array(velocity), sat.error_message
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
        """
示例#24
0
def test_sgp4_g(client):
    """ test the sgp4 device propagation engine """
    @cuda.jit('void(float64[:], float64[:, :], float64[:, :])')
    def sample_function(tsince, which_const, satrec):
        idx = cuda.grid(1)
        stride = cuda.gridsize(1)

        for i in range(idx, tsince.shape[0], stride):
            sgp4.sgp4_g(tsince[i], which_const[i, :], satrec[i, :])

    tsince = np.linspace(0, 100, client.n, dtype=np.float64)

    sample_function(tsince, client.whichconst_array, client.satrec_array)

    array = []
    for ts in tsince:
        r, v = prop.sgp4(client.Satrec(), ts, wgs72)
        array.append([r[0], r[1], r[2], v[0], v[1], v[2]])
    expected = np.array(array)
    assert np.allclose(expected, client.satrec_array[:, 94:])
示例#25
0
def trad(jd_array, fr_array):
    from sgp4.earth_gravity import wgs72
    from sgp4.io import twoline2rv
    from sgp4.propagation import sgp4

    sats = []
    lines = iter(text.splitlines())
    for name in lines:
        line1 = next(lines)
        line2 = next(lines)
        sat = twoline2rv(line1, line2, wgs72)
        sats.append(sat)

    sats = sats[:20]  # first 20 sats

    print(len(sats), 'pure Python sats')
    print(len(jd_array), 'and', len(fr_array), 'times')

    zipped_times = list(zip(jd_array, fr_array))

    for sat in sats:
        for jd, fr in zipped_times:
            t = (jd - sat.jdsatepoch + fr) * 1440.0
            r, v = sgp4(sat, t)
示例#26
0
# setup for reading TLE file all at once
tles = open(tlefile, 'r')
tlelines = tles.readlines()
nolines = len(tlelines)
tles.close()
satrec = []

# generate satrec, here one for all, but can also do one at a time (satrec1)
startline = linespertle - 2
for i in range(startline, nolines, linespertle):
    # create satellite object
    satrec1 = twoline2rv(tlelines[i], tlelines[i + 1], wgs84)
    # append until all objects are read in
    satrec.append(satrec1)
print(satrec)
# obtain position and velocity at reference epoch
minday = 1440.0  #minutes per day, input in minutes needed (see sgp4)
posvel = [sgp4(n, (jd_epoch - n.jdsatepoch) * minday)
          for n in satrec]  # state in km and km/s

nobj = len(posvel)  # how many objects
r = [posvel[i][0] for i in range(nobj)]  # position at epoch in km
v = [posvel[i][1] for i in range(nobj)]  # velocity at epoch in km/s

print(r)
print(v)

# those are the position and velocity at the epoch you have defined, for multiple epochs you can make a vector or a for loop
# which then give you the full orbit
示例#27
0
 def sgp4(self, jd, fr):
     tsince = (jd - self.jdsatepoch + fr) * minutes_per_day
     r, v = sgp4(self, tsince)
     return self.error, r, v
示例#28
0
 def propagate(self, year, month=1, day=1, hour=0, minute=0, second=0.0):
     j = jday(year, month, day, hour, minute, second)
     m = (j - self.jdsatepoch) * minutes_per_day
     r, v = sgp4(self, m)
     return r, v
示例#29
0
(jd, fr) = divmod(satnew.jdsatepoch, 1)
satnew.sgp4(jd, fr)

satrec3 = Satrec()
satrec3_jdsatepoch = 2451723.28495062
satrec3.sgp4init(WGS72, 'i', satnum, satrec3_jdsatepoch - 2433281.5, bstar,
                 ndot, nddot, ecco, argpo, inclo, mo, no_kozai, nodeo)

print("Single element SGP4")
baseline = Timer(lambda: satrec3.sgp4(jd, fr)).timeit(number=num)
print("sgp4_cpp(1):                 {:.6f} {:.2f}x".format(
    *tac(baseline,
         Timer(lambda: satrec3.sgp4(jd, fr)).timeit(number=num))))
print("sgp4_py:                     {:.6f} {:.2f}x".format(
    *tac(baseline,
         Timer(lambda: sgp4(satold, tsince)).timeit(number=num))))
print()

print("Vector element SGP4 vs scalar loop of same #")
sats = []
sats.append(satnew)
a = SatrecArray(sats)

for j in range(len(odata)):
    r = np.ndarray((len(a), j + 1, 3))
    v = np.ndarray((len(a), j + 1, 3))
    err = np.ndarray((len(a), j + 1), 'uint8')
    jd = np.zeros((j + 1, ))
    fr = np.ndarray((j + 1, ))

    for i in range(j):
示例#30
0
 def invoke_satrec(self, satrec, tsince):
     r, v = sgp4(satrec, tsince)
     e = satrec.error
     emsg = satrec.error_message
     return e, emsg, r, v
    def predict(self, satrec, startJTime, obsPos):
        obsGeo={'x':obsPos['lon'],'y':obsPos['lat'],'z':obsPos['alt']}
        obsEci={'x':0,'y':0,'z':0}
        satGeo={'x':0,'y':0,'z':0}
        satEci={'x':0,'y':0,'z':0}

        bearingPrev     = 0 #initialize bearing buffer
        bearingDiffPrev = 100 #initialize bearing difference buffer
        beginnerFlag    = 2 #ignore the first 2 iterations for propagation init.
        propCnt         = 0 #initialize propagation count
        error           = 0 #error flag
        iteLimit        = iteLimitDef #propagation itemration limit
        halfSwath       = swath/2
        startEpoch      = startJTime

        actualEpoch     = startJTime
        surfaceDistance = 0
        bearing         = 0
        tspan           = tspanDef

        tspanBuff       = 0
        passedObsBuff   = 0
        visibleBuff     = 0
        passedObs       = 0
        visible         = 0

        #Start Propogation
        bearingPrecision=0.0001

        while (not(passedObs and visible and (math.fabs(bearingDiffPrev) < bearingPrecision)) 
               and not error):
            
            propCnt=propCnt+1

            if propCnt > iteLimit-1:
                if self.verbose:
                    print 'Exceed iteration limit.'
                error=1

            dtMinutes=(actualEpoch - satrec.jdsatepoch)*mpd
            r,v=sgp4(satrec,dtMinutes)
            satEci={'x':r[0],'y':r[1],'z':r[2]}
            satVel={'x':v[0],'y':v[1],'z':v[2]}

            epoch=actualEpoch

            satGeo=self._eci2geo(satEci, actualEpoch)
            obsEci=self._geo2eci(obsGeo, actualEpoch)
            scn=self._getVec(obsEci,satEci) #scan direction vector from sat to obs
            
            bearingRaw=self._getAng(scn,satVel)*rad2deg

            bearing=bearingRaw
            if satGeo['x'] > obsGeo['x']: 
                bearing=0-bearingRaw

            bearingDiff=math.fabs(bearing)-90

            #check if propogation had passed the observer
            passedObs=0
            if ((bearingDiff*bearingDiffPrev < 0) and not beginnerFlag):
                passedObs=1

            #decrease beginner flag count till zero
            beginnerFlag=beginnerFlag-1
            beginnerFlag=math.fabs(beginnerFlag*(beginnerFlag>0))

            #update bearing buffers
            bearingDiffPrev=bearingDiff
            bearingPrev=bearing

            #Spherical Earth big circle distance
            if self.sphericalEarth:
                ang=self._getAng(obsEci,satEci)
                surfaceDistance=(ang*earthR)
                try:
                    surfaceDistance_v=self.getDis(obsGeo,satGeo)
                except:
                    surfaceDistance_v=0

            else:
            #Vincenty's Formulae
                try:
                    surfaceDistance=self.getDis(obsGeo,satGeo)
                except:
                    if self.verbose:
                        print 'Vincenty\'s formulae failed. Fall back to spherical Earth.'
                    ang=self._getAng(obsEci,satEci)
                    if self.verbose:
                        print 'Angle between coordinated: '+'%.3f'%ang
                    surfaceDistance=(ang*earthR)
                
            visible=0
            if (surfaceDistance < halfSwath):
                visible=1

            actualEpoch=actualEpoch+tspan/spd

            if ((not passedObsBuff and passedObs) and (visibleBuff and not visible)):
                visible=1

            #update buffer
            passedObsBuff = passedObs
            visibleBuff   = visible

            if (passedObs and visible):
                tspan=float(tspan)/(-20.)

        dx=satEci['x']-obsEci['x']
        dy=satEci['y']-obsEci['y']
        dz=satEci['z']-obsEci['z']
        slant=math.sqrt(dx*dx+dy*dy+dz*dz)
        alpha=self._getAng(obsEci,satEci)
        scanAngle=math.asin(earthR*math.sin(alpha)/slant)*rad2deg

        #Correction will only be applied when spherical earth assumption is true.
        if self.applyCorrection and self.sphericalEarth:
            endTimeJulUtc=self._applyCorrection(actualEpoch,obsGeo['y'])
        else:
            endTimeJulUtc=actualEpoch

        endTimeJulLoc=endTimeJulUtc+(self.timeZone)/24.
        iniTimeJulLoc=startEpoch+(self.timeZone)/24.
#        print 'do return'
        return {'satLat':satGeo['y'],'satLon':satGeo['x'],'satAlt':satGeo['z'],
                'obsLat':obsGeo['y'],'obsLon':obsGeo['x'],'obsAlt':obsGeo['z'],
                'satVelX':satVel['x'],'satVelY':satVel['y'],'satVelZ':satVel['z'],
                'satEciX':satEci['x'],'satEciY':satEci['y'],'satEciZ':satEci['z'],
                'obsEciX':obsEci['x'],'obsEciY':obsEci['y'],'obsEciZ':obsEci['z'],
                'scanAngle':scanAngle,
                'distance':surfaceDistance,
                'bearing':bearing,
                'timeEndUTC':endTimeJulUtc, 'timeIniUTC':startEpoch,
                'timeEndLOC':endTimeJulLoc, 'timeIniLOC':iniTimeJulLoc,
                'timeZone':timeZone,
                'propCnt':propCnt, 'timeSpan':tspan,
                'error':error}
示例#32
0
 def run_legacy_sgp4(satrec, tsince):
     r, v = sgp4(satrec, tsince)
     return (satrec.error, satrec.error_message), r, v
示例#33
0
 def sgp4(self, jd, fr):
     tsince = ((jd - self.jdsatepoch) * minutes_per_day +
               (fr - self.jdsatepochF) * minutes_per_day)
     r, v = sgp4(self, tsince)
     return self.error, r, v
示例#34
0
 def sgp4_tsince(self, tsince):
     r, v = sgp4(self, tsince)
     return self.error, r, v