forked from jolivetr/csi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opticorr.py
1896 lines (1511 loc) · 60.5 KB
/
opticorr.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 Optical correlation data
Written by R. Jolivet, B. Riel and Z. Duputel, April 2013.
'''
# Externals
import numpy as np
import pyproj as pp
import os
import matplotlib.pyplot as plt
from scipy.linalg import block_diag
import scipy.spatial.distance as scidis
# Personals
from .SourceInv import SourceInv
from .geodeticplot import geodeticplot as geoplot
from . import csiutils as utils
class opticorr(SourceInv):
'''
A class that handles optical correlation results
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)
'''
def __init__(self, name, utmzone=None, ellps='WGS84', verbose=True, lon0=None, lat0=None):
# Base class init
super(opticorr,self).__init__(name,
utmzone=utmzone,
lon0=lon0,
lat0=lat0,
ellps=ellps)
# Initialize the data set
self.dtype = 'opticorr'
self.verbose = verbose
if self.verbose:
print ("---------------------------------")
print ("---------------------------------")
print ("Initialize Opticorr data set {}".format(self.name))
# Initialize some things
self.east = None
self.north = None
self.east_synth = None
self.north_synth = None
self.up_synth = None
self.err_east = None
self.err_north = None
self.lon = None
self.lat = None
self.corner = None
self.xycorner = None
self.Cd = None
# All done
return
def read_from_varres(self,filename, factor=1.0, step=0.0, header=2, cov=False):
'''
Read the Optical Corr east-north offsets from the VarRes output. This is what comes from the decimation process in imagedownsampling
Args:
* filename : Name of the input file. Two files are opened filename.txt and filename.rsp.
Kwargs:
* factor : Factor to multiply the east-north offsets.
* step : Add a value to the velocity.
* header : Size of the header.
* cov : Read an additional covariance file (binary float32, Nd*Nd elements).
Returns:
* None
'''
if self.verbose:
print ("Read from file {} into data set {}".format(filename, self.name))
# Open the file
fin = open(filename+'.txt', 'r')
fsp = open(filename+'.rsp', 'r')
# Read it all
A = fin.readlines()
B = fsp.readlines()
# Initialize the business
self.lon = []
self.lat = []
self.east = []
self.north = []
self.err_east = []
self.err_north = []
self.corner = []
# Loop over the A, there is a header line header
for i in range(header, len(A)):
tmp = A[i].split()
self.lon.append(np.float(tmp[1]))
self.lat.append(np.float(tmp[2]))
self.east.append(np.float(tmp[3]))
self.north.append(np.float(tmp[4]))
self.err_east.append(np.float(tmp[5]))
self.err_north.append(np.float(tmp[6]))
tmp = B[i].split()
self.corner.append([np.float(tmp[6]), np.float(tmp[7]),
np.float(tmp[8]), np.float(tmp[9])])
# Make arrays
self.east = factor * (np.array(self.east) + step)
self.north = factor * (np.array(self.north) + step)
self.lon = np.array(self.lon)
self.lat = np.array(self.lat)
self.err_east = np.array(self.err_east) * factor
self.err_north = np.array(self.err_north) * factor
self.corner = np.array(self.corner)
# Close file
fin.close()
fsp.close()
# set lon to (0, 360.)
self._checkLongitude()
# Compute lon lat to utm
self.x, self.y = self.ll2xy(self.lon, self.lat)
# Compute corner to xy
self.xycorner = np.zeros(self.corner.shape)
x, y = self.putm(self.corner[:,0], self.corner[:,1])
self.xycorner[:,0] = x/1000.
self.xycorner[:,1] = y/1000.
x, y = self.putm(self.corner[:,2], self.corner[:,3])
self.xycorner[:,2] = x/1000.
self.xycorner[:,3] = y/1000.
# Read the covariance
if cov:
nd = self.east.size + self.north.size
self.Cd = np.fromfile(filename + '.cov', dtype=np.float32).reshape((nd,nd))
self.Cd *= factor*factor
# Store the factor
self.factor = factor
# Save number of observations per station
self.obs_per_station = 2
# All done
return
def read_from_xyz(self, filename, factor=1.0, step=0.0, header=0):
'''
Reads the maps from a xyz file formatted as
+---+---+----+-----+--------+---------+
|lon|lat|east|north|east_err|north_err|
+===+===+====+=====+========+=========+
| | | | | | |
+---+---+----+-----+--------+---------+
Args:
* filename : name of the input file.
Kwargs:
* factor : scale by a factor.
* step : add a value.
* header : length of the file header
Returns:
* None
'''
# Initialize values
self.east = []
self.north = []
self.lon = []
self.lat = []
self.err_east = []
self.err_north = []
# Open the file and read
fin = open(filename, 'r')
A = fin.readlines()
fin.close()
# remove the header lines
A = A[header:]
# Loop
for line in A:
l = line.split()
self.lon.append(np.float(l[0]))
self.lat.append(np.float(l[1]))
self.east.append(np.float(l[2]))
self.north.append(np.float(l[3]))
self.err_east.append(np.float(l[4]))
self.err_north.append(np.float(l[5]))
# Make arrays
self.east = factor * (np.array(self.east) + step)
self.north = factor * (np.array(self.north) + step)
self.lon = np.array(self.lon)
self.lat = np.array(self.lat)
self.err_east = np.array(self.err_east) * factor
self.err_north = np.array(self.err_north) * factor
# set lon to (0, 360.)
self._checkLongitude()
# Compute lon lat to utm
self.x, self.y = self.ll2xy(self.lon, self.lat)
# Store the factor
self.factor = factor
# Save number of observations per station
self.obs_per_station = 2
# All done
return
def read_from_binary(self, east, north, lon, lat, err_east=None, err_north=None, factor=1.0, step=0.0, dtype=np.float32, remove_nan=True):
'''
Read from a set of binary files or from a set of arrays.
Args:
* east : array or filename of the east displacement
* north : array or filename of the north displacement
* lon : array or filename of the longitude
* lat : array or filename of the latitude
Kwargs:
* err_east : uncertainties on the east displacement (file or array)
* err_north : uncertainties on the north displacememt (file or array)
* factor : multiplication factor
* step : offset
* dtype : type of binary file
* remove_nan: Remove nans or not
Returns:
* None
'''
# Get east
if type(east) is str:
east = np.fromfile(east, dtype=dtype)
east = np.array(east).flatten()
# Get north
if type(north) is str:
north = np.fromfile(north, dtype=dtype)
north = np.array(north).flatten()
# Get lon
if type(lon) is str:
lon = np.fromfile(lon, dtype=dtype)
lon = np.array(lon).flatten()
# Get Lat
if type(lat) is str:
lat = np.fromfile(lat, dtype=dtype)
lat = np.array(lat).flatten()
# Errors
if err_east is not None:
if type(err_east) is str:
err_east = np.fromfile(err_east, dtype=dtype)
err_east = np.array(err_east).flatten()
else:
err_east = np.zeros(east.shape)
if err_north is not None:
if type(err_north) is str:
err_north = np.fromfile(err_north, dtype=dtype)
err_north = np.array(err_north).flatten()
else:
err_north = np.zeros(north.shape)
# Check NaNs
if remove_nan:
eFinite = np.flatnonzero(np.isfinite(east))
nFinite = np.flatnonzero(np.isfinite(north))
iFinite = np.intersect1d(eFinite, nFinite).tolist()
else:
iFinite = range(east.shape[0])
# Set things in there
self.east = factor * (east[iFinite] + step)
self.north = factor * (north[iFinite] + step)
self.lon = lon[iFinite]
self.lat = lat[iFinite]
self.err_east = err_east[iFinite] * factor
self.err_north = err_north[iFinite] * factor
# set lon to (0, 360.)
self._checkLongitude()
# Compute lon lat to utm
self.x, self.y = self.ll2xy(self.lon, self.lat)
# Store the factor
self.factor = factor
# Save number of observations per station
self.obs_per_station = 2
# All done
return
def read_from_envi(self, filename, component='EW', remove_nan=True):
'''
Reads displacement map from an ENVI file.
Args:
* filename : Name of the input file
Kwargs:
* component : 'EW' or 'NS'
* remove_nan: Remove Nans or not
Returns:
* None
'''
assert component=='EW' or component=='NS', 'component must be EW or NS'
# Read header
hdr = open(filename+'.hdr','r').readlines()
for l in hdr:
items = l.strip().split('=')
if items[0].strip()=='data type':
assert float(items[1])==4,'data type is not float32'
if items[0].strip()=='samples':
self.samples = int(items[1])
if items[0].strip()=='lines':
self.lines = int(items[1])
if items[0].strip()=='map info':
map_items = l.strip().split('{')[1].strip('}').split(',')
assert map_items[0].strip()=='UTM', 'Map is not UTM {}'.format(map_items[0])
x0 = float(map_items[3])
y0 = float(map_items[4])
dx = float(map_items[5])
dy = float(map_items[6])
assert int(map_items[7])==self.utmzone, 'UTM zone does not match'
assert map_items[9].strip().replace('-','')==self.ellps, 'ellps zone does not match'
# Coordinates
x = x0 + np.arange(self.samples) * dx
y = y0 - np.arange(self.lines) * dy
xg,yg = np.meshgrid(x,y)
self.x = xg.flatten()/1000.
self.y = yg.flatten()/1000.
self.lon, self.lat = self.xy2ll(self.x,self.y)
# Data
if component=='EW':
self.east = np.fromfile(filename,dtype='float32')
print('read length',len(self.east))
if remove_nan:
u = np.flatnonzero(np.isfinite(self.east))
self.east = self.east[u]
self.err_east=np.zeros(self.east.shape) # set to zero error for now
print('after mask',len(self.east))
elif component=='NS':
self.north = np.fromfile(filename,dtype='float32')
if remove_nan:
u = np.flatnonzero(np.isfinite(self.north))
self.north = self.north[u]
self.err_north=np.zeros(self.north.shape) # set to zero error for now
if remove_nan:
self.lon = self.lon[u]; self.lat = self.lat[u]
self.x = self.x[u] ; self.y = self.y[u]
# set lon to (0, 360.)
self._checkLongitude()
# Check size of arrays
if self.north!=None and self.east!=None:
assert len(self.north) == len(self.east), 'inconsistent data size'
assert len(self.lon)==len(self.lat), 'inconsistent lat/lon size'
assert len(self.lon)==len(self.north), 'inconsistent lon/data size'
self.factor = 1.0
self.obs_per_station = 2
# All done
return
def splitFromShapefile(self, shapefile, remove_nan=True):
'''
Uses the paths defined in a Shapefile to select and return particular domains of self.
Args:
* shapefile : Input file (shapefile format).
Kwargs:
* remove_nan: Remove nans
Returns:
* None
'''
# Import necessary library
import shapefile as shp
import matplotlib.path as path
# Build a list of points
AllXY = np.vstack((self.x, self.y)).T
# Read the shapefile
shape = shp.Reader(shapefile)
# Create the list of new objects
OutOpti = []
# Iterate over the shape records
for record, iR in zip(shape.shapeRecords(), range(len(shape.shapeRecords()))):
# Get x, y
x = np.array([record.shape.points[i][0] for i in range(len(record.shape.points))])/1000.
y = np.array([record.shape.points[i][1] for i in range(len(record.shape.points))])/1000.
xyroi = np.vstack((x, y)).T
# Build a path with that
roi = path.Path(xyroi, closed=False)
# Get the ones inside
check = roi.contains_points(AllXY)
# Get the values
east = self.east[check]
north = self.north[check]
lon = self.lon[check]
lat = self.lat[check]
if self.err_east is not None:
err_east = self.err_east[check]
else:
err_east = None
if self.err_north is not None:
err_north = self.err_north[check]
else:
err_north = None
# Create a new opticorr object
opti = opticorr('{} #{}'.format(self.name, iR), utmzone=self.utmzone, lon0=self.lon0, lat0=self.lat0, ellps=self.ellps)
# Put the values in there
opti.read_from_binary(east, north, lon, lat, err_east=err_east, err_north=err_north, remove_nan=True)
# Store this object
OutOpti.append(opti)
# All done
return OutOpti
def read_from_grd(self, filename, factor=1.0, step=0.0, flip=False, keepnans=False, variableName='z'):
'''
Reads velocity map from a grd file.
Args:
* filename : Name of the input file. As we are reading two files, the files are filename_east.grd and filename_north.grd
Kwargs:
* factor : scale by a factor
* step : add a value.
* flip : Flip image upside down (some netcdf files require this)
* keepnans : Keeps NaNs or not
* variableName : Name of the variable in the netcdf file
Returns:
* None
'''
if self.verbose:
print ("Read from file {} into data set {}".format(filename, self.name))
# Initialize values
self.east = []
self.north = []
self.lon = []
self.lat = []
self.err_east = []
self.err_north = []
# Open the input file
try:
import scipy.io.netcdf as netcdf
feast = netcdf.netcdf_file(filename+'_east.grd')
fnorth = netcdf.netcdf_file(filename+'_north.grd')
except:
from netCDF4 import Dataset as netcdf
feast = netcdf(filename+'_east.grd', format='NETCDF4')
fnorth = netcdf(filename+'_north.grd', format='NETCDF4')
# Shape
self.grd_shape = feast.variables[variableName][:].shape
# Get the values
self.east = (feast.variables[variableName][:].flatten() + step)*factor
self.north = (fnorth.variables[variableName][:].flatten() + step)*factor
self.err_east = np.ones((self.east.shape)) * factor
self.err_north = np.ones((self.north.shape)) * factor
self.err_east[np.where(np.isnan(self.east))] = np.nan
self.err_north[np.where(np.isnan(self.north))] = np.nan
# Deal with lon/lat
if 'x' in feast.variables.keys():
Lon = feast.variables['x'][:]
Lat = feast.variables['y'][:]
elif 'x_range' in feast.variables.keys():
LonS, LonE = feast.variables['x_range'][:]
LatS, LatE = feast.variables['y_range'][:]
nLon, nLat = feast.variables['dimension'][:]
Lon = np.linspace(LonS, LonE, num=nLon)
Lat = np.linspace(LatS, LatE, num=nLat)
elif 'lon' in feast.variables.keys():
Lon = feast.variables['lon'][:]
Lat = feast.variables['lat'][:]
self.lonarr = Lon.copy()
self.latarr = Lat.copy()
Lon, Lat = np.meshgrid(Lon,Lat)
# Flip if necessary
if flip:
Lat = np.flipud(Lat)
w, l = Lon.shape
self.lon = Lon.reshape((w*l,)).flatten()
self.lat = Lat.reshape((w*l,)).flatten()
# Keep the non-nan pixels only
if not keepnans:
u = np.flatnonzero(np.isfinite(self.east))
self.lon = self.lon[u]
self.lat = self.lat[u]
self.east = self.east[u]
self.north = self.north[u]
self.err_east = self.err_east[u]
self.err_north = self.err_north[u]
# set lon to (0, 360.)
self._checkLongitude()
# Convert to utm
self.x, self.y = self.ll2xy(self.lon, self.lat)
# Store the factor and step
self.factor = factor
self.step = step
# Save number of observations per station
self.obs_per_station = 2
# All done
return
def read_with_reader(self, readerFunc, filePrefix, factor=1.0, cov=False):
'''
Read data from a .txt file using a user provided reading function. Assume the user knows what they are doing and are returning the correct values.
Args:
* readerFunc : A method that knows how to read a file and returns lon, lat, east, north, east_err and north_err (1d arrays)
Kwargs:
* filePrefix : filename before .txt
* factor : scaling factor
* cov : read a covariance from a binary file
'''
lon,lat,east,north,east_err,north_err = readerFunc(filePrefix + '.txt')
self.lon = lon
self.lat = lat
self.east = factor * east
self.north = factor * north
self.err_east = factor * east_err
self.err_north = factor * north_err
# set lon to (0, 360.)
self._checkLongitude()
# Convert to utm
self.x, self.y = self.ll2xy(self.lon, self.lat)
# Read the covariance
if cov:
nd = self.east.size + self.north.size
self.Cd = np.fromfile(filePrefix + '.cov', dtype=np.float32).reshape((nd,nd))
# Store the factor
self.factor = factor
# Save number of observations per station
self.obs_per_station = 2
# All done
return
def select_pixels(self, minlon, maxlon, minlat, maxlat):
'''
Select the pixels in a box defined by min and max, lat and lon.
Args:
* minlon : Minimum longitude.
* maxlon : Maximum longitude.
* minlat : Minimum latitude.
* maxlat : Maximum latitude.
Returns:
* None
'''
# Store the corners
self.minlon = minlon
self.maxlon = maxlon
self.minlat = minlat
self.maxlat = maxlat
# Select on latitude and longitude
u = np.flatnonzero((self.lat>minlat) & (self.lat<maxlat) & (self.lon>minlon) & (self.lon<maxlon))
# Select the stations
npts = self.lon.size
self.lon = self.lon[u]
self.lat = self.lat[u]
self.x = self.x[u]
self.y = self.y[u]
self.east = self.east[u]
self.north = self.north[u]
self.err_east = self.err_east[u]
self.err_north = self.err_north[u]
if self.east_synth is not None:
self.east_synth = self.east_synth[u]
self.north_synth = self.north_synth[u]
if self.corner is not None:
self.corner = self.corner[u,:]
self.xycorner = self.xycorner[u,:]
# Deal with the covariance matrix
if self.Cd is not None:
indCd = np.hstack((u, u+npts))
Cdt = self.Cd[indCd,:]
self.Cd = Cdt[:,indCd]
# All done
return
def setGFsInFault(self, fault, G, vertical=True):
'''
From a dictionary of Green's functions, sets these correctly into the fault
object fault for future computation.
Args:
* fault : Instance of Fault
* G : Dictionary with 3 entries 'strikeslip', 'dipslip' and 'tensile'
Kwargs:
* vertical : Do we use vertical predictions? Default is True
Returns:
* None
'''
# Get values
try:
Gss = G['strikeslip']
except:
Gss = None
try:
Gds = G['dipslip']
except:
Gds = None
try:
Gts = G['tensile']
except:
Gts = None
try:
Gcp = G['coupling']
except:
Gcp = None
# Set these values
fault.setGFs(self, strikeslip=[Gss], dipslip=[Gds], tensile=[Gts], coupling=[Gcp], vertical=vertical)
# All done
return
def setTransformNormalizingFactor(self, x0, y0, normX, normY):
'''
Set orbit normalizing factors in insar object.
Args:
* x0 : Normalization reference x-axis
* y0 : Normalization reference y-axis
* normX : Normalizing length along x-axis
* normY : Normalizing length along y-axis
Returns:
* None
'''
self.TransformNormalizingFactor = {}
self.TransformNormalizingFactor['x'] = normX
self.TransformNormalizingFactor['y'] = normY
self.TransformNormalizingFactor['ref'] = [x0, y0]
# All done
return
def computeTransformNormalizingFactor(self):
'''
Compute orbit normalizing factors and store them in insar object.
Returns:
* None
'''
x0 = self.x[0]
y0 = self.y[0]
normX = np.abs(self.x - x0).max()
normY = np.abs(self.y - y0).max()
self.TransformNormalizingFactor = {}
self.TransformNormalizingFactor['x'] = normX
self.TransformNormalizingFactor['y'] = normY
self.TransformNormalizingFactor['ref'] = [x0, y0]
# All done
return
def getTransformEstimator(self, trans, computeNormFact=True):
'''
Returns the Estimator for the transformation to estimate in the InSAR data.
Args:
* trans : Transformation type
- 1: constant offset to the data
- 3: constant and linear function of x and y
- 4: constant, linear term and cross term.
- 'strain': estimates an aerial strain tensor
Kwargs:
* computeNormFact : Recompute the normalization factor
Returns:
* None
'''
# Several cases
if type(trans) is int:
T = self.getPolyEstimator(trans, computeNormFact=computeNormFact)
else:
assert False, 'No {} transformation available'.format(trans)
# All done
return T
def getPolyEstimator(self, ptype, computeNormFact=True):
'''
Returns the Estimator for the polynomial form to estimate in the optical correlation data.
Args:
* ptype : Style of polynomial
+-------+------------------------------------------------------------+
| ptype | what it means |
+=======+============================================================+
| 1 | apply a constant offset to the data (1 parameter) |
+-------+------------------------------------------------------------+
| 3 | apply offset and linear function of x and y (3 parameters) |
+-------+------------------------------------------------------------+
| 4 | apply offset, linear function and cross term (4 parameters)|
+-------+------------------------------------------------------------+
Watch out: If vertical is True, you should only estimate polynomials for the horizontals.
Kwargs:
* computeNormFact : bool. If False, uses parameters in self.TransformNormalizingFactor
Returns:
* 2d array
'''
# Get the basic size of the polynomial
basePoly = int(ptype / self.obs_per_station)
assert basePoly >= 3 or basePoly == 1, """
only support 0th, 1st and 2nd order polynomials, here {} asked
""".format(basePoly)
# Get number of points
nd = self.east.shape[0]
# Compute normalizing factors
if computeNormFact:
self.computeTransformNormalizingFactor()
else:
assert hasattr(self, 'TransformNormalizingFactor'), 'You must set TransformNormalizingFactor first'
normX = self.TransformNormalizingFactor['x']
normY = self.TransformNormalizingFactor['y']
x0, y0 = self.TransformNormalizingFactor['ref']
# Pre-compute position-dependent functional forms
f1 = self.factor * np.ones((nd,))
f2 = self.factor * (self.x - x0) / normX
f3 = self.factor * (self.y - y0) / normY
f4 = self.factor * (self.x - x0) * (self.y - y0) / (normX*normY)
f5 = self.factor * (self.x - x0)**2 / normX**2
f6 = self.factor * (self.y - y0)**2 / normY**2
polyFuncs = [f1, f2, f3, f4, f5, f6]
# Fill in orb matrix given an order
orb = np.zeros((nd, basePoly))
for ind in range(basePoly):
orb[:,ind] = polyFuncs[ind]
# Block diagonal for both components
if self.obs_per_station > 1:
orb = block_diag(orb, orb)
# Check to see if we're including verticals
if self.obs_per_station == 3:
orb = np.vstack((orb, np.zeros((nd, 2*basePoly))))
# All done
return orb
def computePoly(self, fault, computeNormFact=True):
'''
Computes the orbital bias estimated in fault
Args:
* fault : Fault object that has a polysol structure.
Kwargs:
* computeNormFact: if True, recompute the normalization.
Returns:
* None
'''
# Get the polynomial type
ptype = fault.poly[self.name]
# Get the parameters
params = fault.polysol[self.name]
# Get the estimator
Horb = self.getPolyEstimator(ptype, computeNormFact=computeNormFact)
# Compute the polynomial
tmporbit = np.dot(Horb, params)
# Store them
nd = self.east.shape[0]
self.east_orbit = tmporbit[:nd]
self.north_orbit = tmporbit[nd:2*nd]
# All done
return
def computeCustom(self, fault):
'''
Computes the displacements associated with the custom green's functions.
Args:
* fault : Fault object with custom green's functions
Returns:
* None. Stores the prediction in self.custompred
'''
# Get the GFs and the parameters
G = fault.G[self.name]['custom']
custom = fault.custom[self.name]
# Compute
custompred = np.dot(G, custom)
# Store
nd = self.east.shape[0]
self.east_custompred = custompred[:nd]
self.north_custompred = custompred[nd:2*nd]
# All done
return
def removePoly(self, fault, verbose=False, custom=False,computeNormFact=True):
'''
Removes a polynomial from the parameters that are in a fault.
Args:
* fault : instance of fault that has a polysol structure
Kwargs:
* verbose : Talk to me
* custom : Is there custom GFs?
* computeNormFact : If True, recomputes Normalization factor
Returns:
* None. Directly corrects the data
'''
# Compute the polynomial
self.computePoly(fault,computeNormFact=computeNormFact)
# Print Something
if verbose:
params = fault.polysol[self.name].tolist()
print('Correcting opticor {} from polynomial function: {}'.format(self.name, tuple(p for p in params)))
# Correct data
self.east -= self.east_orbit
self.north -= self.north_orbit
# Correct custom
if custom:
self.computeCustom(fault)
self.east -= self.east_custompred
self.north -= self.north_custompred
# All done
return
def removeRamp(self, order=3, maskPoly=None):
'''
Note: No Idea who started implementing this, but it is clearly not finished...
Pre-remove a ramp from the data that fall outside of mask. If no mask is provided,
we use all the points to fit a mask.
Kwargs:
* order : Polynomial order
* maskPoly : path to make a mask
Returns:
* None
'''
raise NotImplementedError('This method is not fully implemented')
assert order == 1 or order == 3, 'unsupported order for ramp removal'
# Define normalized coordinates
x0, y0 = self.x[0], self.y[0]
xd = self.x - x0
yd = self.y - y0
normX = np.abs(xd).max()
normY = np.abs(yd).max()
# Find points that fall outside of mask
east = self.east.copy()
north = self.north.copy()
if maskPoly is not None:
path = Path(maskPoly)
mask = path.contains_points(zip(self.x, self.y))
badIndices = mask.nonzero()[0]
xd = xd[~badIndices]
yd = yd[~badIndices]
east = east[~badIndices]
north = north[~badIndices]
# Construct ramp design matrix
nPoints = east.shape[0]
nDat = 2 * nPoints
nPar = 2 * order
Gramp = np.zeros((nDat,nPar))
if order == 1:
Gramp[:nPoints,0] = 1.0
Gramp[nPoints:,1] = 1.0
else:
Gramp[:nPoints,0] = 1.0
Gramp[:nPoints,1] = xd / normX
Gramp[:nPoints,2] = yd / normY
Gramp[nPoints:,3] = 1.0
Gramp[nPoints:,4] = xd / normX
Gramp[nPoints:,5] = yd / normY
# Estimate ramp parameters
d = np.hstack((east,north))
m_ramp = np.linalg.lstsq(Gramp, d)[0]
# Not Finished
return
def removeSynth(self, faults, direction='sd', poly=None, vertical=False, custom=False,computeNormFact=True):