Exemplo n.º 1
0
    def test_writeRinex3Obs(self):
        """Test reading and writing back out a rinex obs file"""

        header, data = gpstk.readRinex3Obs(args.input_dir + "/arlm200a.15o",
                                           strict=True)
        # Now let's write it all back to a different file
        gpstk.writeRinex3Obs(args.output_dir + '/swig-arlm200a.15o', header,
                             data)
Exemplo n.º 2
0
 def test_stream(self):
     header, data = gpstk.readRinex3Obs('rinex3obs_data.txt', strict=True)
     self.assertEqual(0L, header.numSVs)
     self.assertEqual('NATIONAL IMAGERY AND MAPPING AGENCY', header.agency)
     self.assertEqual(120, len(data))
     dataPoint = data[0]
     datum = dataPoint.getObs(gpstk.SatID(4), header.getObsIndex("C1"))
     self.assertAlmostEqual(24236698.057, datum.data)
     self.assertEqual(0, dataPoint.clockOffset)
     expectedTime = gpstk.CommonTime()
     expectedTime.set(2453167)
     expectedTime.setTimeSystem(gpstk.TimeSystem(gpstk.TimeSystem.GPS))
     self.assertEqual(expectedTime, dataPoint.time)
Exemplo n.º 3
0
 def test_stream(self):
     header, data = gpstk.readRinex3Obs('rinex3obs_data.txt', strict=True)
     self.assertEqual(0L, header.numSVs)
     self.assertEqual('NATIONAL IMAGERY AND MAPPING AGENCY', header.agency)
     self.assertEqual(120, len(data))
     dataPoint = data[0]
     datum = dataPoint.getObs(gpstk.SatID(4), header.getObsIndex("C1"))
     self.assertAlmostEqual(24236698.057, datum.data)
     self.assertEqual(0, dataPoint.clockOffset)
     expectedTime = gpstk.CommonTime()
     expectedTime.set(2453167)
     expectedTime.setTimeSystem(gpstk.TimeSystem(gpstk.TimeSystem.GPS))
     self.assertEqual(expectedTime, dataPoint.time)
Exemplo n.º 4
0
def tweakInternalHeaderState(rinex_obs_header):
    '''
    There's a slight defect in the Rinex3ObsHeader object which causes it
    to only be in the correct state for full file writing if the header
    has been read from a file.

    This method is a hack to write the fully-built header (no data) to a file and
    read it back in.

    That way the header can be used to write another file which _does_ have data.
    '''
    temp_file = tempfile.NamedTemporaryFile().name
    gpstk.writeRinex3Obs(temp_file, rinex_obs_header, [])
    tweaked_header, _ = gpstk.readRinex3Obs(temp_file)
    os.remove(temp_file)
    return tweaked_header
Exemplo n.º 5
0
def tweakInternalHeaderState(rinex_obs_header):
    '''
    There's a slight defect in the Rinex3ObsHeader object which causes it
    to only be in the correct state for full file writing if the header
    has been read from a file.

    This method is a hack to write the fully-built header (no data) to a file and
    read it back in.

    That way the header can be used to write another file which _does_ have data.
    '''
    temp_file = tempfile.NamedTemporaryFile().name
    gpstk.writeRinex3Obs(temp_file, rinex_obs_header, [])
    tweaked_header, _ = gpstk.readRinex3Obs(temp_file)
    os.remove(temp_file)
    return tweaked_header
Exemplo n.º 6
0
    def test_readRinex3Obs(self):
        """Test reading entire rinex obs file and spot check the data"""
        header, data = gpstk.readRinex3Obs( args.input_dir+"/arlm200a.15o", strict=True)

        # Find the earliest and latest observations
        # function for how to compare Rinex3ObsData objects for min/max functions:
        timeFunction = lambda self: self.time
        earliest = min(data, key=timeFunction)
        latest = max(data, key=timeFunction)

        self.assertEqual(
            gpstk.CivilTime(2015, 7, 19, 0, 0, 0, gpstk.TimeSystem(gpstk.TimeSystem.GPS)),
            gpstk.CivilTime(earliest.time))

        self.assertEqual(
            gpstk.CivilTime(2015, 7, 19, 0, 59, 30, gpstk.TimeSystem(gpstk.TimeSystem.GPS)),
            gpstk.CivilTime(latest.time))
Exemplo n.º 7
0
def main():
    # Read in the rinex data
    header, data = gpstk.readRinex3Obs('rinex3obs_data.txt', strict=True)

    # Let's pretend we want to change something in the header
    # (otherwise this would be a two-line example!)
    header.receiverOffset = 47

    # Now let's find the earliest and latest observations
    # function for how to compare Rinex3ObsData objects for min/max functions:
    timeFunction = lambda self: self.time
    earliest = min(data, key=timeFunction)
    latest = max(data, key=timeFunction)

    print 'Earliest time found:', gpstk.CivilTime(earliest.time)
    print 'Latest time found:  ', gpstk.CivilTime(latest.time)

    # Now let's write it all back to a different file
    gpstk.writeRinex3Obs('rinex3obs_data.txt.new', header, data)
Exemplo n.º 8
0
def main():
    # Read in the rinex data
    header, data = gpstk.readRinex3Obs('rinex3obs_data.txt', strict=True)

    # Let's pretend we want to change something in the header
    # (otherwise this would be a two-line example!)
    header.receiverOffset = 47

    # Now let's find the earliest and latest observations
    # function for how to compare Rinex3ObsData objects for min/max functions:
    timeFunction = lambda self: self.time
    earliest = min(data, key=timeFunction)
    latest = max(data, key=timeFunction)

    print 'Earliest time found:', gpstk.CivilTime(earliest.time)
    print 'Latest time found:  ', gpstk.CivilTime(latest.time)

    # Now let's write it all back to a different file
    gpstk.writeRinex3Obs('rinex3obs_data.txt.new', header, data)
Exemplo n.º 9
0
    def test_readRinex3Obs(self):
        """Test reading entire rinex obs file and spot check the data"""
        header, data = gpstk.readRinex3Obs(args.input_dir + "/arlm200a.15o",
                                           strict=True)

        # Find the earliest and latest observations
        # function for how to compare Rinex3ObsData objects for min/max functions:
        timeFunction = lambda self: self.time
        earliest = min(data, key=timeFunction)
        latest = max(data, key=timeFunction)

        self.assertEqual(
            gpstk.CivilTime(2015, 7, 19, 0, 0, 0,
                            gpstk.TimeSystem(gpstk.TimeSystem.GPS)),
            gpstk.CivilTime(earliest.time))

        self.assertEqual(
            gpstk.CivilTime(2015, 7, 19, 0, 59, 30,
                            gpstk.TimeSystem(gpstk.TimeSystem.GPS)),
            gpstk.CivilTime(latest.time))
Exemplo n.º 10
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('rinex3obs_filename')
    args = parser.parse_args()

    user_input = raw_input(
        'Name your PRN of interest, by number: 1 through 32: ')
    int_prn = int(user_input)

    try:
        print('Reading {}'.format(args.rinex3obs_filename))
        header, data = gpstk.readRinex3Obs(
            args.rinex3obs_filename)  # read in everything
        print(header)

        # Now we loop through all the epochs and process the data for each one
        for d in data:
            # Let's use the CivilTime class to print an easy to understand time:
            civtime = gpstk.CivilTime(d.time)
            print(civtime, )

            # Make a GPSTk SatID for the user's PRN so we can search for it
            prn = gpstk.RinexSatID(int_prn, gpstk.SatID.systemGPS)

            # Check if the PRN is in view (by searching for it)
            if d.obs.find(prn) == d.obs.end():
                print('PRN {} not in view'.format(int_prn))

            else:
                P1 = d.getObs(prn, "P1", header).data
                P2 = d.getObs(prn, "P2", header).data
                L1 = d.getObs(prn, "L1", header).data
                mu = P1 - L1 * (C_MPS /
                                L1_FREQ_GPS) - 2 * (P1 - P2) / (1 - GAMMA_GPS)
                print('PRN {} biased multipath {}'.format(int_prn, mu))

    # We can catch any custom gpstk exception like this:
    except gpstk.Exception as e:
        print(e)
Exemplo n.º 11
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('rinex3obs_filename')
    args = parser.parse_args()

    user_input = raw_input('Name your PRN of interest, by number: 1 through 32: ')
    int_prn = int(user_input)

    try:
        print 'Reading ' + args.rinex3obs_filename + '.'
        header, data = gpstk.readRinex3Obs(args.rinex3obs_filename)  # read in everything
        print header

        # Now we loop through all the epochs and process the data for each one
        for d in data:
            # Let's use the CivilTime class to print an easy to understand time:
            civtime = gpstk.CivilTime(d.time)
            print civtime,

            # Make a GPSTk SatID for the user's PRN so we can search for it
            prn = gpstk.RinexSatID(int_prn, gpstk.SatID.systemGPS)

            # Check if the PRN is in view (by searching for it)
            if d.obs.find(prn) == d.obs.end():
                print 'PRN', int_prn, 'not in view'

            else:
                P1 = d.getObs(prn, "P1", header).data
                P2 = d.getObs(prn, "P2", header).data
                L1 = d.getObs(prn, "L1", header).data
                mu = P1 - L1*(C_MPS/L1_FREQ_GPS) - 2*(P1-P2)/(1-GAMMA_GPS)
                print 'PRN', int_prn, 'biased multipath', mu

    # We can catch any custom gpstk exception like this:
    except gpstk.Exception as e:
        print e
Exemplo n.º 12
0
def rinex_to_dataframe(obsfile, navfile):
    c = 299792458.

    #observation_types=["P1", "P2", "L1", "L2"]
    observation_types = ["C1", "P2", "L1", "L2"]
    obsHeader, obsData = gpstk.readRinex3Obs(obsfile)
    navHeader, navData = gpstk.readRinex3Nav(navfile)
    # setup ephemeris store to look for satellite positions
    bcestore = gpstk.GPSEphemerisStore()
    for navDataObj in navData:
        ephem = navDataObj.toGPSEphemeris()
        bcestore.addEphemeris(ephem)
    bcestore.SearchNear()
    navData.close()

    rec_pos = [
        obsHeader.antennaPosition[0], obsHeader.antennaPosition[1],
        obsHeader.antennaPosition[2]
    ]
    requested_obstypes = observation_types
    obsidxs = []
    obstypes = []
    obsdefs = np.array([i for i in obsHeader.R2ObsTypes])
    for i in requested_obstypes:
        w = np.where(obsdefs == i)[0]
        if len(w) != 0:
            obsidxs.append(w[0])
            obstypes.append(i)
        else:
            print("WARNING! observation `" + i + "` no present in file")
    obsidxs, obstypes
    print obsdefs  #que tipos hay

    r = []
    for obsObject in obsData:
        prnlist = []
        obsdict = {}
        prnspos = []
        prns_clockbias = []
        prns_relcorr = []
        prnselev = []
        prnsaz = []
        for i in obstypes:
            obsdict[i] = []

        gpsTime = gpstk.GPSWeekSecond(obsObject.time)

        for satID, datumList in obsObject.obs.iteritems():
            if satID.system == satID.systemGPS:
                prnlist.append("".join(str(satID).split()))
                try:
                    eph = bcestore.findEphemeris(satID, obsObject.time)
                except:
                    print "no encontrada!"

                for i in range(len(obsidxs)):
                    obsdict[obstypes[i]].append(
                        obsObject.getObs(satID, obsidxs[i]).data)

                P1 = obsObject.getObs(satID, obsidxs[0]).data
                svTime = obsObject.time - P1 / c
                svXvt = eph.svXvt(svTime)
                svTime += -svXvt.getClockBias() + svXvt.getRelativityCorr()
                svXvt = eph.svXvt(svTime)

                prnspos.append([svXvt.x[0], svXvt.x[1], svXvt.x[2]])
                prns_clockbias.append(svXvt.getClockBias())
                prns_relcorr.append(svXvt.getRelativityCorr())

                prnselev.append(
                    obsHeader.antennaPosition.elvAngle(svXvt.getPos()))
                prnsaz.append(obsHeader.antennaPosition.azAngle(
                    svXvt.getPos()))

                correct_sod = np.round(
                    gpstk.YDSTime(obsObject.time).sod / 30.0) * 30  #mod 30s

        r.append([
            gpsTime.getWeek(),
            gpsTime.getSOW(), correct_sod,
            np.array(prnlist),
            np.array(prnspos),
            np.array(prns_clockbias),
            np.array(prns_relcorr),
            np.array(prnselev),
            np.array(prnsaz)
        ] + [np.array(obsdict[i]) for i in obstypes])

    names = [
        "gps_week", "gps_sow", "tod", "prns", "prns_pos", "prns_clockbias",
        "prns_relcorr", "prns_elev", "prns_az"
    ] + obstypes
    r = pd.DataFrame(r, columns=names)
    obsData.close()
    return r, bcestore, np.array(rec_pos)
Exemplo n.º 13
0
def rinex_to_dataframe(obsfile, navfile):
    c = 299792458.

    observation_types=["P1", "P2", "L1", "L2"]
    obsHeader, obsData = gpstk.readRinex3Obs(obsfile)
    navHeader, navData = gpstk.readRinex3Nav(navfile)
    # setup ephemeris store to look for satellite positions
    bcestore = gpstk.GPSEphemerisStore()
    for navDataObj in navData:
        ephem = navDataObj.toGPSEphemeris()
        bcestore.addEphemeris(ephem)
    bcestore.SearchNear()
    navData.close()

    rec_pos = [obsHeader.antennaPosition[0], obsHeader.antennaPosition[1], obsHeader.antennaPosition[2]]
    
    requested_obstypes = observation_types
    obsidxs = []
    obstypes = []
    obsdefs = np.array([i for i in obsHeader.R2ObsTypes])
    for i in requested_obstypes:
        w = np.where(obsdefs==i)[0]
        if len(w)!=0:
            obsidxs.append(w[0])
            obstypes.append(i)
        else:
            print ("WARNING! observation `"+i+"` no present in file")
    obsidxs, obstypes

    r = []
    for obsObject in obsData:
        prnlist = []
        obsdict = {}
        prnspos = []
        prns_clockbias = []
        prns_relcorr = []
        prnselev = []
        prnsaz   = []
        for i in obstypes:
            obsdict[i]=[]

        gpsTime = gpstk.GPSWeekSecond(obsObject.time)

        for satID, datumList in obsObject.obs.iteritems():
            if satID.system == satID.systemGPS:
                prnlist.append("".join(str(satID).split()))
                eph   = bcestore.findEphemeris(satID, obsObject.time)
                

                for i in range(len(obsidxs)):
                    obsdict[obstypes[i]].append(obsObject.getObs(satID, obsidxs[i]).data)
                
                P1 = obsObject.getObs(satID, obsidxs[0]).data
                svTime = obsObject.time - P1/c
                svXvt = eph.svXvt(svTime)
                svTime += - svXvt.getClockBias() + svXvt.getRelativityCorr()
                svXvt = eph.svXvt(svTime)
                
                prnspos.append([svXvt.x[0], svXvt.x[1], svXvt.x[2]])
                prns_clockbias.append(svXvt.getClockBias())
                prns_relcorr.append(svXvt.getRelativityCorr())

                prnselev.append(obsHeader.antennaPosition.elvAngle(svXvt.getPos()))
                prnsaz.append(obsHeader.antennaPosition.azAngle(svXvt.getPos()))
                
        r.append([gpsTime.getWeek(), gpsTime.getSOW(), np.array(prnlist), np.array(prnspos), np.array(prns_clockbias), np.array(prns_relcorr), np.array(prnselev), np.array(prnsaz)] + [np.array(obsdict[i]) for i in obstypes])

    names=["gps_week", "gps_sow", "prns", "prns_pos", "prns_clockbias", "prns_relcorr", "prns_elev", "prns_az"] + obstypes
    r = pd.DataFrame(r, columns=names)
    obsData.close()
    return r, bcestore, np.array(rec_pos)
Exemplo n.º 14
0
 def test_stream_lazy(self):
     header, gen = gpstk.readRinex3Obs(
         gpstk.data.full_path('rinex2obs_data.txt'), strict=False)
     data = list(gen)
     self.assertEqual(120, len(data))
Exemplo n.º 15
0
def getdata(nfile, ofile, strsat=None):  # one week data
    f1, f2 = gpstk.L1_FREQ_GPS, gpstk.L2_FREQ_GPS
    alfa = 1.0 / ((f1 ** 2 / f2 ** 2) - 1)
    t = []  # observation epoch on code and phase
    Iphase, Icode, IPPS = {}, {}, {}  # dicc: key=time observer; values=iono delay and IPP
    VTECphase, VTECcode, ELEV = {}, {}, {}
    PhaseL1, PhaseL2 = {}, {}
    CodeL1, CodeL2 = {}, {}

    oheader, odata = gpstk.readRinex3Obs(ofile, strict=True)
    nheader, ndata = gpstk.readRinex3Nav(nfile)

    bcestore = gpstk.GPSEphemerisStore()

    for ndato in ndata:
        ephem = ndato.toGPSEphemeris()
        bcestore.addEphemeris(ephem)
    bcestore.SearchNear()

    for observation in odata:
        sats = [satID for satID, datumList in observation.obs.iteritems() if str(satID).split()[0] == "GPS"]
        obs_types = np.array([i for i in oheader.R2ObsTypes])
        if "C1" and "P2" and "L1" and "L2" in obs_types:
            for sat in sats:
                if str(sat) == strsat:  # Return for a specific satellite
                    eph = bcestore.findEphemeris(sat, observation.time)
                    Tgd = eph.Tgd
                    sat_pos = eph.svXvt(observation.time)
                    rec_pos = gpstk.Position(
                        oheader.antennaPosition[0], oheader.antennaPosition[1], oheader.antennaPosition[2]
                    ).asECEF()
                    elev = oheader.antennaPosition.elvAngle(sat_pos.x)
                    azim = oheader.antennaPosition.azAngle(sat_pos.x)
                    time = observation.time
                    R = 6.378e6  # earth radius
                    mapp = 1 / np.cos(np.arcsin(R / (R + 350000)) * np.sin(elev))
                    IPP = rec_pos.getIonosphericPiercePoint(elev, azim, 350000).asECEF()
                    t.append(np.trunc(gpstk.YDSTime(time).sod))

                    if (
                        np.size(np.where(obs_types == "C1")) > 0
                        and np.size(np.where(obs_types == "P2")) > 0
                        and np.size(np.where(obs_types == "L1")) > 0
                        and np.size(np.where(obs_types == "L2")) > 0
                    ):

                        C1_idx = np.where(obs_types == "C1")[0][0]
                        P2_idx = np.where(obs_types == "P2")[0][0]
                        R1 = observation.getObs(sat, C1_idx).data
                        R2 = observation.getObs(sat, P2_idx).data

                        L1_idx = np.where(obs_types == "L1")[0][0]
                        L2_idx = np.where(obs_types == "L2")[0][0]
                        L1 = observation.getObs(sat, L1_idx).data * gpstk.L1_WAVELENGTH_GPS
                        L2 = observation.getObs(sat, L2_idx).data * gpstk.L2_WAVELENGTH_GPS

                        if (
                            R2 < 3e7 and R1 < 3e7 and L2 < 3e7 and L1 < 3e7
                        ):  # Distances should be in order of 1e7 meters, more than that is considered an error

                            iono_delay_c = alfa * (R2 - R1)
                            iono_delay_p = alfa * (L1 - L2)

                            vtec_C = iono_delay_c / mapp
                            vtec_P = iono_delay_p / mapp

                            VTECcode[np.trunc(gpstk.YDSTime(time).sod)] = vtec_C
                            VTECphase[np.trunc(gpstk.YDSTime(time).sod)] = vtec_P
                            Icode[np.trunc(gpstk.YDSTime(time).sod)] = iono_delay_c
                            Iphase[np.trunc(gpstk.YDSTime(time).sod)] = iono_delay_p
                            ELEV[np.trunc(gpstk.YDSTime(time).sod)] = elev
                            IPPS[np.trunc(gpstk.YDSTime(time).sod)] = IPP
                            PhaseL1[np.trunc(gpstk.YDSTime(time).sod)] = L1
                            PhaseL2[np.trunc(gpstk.YDSTime(time).sod)] = L2
                            CodeL1[np.trunc(gpstk.YDSTime(time).sod)] = R1
                            CodeL2[np.trunc(gpstk.YDSTime(time).sod)] = R2

                            # stec=(iono_delay_p*f1**2)/(-40.3) #STEC delay on phase [mm]
                            # vtec=stec/mapp #vertical delay!
        else:
            print "Needs both L1 and L2 frequencies to compute delay"
            break

    return t, Icode, Iphase, VTECphase, ELEV, IPPS, PhaseL1, PhaseL2, CodeL1, CodeL2, Tgd
Exemplo n.º 16
0
def process(input_file, output_file):
    try:
        print 'Reading {}.'.format(input_file)
        header, data = gpstk.readRinex3Obs(input_file)  # read in everything
        #print header
        
        new_header = gpstk.Rinex3ObsHeader()
        
        # Initially, valid = 0L, but other values get masked into it.
        new_header.version = header.version
        new_header.fileType = header.fileType
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validVersion
        
        new_header.fileProgram = header.fileProgram
        new_header.date = header.date
        new_header.fileAgency = header.fileAgency
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validRunBy
        
        new_header.markerName = header.markerName
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validMarkerName
        
        new_header.observer = header.observer
        new_header.agency = header.agency
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validObserver
        
        new_header.recNo = header.recNo
        new_header.recType = header.recType
        new_header.recVers = header.recVers
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validReceiver
        
        new_header.antNo = header.antNo
        new_header.antType = header.antType
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validAntennaType 
        
        newAntPosition = gpstk.Triple(header.antennaPosition[0],header.antennaPosition[1],header.antennaPosition[2])
        new_header.antennaPosition = newAntPosition
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validAntennaPosition

        newAntDelta = gpstk.Triple(header.antennaDeltaHEN[0],header.antennaDeltaHEN[1],header.antennaDeltaHEN[2])
        new_header.antennaDeltaHEN = newAntDelta
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validAntennaDeltaHEN
        
        # This is kind of odd.  The Rinex3ObsHeader can handle both V3 and V2
        # formatted files.  The two versions handle observation types differently.
        # - The first structure "mapObsTypes" holds the V3 definitions in a 
        # "dictionary of lists" (or "map of vectors" in c++)
        # - The second structure "R2ObsTypes" holds the V2 definitions and is 
        # stored as list of strings (or Vector of Strings in c++)
        # It's not clear whether either or both are necessary to write a file.
        # It DOES seem to be clear that both will be available after reading a file.
        
        for rinObsType in header.mapObsTypes:
            #print "Found obs-type:{}".format(rinObsType)
            newObsIds = []
            for rinObsId in header.mapObsTypes[rinObsType]:
                #print "Found obs-id:{}".format(str(rinObsId))
                #print " --type={} code={} band={}".format(rinObsId.type, rinObsId.code, rinObsId.band)
                newObsId = gpstk.RinexObsID(str(rinObsId))
                newObsIds.append(newObsId)
            new_header.mapObsTypes[rinObsType] = tuple(newObsIds) 
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validNumObs

        for rin_obs_id in header.R2ObsTypes:
            #print "Found obs-id:{}".format(rin_obs_id)
            new_header.R2ObsTypes.append(rin_obs_id)
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validNumObs
            
        # This creates a new CivilTime object that we can populate
        new_header.firstObs = gpstk.CivilTime()
        new_header.firstObs.year = header.firstObs.year
        new_header.firstObs.month = header.firstObs.month
        new_header.firstObs.day = header.firstObs.day
        new_header.firstObs.hour = header.firstObs.hour
        new_header.firstObs.minute = header.firstObs.minute
        new_header.firstObs.second = header.firstObs.second
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validFirstTime
        
        new_header.markerNumber = header.markerNumber
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validMarkerNumber
        
        new_header.interval = header.interval
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validInterval 
        
        #####
        # Unfortunately, sigStrengthUnit is tied to the wavelengthFactor property,
        # We cannot set the latter due to a missing SWIG Python adapter, and 
        # because the same "validity flag" governs both, we can't output
        # sigStrengthUnit without inadvertently outputting a bogus wavelengthFactor.
        #####
        #new_header.wavelengthFactor = header.wavelengthFactor
        #new_header.sigStrengthUnit = header.sigStrengthUnit
        #new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validSigStrengthUnit
        
        for comment in header.commentList: 
            new_header.commentList.append(comment)
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validComment
        
        new_header.validEoH = True
        
        # This method is a huge hack to get around a problem in the Rinex3ObsData
        # writer.  See the method for details.
        new_header = tweakInternalHeaderState(new_header)
        #print new_header
        
        processed_data = []
        # Now we loop through all the epochs and process the data for each one
        for d in data:
            
            # This creates a new CommonTime object with the system set to GPS.
            timec = gpstk.CommonTime(gpstk.TimeSystem(gpstk.TimeSystem.GPS))
            # This creates a new CommonTime object with the system set to GPS.
            mjd = int(d.time.getDays())
            sod = float(d.time.getSecondOfDay())
            timec.set(mjd, sod, gpstk.TimeSystem(gpstk.TimeSystem.GPS))
            
            # Assign values to a new Rinex Obs Data object
            nd = gpstk.Rinex3ObsData()
            nd.time = timec
            nd.auxHeader = d.auxHeader
            nd.clockOffset = d.clockOffset
            nd.epochFlag= d.epochFlag
            nd.numSVs = d.numSVs
            
            for satkey in d.obs.keys():
                newSatKey = gpstk.RinexSatID(satkey.toString())
                satObss = d.obs[newSatKey]
                # satObss is a tuple of  RinexDatum
                newSatObss = []
                for satObs in satObss:
                    #print "{} {} {} {}".format(satkey.toString(), satObs.data, satObs.lli, satObs.ssi)
                    newSatObs = gpstk.RinexDatum()
                    newSatObs.data = satObs.data
                    newSatObs.lli = satObs.lli
                    newSatObs.ssi = satObs.ssi
                    newSatObss.append(newSatObs)

                nd.obs[newSatKey] = tuple(newSatObss)

            #print "O{}".format(d)
            #print "S{}".format(nd)
            processed_data.append(nd)

        gpstk.writeRinex3Obs(output_file, new_header, processed_data)
        print "Wrote output file: {}".format(output_file)

    # We can catch any custom gpstk exception like this:
    except gpstk.Exception as e:
        print e
Exemplo n.º 17
0
"""
1. Extract pseudorange obs 
2. compute biased multipath observation.
"""
from __future__ import print_function
from gpstk import C_MPS, GAMMA_GPS, L1_FREQ_GPS
import gpstk


rfn = gpstk.getPathData() + '/test_input_rinex2_obs_RinexObsFile.06o'

# Make a GPSTk SatID used to find a specific satellite in the data
svid = gpstk.RinexSatID(5, gpstk.SatID.systemGPS)

try:
    header, data = gpstk.readRinex3Obs(rfn, strict=True)
    print(header)

    # Loop through all the epochs and process the data for each one
    for d in data:
        # Note that d is now a Rinex3ObsData

        # Check if the PRN is in view (by searching for it)
        if d.obs.find(svid) == d.obs.end():
            print(gpstk.CivilTime(d.time), 'svid', svid, 'not in view')
        else:
            P1 = d.getObs(svid, "C1W", header).data
            P2 = d.getObs(svid, "C2W", header).data
            L1 = d.getObs(svid, "L1C", header).data
            mu = P1 - L1 * (C_MPS / L1_FREQ_GPS) - 2 * (P1 - P2) / (1 - GAMMA_GPS)
            print(gpstk.CivilTime(d.time), svid, 'biased multipath', mu)
Exemplo n.º 18
0
  python ./example5.py rinex2obs_data.txt

"""

import argparse
import gpstk

parser = argparse.ArgumentParser()
parser.add_argument('rinex2obs_filename')
args = parser.parse_args()

try:
    print 'Reading ' + args.rinex2obs_filename + '.'

    # read in header and get a generator for the data
    header, data = gpstk.readRinex3Obs(args.rinex2obs_filename)
    print header

    for d in data:
        civtime = gpstk.CivilTime(d.time)
        print civtime
        oe = gpstk.ObsEpoch()
        oe.time = d.time
        for sv in d.obs.keys():
            print sv,
            epoch = d.obs[sv]
            soe = gpstk.SvObsEpoch()
            soe.svid = sv
            for i in range(len(epoch)):
                rinex2_obs_type = header.R2ObsTypes[i]
                oid = header.mapObsTypes['G'][i]
#!/usr/bin/env python
"""
An example of generating new rinex file (both v2,11 and v3.02.
First an existing v2.11 file is read in just so we don't have
to make up all the data that goes into the new files.
"""

import gpstk

ifn = gpstk.getPathData() + '/test_input_rinex2_obs_RinexObsFile.06o'
header, data = gpstk.readRinex3Obs(ifn, strict=True)

new_header = gpstk.Rinex3ObsHeader()

new_header.fileType = header.fileType

new_header.fileProgram = header.fileProgram
new_header.date = header.date
new_header.fileAgency = header.fileAgency
new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validRunBy

new_header.markerName = header.markerName
new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validMarkerName

new_header.observer = header.observer
new_header.agency = header.agency
new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validObserver

new_header.recNo = header.recNo
new_header.recType = header.recType
new_header.recVers = header.recVers
Exemplo n.º 20
0
#!/usr/bin/env python
"""
An example of how to walk a RINEX data set and use SatID and ObsID,
building an obsEpochMap of the data along the way.
"""
from __future__ import print_function
import gpstk

fn = gpstk.getPathData() + '/arlm200z.15o'

# read in header and get a generator for the data
header, data = gpstk.readRinex3Obs(fn)
print(header)

oem = gpstk.ObsEpochMap()
for d in data:
    print(gpstk.CivilTime(d.time))
    oe = gpstk.ObsEpoch()
    oe.time = d.time
    for sv in list(d.obs.keys()):
        # sv is an SatID object
        print(sv, end=' ')
        epoch = d.obs[sv]
        soe = gpstk.SvObsEpoch()
        soe.svid = sv
        for i in range(len(epoch)):
            rinex2_obs_type = header.R2ObsTypes[i]
            oid = header.mapObsTypes['G'][i]
            print("{}({})={}".format(oid, rinex2_obs_type, epoch[i].data),
                  end=' ')
            soe[oid] = epoch[i].data
Exemplo n.º 21
0
    def test_writeRinex3Obs(self):
        """Test reading and writing back out a rinex obs file"""

        header, data = gpstk.readRinex3Obs( args.input_dir+"/arlm200a.15o", strict=True)
        # Now let's write it all back to a different file
        gpstk.writeRinex3Obs( args.output_dir+'/swig-arlm200a.15o', header, data)
Exemplo n.º 22
0
 def test_stream_lazy(self):
     header, gen = gpstk.readRinex3Obs('rinex3obs_data.txt', strict=False)
     data = list(gen)
     self.assertEqual(120, len(data))
Exemplo n.º 23
0
#!/usr/bin/env python

"""
An example of how to walk a RINEX data set and use SatID and ObsID,
building an obsEpochMap of the data along the way.
"""

import gpstk

fn = gpstk.getPathData() + '/arlm200z.15o'

# read in header and get a generator for the data
header, data = gpstk.readRinex3Obs(fn)
print header

oem = gpstk.ObsEpochMap()
for d in data:
    print gpstk.CivilTime(d.time)
    oe=gpstk.ObsEpoch()
    oe.time = d.time
    for sv in d.obs.keys():
        # sv is an SatID object
        print sv,
        epoch = d.obs[sv]
        soe = gpstk.SvObsEpoch()
        soe.svid = sv
        for i in range(len(epoch)):
            rinex2_obs_type = header.R2ObsTypes[i]
            oid = header.mapObsTypes['G'][i]
            print "{}({})={}".format(str(oid), rinex2_obs_type, epoch[i].data),
            soe[oid] = epoch[i].data
Exemplo n.º 24
0
def process(input_file, output_file):
    try:
        print 'Reading {}.'.format(input_file)
        header, data = gpstk.readRinex3Obs(input_file)  # read in everything
        #print header

        new_header = gpstk.Rinex3ObsHeader()

        # Initially, valid = 0L, but other values get masked into it.
        new_header.version = header.version
        new_header.fileType = header.fileType
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validVersion

        new_header.fileProgram = header.fileProgram
        new_header.date = header.date
        new_header.fileAgency = header.fileAgency
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validRunBy

        new_header.markerName = header.markerName
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validMarkerName

        new_header.observer = header.observer
        new_header.agency = header.agency
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validObserver

        new_header.recNo = header.recNo
        new_header.recType = header.recType
        new_header.recVers = header.recVers
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validReceiver

        new_header.antNo = header.antNo
        new_header.antType = header.antType
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validAntennaType

        newAntPosition = gpstk.Triple(header.antennaPosition[0],
                                      header.antennaPosition[1],
                                      header.antennaPosition[2])
        new_header.antennaPosition = newAntPosition
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validAntennaPosition

        newAntDelta = gpstk.Triple(header.antennaDeltaHEN[0],
                                   header.antennaDeltaHEN[1],
                                   header.antennaDeltaHEN[2])
        new_header.antennaDeltaHEN = newAntDelta
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validAntennaDeltaHEN

        # This is kind of odd.  The Rinex3ObsHeader can handle both V3 and V2
        # formatted files.  The two versions handle observation types differently.
        # - The first structure "mapObsTypes" holds the V3 definitions in a
        # "dictionary of lists" (or "map of vectors" in c++)
        # - The second structure "R2ObsTypes" holds the V2 definitions and is
        # stored as list of strings (or Vector of Strings in c++)
        # It's not clear whether either or both are necessary to write a file.
        # It DOES seem to be clear that both will be available after reading a file.

        for rinObsType in header.mapObsTypes:
            #print "Found obs-type:{}".format(rinObsType)
            newObsIds = []
            for rinObsId in header.mapObsTypes[rinObsType]:
                #print "Found obs-id:{}".format(str(rinObsId))
                #print " --type={} code={} band={}".format(rinObsId.type, rinObsId.code, rinObsId.band)
                newObsId = gpstk.RinexObsID(str(rinObsId))
                newObsIds.append(newObsId)
            new_header.mapObsTypes[rinObsType] = tuple(newObsIds)
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validNumObs

        for rin_obs_id in header.R2ObsTypes:
            #print "Found obs-id:{}".format(rin_obs_id)
            new_header.R2ObsTypes.append(rin_obs_id)
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validNumObs

        # This creates a new CivilTime object that we can populate
        new_header.firstObs = gpstk.CivilTime()
        new_header.firstObs.year = header.firstObs.year
        new_header.firstObs.month = header.firstObs.month
        new_header.firstObs.day = header.firstObs.day
        new_header.firstObs.hour = header.firstObs.hour
        new_header.firstObs.minute = header.firstObs.minute
        new_header.firstObs.second = header.firstObs.second
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validFirstTime

        new_header.markerNumber = header.markerNumber
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validMarkerNumber

        new_header.interval = header.interval
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validInterval

        #####
        # Unfortunately, sigStrengthUnit is tied to the wavelengthFactor property,
        # We cannot set the latter due to a missing SWIG Python adapter, and
        # because the same "validity flag" governs both, we can't output
        # sigStrengthUnit without inadvertently outputting a bogus wavelengthFactor.
        #####
        #new_header.wavelengthFactor = header.wavelengthFactor
        #new_header.sigStrengthUnit = header.sigStrengthUnit
        #new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validSigStrengthUnit

        for comment in header.commentList:
            new_header.commentList.append(comment)
        new_header.valid = new_header.valid | gpstk.Rinex3ObsHeader.validComment

        new_header.validEoH = True

        # This method is a huge hack to get around a problem in the Rinex3ObsData
        # writer.  See the method for details.
        new_header = tweakInternalHeaderState(new_header)
        #print new_header

        processed_data = []
        # Now we loop through all the epochs and process the data for each one
        for d in data:

            # This creates a new CommonTime object with the system set to GPS.
            timec = gpstk.CommonTime(gpstk.TimeSystem(gpstk.TimeSystem.GPS))
            # This creates a new CommonTime object with the system set to GPS.
            mjd = int(d.time.getDays())
            sod = float(d.time.getSecondOfDay())
            timec.set(mjd, sod, gpstk.TimeSystem(gpstk.TimeSystem.GPS))

            # Assign values to a new Rinex Obs Data object
            nd = gpstk.Rinex3ObsData()
            nd.time = timec
            nd.auxHeader = d.auxHeader
            nd.clockOffset = d.clockOffset
            nd.epochFlag = d.epochFlag
            nd.numSVs = d.numSVs

            for satkey in d.obs.keys():
                newSatKey = gpstk.RinexSatID(satkey.toString())
                satObss = d.obs[newSatKey]
                # satObss is a tuple of  RinexDatum
                newSatObss = []
                for satObs in satObss:
                    #print "{} {} {} {}".format(satkey.toString(), satObs.data, satObs.lli, satObs.ssi)
                    newSatObs = gpstk.RinexDatum()
                    newSatObs.data = satObs.data
                    newSatObs.lli = satObs.lli
                    newSatObs.ssi = satObs.ssi
                    newSatObss.append(newSatObs)

                nd.obs[newSatKey] = tuple(newSatObss)

            #print "O{}".format(d)
            #print "S{}".format(nd)
            processed_data.append(nd)

        gpstk.writeRinex3Obs(output_file, new_header, processed_data)
        print "Wrote output file: {}".format(output_file)

    # We can catch any custom gpstk exception like this:
    except gpstk.Exception as e:
        print e
Exemplo n.º 25
0
  python ./example5.py rinex2obs_data.txt

"""

import argparse
import gpstk

parser = argparse.ArgumentParser()
parser.add_argument("rinex2obs_filename")
args = parser.parse_args()

try:
    print "Reading " + args.rinex2obs_filename + "."

    # read in header and get a generator for the data
    header, data = gpstk.readRinex3Obs(args.rinex2obs_filename)
    print header

    for d in data:
        civtime = gpstk.CivilTime(d.time)
        print civtime
        oe = gpstk.ObsEpoch()
        oe.time = d.time
        for sv in d.obs.keys():
            print sv,
            epoch = d.obs[sv]
            soe = gpstk.SvObsEpoch()
            soe.svid = sv
            for i in range(len(epoch)):
                rinex2_obs_type = header.R2ObsTypes[i]
                oid = header.mapObsTypes["G"][i]
Exemplo n.º 26
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('rinex3obs_filename')
    parser.add_argument('rinex3nav_filename')
    parser.add_argument('-m', '--rinexmet_filename')
    args = parser.parse_args()

    # Declaration of objects for storing ephemerides and handling RAIM
    bcestore = gpstk.GPSEphemerisStore()
    raimSolver = gpstk.PRSolution2()

    # Object for void-type tropospheric model (in case no meteorological
    # RINEX is available)
    noTropModel = gpstk.ZeroTropModel()

    # Object for GG-type tropospheric model (Goad and Goodman, 1974)
    #  Default constructor => default values for model
    ggTropModel = gpstk.GGTropModel()

    # Pointer to one of the two available tropospheric models. It points
    # to the void model by default
    tropModel = noTropModel

    navHeader, navData = gpstk.readRinex3Nav(args.rinex3nav_filename)
    for navDataObj in navData:
        ephem = navDataObj.toEngEphemeris()
        bcestore.addEphemeris(ephem)

    # Setting the criteria for looking up ephemeris:
    bcestore.SearchNear()

    if args.rinexmet_filename is not None:
        metHeader, metData = gpstk.readRinexMet(args.rinexmet_filename)
        tropModel = ggTropModel

    obsHeader, obsData = gpstk.readRinex3Obs(args.rinex3obs_filename)

    # The following lines fetch the corresponding indexes for some
    # observation types we are interested in. Given that old-style
    # observation types are used, GPS is assumed.
    try:
        indexP1 = obsHeader.getObsIndex('P1')
    except:
        print 'The observation files has no P1 pseudoranges.'
        sys.exit()

    try:
        indexP2 = obsHeader.getObsIndex('P2')
    except:
        indexP2 = -1

    for obsObj in obsData:
        # Find a weather point. Only if a meteorological RINEX file
        # was provided, the meteorological data linked list "rml" is
        # neither empty or at its end, and the time of meteorological
        # records are below observation data epoch.
        if args.rinexmet_filename is not None:
            for metObj in metData:
                if metObj.time >= obsObj.time:
                    break
                else:
                    metDataDict = metObj.getData()
                    temp = metDataDict[gpstk.RinexMetHeader.TD]
                    pressure = metDataDict[gpstk.RinexMetHeader.PR]
                    humidity = metDataDict[gpstk.RinexMetHeader.HR]
                    ggTropModel.setWeather(temp, pressure, humidity)

        if obsObj.epochFlag == 0 or obsObj.epochFlag == 1:
            # Note that we use lists here, but we will need types backed
            # by C++ std::vectors later. We'll just keep it easy and use
            # gpstk.seqToVector to convert them. If there was a speed
            # bottleneck we could use gpstk.cpp.vector_SatID and
            # gpstk.cpp.vector_double though.
            prnList = []
            rangeList = []

            # This part gets the PRN numbers and ionosphere-corrected
            # pseudoranges for the current epoch. They are correspondly fed
            # into "prnList" and "rangeList"; "obs" is a public attribute of
            # Rinex3ObsData to get the map of observations
            for satID, datumList in obsObj.obs.iteritems():
                # The RINEX file may have P1 observations, but the current
                # satellite may not have them.
                P1 = 0.0
                try:
                    P1 = obsObj.getObs(satID, indexP1).data
                except gpstk.exceptions.Exception:
                    continue  # Ignore this satellite if P1 is not found

                ionocorr = 0.0

                # If there are P2 observations, let's try to apply the
                # ionospheric corrections
                if indexP2 >= 0:
                    # The RINEX file may have P2 observations, but the
                    # current satellite may not have them.
                    P2 = 0.0
                    try:
                        P2 = obsObj.getObs(satID, indexP2).data
                    except gpstk.exceptions.Exception:
                        continue  # Ignore this satellite if P1 is not found
                    # list 'vecList' contains RinexDatum, whose public
                    # attribute "data" indeed holds the actual data point
                    ionocorr = 1.0 / (1.0 - gpstk.constants.GAMMA_GPS) * (P1 -
                                                                          P2)

                # Now, we include the current PRN number in the first part
                # of "it" iterator into the list holding the satellites.
                # All satellites in view at this epoch that have P1 or P1+P2
                # observations will be included.
                prnList.append(satID)

                # The same is done for the list of doubles holding the
                # corrected ranges
                rangeList.append(P1 - ionocorr)
                # WARNING: Please note that so far no further correction
                # is done on data: Relativistic effects, tropospheric
                # correction, instrumental delays, etc

            # The default constructor for PRSolution2 objects (like
            # "raimSolver") is to set a RMSLimit of 6.5. We change that
            # here. With this value of 3e6 the solution will have a lot
            # more dispersion.
            raimSolver.RMSLimit = 3e6

            # In order to compute positions we need the current time, the
            # vector of visible satellites, the vector of corresponding
            # ranges, the object containing satellite ephemerides, and a
            # pointer to the tropospheric model to be applied

            time = obsObj.time

            # the RAIMComputer method of PRSolution2 accepts a vector<SatID> as its
            # 2nd argument, but the list is of RinexSatID, which is a subclass of SatID.
            # Since C++ containers are NOT covariant, it is neccessary to change the
            # output to a vector or SatID's rather thta a vector of RinexSatID's.
            satVector = gpstk.cpp.seqToVector(prnList, outtype='vector_SatID')
            rangeVector = gpstk.cpp.seqToVector(rangeList)
            raimSolver.RAIMCompute(time, satVector, rangeVector, bcestore,
                                   tropModel)

            # Note: Given that the default constructor sets public
            # attribute "Algebraic" to FALSE, a linearized least squares
            # algorithm will be used to get the solutions.
            # Also, the default constructor sets ResidualCriterion to true,
            # so the rejection criterion is based on RMS residual of fit,
            # instead of RMS distance from an a priori position.

            if raimSolver.isValid():
                # Vector "Solution" holds the coordinates, expressed in
                # meters in an Earth Centered, Earth Fixed (ECEF) reference
                # frame. The order is x, y, z  (as all ECEF objects)
                x, y, z = raimSolver.Solution[0], raimSolver.Solution[
                    1], raimSolver.Solution[2]
                print "%12.5f %12.5f %12.5f" % (x, y, z)
Exemplo n.º 27
0
def getdata(nfile, ofile, strsat=None):  #one week data
    f1, f2 = gpstk.L1_FREQ_GPS, gpstk.L2_FREQ_GPS
    alfa = 1.0 / ((f1**2 / f2**2) - 1)
    t = []  #observation epoch on code and phase
    Iphase, Icode, IPPS = {}, {}, {
    }  #dicc: key=time observer; values=iono delay and IPP
    VTECphase, VTECcode, ELEV = {}, {}, {}
    PhaseL1, PhaseL2 = {}, {}
    CodeL1, CodeL2 = {}, {}

    oheader, odata = gpstk.readRinex3Obs(ofile, strict=True)
    nheader, ndata = gpstk.readRinex3Nav(nfile)

    bcestore = gpstk.GPSEphemerisStore()

    for ndato in ndata:
        ephem = ndato.toGPSEphemeris()
        bcestore.addEphemeris(ephem)
    bcestore.SearchNear()

    for observation in odata:
        sats = [
            satID for satID, datumList in observation.obs.iteritems()
            if str(satID).split()[0] == "GPS"
        ]
        obs_types = np.array([i for i in oheader.R2ObsTypes])
        if 'C1' and 'P2' and 'L1' and 'L2' in obs_types:
            for sat in sats:
                if str(sat) == strsat:  #Return for a specific satellite
                    eph = bcestore.findEphemeris(sat, observation.time)
                    Tgd = eph.Tgd
                    sat_pos = eph.svXvt(observation.time)
                    rec_pos = gpstk.Position(
                        oheader.antennaPosition[0], oheader.antennaPosition[1],
                        oheader.antennaPosition[2]).asECEF()
                    elev = oheader.antennaPosition.elvAngle(sat_pos.x)
                    azim = oheader.antennaPosition.azAngle(sat_pos.x)
                    time = observation.time
                    R = 6.378e6  #earth radius
                    mapp = 1 / np.cos(
                        np.arcsin(R / (R + 350000)) * np.sin(elev))
                    IPP = rec_pos.getIonosphericPiercePoint(
                        elev, azim, 350000).asECEF()
                    t.append(np.trunc(gpstk.YDSTime(time).sod))

                    if np.size(np.where(obs_types == 'C1')) > 0 and np.size(
                            np.where(obs_types == 'P2')) > 0 and np.size(
                                np.where(obs_types == 'L1')) > 0 and np.size(
                                    np.where(obs_types == 'L2')) > 0:

                        C1_idx = np.where(obs_types == 'C1')[0][0]
                        P2_idx = np.where(obs_types == 'P2')[0][0]
                        R1 = observation.getObs(sat, C1_idx).data
                        R2 = observation.getObs(sat, P2_idx).data

                        L1_idx = np.where(obs_types == 'L1')[0][0]
                        L2_idx = np.where(obs_types == 'L2')[0][0]
                        L1 = observation.getObs(
                            sat, L1_idx).data * gpstk.L1_WAVELENGTH_GPS
                        L2 = observation.getObs(
                            sat, L2_idx).data * gpstk.L2_WAVELENGTH_GPS

                        if R2 < 3e7 and R1 < 3e7 and L2 < 3e7 and L1 < 3e7:  #Distances should be in order of 1e7 meters, more than that is considered an error

                            iono_delay_c = alfa * (R2 - R1)
                            iono_delay_p = alfa * (L1 - L2)

                            vtec_C = iono_delay_c / mapp
                            vtec_P = iono_delay_p / mapp

                            VTECcode[np.trunc(
                                gpstk.YDSTime(time).sod)] = vtec_C
                            VTECphase[np.trunc(
                                gpstk.YDSTime(time).sod)] = vtec_P
                            Icode[np.trunc(
                                gpstk.YDSTime(time).sod)] = iono_delay_c
                            Iphase[np.trunc(
                                gpstk.YDSTime(time).sod)] = iono_delay_p
                            ELEV[np.trunc(gpstk.YDSTime(time).sod)] = elev
                            IPPS[np.trunc(gpstk.YDSTime(time).sod)] = IPP
                            PhaseL1[np.trunc(gpstk.YDSTime(time).sod)] = L1
                            PhaseL2[np.trunc(gpstk.YDSTime(time).sod)] = L2
                            CodeL1[np.trunc(gpstk.YDSTime(time).sod)] = R1
                            CodeL2[np.trunc(gpstk.YDSTime(time).sod)] = R2

                            #stec=(iono_delay_p*f1**2)/(-40.3) #STEC delay on phase [mm]
                            #vtec=stec/mapp #vertical delay!
        else:
            print "Needs both L1 and L2 frequencies to compute delay"
            break

    return t, Icode, Iphase, VTECphase, ELEV, IPPS, PhaseL1, PhaseL2, CodeL1, CodeL2, Tgd
Exemplo n.º 28
0
import gpstk
import sys

obsfn = gpstk.getPathData() + '/arlm200z.15o'
navfn = gpstk.getPathData() + '/arlm200z.15n'
metfn = gpstk.getPathData() + '/arlm200z.15m'

navHeader, navData = gpstk.readRinex3Nav(navfn)
ephStore = gpstk.gpstk.Rinex3EphemerisStore()
for navDataObj in navData:
    ephStore.addEphemeris(navDataObj)

tropModel = gpstk.GGTropModel()
metHeader, metData = gpstk.readRinexMet(metfn)

obsHeader, obsData = gpstk.readRinex3Obs(obsfn)

indexP1 = obsHeader.getObsIndex('C1W')
indexP2 = obsHeader.getObsIndex('C2W')
raimSolver = gpstk.PRSolution2()

for obsObj in obsData:
    for metObj in metData:
        if metObj.time >= obsObj.time:
            break
        else:
            metDataDict = metObj.getData()
            temp = metDataDict[gpstk.RinexMetHeader.TD]
            pressure = metDataDict[gpstk.RinexMetHeader.PR]
            humidity = metDataDict[gpstk.RinexMetHeader.HR]
            tropModel.setWeather(temp, pressure, humidity)
Exemplo n.º 29
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('rinex3obs_filename')
    parser.add_argument('rinex3nav_filename')
    parser.add_argument('-m', '--rinexmet_filename')
    args = parser.parse_args()

    # Declaration of objects for storing ephemerides and handling RAIM
    bcestore = gpstk.GPSEphemerisStore()
    raimSolver = gpstk.PRSolution2()

    # Object for void-type tropospheric model (in case no meteorological
    # RINEX is available)
    noTropModel = gpstk.ZeroTropModel()

    # Object for GG-type tropospheric model (Goad and Goodman, 1974)
    #  Default constructor => default values for model
    ggTropModel = gpstk.GGTropModel()

    # Pointer to one of the two available tropospheric models. It points
    # to the void model by default
    tropModel = noTropModel


    navHeader, navData = gpstk.readRinex3Nav(args.rinex3nav_filename)
    for navDataObj in navData:
        ephem = navDataObj.toEngEphemeris()
        bcestore.addEphemeris(ephem)

    # Setting the criteria for looking up ephemeris:
    bcestore.SearchNear()

    if args.rinexmet_filename is not None:
        metHeader, metData = gpstk.readRinexMet(args.rinexmet_filename)
        tropModel = ggTropModel

    obsHeader, obsData = gpstk.readRinex3Obs(args.rinex3obs_filename)

    # The following lines fetch the corresponding indexes for some
    # observation types we are interested in. Given that old-style
    # observation types are used, GPS is assumed.
    try:
        indexP1 = obsHeader.getObsIndex('C1P')
    except:
        print 'The observation files has no L1 C/A pseudoranges.'
        sys.exit()

    try:
        indexP2 = obsHeader.getObsIndex('C2W')
    except:
        print 'The observation files has no L2 codeless pseudoranges.'
        indexP2 = -1

    for obsObj in obsData:
        # Find a weather point. Only if a meteorological RINEX file
        # was provided, the meteorological data linked list "rml" is
        # neither empty or at its end, and the time of meteorological
        # records are below observation data epoch.
        if args.rinexmet_filename is not None:
            for metObj in metData:
                if metObj.time >= obsObj.time:
                    break
                else:
                    metDataDict = metObj.getData()
                    temp = metDataDict[gpstk.RinexMetHeader.TD]
                    pressure = metDataDict[gpstk.RinexMetHeader.PR]
                    humidity = metDataDict[gpstk.RinexMetHeader.HR]
                    ggTropModel.setWeather(temp, pressure, humidity)

        if obsObj.epochFlag == 0 or obsObj.epochFlag == 1:
            # Note that we use lists here, but we will need types backed
            # by C++ std::vectors later. We'll just keep it easy and use
            # gpstk.seqToVector to convert them. If there was a speed
            # bottleneck we could use gpstk.cpp.vector_SatID and
            # gpstk.cpp.vector_double though.
            prnList = []
            rangeList = []

            # This part gets the PRN numbers and ionosphere-corrected
            # pseudoranges for the current epoch. They are correspondly fed
            # into "prnList" and "rangeList"; "obs" is a public attribute of
            # Rinex3ObsData to get the map of observations
            for satID, datumList in obsObj.obs.iteritems():
                # The RINEX file may have P1 observations, but the current
                 # satellite may not have them.
                P1 = 0.0
                try:
                    P1 = obsObj.getObs(satID, indexP1).data
                except gpstk.exceptions.Exception:
                    continue  # Ignore this satellite if P1 is not found

                ionocorr = 0.0

                  # If there are P2 observations, let's try to apply the
                  # ionospheric corrections
                if indexP2 >= 0:
                    # The RINEX file may have P2 observations, but the
                    # current satellite may not have them.
                    P2 = 0.0
                    try:
                        P2 = obsObj.getObs(satID, indexP2).data
                    except gpstk.exceptions.Exception:
                        continue  # Ignore this satellite if P1 is not found
                    # list 'vecList' contains RinexDatum, whose public
                    # attribute "data" indeed holds the actual data point
                    ionocorr = 1.0 / (1.0 - gpstk.GAMMA_GPS) * ( P1 - P2 )

                # Now, we include the current PRN number in the first part
                # of "it" iterator into the list holding the satellites.
                # All satellites in view at this epoch that have P1 or P1+P2
                # observations will be included.
                prnList.append(satID)

                # The same is done for the list of doubles holding the
                # corrected ranges
                rangeList.append(P1 - ionocorr)
                # WARNING: Please note that so far no further correction
                # is done on data: Relativistic effects, tropospheric
                # correction, instrumental delays, etc

            # The default constructor for PRSolution2 objects (like
            # "raimSolver") is to set a RMSLimit of 6.5. We change that
            # here. With this value of 3e6 the solution will have a lot
            # more dispersion.
            raimSolver.RMSLimit = 3e6


            # In order to compute positions we need the current time, the
            # vector of visible satellites, the vector of corresponding
            # ranges, the object containing satellite ephemerides, and a
            # pointer to the tropospheric model to be applied

            time = obsObj.time

            # the RAIMComputer method of PRSolution2 accepts a vector<SatID> as its
            # 2nd argument, but the list is of RinexSatID, which is a subclass of SatID.
            # Since C++ containers are NOT covariant, it is neccessary to change the
            # output to a vector or SatID's rather thta a vector of RinexSatID's.
            satVector = gpstk.cpp.seqToVector(prnList, outtype='vector_SatID')
            rangeVector = gpstk.cpp.seqToVector(rangeList)
            raimSolver.RAIMCompute(time, satVector, rangeVector, bcestore, tropModel)

            # Note: Given that the default constructor sets public
            # attribute "Algebraic" to FALSE, a linearized least squares
            # algorithm will be used to get the solutions.
            # Also, the default constructor sets ResidualCriterion to true,
            # so the rejection criterion is based on RMS residual of fit,
            # instead of RMS distance from an a priori position.


            if raimSolver.isValid():
                # Vector "Solution" holds the coordinates, expressed in
                # meters in an Earth Centered, Earth Fixed (ECEF) reference
                # frame. The order is x, y, z  (as all ECEF objects)
                x, y, z = raimSolver.Solution[0],  raimSolver.Solution[1], raimSolver.Solution[2]
                print "%12.5f %12.5f %12.5f" % (x, y, z)