-
Notifications
You must be signed in to change notification settings - Fork 32
/
timefnutils.py
464 lines (364 loc) · 12.4 KB
/
timefnutils.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
'''Time utilities for time-series InSAR analysis.
.. author:
Piyush Agram <[email protected]>
.. Dependencies:
numpy, datetime, scipy.factorial, logmgr'''
import numpy as np
import datetime as dt
import sys
try:
from scipy import factorial
except ImportError:
from scipy.special import factorial
from numpy import arange as xrange
###########################Time-series utils##############################
def nCk(n,k):
'''Combinatorial function.'''
c = factorial(n)/(factorial(n-k)*factorial(k)*1.0)
return c
def bspline_nu(n,tk,t):
'''Non uniform b-splines.
n - spline order
tk - knots
t - time vector'''
B = np.zeros((len(tk),len(t)))
assert (n+1) < len(tk), 'Not enough knots for order {} bspline'.format(n)
for m in xrange(len(tk)-1):
ind = where((t>=tk[m]) & (t<tk[m+1]))
B[m,ind] = 1.0
for p in xrange(n):
for q in xrange(len(tk)-2-p):
B[q,:] = ((t-tk[q])/(tk[p+q+1]-tk[q]))*B[q,:] + ((tk[p+q+2]-t)/(tk[p+q+2]-tk[q+1]))*B[q+1,:]
ihalf = np.int_((n+1)/2)
B = B[ihalf:len(tk)-ihalf,:]
return B
def bspline(n,dtk,t):
'''Uniform b-splines.
n - Order
dtk - Spacing
t - Time vector'''
x = (t/dtk) + n +1
b = np.zeros(len(x))
for k in range(n+2):
m = x-k-(n+1)/2
up = np.power(m,n)
b = b+((-1)**k)*nCk(n+1,k)*up*(m>=0)
b = b/(1.0*factorial(n))
return b
def ispline(n,dtk,t):
'''Uniform integrated b-splines
n - Order
dtk - Spacing
t - Time vector'''
x = (t/dtk)+n+1
b = np.zeros(len(x))
for k in range(n+2):
m = x-k-(n+1)/2
up = m**(n+1)
b += ((-1)**k)*nCk(n+1,k)*up*(m>=0)
b = b*dtk/((n+1.0)*factorial(n))
return b
def Timefn(rep,t):
'''Interprets a list as time-series representation and returns time function matrix.
Args:
* rep - Representation of the functions (cnt).
* t - Time vector.
Returns:
* H - a time-series matrix of size (Nsar x cnt)
* vname - Unique name for each of the model parameters
* rflag - Regularization family number for each model parameter'''
Nsar = len(t)
Nrep = len(rep)
cnt = 0 #Number of model parameters
H = [] #Greens functions
rflag = [] #Regularization flag
vname = [] #Parameter name
regstart = 1 #Set of params that need to be regularized together
for k in xrange(Nrep):
fn = rep[k]
fname = fn[0].upper()
if fname in ('LINEAR'): #f = (t-t1)
num = len(fn) - 1
assert num==1, 'Undefined LINEAR sequence.'
ts = fn[1]
for m in xrange(len(ts)):
hfn = (t-ts[m])
vn = 'LINE/{:2.3f}'.format(ts[m])
rf = 0.0
H.append(hfn)
vname.append(vn)
rflag.append(rf)
elif fname in ('LINEAR_FINITE'):
num = len(fn) - 1
assert num==1, 'Undefined LINEAR_FINITE sequence.'
for trange in fn[1]:
hfn = (t - trange[0]) * ((t >= trange[0]) & (t <= trange[1]))
vn = 'LINEFIN/{:2.3f}/{:2.3f}'.format(trange[0], trange[1])
rf = 0.0
H.append(hfn)
vname.append(vn)
rflag.append(rf)
elif fname in ('POLY'):
num = len(fn) - 1
assert num==2, 'Undefined POLY sequence.'
order = fn[1]
ts = fn[2]
assert len(order) == len(ts), 'POLY: Orders and times dont match'
for p in xrange(len(order)):
g = (t-ts[p])
for m in xrange(order[p]+1):
hfn = g**m
vn = 'P/{d}/{:2.1f}'.format(m,ts[p])
rf = 0.0
H.append(hfn)
vname.append(vn)
rflag.append(rf)
elif fname in ('QUADRATIC'):
num = len(fn) - 1
assert num==1, 'Undefined QUADRATIC sequence'
ts = fn[1]
for m in xrange(len(ts)):
hfn = (t-ts[m])**2
vn = 'QUAD/{:2.3f}'.format(ts[m])
rf = 0.0
H.append(hfn)
vname.append(vn)
rflag.append(rf)
elif fname in ('OFFSET'): # constant offset
num = len(fn) - 1
if (num != 1):
print('Undefined sequence: {}'.format(fn))
print('Eg: [[\'OFFSET\'],[t_dummy]]')
sys.exit(1)
ts = fn[1]
H.append(np.ones(t.shape, dtype=float))
vname.append('OFFSET')
rflag.append(0.0)
elif fname in ('EXP'): #f = (1-exp(-(t-t1)/tau1))*u(t-t1)
num = len(fn) - 1
assert num == 2, 'Undefined EXP sequence.'
ts = fn[1]
taus = fn[2]
assert len(ts) == len(taus), 'EXP: Times and Taus dont match'
for m in xrange(len(ts)):
hfn = (1 - np.exp(-(t-ts[m])/taus[m]))*(t>=ts[m])
vn = 'EXP/{:2.3f}/{:2.3f}'.format(ts[m],taus[m])
rf = 0.0
H.append(hfn)
vname.append(vn)
rflag.append(rf)
elif fname in ('LOG'): #f = log(1+(t-t1)/tau1)*u(t-t1)
num = len(fn) - 1
assert num == 2, 'Undefined LOG sequence.'
ts = fn[1]
taus = fn[2]
assert len(ts) == len(taus), 'LOG: Times and Taus dont match'
for m in xrange(len(ts)):
hfn = np.log(1.0+ ((t-ts[m])/taus[m])*(t>=ts[m]))
vn = 'LOG/{:2.3f}/{:2.3f}'.format(ts[m],taus[m])
rf = 0.0
H.append(hfn)
vname.append(vn)
rflag.append(rf)
elif fname in ('STEP'): #f = u(t-t1)
num = len(fn) - 1
assert num==1, 'Undefined STEP sequence.'
ts = fn[1]
for m in xrange(len(ts)):
hfn = 1.0*(t>=ts[m])
vn = 'STEP/{:2.3f}'.format(ts[m])
rf = 0.0
H.append(hfn)
vname.append(vn)
rflag.append(rf)
elif fname in ('SEASONAL'): # f = cos(t/tau1) , sin(t/tau1)
num = len(fn) - 1
assert num == 1, 'Undefined SEASONAL sequence.'
taus = fn[1]
for m in xrange(len(taus)):
#hfn = 1-np.cos(2*np.pi*t/taus[m])
hfn = np.cos(2*np.pi*t/taus[m])
vn = 'COS/{:2.3f}'.format(taus[m])
rf = 0.0
H.append(hfn)
vname.append(vn)
rflag.append(rf)
hfn = np.sin(2*np.pi*t/taus[m])
vn = 'SIN/{:2.3f}'.format(taus[m])
rf = 0.0
H.append(hfn)
vname.append(vn)
rflag.append(rf)
elif fname in ('BSPLINE','BSPLINES'): #Currently only uniform splines.
num = len(fn) - 1
assert num == 2, 'Undefined BSPLINE sequence.'
orders = fn[1]
nums = fn[2]
assert len(orders) == len(nums), 'BSPLINE: Orders and Numbers dont match. '
for m in xrange(len(orders)):
ts = np.linspace(t.min(),t.max(),nums[m])
dtk = ts[2] - ts[1]
for p in xrange(len(ts)):
hfn = bspline(orders[m],dtk,t-ts[p])
vn = 'Bsp/{}/{}'.format(p,orders[m])
rf = regstart
H.append(hfn)
vname.append(vn)
rflag.append(rf)
regstart = regstart+1
elif fname in ('ISPLINE','ISPLINES'): #Currently only uniform splines.
num = len(fn) - 1
assert num==2, ' Undefined ISPLINE sequence.'
orders = fn[1]
nums = fn[2]
assert len(orders) == len(nums), 'Orders and Numbers dont match.'
for m in xrange(len(orders)):
ts = np.linspace(t.min(),t.max(),nums[m])
dtk = ts[2] - ts[1]
for p in xrange(len(ts)):
hfn = ispline(orders[m],dtk,t-ts[p])
vn = 'Isp/{}/{}'.format(p,orders[m])
rf = regstart
H.append(hfn)
vname.append(vn)
rflag.append(rf)
regstart = regstart+1
elif fname in ('SBAS'): #[[['SBAS'],[ind]]]
num = len(fn)-1
assert num == 1, 'Undefined SBAS sequence.'
master = fn[1]
num = len(t)
for m in xrange(num):
hfn = np.zeros(num)
if m < master:
hfn[m:master] = -1
elif m > master:
hfn[master+1:m+1] = 1
rf = 0.0
vn = 'SBAS/{}/{}'.format(m,master)
H.append(hfn)
vname.append(vn)
rflag.append(rf)
H = np.array(H)
H = H.transpose() #####For traditional column-wise representation.
vname = np.array(vname)
rflag = np.array(rflag)
return H,vname,rflag
def mName2Rep(mName):
''' From mName given by TimeFn, returns the equivalent function representation
Args:
* mName -> list of the model names
Returns:
* rep -> list of parametric functions'''
rep = []
m = 0
while m<len(mName):
# Get the model name
model = mName[m].split('/')
if model[0] in ('LINE'): # Case Linear
r = ['LINEAR',[float(model[1])]]
rep.append(r)
elif model[0] in ('LINEFIN'):
r = ['LINEAR_FINITE',[[float(model[1]),float(model[2])]]]
rep.append(r)
elif model[0] in ('P'): # Case Polynom
# Check how many orders in the poly function
tm = 1
polyflag = True
while polyflag:
if m+tm==len(mName):
polyflag = False
else:
tmodel = mName[m+tm].split('/')
if tmodel[0] in ('P') and tmodel[1] not in ('0'):
polyflag = True
tm+=1
else:
polyflag = False
tm = tm - 1
r = ['POLY',[tm],[float(model[2])]]
rep.append(r)
m = m + tm
elif model[0] in ('QUAD'): # Case Quadratic
r = ['QUADRATIC',[float(model[1])]]
rep.append(r)
elif model[0] in ('OFFSET'): # Case Offset
r = ['OFFSET',[0]]
rep.append(r)
elif model[0] in ('EXP'): # Case exponential
t1 = float(model[1])
tau = float(model[2])
r = ['EXP',[t1],[tau]]
rep.append(r)
elif model[0] in ('LOG'): # Case Logarithm
t1 = float(model[1])
tau = float(model[2])
r = ['LOG',[t1],[tau]]
rep.append(r)
elif model[0] in ('STEP'): # Case step function
t1 = float(model[1])
r = ['STEP',[t1]]
rep.append(r)
elif model[0] in ('COS'): # Case seasonal
tau = float(model[1])
r = ['SEASONAL',[tau]]
rep.append(r)
m+=1
elif model[0] in ('Bsp'): # Case Bspline
# Check how many B-Splines is there
tm = 1
bspflag = True
while bspflag:
if m+tm==len(mName):
bspflag = False
else:
tmodel = mName[m+tm].split('/')
if tmodel[0] in ('Bsp') and tmodel[1] not in ('0'):
bspflag = True
tm+=1
else:
bspflag = False
order = int(model[2])
r = ['BSPLINE',[order],[tm]]
rep.append(r)
m = m + tm - 1
elif model[0] in ('Isp'): # Case ISpline
# Check How many I-splines is there
tm = 1
ispflag = True
while ispflag:
if m+tm==len(mName):
ispflag = False
else:
tmodel = mName[m+tm].split('/')
if tmodel[0] in ('Isp') and tmodel[1] not in ('0'):
ispflag = True
tm += 1
else:
ispflag = False
order = int(model[2])
r = ['ISPLINE',[order],[tm]]
rep.append(r)
m = m + tm - 1
elif model[0] in ('SBAS'):
# Check how many SBAS pieces is there
tm = 1
sbasflag = True
while sbasflag:
if m+tm==len(mName):
sbasflag=False
else:
tmodel = mName[m+tm].split('/')
if tmodel[0] in ('SBAS') and tmodel[1] not in ('0'):
sbasflag = True
tm += 1
else:
sbasflag = False
master = int(model[2])
r = ['SBAS',master]
rep.append(r)
m = m + tm - 1
# Increase the pointer
m+=1
return rep
#######################Time-series utils##################################################