This repository has been archived by the owner on Nov 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
gps.py
4162 lines (3820 loc) · 147 KB
/
gps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!usr/bin/env python
# -*- coding: utf-8 -*-
# kristine larson, june 2017
# toolbox for GPS/GNSS data analysis
import datetime
from datetime import date
import math
import os
import pickle
import re
import scipy.signal as spectral
from scipy.interpolate import interp1d
import subprocess
import sys
import matplotlib.pyplot as plt
import numpy as np
import wget
import read_snr_files as snr
# various numbers you need in the GNSS world
# mostly frequencies and wavelengths
class constants:
c= 299792458 # m/sec
# GPS frequencies and wavelengths
fL1 = 1575.42 # MegaHz 154*10.23
fL2 = 1227.60 # 120*10.23
fL5 = 115*10.23
# GPS wavelengths
wL1 = c/(fL1*1e6) # meters wavelength
wL2 = c/(fL2*1e6)
wL5 = c/(fL5*1e6)
# galileo frequency values
gal_L1 = 1575.420
gal_L5 = 1176.450
gal_L6 = 1278.70
gal_L7 = 1207.140
gal_L8 = 1191.795
# galileo wavelengths, meters
wgL1 = c/(gal_L1*1e6)
wgL5 = c/(gal_L5*1e6)
wgL6 = c/(gal_L6*1e6)
wgL7 = c/(gal_L7*1e6)
wgL8 = c/(gal_L8*1e6)
# beidou frequencies and wavelengths
bei_L2 = 1561.098
bei_L7 = 1207.14
bei_L6 = 1268.52
wbL2 = c/(bei_L2*1e6)
wbL7 = c/(bei_L7*1e6)
wbL6 = c/(bei_L6*1e6)
# Earth rotation rate used in GPS Nav message
omegaEarth = 7.2921151467E-5 # %rad/sec
mu = 3.986005e14 # Earth GM value
class wgs84:
"""
wgs84 parameters
"""
a = 6378137. # meters
f = 1./298.257223563 # flattening factor
e = np.sqrt(2*f-f**2) #
def define_filename(station,year,doy,snr):
"""
given station name, year, doy, snr type
year doy and snr are integers
returns snr filenames (both uncompressed and compressed)
author: Kristine Larson
19mar25: return compressed filename too
20apr12: fixed typo in xz name!
"""
xdir = os.environ['REFL_CODE']
cdoy = '{:03d}'.format(doy)
cyy = '{:02d}'.format(year-2000)
f= station + str(cdoy) + '0.' + cyy + '.snr' + str(snr)
fname = xdir + '/' + str(year) + '/snr/' + station + '/' + f
fname2 = xdir + '/' + str(year) + '/snr/' + station + '/' + f + '.xz'
return fname, fname2
def define_and_xz_snr(station,year,doy,snr):
"""
given station name, year, doy, snr type
returns snr filename
author: Kristine Larson
19mar25: return compressed filename too
20apr12: fixed typo in xz name! now try to compress here
"""
xdir = os.environ['REFL_CODE']
cdoy = '{:03d}'.format(doy)
cyy = '{:02d}'.format(year-2000)
f= station + str(cdoy) + '0.' + cyy + '.snr' + str(snr)
fname = xdir + '/' + str(year) + '/snr/' + station + '/' + f
fname2 = xdir + '/' + str(year) + '/snr/' + station + '/' + f + '.xz'
snre = False
if os.path.isfile(fname):
print('snr file exists')
snre = True
else:
if os.path.isfile(fname2):
print('found xz compressed snr file - try to unxz it')
subprocess.call(['unxz', fname2])
# check that it was success
if os.path.isfile(fname):
snre = True
# return fname2 but mostly for backwards compatibility
return fname, fname2, snre
def define_filename_prevday(station,year,doy,snr):
"""
given station name, year, doy, snr type
returns snr filename for the PREVIOUS day
author: Kristine Larson
"""
xdir = os.environ['REFL_CODE']
year = int(year)
doy = int(doy)
if (doy == 1):
pyear = year -1
print('found january 1, so previous day is december 31')
doyx,cdoyx,cyyyy,cyy = ymd2doy(pyear,12,31)
pdoy = doyx
else:
# doy is decremented by one and year stays the same
pdoy = doy - 1
pyear = year
cdoy = '{:03d}'.format(pdoy)
cyy = '{:02d}'.format(pyear-2000)
f= station + str(cdoy) + '0.' + cyy + '.snr' + str(snr)
fname = xdir + '/' + str(year) + '/snr/' + station + '/' + f
fname2 = xdir + '/' + str(year) + '/snr/' + station + '/' + f + '.xv'
print('snr filename for the previous day is ', fname)
return fname, fname2
def read_inputs(station,**kwargs):
"""
given station name, read LSP parameters for strip_snrfile.py
author: Kristine M Larson
19sep22 change name of longitude variable, add error messages
20may20 add peak to noise as an returned variable
"""
# directory name is currently defined using REFL_CODE
peak2noise = 0 # assume it is not set here but in the main code,
# which is how it used to be
xdir = os.environ['REFL_CODE']
fname = xdir + '/input/' + station
print('default inputs should be in this file: ', fname)
# default location values - not used now
lat = 0; lon = 0; h = 0;
# counter variables
k = 0
lc = 0
# elevation angle list, degrees
elang = []
# azimuth angle list, degrees
azval = []
freqs = [] ; reqAmp = []
# this limits the reflector height values you compute LSP for
Hlimits = []
# default polyfit, elevation angle limits for DC removal
polyFit = 3; pele = [5, 30]
# desired reflector height precision, in meters
desiredP = 0.01
ediff = 2
noiseRegion = [0.25, 6]
default_extension = ''
extension = kwargs.get('extension',default_extension)
if os.path.exists(fname + '.' + extension):
fname = fname + '.' + extension
print('extension input file found: ', fname)
else:
print('use the original input file')
try:
f = open(fname, 'r')
# read all the lines
l=f.readlines()
# figure out what is on each
for line in l:
# print(line)
if line[0] == '#':
lc = lc + 1
else:
k=k+1
nfo=line.split()
if k==1:
# read in the latitude, longitude, and height. currently this information is not used
lat = float(nfo[0])
lon = float(nfo[1])
h = float(nfo[2])
print("latitude/longitude/height:", lat,lon,h)
# read in the elevation angle ranges
if k==2:
elang.append(float(nfo[0]))
elang.append(float(nfo[1]))
print('elevation angle limits', elang[0], elang[1])
# these are elevation angle limits for polyfit
if (len(nfo)==4):
pele = [float(nfo[2]), float(nfo[3]) ]
# read in the azimuth ranges
if k==3:
naz = len(nfo)
for j in range(naz):
azval.append(float(nfo[j]))
# read in the frequencies and the required spectral amplitudes
if k==4:
nnp = int(len(nfo)/2)
for j in range(nnp):
ni = 2*j; nj = 2*j+1
freqs.append(int(nfo[ni]))
reqAmp.append(float(nfo[nj]))
print('Frequency ', int(nfo[ni]), ' Amplitude ', float(nfo[nj]))
# read in reflector height restrictions etc
if k==5:
np = len(nfo)
polyFit = int(nfo[0])
# this is desired precision of the LSP
desiredP = float(nfo[1])
H1 = Hlimits.append(float(nfo[2]))
H2 = Hlimits.append(float(nfo[3]))
ediff = float(nfo[4])
print('Polynomial Fit ', polyFit, ' Precision: ', desiredP,' ediff ', ediff)
if (np > 5):
# range of reflector heights used for noise calculation
ns1 = float(nfo[5])
ns2 = float(nfo[6])
noiseRegion = [ns1,ns2]
# this means peak to noise is on the line too
if np > 7:
peak2noise = float(nfo[7])
f.close
except:
print('Some kind of problem reading the required input file: ' + fname)
print('Please use make_input_file.py if it does not exist. It will need at a minimum the ')
print('latitude, longitude, and height of the station. This location does not need to be precise')
print('If you do not have your site location handy, just enter 0,0,0.')
print('The rest of the inputs can be defaults, but if ')
print('your site requires RH > 6 meters, please adjust using -h1 and -h2. Exiting now.')
sys.exit()
return lat,lon,h,elang, azval, freqs, reqAmp,polyFit, desiredP, Hlimits, ediff, pele,noiseRegion, peak2noise
def satclock(week, epoch, prn, closest_ephem):
"""
inputs: gps week, second of week, satellite number (PRN)
and ephemeris. returns clock clorrection in meters
note: although second order correction exists, it is not used
"""
# what is sent should be the appropriate ephemeris for given
# satellite and time
prn, week, Toc, Af0, Af1, Af2, IODE, Crs, delta_n, M0, Cuc,\
ecc, Cus, sqrta, Toe, Cic, Loa, Cis, incl, Crc, perigee, radot, idot,\
l2c, week, l2f, sigma, health, Tgd, IODC, Tob, interval = closest_ephem
correction = (Af0+Af1*(epoch-Toc))*constants.c
return correction[0]
def ionofree(L1, L2):
"""
input are L1 and L2 observables (either phase or pseudorange, in meters)
output is L3 (meters)
author: kristine larson
"""
f1 = constants.fL1
f2 = constants.fL2
P3 = f1**2/(f1**2-f2**2)*L1-f2**2/(f1**2-f2**2)*L2
return P3
def azimuth_angle(RecSat, East, North):
"""
kristine larson
inputs are receiver satellite vector (meters)
east and north unit vectors, computed with the up vector
returns azimuth angle in degrees
"""
staSatE = East[0]*RecSat[0] + East[1]*RecSat[1] + East[2]*RecSat[2]
staSatN = North[0]*RecSat[0] + North[1]*RecSat[1] + North[2]*RecSat[2]
# azangle = 0
azangle = np.arctan2(staSatE, staSatN)*180/np.pi
if azangle < 0:
azangle = 360 + azangle
#
return azangle
def rot3(vector, angle):
"""
input a vector (3) and output the same vector rotated by angle
in radians apparently.
from ryan hardy
"""
rotmat = np.matrix([[ np.cos(angle), np.sin(angle), 0],
[-np.sin(angle), np.cos(angle), 0],
[ 0, 0, 1]])
vector2 = np.array((rotmat*np.matrix(vector).T).T)[0]
return vector2
def xyz2llh(xyz, tol):
"""
inputs are station coordinate vector xyz (x,y,z in meters), tolerance for convergence
outputs are lat, lon in radians and wgs84 ellipsoidal height in meters
kristine larson
"""
x=xyz[0]
y=xyz[1]
z=xyz[2]
lon = np.arctan2(y, x)
p = np.sqrt(x**2+y**2)
lat0 = np.arctan((z/p)/(1-wgs84.e**2))
b = wgs84.a*(1-wgs84.f)
error = 1
a2=wgs84.a**2
i=0 # make sure it doesn't go forever
while error > tol and i < 10:
n = a2/np.sqrt(a2*np.cos(lat0)**2+b**2*np.sin(lat0)**2)
h = p/np.cos(lat0)-n
lat = np.arctan((z/p)/(1-wgs84.e**2*n/(n+h)))
error = np.abs(lat-lat0)
lat0 = lat
i+=1
return lat, lon, h
def xyz2llhd(xyz):
"""
inputs are station vector xyz (x,y,z in meters), tolerance for convergence is hardwired
outputs are lat, lon in degrees and wgs84 ellipsoidal height in meters
author : kristine larson
"""
x=xyz[0]
y=xyz[1]
z=xyz[2]
lon = np.arctan2(y, x)
p = np.sqrt(x**2+y**2)
lat0 = np.arctan((z/p)/(1-wgs84.e**2))
b = wgs84.a*(1-wgs84.f)
error = 1
a2=wgs84.a**2
i=0 # make sure it doesn't go forever
tol = 1e-10
while error > tol and i < 10:
n = a2/np.sqrt(a2*np.cos(lat0)**2+b**2*np.sin(lat0)**2)
h = p/np.cos(lat0)-n
lat = np.arctan((z/p)/(1-wgs84.e**2*n/(n+h)))
error = np.abs(lat-lat0)
lat0 = lat
i+=1
return lat*180/np.pi, lon*180/np.pi, h
def zenithdelay(h):
"""
author: kristine larson
input the station ellipsoidal (height) in meters
the output is a very simple zenith troposphere delay in meters
"""
zd = 0.1 + 2.31*np.exp(-h/7000.0)
return zd
def up(lat,lon):
"""
author: kristine larson
inputs rae latitude and longitude in radians
returns the up unit vector, and local east and north used for azimuth calc.
"""
xo = np.cos(lat)*np.cos(lon)
yo = np.cos(lat)*np.sin(lon)
zo = np.sin(lat)
u= np.array([xo,yo,zo])
# c ... also define local east/north for station: took these from fortran
North = np.zeros(3)
East = np.zeros(3)
North[0] = -np.sin(lat)*np.cos(lon)
North[1] = -np.sin(lat)*np.sin(lon)
North[2] = np.cos(lat)
East[0] = -np.sin(lon)
East[1] = np.cos(lon)
East[2] = 0
return u, East, North
def norm(vect):
"""
given a three vector - return its norm
"""
nv = np.sqrt(np.dot(vect,vect))
return nv
def elev_angle(up, RecSat):
"""
inputs:
up - unit vector in up direction
RecSat is the Cartesian vector that points from receiver
to the satellite in meters
the output is elevation angle in radians
author: kristine larson
"""
ang = np.arccos(np.dot(RecSat,up) / (norm(RecSat)))
angle = np.pi/2.0 - ang
return angle
def sp3_interpolator(t, tow, x0, y0, z0, clock0):
"""
got this from ryan hardy - who coded it for my class?
inputs are??? tow is GPS seconds
xyz are the precise satellite coordinates (in meters)
clocks are likely satellite clock corrections (microseconds)
i believe n is the order fit, based on what i recall.
these values do not agree with my test cases in matlab or fortran
presumably there is an issue with the estimation of the coefficients.
they are good enough for calculating an elevation angle used in reflectometry
"""
# ryan set it to 7 - which is not recommended by the paper
# ryan confirmed that he doesn't know why this doesn't work ...
n = 7 # don't know why this was being sent before
coeffs = np.zeros((len(t), 3, n))
# whatever ryan was doing was not allowed here. had to make
# sure these are treated as integers
s1 = int(-(n-1)/2)
s2 = int((n-1)/2+1)
# print(s1,s2)
omega = 2*2*np.pi/(86164.090530833)
x = np.zeros(len(t))
y = np.zeros(len(t))
z = np.zeros(len(t))
clockf = interp1d(tow, clock0, bounds_error=False, fill_value=clock0[-1])
clock = clockf(t)
# looks like it computes it for a number of t values?
for i in range(len(t)):
# sets up a matrix with zeros in it - 7 by 7
independent = np.matrix(np.zeros((n, n)))
# no idea what this does ...
m = np.sort(np.argsort(np.abs(tow-t[i]))[:n])
tinterp = tow[m]-np.median(tow[m])
# set x, y, and z to zeros
xr = np.zeros(n)
yr = np.zeros(n)
zr = np.zeros(n)
# coefficients are before and after the time
for j in range(s1, s2):
independent[j] = np.cos(np.abs(j)*omega*tinterp-(j > 0)*np.pi/2)
for j in range(n):
xr[j], yr[j], zr[j] = rot3(np.array([x0[m], y0[m], z0[m]]).T[j], omega/2*tinterp[j])
# print(j, xr[j], yr[j], zr[j])
independent = independent.T
eig = np.linalg.eig(independent)
iinv = (eig[1]*1/eig[0]*np.eye(n)*np.linalg.inv(eig[1]))
# set up the coefficients
coeffs[i, 0] = np.array(iinv*np.matrix(xr).T).T[0]
coeffs[i, 1] = np.array(iinv*np.matrix(yr).T).T[0]
coeffs[i, 2] = np.array(iinv*np.matrix(zr).T).T[0]
j = np.arange(s1, s2)
# time since median of the values?
tx = (t[i]-np.median(tow[m]))
r_inertial = np.sum(coeffs[i][:, j]*np.cos(np.abs(j)*omega*tx-(j > 0)*np.pi/2), -1)
x[i], y[i], z[i] = rot3(r_inertial, -omega/2*tx)
# returns xyz, in meters ? and satellite clock in microseconds
return x*1e3, y*1e3, z*1e3, clock
def readPreciseClock(filename):
"""
author: kristine larson
filename of precise clocks
returns prn, time (gps seconds of the week), and clock corrections (in meters)
"""
StationNFO=open(filename).readlines()
c= 299792458 # m/sec
nsat = 32
k=0
# this is for 5 second clocks
nepochs = 17280
prn = np.zeros(nepochs*nsat)
t = np.zeros(nepochs*nsat)
clockc = np.zeros(nepochs*nsat)
# reads in the high-rate clock file
for line in StationNFO:
if line[0:4] == 'AS G':
lines= line[7:60]
sat = int(line[4:6])
year = int(lines.split()[0])
month = int(lines.split()[1])
day = int(lines.split()[2])
hour = int(lines.split()[3])
minutes = int(lines.split()[4])
second = float(lines.split()[5])
[gw, gpss] = kgpsweek(year, month, day, hour, minutes, second)
clock = float(lines.split()[7])
prn[k] = sat
t[k]=int(gpss)
clockc[k]=c*clock
k += 1
return prn, t, clockc
def ymd2doy(year,month,day):
"""
takes in year, month, day and returns day of year (doy)
and the character version of that day of year
19mar20: and now it returns character versions of 4 and 2 character years
"""
today=datetime.datetime(year,month,day)
doy = (today - datetime.datetime(today.year, 1, 1)).days + 1
cdoy = '{:03d}'.format(doy)
cyyyy = '{:04d}'.format(year)
cyy = '{:02d}'.format(year-2000)
return doy, cdoy, cyyyy, cyy
def rinex_unavco(station, year, month, day):
"""
author: kristine larson
picks up a RINEX file from unavco. it tries to pick up an o file,
but if it does not work, it tries the "d" version, which must be
decompressed. the location of this executable is defined in the crnxpath
variable. This is from the main unavco directory - not the highrate directory.
WARNING: only rinex version 2 in this world
"""
exedir = os.environ['EXE']
crnxpath = hatanaka_version()
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
rinexfile,rinexfiled = rinex_name(station, year, month, day)
unavco= 'ftp://data-out.unavco.org'
filename1 = rinexfile + '.Z'
filename2 = rinexfiled + '.Z'
# URL path for the o file and the d file
url1 = unavco+ '/pub/rinex/obs/' + cyyyy + '/' + cdoy + '/' + filename1
url2 = unavco+ '/pub/rinex/obs/' + cyyyy + '/' + cdoy + '/' + filename2
try:
print('try to get observation file')
wget.download(url1,filename1)
status = subprocess.call(['uncompress', filename1])
print('found the rinex file')
except:
print('did not find observation file, try hatanaka version')
try:
wget.download(url2,filename2)
status = subprocess.call(['uncompress', filename2])
status = subprocess.call([crnxpath, rinexfiled])
status = subprocess.call(['rm', '-f', rinexfiled])
print('found d file and converted to observation file')
except:
print('failed to find either RINEX file at unavco')
def rinex_sopac(station, year, month, day):
"""
author: kristine larson
inputs: station name, year, month, day
picks up a hatanaka RINEX file from SOPAC - converts to o
hatanaka exe hardwired for my machine
"""
exedir = os.environ['EXE']
crnxpath = hatanaka_version()
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
sopac = 'ftp://garner.ucsd.edu'
oname,fname = rinex_name(station, year, month, day)
# compressed version??
file1 = fname + '.Z'
path1 = '/pub/rinex/' + cyyyy + '/' + cdoy + '/'
url1 = sopac + path1 + file1
#file2 = oname + '.Z'
#path2 = '/pub/rinex/' + cyyyy + '/' + cdoy + '/'
#url2 = sopac + path2 + file2
try:
wget.download(url1,file1)
subprocess.call(['uncompress', file1])
subprocess.call([crnxpath, fname])
subprocess.call(['rm', '-f',fname])
print('successful Hatanaka download from SOPAC ')
except:
print('not able to download from SOPAC',file1)
subprocess.call(['rm', '-f',file1])
subprocess.call(['rm', '-f',fname])
def rinex_sonel(station, year, month, day):
"""
author: kristine larson
inputs: station name, year, month, day
picks up a hatanaka RINEX file from SOPAC - converts to o
hatanaka exe hardwired for my machine
"""
exedir = os.environ['EXE']
crnxpath = hatanaka_version()
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
sonel = 'ftp://ftp.sonel.org'
oname,fname = rinex_name(station, year, month, day)
file1 = fname + '.Z'
path1 = '/gps/data/' + cyyyy + '/' + cdoy + '/'
url = sonel + path1 + file1
print(url)
# I don't think they have normal RINEX, so only hatanaka
try:
wget.download(url,file1)
subprocess.call(['uncompress', file1])
subprocess.call([crnxpath, fname])
subprocess.call(['rm', '-f',fname])
print('successful Hatanaka download from SONEL ')
except:
print('some kind of problem with Hatanaka download from SONEL',file1)
subprocess.call(['rm', '-f',file1])
def rinex_cddis(station, year, month, day):
"""
author: kristine larson
inputs: station name, year, month, day
picks up a hatanaka RINEX file from CDDIS - converts to o
June 2020, changed to use secure ftp
if day is zero, then month is assumed to be doy
"""
exedir = os.environ['EXE'] # do not need this?
crnxpath = hatanaka_version()
if (day == 0):
doy = month
year, month, day, cyyyy,cdoy, YMD = ydoy2useful(year,doy)
cyy = cyyyy[2:4]
else:
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
cddis = 'ftp://ftp.cddis.eosdis.nasa.gov'
oname,fname = rinex_name(station, year, month, day)
file1 = oname + '.Z'
url = cddis + '/pub/gnss/data/daily/' + cyyyy + '/' + cdoy + '/' + cyy + 'o/' + file1
# try new way using secure ftp
dir_secure = '/pub/gnss/data/daily/' + cyyyy + '/' + cdoy + '/' + cyy + 'o/'
file_secure = file1
try:
#wget.download(url,file1)
cddis_download(file_secure,dir_secure)
subprocess.call(['uncompress', file1])
except:
print('some issue at CDDIS',file1)
subprocess.call(['rm', '-f',file1])
if os.path.exists(oname):
print('successful RINEX 2.11 download from CDDIS')
else:
print('unsuccessful RINEX 2.11 download from CDDIS')
def rinex_nz(station, year, month, day):
"""
author: kristine larson
inputs: station name, year, month, day
picks up a RINEX file from GNS New zealand
you can input day =0 and it will assume month is day of year
20jul10 - changed access point and ending
"""
# if doy is input
if day == 0:
doy=month
d = doy2ymd(year,doy);
month = d.month; day = d.day
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
gns = 'ftp://ftp.geonet.org.nz/gnss/rinex/'
oname,fname = rinex_name(station, year, month, day)
file1 = oname + '.gz'
url = gns + cyyyy + '/' + cdoy + '/' + file1
print(url)
try:
wget.download(url,file1)
subprocess.call(['gunzip', file1])
print('successful download from GeoNet New Zealand')
except:
print('some kind of problem with download',file1)
subprocess.call(['rm', '-f',file1])
def rinex_bkg(station, year, month, day):
"""
author: kristine larson
inputs: station name, year, month, day
picks up a lowrate RINEX file BKG
you can input day =0 and it will assume month is day of year
"""
crnxpath = hatanaka_version()
# if doy is input
if day == 0:
doy=month
d = doy2ymd(year,doy);
month = d.month; day = d.day
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
gns = 'ftp://igs.bkg.bund.de/EUREF/obs/'
oname,fname = rinex_name(station, year, month, day)
# they store hatanaka and normal unix compression
file1 = fname + '.Z'
url = gns + cyyyy + '/' + cdoy + '/' + file1
print(url)
try:
wget.download(url,file1)
subprocess.call(['uncompress', file1])
print('successful download from BKG')
subprocess.call([crnxpath, fname])
subprocess.call(['rm', '-f',fname])
print('successful Hatanaka download and translation from BKG')
except:
print('some kind of problem with download',file1)
subprocess.call(['rm', '-f',file1])
def rinex_nrcan(station, year, month, day):
"""
author: kristine larson
inputs: station name, year, month, day
picks up a RINEX file from GNS New zealand
you can input day =0 and it will assume month is day of year
Note: this code does not work - let me know if you have a way
to access NRCAN anonymously
"""
exedir = os.environ['EXE']
crnxpath = exedir + '/CRX2RNX'
# if doy is input
if day == 0:
doy=month
d = doy2ymd(year,doy);
month = d.month; day = d.day
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
# was using this ...
gns = 'ftp://gauss.geod.nrcan.gc.ca/data/ftp/naref/pub/rinex/'
gns = 'ftp://gauss.geod.nrcan.gc.ca/data/ftp/naref/pub/data/rinex/'
# user narefftp
# password 4NAREF2use
oname,fname = rinex_name(station, year, month, day)
# only hatanaka in canada and normal compression
file1 = fname + '.Z'
url = gns + cyy + cdoy + '/' + file1
print(url)
try:
wget.download(url,file1)
subprocess.call(['uncompress', file1])
print('successful download from NRCAN ')
except:
print('some kind of problem with download',file1)
subprocess.call(['rm', '-f',file1])
def getnavfile(year, month, day):
"""
author: kristine larson
given year, month, day it picks up a GPS nav file from SOPAC
and stores it in the ORBITS directory
returns the name of the file, its directory, and a boolean
19may7 now checks for compressed and uncompressed nav file
19may20 now allows day of year input if day is set to zero
20apr15 check for xz compression
if the day is zero it assumes month is doy
"""
foundit = False
ann = make_nav_dirs(year)
if (day == 0):
doy = month
year, month, day, cyyyy,cdoy, YMD = ydoy2useful(year,doy)
cyy = cyyyy[2:4]
else:
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
navname,navdir = nav_name(year, month, day)
nfile = navdir + '/' + navname
if os.path.exists(navdir):
print('navdir already exists')
else:
subprocess.call(['mkdir',navdir])
if os.path.exists(nfile):
foundit = True
elif os.path.exists(nfile + '.xz' ):
print('xz compressed navfile exists online')
subprocess.call(['unxz',nfile + '.xz'])
foundit = True
else:
print('go pick up the navfile')
navstatus = navfile_retrieve(navname, cyyyy,cyy,cdoy)
if navstatus:
print('mv the navfile')
subprocess.call(['mv',navname, navdir])
foundit = True
else:
print('no navfile')
return navname,navdir,foundit
def getsp3file(year,month,day):
"""
author: kristine larson
retrieves IGS sp3 precise orbit file from CDDIS
inputs are year, month, and day
modified in 2019 to use wget
returns the name of the file and its directory
20jun14 - add CDDIS secure ftp
"""
name, fdir = sp3_name(year,month,day,'igs')
print(name,fdir)
cddis = 'ftp://cddis.nasa.gov'
# try new way using secure ftp
#dir_secure = '/pub/gnss/data/daily/' + cyyyy + '/' + cdoy + '/' + cyy + 'o/'
#file_secure = file1
if (os.path.isfile(fdir + '/' + name ) == True):
print('sp3file already exists')
else:
gps_week = name[3:7]
file1 = name + '.Z'
filename1 = '/gnss/products/' + str(gps_week) + '/' + file1
url = cddis + filename1
# new secure ftp way
sec_dir = '/gnss/products/' + str(gps_week) + '/'
sec_file = file1
try:
#wget.download(url,file1)
cddis_download(sec_file, sec_dir)
subprocess.call(['uncompress',file1])
store_orbitfile(name,year,'sp3')
except:
print('some kind of problem-remove empty file')
subprocess.call(['rm',file1])
# return the name of the file so that if you want to store it
return name, fdir
def getsp3file_flex(year,month,day,pCtr):
"""
author: kristine larson
retrieves sp3 orbit files from CDDIS
inputs are year, month, and day (integers), and
pCtr, the processing center (3 characters)
returns the name of the file and its directory
20apr15 check for xz compression
20jun14 add CDDIS secure ftp
unfortunately this won't work with the long sp3 file names. use mgex instead
"""
# returns name and the directory
name, fdir = sp3_name(year,month,day,pCtr)
print(name, fdir)
gps_week = name[3:7]
file1 = pCtr + name[3:8] + '.sp3.Z'
name = pCtr + name[3:8] + '.sp3'
foundit = False
ofile = fdir + '/' + name
# new CDDIS way
sec_dir = '/gnss/products/' + str(gps_week) + '/'
sec_file = file1
if (os.path.isfile(ofile ) == True):
print('sp3file already exists online')
foundit = True
elif (os.path.isfile(ofile + '.xz') == True):
print('xz compressed sp3file already exists online')
subprocess.call(['unxz', ofile + '.xz'])
foundit = True
else:
filename1 = '/gnss/products/' + str(gps_week) + '/' + file1
cddis = 'ftp://cddis.nasa.gov'
url = cddis + filename1
try:
cddis_download(sec_file, sec_dir)
#wget.download(url,file1)
subprocess.call(['uncompress',file1])
store_orbitfile(name,year,'sp3')
foundit = True
except:
print('some kind of problem-remove empty file, if it exists')
subprocess.call(['rm','-f',file1])
# return the name of the file so that if you want to store it
return name, fdir, foundit
def getsp3file_mgex(year,month,day,pCtr):
"""
author: kristine larson
retrieves MGEX sp3 orbit files
inputs are year, month, and day (integers), and
pCtr, the processing center (3 characters)
right now it checks for the "new" name, but in reality, it
assumes you are going to use the GFZ product
20apr15 check for xz compression
20jun14 add CDDIS secure ftp. what a nightmare
20jun25 add Shanghai GNSS orbits - as they are available sooner than GFZ
20jun25 added French and JAXA orbits
20jul01 allow year, doy as input instead of year, month, day
20jul10 allow Wuhan, but only one of them.
"""
foundit = False
# this returns sp3 orbit product name
if day == 0:
print('assume you were given doy in the month input')
doy = month
year,month,day= ydoy2ymd(year,doy)
name, fdir = sp3_name(year,month,day,pCtr)
gps_week = name[3:7]
igps_week = int(gps_week)
print('GPS week', gps_week,igps_week)
file1 = name + '.Z'
# get the sp3 filename for the new format
doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day)
if pCtr == 'gbm': # GFZ
file2 = 'GFZ0MGXRAP_' + cyyyy + cdoy + '0000_01D_05M_ORB.SP3.gz'
if pCtr == 'wum': # Wuhan, but only the one at midnite(they are updated more frequently)
print('use previous day for Wuhan ultra products since gnssSNR does not allow two day files')
nyear, ndoy = nextdoy(year,doy)
cndoy = '{:03d}'.format(ndoy); cnyear = '{:03d}'.format(nyear)
file2 = 'WUM0MGXULA_' + cnyear + cndoy + '0000_01D_05M_ORB.SP3.gz'
if pCtr == 'grg': # french group
file2 = 'GRG0MGXFIN_' + cyyyy + cdoy + '0000_01D_15M_ORB.SP3.gz'
if pCtr == 'sha': # shanghai observatory
file2 = 'SHA0MGXRAP_' + cyyyy + cdoy + '0000_01D_05M_ORB.SP3.gz'
# try out JAXA - should have GPS and glonass
if pCtr == 'jax':
file2 = 'JAX0MGXFIN_' + cyyyy + cdoy + '0000_01D_05M_ORB.SP3.gz'
name2 = file2[:-3]
# where the files used to live at CDDIS
#cddis = 'ftp://cddis.nasa.gov'
dirlocation = '/gps/products/mgex/' + str(gps_week) + '/'
#url = cddis + dirlocation + file1;
#url2 = cddis + dirlocation + file2;
# this is the default setting - no file exists
mgex = 0
n1 = os.path.isfile(fdir + '/' + name)
n1c = os.path.isfile(fdir + '/' + name + '.xz')
if (n1 == True):
print('first kind of MGEX sp3file already exists online')
mgex = 1
foundit = True
elif (n1c == True):
print('xz first kind of MGEX sp3file already exists online-unxz it')
fx = fdir + '/' + name + '.xz'
subprocess.call(['unxz', fx])
mgex = 1
foundit = True
n2 = os.path.isfile(fdir + '/' + name2)
n2c = os.path.isfile(fdir + '/' + name2 + '.xz')
if (n2 == True):
print('second kind of MGEX sp3file already exists online')
mgex = 2 ; foundit = True
elif (n2c == True):
print('xz second kind of MGEX sp3file already exists online')
mgex = 2 ; foundit = True
fx = fdir + '/' + name2 + '.xz'
subprocess.call(['unxz', fx])
if (mgex == 2):
name = name2
if (mgex == 1):
name = file1[:-2]
# there has to be a better way ... but for now this works
# only try to download if neither exists
# new using secure ftp
# this is the directory
secure_dir = '/gps/products/mgex/' + str(gps_week) + '/'
if (mgex == 0):
secure_file = file1
name = file1[:-2]
print('first file input',secure_file)
#https://cddis.nasa.gov/Data_and_Derived_Products/GNSS/gnss_mgex_products.html
# CDDIS claims the old way stopped at GPS week 1945
if (igps_week < 1944):
try:
# secure filename # 1??
cddis_download(secure_file, secure_dir)
if os.path.isfile(file1):
subprocess.call(['uncompress', file1])
store_orbitfile(name,year,'sp3') ; foundit = True
except:
print('did not find', file1)
else:
print('will only use the long orbit name for weeks after 1944')
if not foundit:
name = file2[:-3]
# new secure filename
secure_file = file2
print('next secure file to check',secure_file)