-
Notifications
You must be signed in to change notification settings - Fork 32
/
insartimeseries.py
1641 lines (1284 loc) · 52.6 KB
/
insartimeseries.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 InSAR data, after decimation using VarRes.
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 matplotlib.dates as mpdates
import sys
import datetime as dt
import scipy.interpolate as sciint
import scipy.io as scio
import copy
# Personals
from .csiutils import *
from .SourceInv import SourceInv
from .insar import insar
from .gpstimeseries import gpstimeseries
class insartimeseries(insar):
'''
A class that handles a time series of insar data
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(insartimeseries,self).__init__(name,
utmzone=utmzone,
ellps=ellps,
lon0=lon0,
lat0=lat0,
verbose=False)
# Initialize the data set
self.dtype = 'insartimeseries'
if verbose:
print ("---------------------------------")
print ("---------------------------------")
print ("Initialize InSAR Time Series data set {}".format(self.name))
# Initialize some things
self.vel = None
self.synth = None
self.err = None
self.lon = None
self.lat = None
self.los = None
self.corner = None
self.xycorner = None
self.Cd = None
# Save
self.verbose = verbose
# All done
return
def setLonLat(self, lon, lat, incidence=None, heading=None, elevation=None, dtype='d'):
'''
Sets the lon and lat array and initialize things.
Args:
* lon : Can be an array or a string.
* lat : Can be an array or a string.
Kwargs:
* incidence : Can be an array or a string.
* heading : Can be an array or a string.
* elevation : Can be an array or a string.
Returns:
* None
'''
# Get some size
if type(lon) is str:
lon = np.fromfile(lon, dtype=dtype)
nSamples = lon.shape[0]
# Set the main stuff
self.read_from_binary(np.ones((nSamples,)), lon, lat, incidence=incidence, heading=heading, dtype=dtype, remove_nan=False, remove_zeros=False)
self.vel = None
# Set the elevation if provided
if elevation is not None:
self.elevation = insar('Elevation', utmzone=self.utmzone, verbose=False, lon0=self.lon0, lat0=self.lat0, ellps=self.ellps)
self.elevation.read_from_binary(elevation, lon, lat, incidence=None, heading=None, remove_nan=False, remove_zeros=False)
self.z = self.elevation.vel
# All done
return
def initializeTimeSeries(self, time=None, start=None, end=None, increment=None,
steps=None, dtype='d'):
'''
Initializes the time series object using a series of dates. Two modes of input are possible
:Mode 1:
* time : List of dates (datetime object)
:Mode 2:
* start : Starting date (datetime object)
* end : Ending date
* increment : Increment of time in days
* steps : How many steps
Returns:
* None
'''
# Set up a list of Dates
if time is not None:
self.time = time
else:
assert start is not None, 'Need a starting point...'
assert increment is not None, 'Need an increment in days...'
assert steps is not None, 'Need a number of steps...'
self.time = [dt.datetime.fromordinal(start.toordinal()+increment*i)\
for i in range(steps)]
# Create timeseries
self.timeseries = []
# Create an insarrate instance for each step
for date in self.time:
sar = insar(date.isoformat(), utmzone=self.utmzone, verbose=False,
lon0=self.lon0, lat0=self.lat0, ellps=self.ellps)
sar.read_from_binary(np.zeros(self.lon.shape), self.lon, self.lat,
incidence=self.incidence, heading=self.heading,
dtype=dtype, remove_nan=False, remove_zeros=False)
self.timeseries.append(sar)
# All done
return
def buildCd(self, sigma, lam, function='exp', diagonalVar=False,
normalizebystd=False):
'''
Builds the full Covariance matrix from values of sigma and lambda.
:If function='exp':
.. math::
C_d(i,j) = \\sigma^2 e^{-\\frac{||i,j||_2}{\\lambda}}
:elif function='gauss':
.. math::
C_d(i,j) = \\sigma^2 e^{-\\frac{||i,j||_2^2}{2\\lambda}}
Args:
* sigma : Sigma term of the covariance
* lam : Caracteristic length of the covariance
Kwargs:
* function : Can be 'gauss' or 'exp'
* diagonalVar : Substitute the diagonal by the standard deviation of the measurement squared
* normalizebystd : Normalize Cd by the stddeviation (weird idea... why would you do that?)
'''
# Iterate over the time serie
for sar in self.timeseries:
sar.buildCd(sigma, lam, function=function,
diagonalVar=diagonalVar, normalizebystd=normalizebystd)
# All done
return
def getInsarAtDate(self, date, verbose=True):
'''
Given a datetime instance, returns the corresponding insar instance.
Args:
* date : datetime instance.
Kwargs:
* verbose : talk to me
Returns:
* insar : instance of insar class
'''
# Find the right index
try:
udate = self.time.index(date)
except:
if verbose:
print('Date {} not available'.format(date.isoformat()))
return None
# Speak to me
if verbose:
print('Returning insar image at date {}'.format(self.time[udate]))
return self.timeseries[udate]
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. Directly kicks out pixels that are outside the box
'''
# 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))
# Iterate over the timeseries
for sar in self.timeseries:
sar.keepPixels(u)
# Keep pixels
self.keepPixels(u)
# All done
return
def setTimeSeries(self, timeseries):
'''
Sets the values in the time series.
Args:
* timeseries : List of arrays of the right size.
Returns:
* None
'''
# Assert
assert type(timeseries) is list, 'Input argument must be a list...'
# Iterate
for data, ts in zip(timeseries, self.timeseries):
# Convert
data = np.array(data)
# Check
assert data.shape==self.lon.shape, 'Wrong size for input for {}...'.format(ts.name)
# Set
ts.vel = data
# All done
return
def reference2area(self, lon, lat, radius):
'''
References the time series to an area. Selects the area and sets all dates to zero at this area.
Args:
* lon : longitude of the center of the area
* lat : latitude of the center of the area
* radius : Radius of the area
Returns:
* None
'''
# Iterate
for insar in self.timeseries:
# Reference
insar.reference2area(lon, lat, radius)
# All done
return
def referenceTimeSeries2Date(self, date):
'''
References the time series to the date given as argument.
Args:
* date : Can a be tuple/list of 3 integers (year, month, day) or a tuple/list of 6 integers (year, month, day, hour, min, sec) or a datetime object.
Returns:
* None. Directly modifies time series
'''
# Make date
if type(date) in (tuple, list):
if len(date)==3:
date = dt.datetime(date[0], date[1], date[2])
elif len(date)==6:
date = dt.datetime(date[0], date[1], date[2], date[3], date[4], date[5])
elif len(date)==1:
print('Unknow date format...')
sys.exit(1)
assert (type(date) is type(self.time[0])), 'Provided date can be \n \
tuple of (year, month, day), \n \
tuple of (year, month, day ,hour, min,s), \n \
datetime.datetime object'
# Get the reference
try:
i = self.time.index(date)
except:
print('Date {} not available'.format(date.isformat()))
reference = copy.deepcopy(self.timeseries[i].vel)
# Reference
for ts in self.timeseries:
ts.vel -= reference
# All done
return
def write2h5file(self, h5file, field='recons'):
'''
Writes the time series in a h5file
Args:
* h5file : Output h5file
Kwargs:
* field : name of the field in the h5 file
Returns:
* None
'''
try:
import h5py
except:
print('No hdf5 capabilities detected')
# Open the file
h5out = h5py.File(h5file, 'w')
# Create the data field
time = h5out.create_dataset('dates', shape=(len(self.timeseries),))
data = h5out.create_dataset(field, shape=(len(self.timeseries), len(self.timeseries[0].lon), 1))
# Iterate over time
for itime, date in enumerate(self.time):
# Get the time series
data[itime,:,0] = self.timeseries[itime].vel
time[itime] = date.toordinal()
# Close the file
h5out.close()
# All done
return
def readFromKFts(self, h5file, setmaster2zero=None,
zfile=None, lonfile=None, latfile=None, filetype='f',
incidence=None, heading=None, inctype='onefloat', closeh5=True, box=None,
field='rawts', error='rawts_std', keepnan=False, mask=None, readModel=False):
'''
Read the output from a typical GIAnT h5 output file.
Args:
* h5file : Input h5file (phase file)
Kwargs:
* setmaster2zero: If index is provided, master will be replaced by zeros (no substraction)
* zfile : File with elevation
* lonfile : File with longitudes
* latfile : File with latitudes
* filetype : type of data in lon, lat and elevation file (default: 'f')
* incidence : Incidence angle (degree)
* box : Crop data (default None), ex: [y0:y1,x0:x1]
* heading : Heading angle (degree)
* inctype : Type of the incidence and heading values (see insar.py for details). Can be 'onefloat', 'grd', 'binary', 'binaryfloat'
* field : Name of the field in the h5 file.
* error : Name of the phase std deviation field.
* mask : Adds a common mask to the data. mask is an array the same size as the data with nans and 1. It can also be a tuple with a key word in the h5file, a value and 'above' or 'under'
Returns:
* None
'''
try:
import h5py
except:
print('No hdf5 capabilities detected')
# open the h5file
h5in = h5py.File(h5file, 'r')
self.h5in = h5in
# Get the data
data = h5in[field]
err = h5in[field+'_std']
# Box
if box is None:
bbox = [0,data.shape[0],0,data.shape[1]]
else:
bbox = box
# Get some sizes
nDates = data.shape[2]
nLines = bbox[1]-bbox[0]
nCols = bbox[3]-bbox[2]
# Deal with the mask instructions
if mask is not None:
if type(mask) is tuple:
key = mask[0]
value = mask[1]
instruction = mask[2]
mask = np.ones((nLines, nCols))
if instruction in ('above'):
mask[np.where(h5in[key][bbox[0]:bbox[1],bbox[2]:bbox[3]]>value)] = np.nan
elif instruction in ('under'):
mask[np.where(h5in[key][bbox[0]:bbox[1],bbox[2]:bbox[3]]<value)] = np.nan
else:
print('Unknow instruction type for Masking...')
sys.exit(1)
else:
mask = np.ones((nLines, nCols))
# Read Lon Lat
if lonfile is not None:
self.lon = np.fromfile(lonfile, dtype=filetype).reshape((data.shape[0],data.shape[1]))[bbox[0]:bbox[1],bbox[2]:bbox[3]].flatten()
if latfile is not None:
self.lat = np.fromfile(latfile, dtype=filetype).reshape((data.shape[0],data.shape[1]))[bbox[0]:bbox[1],bbox[2]:bbox[3]].flatten()
# Compute utm
self.x, self.y = self.ll2xy(self.lon, self.lat)
# Elevation
if zfile is not None:
self.elevation = insar('Elevation', utmzone=self.utmzone,
verbose=False, lon0=self.lon0, lat0=self.lat0,
ellps=self.ellps)
z = np.fromfile(zfile, dtype=filetype).reshape((data.shape[0],data.shape[1]))[bbox[0]:bbox[1],bbox[2]:bbox[3]].flatten()
self.elevation.read_from_binary(z, self.lon, self.lat,
incidence=None, heading=None,
remove_nan=False, remove_zeros=False,
dtype=filetype)
self.z = self.elevation.vel
# Get the time
dates = h5in['dates']
self.time = []
for i in range(nDates):
self.time.append(dt.datetime.fromordinal(int(dates[i])))
# Create a list to hold the dates
self.timeseries = []
# Iterate over the dates
for i in range(nDates):
# Get things
date = self.time[i]
if self.verbose:
sys.stdout.write('\r Reading {}'.format(date.isoformat()))
sys.stdout.flush()
dat = data[bbox[0]:bbox[1],bbox[2]:bbox[3],i]*mask[bbox[0]:bbox[1],bbox[2]:bbox[3]]
std = err[bbox[0]:bbox[1],bbox[2]:bbox[3],i]*mask[bbox[0]:bbox[1],bbox[2]:bbox[3]]
# check master date
if i is setmaster2zero:
dat[:,:] = 0.
# Create an insar object
sar = insar('{} {}'.format(self.name,date.isoformat()), utmzone=self.utmzone,
verbose=False, lon0=self.lon0, lat0=self.lat0, ellps=self.ellps)
# Put thing in the insarrate object
sar.vel = dat.flatten()
sar.err = std.flatten()
sar.lon = self.lon
sar.lat = self.lat
sar.x = self.x
sar.y = self.y
# Things should remain None
sar.corner = None
# Set factor
sar.factor = 1.0
# Take care of the LOS
if incidence is not None and heading is not None:
assert box is None, 'Incidence cropping not implemented yet'
sar.inchd2los(incidence, heading, origin=inctype)
else:
sar.los = np.zeros((sar.vel.shape[0], 3))
# Store the object in the list
self.timeseries.append(sar)
# Remove nans
if not keepnan:
sar.checkNaNs()
# Keep incidence and heading
self.incidence = incidence
self.heading = heading
self.inctype = inctype
# Close file if asked
if closeh5:
h5in.close()
# Create fakes
self.vel = np.zeros(self.lon.shape)
self.err = None
if not hasattr(self, 'los'):
self.los = None
self.synth = None
self.corner = None
# all done
return
def readFromGIAnT(self, h5file, setmaster2zero=None,
zfile=None, lonfile=None, latfile=None, filetype='f',
incidence=None, heading=None, inctype='onefloat',
field='recons', keepnan=False, mask=None, readModel=False):
'''
Read the output from a typical GIAnT h5 output file.
Args:
* h5file : Input h5file
Kwargs:
* setmaster2zero: If index is provided, master will be replaced by zeros (no substraction)
* zfile : File with elevation
* lonfile : File with longitudes
* latfile : File with latitudes
* filetype : type of data in lon, lat and elevation file (default: 'f')
* incidence : Incidence angle (degree)
* heading : Heading angle (degree)
* inctype : Type of the incidence and heading values (see insar.py for details). Can be 'onefloat', 'grd', 'binary', 'binaryfloat'
* field : Name of the field in the h5 file.
* mask : Adds a common mask to the data. mask is an array the same size as the data with nans and 1. It can also be a tuple with a key word in the h5file, a value and 'above' or 'under'
* readModel : Reads the model parameters
Returns:
* None
'''
try:
import h5py
except:
print('No hdf5 capabilities detected')
# open the h5file
h5in = h5py.File(h5file, 'r')
self.h5in = h5in
# Get the data
data = h5in[field]
# Get some sizes
nDates = data.shape[0]
nLines = data.shape[1]
nCols = data.shape[2]
# Deal with the mask instructions
if mask is not None:
if type(mask) is tuple:
key = mask[0]
value = mask[1]
instruction = mask[2]
mask = np.ones((nLines, nCols))
if instruction in ('above'):
mask[np.where(h5in[key][:]>value)] = np.nan
elif instruction in ('under'):
mask[np.where(h5in[key][:]<value)] = np.nan
else:
print('Unknow instruction type for Masking...')
sys.exit(1)
# Read Lon Lat
if lonfile is not None:
self.lon = np.fromfile(lonfile, dtype=filetype)
if latfile is not None:
self.lat = np.fromfile(latfile, dtype=filetype)
# Compute utm
self.x, self.y = self.ll2xy(self.lon, self.lat)
# Elevation
if zfile is not None:
self.elevation = insar('Elevation', utmzone=self.utmzone,
verbose=False, lon0=self.lon0, lat0=self.lat0,
ellps=self.ellps)
self.elevation.read_from_binary(zfile, lonfile, latfile,
incidence=None, heading=None,
remove_nan=False, remove_zeros=False,
dtype=filetype)
self.z = self.elevation.vel
# Get the time
dates = h5in['dates']
self.time = []
for i in range(nDates):
self.time.append(dt.datetime.fromordinal(int(dates[i])))
# Create a list to hold the dates
self.timeseries = []
# Iterate over the dates
for i in range(nDates):
# Get things
date = self.time[i]
dat = data[i,:,:]
# Mask?
if mask is not None:
dat *= mask
# check master date
if i is setmaster2zero:
dat[:,:] = 0.
# Create an insar object
sar = insar('{} {}'.format(self.name,date.isoformat()), utmzone=self.utmzone,
verbose=False, lon0=self.lon0, lat0=self.lat0, ellps=self.ellps)
# Put thing in the insarrate object
sar.vel = dat.flatten()
sar.lon = self.lon
sar.lat = self.lat
sar.x = self.x
sar.y = self.y
# Things should remain None
sar.corner = None
sar.err = None
# Set factor
sar.factor = 1.0
# Take care of the LOS
if incidence is not None and heading is not None:
sar.inchd2los(incidence, heading, origin=inctype)
else:
sar.los = np.zeros((sar.vel.shape[0], 3))
# Store the object in the list
self.timeseries.append(sar)
# Keep incidence and heading
self.incidence = incidence
self.heading = heading
self.inctype = inctype
# if readVel
if readModel:
self.readModelFromGIAnT()
# Make a common mask if asked
if not keepnan:
# Create an array
checkNaNs = np.zeros(self.lon.shape)
checkNaNs[:] = False
# Trash the pixels where there is only NaNs
for sar in self.timeseries:
checkNaNs += np.isfinite(sar.vel)
uu = np.flatnonzero(checkNaNs==0)
# Keep 'em
for sar in self.timeseries:
sar.reject_pixel(uu)
if zfile is not None:
elevation.reject_pixel(uu)
self.reject_pixel(uu)
h5in.close()
# all done
return
def readModelFromGIAnT(self):
'''
Read the model parameters from GIAnT after one has read the time series
:Note: One needs to run the readFromGIAnT method.
Returns:
* None
'''
# This step needs tsinsar
import tsinsar
# Get the representation
self.rep = tsinsar.mName2Rep(self.h5in['mName'].value)
# Iterate over the model parameters
self.models = []
for u, mName in enumerate(self.h5in['mName']):
# Build the guy
param = insar('Parameter {}'.format(mName),
utmzone=self.utmzone, lon0=self.lon0, lat0=self.lat0, ellps=self.ellps,
verbose=False)
param.vel = self.h5in['parms'][:,:,u].flatten()
param.lon = self.lon
param.lat = self.lat
param.x = self.x
param.y = self.y
param.corner = None
param.err = None
param.factor=1.0
param.inchd2los(self.incidence, self.heading, origin=self.inctype)
# Save it
self.models.append(param)
# All done
return
def readFromStamps(self, tsfile, lonlatfile, datefile, setmaster2zero=None,
incidence=None, heading=None, inctype='onefloat',
keepnan=False):
'''
Read the output from a typical Stamps mat file
Returns:
* None
'''
# open the h5file
ts_file = scio.loadmat(tsfile)
lonlat = np.loadtxt(lonlatfile)
dates = np.loadtxt(datefile).astype(int)
year = np.floor(dates/1e4).astype(int)
month = np.floor((dates-year*1e4)/1e2).astype(int)
day = np.floor(dates-year*1e4-month*1e2).astype(int)
# Compute utm
self.lon = lonlat[:,0]
self.lat = lonlat[:,1]
self.x, self.y = self.ll2xy(self.lon, self.lat)
# Get the time
self.time = [dt.datetime(y, m, d) for y,m,d in zip(year, month, day)]
# Create a list to hold the dates
self.timeseries = []
# Iterate over the dates
for date,phi in zip(self.time, ts_file['ph_disp'].T):
# Create an insar object
sar = insar('{} {}'.format(self.name,date.isoformat()), utmzone=self.utmzone,
verbose=False, lon0=self.lon0, lat0=self.lat0, ellps=self.ellps)
# Put thing in the insarrate object
sar.vel = phi
sar.lon = self.lon
sar.lat = self.lat
sar.x = self.x
sar.y = self.y
# Things should remain None
sar.corner = None
sar.err = None
# Set factor
sar.factor = 1.0
# Take care of the LOS
if incidence is not None and heading is not None:
sar.inchd2los(incidence, heading, origin=inctype)
else:
sar.los = np.zeros((sar.vel.shape[0], 3))
# Store the object in the list
self.timeseries.append(sar)
# Keep incidence and heading
self.incidence = incidence
self.heading = heading
self.inctype = inctype
# all done
return
def removeDate(self, date):
'''
Remove one date from the time series.
Args:
* date : tuple of (year, month, day) or (year, month, day ,hour, min,s)
Returns:
* None
'''
# Make date
if type(date) in (tuple, list):
if len(date)==3:
date = dt.datetime(date[0], date[1], date[2])
elif len(date)==6:
date = dt.datetime(date[0], date[1], date[2], date[3], date[4], date[5])
elif len(date)==1:
print('Unknow date format...')
sys.exit(1)
assert (type(date) is type(self.time[0])), 'Provided date can be \n \
tuple of (year, month, day), \n \
tuple of (year, month, day ,hour, min,s), \n \
datetime.datetime object'
# Find the date
try:
i = self.time.index(date)
except:
print('Nothing to do')
# Remove it
del self.timeseries[i]
del self.time[i]
# All done
return
def removeDates(self, dates):
'''
Remove a list of dates from the time series.
Args:
* dates : List of dates to be removed. Each date can be a tuple (year, month, day) or (year, month, day, hour, min, sd).
Returns:
* None
'''
# Iterate
for date in dates:
self.removeDate(date)
# All done
return
def dates2time(self, start=0):
'''
Computes a time vector in years, starting from the date #start.
Kwargs:
* start : Index of the starting date.
Returns:
* time, an array of floats
'''
# Create a list
Time = []
# Iterate over the dates
for date in self.time:
Time.append(date.toordinal())
# Convert to years
Time = np.array(Time)/365.25
# Reference
Time -= Time[start]
# All done
return Time
def extractAroundGPS(self, gps, distance, doprojection=True, reference=False, verbose=False):
'''
Returns a gps object with values projected along the LOS around the
gps stations included in gps. In addition, it projects the gps displacements
along the LOS
Args:
* gps : gps object
* distance : distance to consider around the stations
Kwargs:
* doprojection : Projects the gps enu disp into the los as well
* reference : if True, removes to the InSAR the average gps displacemnt in the LOS for the points overlapping in time.
* verbose : Talk to me
Returns:
* None
'''
# Print
if verbose:
print('---------------------------------')
print('---------------------------------')
print('Projecting GPS into InSAR LOS')
# Create a gps object
out = copy.deepcopy(gps)
# Initialize time series
out.initializeTimeSeries(time=self.time, los=True, verbose=False)
if not hasattr(gps, 'time'):
gps.initializeTimeSeries(time=self.time, los=True, verbose=False)
# Check
assert gps.time==out.time, 'Time vectors are different between gps object \
and output object'
# Line-of-sight
los = {}
# Iterate over time
for idate,insar in enumerate(self.timeseries):
if verbose:
sys.stdout.write('\r Date: {}'.format(self.time[idate].isoformat()))
# Extract the values at this date
tmp = insar.extractAroundGPS(gps, distance, doprojection=False)
# Iterate over the station names to store correctly
for istation, station in enumerate(out.station):
assert tmp.station[istation]==station, 'Wrong station name'
vel, err = tmp.vel_los[istation], tmp.err_los[istation]
los[station] = tmp.los[istation]
out.timeseries[station].los.value[idate] = vel
out.timeseries[station].los.error[idate] = err
# Print
if verbose:
print(' All Done')
# project
if reference or doprojection:
for station in gps.station:
if los[station] is not None:
gps.timeseries[station].project2InSAR(los[station])
else:
gps.timeseries[station].los = None
# Reference
if reference:
for station in gps.station:
# Get the insar projected time series
insar = out.timeseries[station].los
gpspr = gps.timeseries[station].los
if insar is not None and gpspr is not None:
# Find the common dates
diff = []
for itime, time in enumerate(insar.time):
u = np.flatnonzero(gpspr.time==time)
if len(u)>0:
diff.append(insar.value[itime]-gpspr.value[u[0]])
# Average and correct
if len(diff)>0:
average = np.nanmean(diff)
if not np.isnan(average):
insar.value -= average
# Save the los vectors
out.losvectors = los
# All done
return out
def reference2timeseries(self, gpstimeseries, distance=4.0, verbose=True, parameters=1,
daysaround=2, propagate='mean'):
'''
References the InSAR time series to the GPS time series.
We estimate a linear function of range and azimuth on the difference
between InSAR and GPS at each insar epoch.
We solve for the a, b, c terms in the equation:
.. math:
d_{\\text{sar}} = d_{\\text{gps}} + a + b \\text{range} + c \\text{azimuth} + d\\text{azimuth}\\text{range}
Args:
* gpstimeseries : A gpstimeseries instance.
Kwargs:
* daysaround : How many days around the date do we consider
* distance : Diameter of the circle surrounding a gps station to gather InSAR points
* verbose : Talk to me
* parameters : 1, 3 or 4
* propagate : 'mean' if no gps data available