forked from jolivetr/csi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gps.py
3446 lines (2745 loc) · 109 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
'''
A class that deals with gps rates.
Written by R. Jolivet, B. Riel and Z. Duputel, April 2013.
'''
# Externals
import numpy as np
import pyproj as pp
import matplotlib.pyplot as plt
import os
import copy
import sys
# Personals
from .SourceInv import SourceInv
from .gpstimeseries import gpstimeseries
from .geodeticplot import geodeticplot as geoplot
from . import csiutils as utils
class gps(SourceInv):
'''
A class that handles a network of gps displacements
Args:
* name : Name of the dataset.
Kwargs:
* utmzone : UTM zone (optional, default=None)
* lon0 : Longitude of the center of the UTM zone
* lat0 : Latitude of the center of the UTM zone
* ellps : ellipsoid (optional, default='WGS84')
* verbose : Speak to me (default=True)
'''
# ----------------------------------------------------------------------
# Initialize class
def __init__(self, name, utmzone=None,
ellps='WGS84', lon0=None, lat0=None, verbose=True):
# Base class init
super(gps,self).__init__(name,
utmzone = utmzone,
ellps = ellps,
lon0 = lon0,
lat0 = lat0)
# Set things
self.dtype = 'gps'
# print
if verbose:
print ("---------------------------------")
print ("---------------------------------")
print ("Initialize GPS array {}".format(self.name))
self.verbose = verbose
# Initialize things
self.vel_enu = None
self.err_enu = None
self.rot_enu = None
self.synth = None
# All done
return
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setStat(self,sta_name,x,y,loc_format='LL', initVel=False):
'''
Set station names and locations attributes
Args:
* sta_name: station names
* x: x coordinate (longitude or UTM)
* y: y coordinate (latitude or UTM)
Kwargs:
* loc_format: location format ('LL' for lon/lat or 'XY' for UTM)
* initVel: initialize a vel_enu attribute with zeros
Returns:
* None
'''
# Check input parameters
assert len(sta_name)==len(x)==len(y), 'sta_name, x and y must have the same length'
assert loc_format=='LL' or loc_format=='XY', 'loc_format can be LL or XY'
if type(x)==list:
x = np.array(x)
if type(y)==list:
y = np.array(y)
# Assign input parameters to station attributes
self.station = copy.deepcopy(sta_name)
self.lon = np.array([],dtype='float64')
self.lat = np.array([],dtype='float64')
self.x = np.array([],dtype='float64')
self.y = np.array([],dtype='float64')
if loc_format=='LL':
self.lon = np.append(self.lon,x)
self.lat = np.append(self.lat,y)
self.x, self.y = self.ll2xy(self.lon,self.lat)
else:
self.x = np.append(self.x,x)
self.y = np.append(self.y,y)
self.lon, self.lat = self.xy2ll(self.x,self.y)
# Initialize the vel_enu array
if initVel:
self.vel_enu = np.zeros((len(sta_name), 3))
self.err_enu = np.zeros((len(sta_name), 3))
# convert to arrays
if type(self.station) is list:
self.station = np.array(self.station)
# All done
return
def setStatFromFile(self,filename, initVel=False, header=0):
'''
Set station names and locations attributes. File should be formatted as
+--------------+-----+-----+
| Station Name | lon | lat |
+==============+=====+=====+
| TAGA | 13. | 23. |
+--------------+-----+-----+
| POUT |14.5 | 23.2|
+--------------+-----+-----+
Args:
* filename : name of the station list
Kwargs:
* initVel : Intialize a vel_enu vector or not
* header : Length of the file header
Returns:
* None
'''
# Check input parameters
assert os.path.exists(filename), 'Cannot find file {}'.format(filename)
# Read file
fin = open(filename, 'r')
self.station = []
self.lon = []; self.lat = []
for line in fin.readlines()[header:]:
self.station.append(line.split()[0])
self.lon.append(float(line.split()[1]))
self.lat.append(float(line.split()[2]))
# convert to arrays
self.station = np.array(self.station)
self.lon = np.array(self.lon)
self.lat = np.array(self.lat)
# Assign input parameters to station attributes
self.x, self.y = self.ll2xy(self.lon,self.lat)
# Initialize the vel_enu array
if initVel:
self.vel_enu = np.zeros((len(self.station), 3))
self.err_enu = np.zeros((len(self.station), 3))
# All done
return
def importNetwork(self, gpsdata, iftwo='keep'):
'''
Adds stations from gpsdata to the current network.
If station is already in here, there is several options:
- if iftwo == 'keep': Keep both measures
- if iftwo == gpsdata.name: Keep the incomcing measure
- if iftwo == self.name: Keep the current one
Args:
* gpsdata : A gps instance
Kwargs:
* iftwo : same station policy
Returns:
* None
'''
# Iterate over the stations to import
for station in gpsdata.station:
# Get velocity, errors, lon and lat
lon, lat, vel, err, synth, los = gpsdata.getstation(station)
# Check if we have the station already
u = np.flatnonzero(self.station==station)
# If we do not have it
if len(u)==0:
self.addstation(station, lon, lat, vel, err,
synth=synth, los=los)
else:
# Keep it if asked
if iftwo=='keep':
self.addstation(station, lon, lat, vel, err,
synth=synth, los=los)
# Replace it if asked
elif iftwo==gpsdata.name:
self.deletestation(station)
self.addstation(station, lon, lat, vel, err,
synth=synth, los=los)
# Do nothing if asked
# All done
return
def combineNetworks(self, gpsdata, newNetworkName='Combined Network'):
'''
Combine networks into a new network.
Args:
* gpsdata : List of gps instances.
Kwargs:
* newNetworkName : Name of the returned network
Returns:
* None
'''
# Create lists
lon = []
lat = []
name = []
vel = []
err = []
# Iterate to get name, lon, lat
for gp in gpsdata:
lon += gp.lon.tolist()
lat += gp.lat.tolist()
name += gp.station.tolist()
vel += gp.vel_enu.tolist()
err += gp.err_enu.tolist()
# Create a new instance
gp = gps(newNetworkName, utmzone=self.utmzone, verbose=self.verbose, lon0=self.lon0, lat0=self.lat0)
# Fill it
gp.setStat(np.array(name), np.array(lon), np.array(lat))
# Set displacements and errors
gp.vel_enu = np.array(vel)
gp.err_enu = np.array(err)
# All done
return gp
def readStat(self,station_file,loc_format='LL'):
'''
Read simple station ascii file and populate station attributes
If loc_format='XY', then the file should be as
+--------+---------+---------+
| STNAME | X_COORD | Y_COORD |
+========+=========+=========+
| | | |
+--------+---------+---------+
If loc_format='LL', then the file should be as
+--------+-----+-----+
| STNAME | LON | LAT |
+========+=====+=====+
| | | |
+--------+-----+-----+
Args:
* station_file: station filename including station coordinates
Kwargs:
* loc_format: station file format (default= 'LL')
Returns:
* None
'''
# Assert if station file exists
assert os.path.exists(station_file), 'Cannot read %s (no such file)'%(station_file)
# Assert file format
assert loc_format=='LL' or loc_format=='XY', 'loc_format can be either LL or XY'
# Read the file
X = []
Y = []
sta_name = []
for l in open(station_file):
if (l.strip()[0]=='#'):
continue
items = l.strip().split()
sta_name.append(items[0].strip())
X.append(float(items[1]))
Y.append(float(items[2]))
# Set station attributes
self.setStat(sta_name,X,Y,loc_format)
# Initialize the vel_enu array
self.vel_enu = np.zeros((len(sta_name), 3))
self.err_enu = np.zeros((len(sta_name), 3))
# All done
return
def getstation(self, station):
'''
Gets informations for a station.
Args:
* station : name of the station
Returns:
* lon, lat, vel, err, synth, los
'''
# Get lon, lat
lon = self.lon[self.station==station]
if len(lon)==0: lon = None
lat = self.lat[self.station==station]
if len(lat)==0: lat = None
# Get velocity
vel = self.vel_enu[self.station==station]
if len(vel)==0: vel = None
err = self.err_enu[self.station==station]
if len(err)==0: err = None
# Get synth and los if possible
synth = None; los = None
if self.synth is not None: synth = self.synth[self.station==station]
if hasattr(self, 'vel_los'): los = self.vel_los[self.station==station]
# Squeeze
if vel is not None:
vel = vel.squeeze()
if err is not None:
err = err.squeeze()
if synth is not None:
synth = synth.squeeze()
if los is not None:
los = los.squeeze()
# All done
return lon, lat, vel, err, synth, los
def getvelo(self, station, data='data'):
'''
Gets the velocities enu for the station.
Args:
* station : name of the station.
Kwargs:
* data : which velocity do you want ('data' or 'synth')
Returns:
* vel : 3D vector
'''
# Get the index
u = np.flatnonzero(np.array(self.station) == station)
# return the values
if data in ('data'):
return self.vel_enu[u,0], self.vel_enu[u,1], self.vel_enu[u,2]
elif data in ('synth'):
return self.synth[u,0], self.synth[u,1], self.synth[u,2]
elif data in ('los'):
return self.vel_los[u]
else:
return getattr(self, data)[u,:]
def geterr(self, station):
'''
Gets the errors enu for the station.
Args:
* station : name of the station.
Returns:
* vector : 3D vector of uncertainties
'''
# Get the index
u = np.flatnonzero(self.station == station)
# return the values
return self.err_enu[u,0], self.err_enu[u,1], self.err_enu[u,2]
def scale_errors(self, scale):
'''
Scales the errors (in-place multiplication)
Args:
* scale : float
Returns:
* None
'''
# Multiplyt
self.err_enu[:,:] *= scale
# all done
return
def getSubNetwork(self, name, stations):
'''
Given a list of station names, returns the corresponding gps object.
Args:
* name : Name of the returned gps object
* stations : List of station names.
Returns:
* gps : Instance of the gps class
'''
# initialize lists
Lon = []
Lat = []
Vel = []
Err = []
# Get lon lat velocities and errors values for each stations
for station in stations:
assert station in self.station, 'Site {} not in {} GPS object'.format(station,
self.name)
Lon.append(self.lon[station==self.station])
Lat.append(self.lat[station==self.station])
Vel.append(self.getvelo(station))
Err.append(self.geterr(station))
# Create the object
gpsNew = gps(name, utmzone=self.utmzone, verbose=self.verbose, lon0=self.lon0, lat0=self.lat0)
# Set Stations
gpsNew.setStat(stations, Lon, Lat)
# Set Velocity and Error
gpsNew.vel_enu = np.array(Vel).squeeze()
gpsNew.err_enu = np.array(Err).squeeze()
# Set factor
gpsNew.factor = self.factor
# Lon/Lat
gpsNew.lonlat2xy()
# all done
return gpsNew
def buildCd(self, direction='en'):
'''
Builds a diagonal data covariance matrix using the formal uncertainties in the GPS data.
Kwargs:
* direction : Direction to take into account. Can be any combination of e, n and u.
Returns:
* None
'''
# get the size of the total thing
Nd = self.vel_enu.shape[0]
Ndt = Nd*len(direction)
# Initialize Cd
Cd = np.zeros((Ndt, Ndt))
# Store that diagonal matrix
st = 0
if 'e' in direction:
se = st + Nd
Cd[st:se, st:se] = np.diag(self.err_enu[:,0]*self.err_enu[:,0])
st += Nd
if 'n' in direction:
se = st + Nd
Cd[st:se, st:se] = np.diag(self.err_enu[:,1]*self.err_enu[:,1])
st += Nd
if 'u' in direction:
se = st + Nd
Cd[st:se, st:se] = np.diag(self.err_enu[:,2]*self.err_enu[:,2])
# Store Cd
self.Cd = Cd
# All done
return
def scale(self, factor):
'''
Scales the gps velocities by a factor.
Args:
* factor : multiplication factor (float)
Returns:
* None
'''
self.err_enu = self.err_enu*factor
self.vel_enu = self.vel_enu*factor
if self.rot_enu is not None:
self.rot_enu = self.rot_enu*factor
if self.synth is not None:
self.synth = self.synth*factor
# All done
return
def getprofile(self, name, loncenter, latcenter, length, azimuth, width, data='data'):
'''
Project the GPS velocities onto a profile.
Works on the lat/lon coordinates system.
Args:
* name : Name of the profile.
* loncenter : Profile origin along longitude.
* latcenter : Profile origin along latitude.
* length : Length of profile.
* azimuth : Azimuth in degrees.
* width : Width of the profile.
Kwargs:
* data : Do the profile through the 'data' or the 'synth'etics.
Returns:
* None: Profiles are stored in self.profiles
'''
# the profiles are in a dictionary
if not hasattr(self, 'profiles'):
self.profiles = {}
self.profiles[name] = {}
# What data do we want
if data is 'data':
values = self.vel_enu
self.profiles[name]['data type'] = 'data'
elif data is 'synth':
values = self.synth
self.profiles[name]['data type'] = 'synth'
elif data is 'res':
values = self.vel_enu - self.synth
self.profiles[name]['data_type'] = 'res'
elif data is 'transformation':
values = self.transformation
self.profiles[name]['data_type'] = 'transformation'
# Convert the lat/lon of the center into UTM.
xc, yc = self.ll2xy(loncenter, latcenter)
# Get the profile
Dalong, Dacros, Bol, boxll, box, xe1, ye1, xe2, ye2, lon, lat = \
utils.coord2prof(self, xc, yc, length, azimuth, width, minNum=1)
# 4. Get these GPS
vel = values[Bol,:]
err = self.err_enu[Bol,:]
names = self.station[Bol]
if hasattr(self, 'vel_los'):
vel_los = self.vel_los[Bol]
# Create the lists that will hold these values
Vacros = []; Valong = []; Vup = []; Eacros = []; Ealong = []; Eup = []
# Get some numbers
x1, y1 = box[0]
x2, y2 = box[1]
x3, y3 = box[2]
x4, y4 = box[3]
# Create vectors
vec1 = np.array([x2-xe1, y2-y1])
vec1 = vec1/np.sqrt( vec1[0]**2 + vec1[1]**2 )
vec2 = np.array([x4-x1, y4-y1])
vec2 = vec2/np.sqrt( vec2[0]**2 + vec2[1]**2 )
ang1 = np.arctan2(vec1[1], vec1[0])
ang2 = np.arctan2(vec2[1], vec2[0])
# Loop on the points
for p in range(vel.shape[0]):
# Project velocities
Vacros.append(np.dot(vec2,vel[p,0:2]))
Valong.append(np.dot(vec1,vel[p,0:2]))
# Get errors (along the ellipse)
x = err[p,0]*err[p,1] \
* np.sqrt( 1. / (err[p,1]**2 + (err[p,0]*np.tan(ang2))**2) )
y = x * np.tan(ang2)
Eacros.append(np.sqrt(x**2 + y**2))
x = err[p,0]*err[p,1] \
* np.sqrt( 1. / (err[p,1]**2 + (err[p,0]*np.tan(ang1))**2) )
y = x * np.tan(ang1)
Ealong.append(np.sqrt(x**2 + y**2))
# Up direction
Vup.append(vel[p,2])
Eup.append(err[p,2])
# Store it in the profile list
dic = self.profiles[name]
dic['Center'] = [loncenter, latcenter]
dic['Length'] = length
dic['Width'] = width
dic['Box'] = np.array(boxll)
dic['Normal Velocity'] = np.array(Vacros)
dic['Normal Error'] = np.array(Eacros)
dic['Parallel Velocity'] = np.array(Valong)
dic['Parallel Error'] = np.array(Ealong)
dic['Vertical Velocity'] = np.array(Vup)
dic['Vertical Error'] = np.array(Eup)
dic['Distance'] = np.array(Dalong)
dic['Normal Distance'] = np.array(Dacros)
dic['Stations'] = names
dic['EndPoints'] = [[xe1, ye1], [xe2, ye2]]
lone1, late1 = self.putm(xe1*1000., ye1*1000., inverse=True)
lone2, late2 = self.putm(xe2*1000., ye2*1000., inverse=True)
dic['EndPointsLL'] = [[lone1, late1],
[lone2, late2]]
dic['Vectors'] = [vec1, vec2]
if hasattr(self, 'vel_los'):
dic['LOS Velocity'] = vel_los
# all done
return
def writeProfile2File(self, name, filename, fault=None):
'''
Writes the profile named 'name' to the ascii file filename.
Args:
* name : Name of the profile to write out
* filename : Name of the output file
Kwargs:
* fault : Add the location of a fault (uses the fault trace)
Returns:
* None
'''
# open a file
fout = open(filename, 'w')
# Get the dictionary
dic = self.profiles[name]
# Write the header
fout.write('#---------------------------------------------------\n')
fout.write('# Profile Generated with StaticInv\n')
fout.write('# Center: {} {} \n'.format(dic['Center'][0], dic['Center'][1]))
fout.write('# Endpoints: \n')
fout.write('# {} {} \n'.format(dic['EndPointsLL'][0][0], dic['EndPointsLL'][0][1]))
fout.write('# {} {} \n'.format(dic['EndPointsLL'][1][0], dic['EndPointsLL'][1][1]))
fout.write('# Box Points: \n')
fout.write('# {} {} \n'.format(dic['Box'][0][0],dic['Box'][0][1]))
fout.write('# {} {} \n'.format(dic['Box'][1][0],dic['Box'][1][1]))
fout.write('# {} {} \n'.format(dic['Box'][2][0],dic['Box'][2][1]))
fout.write('# {} {} \n'.format(dic['Box'][3][0],dic['Box'][3][1]))
# Place faults in the header
if fault is not None:
if fault.__class__ is not list:
fault = [fault]
fout.write('# Fault Positions: \n')
for f in fault:
d = self.intersectProfileFault(name, f)
fout.write('# {} {} \n'.format(f.name, d))
fout.write('#---------------------------------------------------\n')
# Write the values
for i in range(len(dic['Distance'])):
d = dic['Distance'][i]
Vp = dic['Parallel Velocity'][i]
Ep = dic['Parallel Error'][i]
Vn = dic['Normal Velocity'][i]
En = dic['Normal Error'][i]
Vu = dic['Vertical Velocity'][i]
Eu = dic['Vertical Error'][i]
fout.write('{} {} {} {} {} {} {} \n'.format(d, Vp, Ep, Vn, En, Vu, Eu))
# Close the file
fout.close()
# all done
return
def plotprofile(self, name, legendscale=10., fault=None, data=['parallel', 'normal', 'vertical'], show=True):
'''
Plot profile.
Args:
* name : Name of the profile.
Kwargs:
* legendscale : Length of the legend arrow.
* fault : Add a fault on the plot
* data : list of type of data to use
* show : Show me
Returns:
* None
'''
if type(data) is str:
data = [data]
# Plo the map
if 'vertical' in data:
vertical=True
else:
vertical=False
self.plot(faults=fault, figure=None, show=False, legendscale=legendscale, vertical=vertical)
# plot the box on the map
b = self.profiles[name]['Box']
bb = np.zeros((5, 2))
for i in range(4):
x, y = b[i,:]
if x<0.:
x += 360.
bb[i,0] = x
bb[i,1] = y
bb[4,0] = bb[0,0]
bb[4,1] = bb[0,1]
self.fig.carte.plot(bb[:,0], bb[:,1], '.k', zorder=0)
self.fig.carte.plot(bb[:,0], bb[:,1], '-k', zorder=0)
# open a figure
fig = plt.figure()
prof = fig.add_subplot(111)
# plot the profile
if 'parallel' in data:
x = self.profiles[name]['Distance']
y = self.profiles[name]['Parallel Velocity']
ey = self.profiles[name]['Parallel Error']
p = prof.errorbar(x, y, yerr=ey,
label='Profile Parallel', marker='.', linestyle='')
if 'normal' in data:
x = self.profiles[name]['Distance']
y = self.profiles[name]['Normal Velocity']
ey = self.profiles[name]['Normal Error']
q = prof.errorbar(x, y, yerr=ey,
label='Profile Normal', marker='.', linestyle='')
if 'vertical' in data:
x = self.profiles[name]['Distance']
y = self.profiles[name]['Vertical Velocity']
ey = self.profiles[name]['Vertical Error']
r = prof.errorbar(x, y, yerr=ey,
label='Vertical', marker='.', linestyle='')
# If a fault is here, plot it
if fault is not None:
# If there is only one fault
if fault.__class__ is not list:
fault = [fault]
# Loop on the faults
for f in fault:
# Get the distance
d = self.intersectProfileFault(name, f)
if d is not None:
ymin, ymax = prof.get_ylim()
prof.plot([d, d], [ymin, ymax], '--', label=f.name)
# plot the legend
prof.legend()
# Show to screen
if show:
self.fig.show(showFig=['map'])
# All done
return
def intersectProfileFault(self, name, fault):
'''
Gets the distance between the fault/profile intersection and the profile center.
Args:
* name : name of the profile.
* fault : fault object from verticalfault.
Returns:
* distance : float
'''
# Grab the fault trace
xf = fault.xf
yf = fault.yf
# Grab the profile
prof = self.profiles[name]
# import shapely
import shapely.geometry as geom
# Build a linestring with the profile center
Lp = geom.LineString(prof['EndPoints'])
# Build a linestring with the fault
ff = []
for i in range(len(xf)):
ff.append([xf[i], yf[i]])
Lf = geom.LineString(ff)
# Get the intersection
if Lp.crosses(Lf):
Pi = Lp.intersection(Lf)
p = Pi.coords[0]
else:
return None
# Get the center
lonc, latc = prof['Center']
xc, yc = self.ll2xy(lonc, latc)
# Get the sign
xa,ya = prof['EndPoints'][0]
vec1 = [xa-xc, ya-yc]
vec2 = [p[0]-xc, p[1]-yc]
sign = np.sign(np.dot(vec1, vec2))
# Compute the distance to the center
d = np.sqrt( (xc-p[0])**2 + (yc-p[1])**2)*sign
# All done
return d
def read_from_en(self, velfile, factor=1., minerr=1., header=0):
'''
Reading velocities from a en file formatted as:
+-------------+-----+-----+-------+-------+-------+-------+
| StationName | Lon | Lat | e_vel | n_vel | e_err | n_err |
+=============+=====+=====+=======+=======+=======+=======+
| | | | | | | |
| | | | | | | |
+-------------+-----+-----+-------+-------+-------+-------+
Args:
* velfile : File containing the velocities.
Kwargs:
* factor : multiplication factor for velocities
* minerr : if err=0, then err=minerr.
* header : length of the file header
Returns:
* None
'''
if self.verbose:
print ("Read data from file {} into data set {}".format(velfile, self.name))
# Keep the file
self.velfile = velfile
# open the file
fvel = open(self.velfile, 'r')
# read it
Vel = fvel.readlines()
# Initialize things
self.lon = [] # Longitude list
self.lat = [] # Latitude list
self.vel_enu = [] # ENU velocities list
self.err_enu = [] # ENU errors list
self.station = [] # Name of the stations
for i in range(header,len(Vel)):
A = Vel[i].split()
if 'nan' not in A:
self.station.append(A[0])
self.lon.append(np.float(A[1]))
self.lat.append(np.float(A[2]))
east = np.float(A[3])
north = np.float(A[4])
self.vel_enu.append([east, north, 0.0])
east = np.float(A[5])
north = np.float(A[6])
up = 0.0
if east == 0.:
east = minerr
if north == 0.:
north = minerr
if up == 0:
up = minerr
self.err_enu.append([east, north, up])
# Make np array with that
self.lon = np.array(self.lon).squeeze()
self.lat = np.array(self.lat).squeeze()
self.vel_enu = np.array(self.vel_enu).squeeze()*factor
self.err_enu = np.array(self.err_enu).squeeze()*factor
self.station = np.array(self.station).squeeze()
self.factor = factor
# set lon to (0, 360.)
self._checkLongitude()
# Pass to xy
self.lonlat2xy()
# All done
return
def read_from_enu(self, velfile, factor=1., minerr=1., header=0, checkNaNs=True):
'''
Reading velocities from a enu file formatted as
+-------------+-----+-----+-------+-------+-------+-------+-------+-------+
| StationName | Lon | Lat | e_vel | n_vel | u_vel | e_err | n_err | u_err |
+=============+=====+=====+=======+=======+=======+=======+=======+=======+
| | | | | | | | | |
| | | | | | | | | |
+-------------+-----+-----+-------+-------+-------+-------+-------+-------+
Args:
* velfile : Input file
Kwargs:
* factor : multiplication factor for velocities
* minerr : if err=0, then err=minerr.
* header : length of the header
* checkNaNs : If True, kicks out stations with NaNs
Returns:
* None
'''
if self.verbose:
print ("Read data from file {} into data set {}".format(velfile, self.name))
# Keep the file
self.velfile = velfile
# open the file
fvel = open(self.velfile, 'r')
# read it
Vel = fvel.readlines()
# Initialize things
self.lon = [] # Longitude list
self.lat = [] # Latitude list
self.vel_enu = [] # ENU velocities list
self.err_enu = [] # ENU errors list
self.station = [] # Name of the stations
for i in range(header,len(Vel)):
A = Vel[i].split()
if 'nan' not in A or not checkNaNs:
self.station.append(A[0])
self.lon.append(np.float(A[1]))
self.lat.append(np.float(A[2]))
east = np.float(A[3])
north = np.float(A[4])
up = np.float(A[5])
self.vel_enu.append([east, north, up])
east = np.float(A[6])
north = np.float(A[7])
up = np.float(A[8])
if east == 0.:
east = minerr
if north == 0.:
north = minerr
if up == 0:
up = minerr