forked from econ-ark/HARK
-
Notifications
You must be signed in to change notification settings - Fork 1
/
HARKinterpolation.py
3515 lines (3191 loc) · 151 KB
/
HARKinterpolation.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
'''
Custom interpolation methods for representing approximations to functions.
It also includes wrapper classes to enforce standard methods across classes.
Each interpolation class must have a distance() method that compares itself to
another instance; this is used in HARKcore's solve() method to check for solution
convergence. The interpolator classes currently in this module inherit their
distance method from HARKobject.
'''
import warnings
import numpy as np
from scipy.interpolate import UnivariateSpline
from HARKcore import HARKobject
from copy import deepcopy
def _isscalar(x):
'''
Check whether x is if a scalar type, or 0-dim.
Parameters
----------
x : anything
An input to be checked for scalar-ness.
Returns
-------
is_scalar : boolean
True if the input is a scalar, False otherwise.
'''
return np.isscalar(x) or hasattr(x, 'shape') and x.shape == ()
class HARKinterpolator1D(HARKobject):
'''
A wrapper class for 1D interpolation methods in HARK.
'''
distance_criteria = []
def __call__(self,x):
'''
Evaluates the interpolated function at the given input.
Parameters
----------
x : np.array or float
Real values to be evaluated in the interpolated function.
Returns
-------
y : np.array or float
The interpolated function evaluated at x: y = f(x), with the same
shape as x.
'''
z = np.asarray(x)
return (self._evaluate(z.flatten())).reshape(z.shape)
def derivative(self,x):
'''
Evaluates the derivative of the interpolated function at the given input.
Parameters
----------
x : np.array or float
Real values to be evaluated in the interpolated function.
Returns
-------
dydx : np.array or float
The interpolated function's first derivative evaluated at x:
dydx = f'(x), with the same shape as x.
'''
z = np.asarray(x)
return (self._der(z.flatten())).reshape(z.shape)
def eval_with_derivative(self,x):
'''
Evaluates the interpolated function and its derivative at the given input.
Parameters
----------
x : np.array or float
Real values to be evaluated in the interpolated function.
Returns
-------
y : np.array or float
The interpolated function evaluated at x: y = f(x), with the same
shape as x.
dydx : np.array or float
The interpolated function's first derivative evaluated at x:
dydx = f'(x), with the same shape as x.
'''
z = np.asarray(x)
y, dydx = self._evalAndDer(z.flatten())
return y.reshape(z.shape), dydx.reshape(z.shape)
def _evaluate(self,x):
'''
Interpolated function evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _der(self,x):
'''
Interpolated function derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _evalAndDer(self,x):
'''
Interpolated function and derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
class HARKinterpolator2D(HARKobject):
'''
A wrapper class for 2D interpolation methods in HARK.
'''
distance_criteria = []
def __call__(self,x,y):
'''
Evaluates the interpolated function at the given input.
Parameters
----------
x : np.array or float
Real values to be evaluated in the interpolated function.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
Returns
-------
fxy : np.array or float
The interpolated function evaluated at x,y: fxy = f(x,y), with the
same shape as x and y.
'''
xa = np.asarray(x)
ya = np.asarray(y)
return (self._evaluate(xa.flatten(),ya.flatten())).reshape(xa.shape)
def derivativeX(self,x,y):
'''
Evaluates the partial derivative of interpolated function with respect
to x (the first argument) at the given input.
Parameters
----------
x : np.array or float
Real values to be evaluated in the interpolated function.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
Returns
-------
dfdx : np.array or float
The derivative of the interpolated function with respect to x, eval-
uated at x,y: dfdx = f_x(x,y), with the same shape as x and y.
'''
xa = np.asarray(x)
ya = np.asarray(y)
return (self._derX(xa.flatten(),ya.flatten())).reshape(xa.shape)
def derivativeY(self,x,y):
'''
Evaluates the partial derivative of interpolated function with respect
to y (the second argument) at the given input.
Parameters
----------
x : np.array or float
Real values to be evaluated in the interpolated function.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
Returns
-------
dfdy : np.array or float
The derivative of the interpolated function with respect to y, eval-
uated at x,y: dfdx = f_y(x,y), with the same shape as x and y.
'''
xa = np.asarray(x)
ya = np.asarray(y)
return (self._derY(xa.flatten(),ya.flatten())).reshape(xa.shape)
def _evaluate(self,x,y):
'''
Interpolated function evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _derX(self,x,y):
'''
Interpolated function x-derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _derY(self,x,y):
'''
Interpolated function y-derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
class HARKinterpolator3D(HARKobject):
'''
A wrapper class for 3D interpolation methods in HARK.
'''
distance_criteria = []
def __call__(self,x,y,z):
'''
Evaluates the interpolated function at the given input.
Parameters
----------
x : np.array or float
Real values to be evaluated in the interpolated function.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
z : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
Returns
-------
fxyz : np.array or float
The interpolated function evaluated at x,y,z: fxyz = f(x,y,z), with
the same shape as x, y, and z.
'''
xa = np.asarray(x)
ya = np.asarray(y)
za = np.asarray(z)
return (self._evaluate(xa.flatten(),ya.flatten(),za.flatten())).reshape(xa.shape)
def derivativeX(self,x,y,z):
'''
Evaluates the partial derivative of the interpolated function with respect
to x (the first argument) at the given input.
Parameters
----------
x : np.array or float
Real values to be evaluated in the interpolated function.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
z : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
Returns
-------
dfdx : np.array or float
The derivative with respect to x of the interpolated function evaluated
at x,y,z: dfdx = f_x(x,y,z), with the same shape as x, y, and z.
'''
xa = np.asarray(x)
ya = np.asarray(y)
za = np.asarray(z)
return (self._derX(xa.flatten(),ya.flatten(),za.flatten())).reshape(xa.shape)
def derivativeY(self,x,y,z):
'''
Evaluates the partial derivative of the interpolated function with respect
to y (the second argument) at the given input.
Parameters
----------
x : np.array or float
Real values to be evaluated in the interpolated function.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
z : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
Returns
-------
dfdy : np.array or float
The derivative with respect to y of the interpolated function evaluated
at x,y,z: dfdy = f_y(x,y,z), with the same shape as x, y, and z.
'''
xa = np.asarray(x)
ya = np.asarray(y)
za = np.asarray(z)
return (self._derY(xa.flatten(),ya.flatten(),za.flatten())).reshape(xa.shape)
def derivativeZ(self,x,y,z):
'''
Evaluates the partial derivative of the interpolated function with respect
to z (the third argument) at the given input.
Parameters
----------
x : np.array or float
Real values to be evaluated in the interpolated function.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
z : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as x.
Returns
-------
dfdz : np.array or float
The derivative with respect to z of the interpolated function evaluated
at x,y,z: dfdz = f_z(x,y,z), with the same shape as x, y, and z.
'''
xa = np.asarray(x)
ya = np.asarray(y)
za = np.asarray(z)
return (self._derZ(xa.flatten(),ya.flatten(),za.flatten())).reshape(xa.shape)
def _evaluate(self,x,y,z):
'''
Interpolated function evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _derX(self,x,y,z):
'''
Interpolated function x-derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _derY(self,x,y,z):
'''
Interpolated function y-derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _derZ(self,x,y,z):
'''
Interpolated function y-derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
class HARKinterpolator4D(HARKobject):
'''
A wrapper class for 4D interpolation methods in HARK.
'''
distance_criteria = []
def __call__(self,w,x,y,z):
'''
Evaluates the interpolated function at the given input.
Parameters
----------
w : np.array or float
Real values to be evaluated in the interpolated function.
x : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
z : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
Returns
-------
fwxyz : np.array or float
The interpolated function evaluated at w,x,y,z: fwxyz = f(w,x,y,z),
with the same shape as w, x, y, and z.
'''
wa = np.asarray(w)
xa = np.asarray(x)
ya = np.asarray(y)
za = np.asarray(z)
return (self._evaluate(wa.flatten(),xa.flatten(),ya.flatten(),za.flatten())).reshape(wa.shape)
def derivativeW(self,w,x,y,z):
'''
Evaluates the partial derivative with respect to w (the first argument)
of the interpolated function at the given input.
Parameters
----------
w : np.array or float
Real values to be evaluated in the interpolated function.
x : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
z : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
Returns
-------
dfdw : np.array or float
The derivative with respect to w of the interpolated function eval-
uated at w,x,y,z: dfdw = f_w(w,x,y,z), with the same shape as inputs.
'''
wa = np.asarray(w)
xa = np.asarray(x)
ya = np.asarray(y)
za = np.asarray(z)
return (self._derW(wa.flatten(),xa.flatten(),ya.flatten(),za.flatten())).reshape(wa.shape)
def derivativeX(self,w,x,y,z):
'''
Evaluates the partial derivative with respect to x (the second argument)
of the interpolated function at the given input.
Parameters
----------
w : np.array or float
Real values to be evaluated in the interpolated function.
x : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
z : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
Returns
-------
dfdx : np.array or float
The derivative with respect to x of the interpolated function eval-
uated at w,x,y,z: dfdx = f_x(w,x,y,z), with the same shape as inputs.
'''
wa = np.asarray(w)
xa = np.asarray(x)
ya = np.asarray(y)
za = np.asarray(z)
return (self._derX(wa.flatten(),xa.flatten(),ya.flatten(),za.flatten())).reshape(wa.shape)
def derivativeY(self,w,x,y,z):
'''
Evaluates the partial derivative with respect to y (the third argument)
of the interpolated function at the given input.
Parameters
----------
w : np.array or float
Real values to be evaluated in the interpolated function.
x : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
z : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
Returns
-------
dfdy : np.array or float
The derivative with respect to y of the interpolated function eval-
uated at w,x,y,z: dfdy = f_y(w,x,y,z), with the same shape as inputs.
'''
wa = np.asarray(w)
xa = np.asarray(x)
ya = np.asarray(y)
za = np.asarray(z)
return (self._derY(wa.flatten(),xa.flatten(),ya.flatten(),za.flatten())).reshape(wa.shape)
def derivativeZ(self,w,x,y,z):
'''
Evaluates the partial derivative with respect to z (the fourth argument)
of the interpolated function at the given input.
Parameters
----------
w : np.array or float
Real values to be evaluated in the interpolated function.
x : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
y : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
z : np.array or float
Real values to be evaluated in the interpolated function; must be
the same size as w.
Returns
-------
dfdz : np.array or float
The derivative with respect to z of the interpolated function eval-
uated at w,x,y,z: dfdz = f_z(w,x,y,z), with the same shape as inputs.
'''
wa = np.asarray(w)
xa = np.asarray(x)
ya = np.asarray(y)
za = np.asarray(z)
return (self._derZ(wa.flatten(),xa.flatten(),ya.flatten(),za.flatten())).reshape(wa.shape)
def _evaluate(self,w,x,y,z):
'''
Interpolated function evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _derW(self,w,x,y,z):
'''
Interpolated function w-derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _derX(self,w,x,y,z):
'''
Interpolated function w-derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _derY(self,w,x,y,z):
'''
Interpolated function w-derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
def _derZ(self,w,x,y,z):
'''
Interpolated function w-derivative evaluator, to be defined in subclasses.
'''
raise NotImplementedError()
class ConstantFunction(HARKobject):
'''
A class for representing trivial functions that return the same real output for any input. This
is convenient for models where an object might be a (non-trivial) function, but in some variations
that object is just a constant number. Rather than needing to make a (Bi/Tri/Quad)-
LinearInterpolation with trivial state grids and the same f_value in every entry, ConstantFunction
allows the user to quickly make a constant/trivial function. This comes up, e.g., in models
with endogenous pricing of insurance contracts; a contract's premium might depend on some state
variables of the individual, but in some variations the premium of a contract is just a number.
'''
convergence_criteria = ['value']
def __init__(self,value):
'''
Make a new ConstantFunction object.
Parameters
----------
value : float
The constant value that the function returns.
Returns
-------
None
'''
self.value = float(value)
def __call__(self,*args):
'''
Evaluate the constant function. The first input must exist and should be an array.
Returns an array of identical shape to args[0] (if it exists).
'''
if len(args) > 0: # If there is at least one argument, return appropriately sized array
if _isscalar(args[0]):
return self.value
else:
shape = args[0].shape
return self.value*np.ones(shape)
else: # Otherwise, return a single instance of the constant value
return self.value
def derivative(self,*args):
'''
Evaluate the derivative of the function. The first input must exist and should be an array.
Returns an array of identical shape to args[0] (if it exists). This is an array of zeros.
'''
if len(args) > 0:
if _isscalar(args[0]):
return 0.0
else:
shape = args[0].shape
return np.zeros(shape)
else:
return 0.0
# All other derivatives are also zero everywhere, so these methods just point to derivative
derivativeX = derivative
derivativeY = derivative
derivativeZ = derivative
derivativeW = derivative
derivativeXX= derivative
class CubicInterp(HARKinterpolator1D):
'''
An interpolating function using piecewise cubic splines. Matches level and
slope of 1D function at gridpoints, smoothly interpolating in between.
Extrapolation above highest gridpoint approaches a limiting linear function
if desired (linear extrapolation also enabled.)
'''
distance_criteria = ['x_list','y_list','dydx_list']
def __init__(self,x_list,y_list,dydx_list,intercept_limit=None,slope_limit=None,lower_extrap=False):
'''
The interpolation constructor to make a new cubic spline interpolation.
Parameters
----------
x_list : np.array
List of x values composing the grid.
y_list : np.array
List of y values, representing f(x) at the points in x_list.
dydx_list : np.array
List of dydx values, representing f'(x) at the points in x_list
intercept_limit : float
Intercept of limiting linear function.
slope_limit : float
Slope of limiting linear function.
lower_extrap : boolean
Indicator for whether lower extrapolation is allowed. False means
f(x) = NaN for x < min(x_list); True means linear extrapolation.
Returns
-------
new instance of CubicInterp
NOTE: When no input is given for the limiting linear function, linear
extrapolation is used above the highest gridpoint.
'''
self.x_list = np.asarray(x_list)
self.y_list = np.asarray(y_list)
self.dydx_list = np.asarray(dydx_list)
self.n = len(x_list)
# Define lower extrapolation as linear function (or just NaN)
if lower_extrap:
self.coeffs = [[y_list[0],dydx_list[0],0,0]]
else:
self.coeffs = [[np.nan,np.nan,np.nan,np.nan]]
# Calculate interpolation coefficients on segments mapped to [0,1]
for i in xrange(self.n-1):
x0 = x_list[i]
y0 = y_list[i]
x1 = x_list[i+1]
y1 = y_list[i+1]
Span = x1 - x0
dydx0 = dydx_list[i]*Span
dydx1 = dydx_list[i+1]*Span
temp = [y0, dydx0, 3*(y1 - y0) - 2*dydx0 - dydx1, 2*(y0 - y1) + dydx0 + dydx1];
self.coeffs.append(temp)
# Calculate extrapolation coefficients as a decay toward limiting function y = mx+b
if slope_limit is None and intercept_limit is None:
slope_limit = dydx_list[-1]
intercept_limit = y_list[-1] - slope_limit*x_list[-1]
gap = slope_limit*x1 + intercept_limit - y1
slope = slope_limit - dydx_list[self.n-1]
if (gap != 0) and (slope <= 0):
temp = [intercept_limit, slope_limit, gap, slope/gap]
elif slope > 0:
temp = [intercept_limit, slope_limit, 0, 0] # fixing a problem when slope is positive
else:
temp = [intercept_limit, slope_limit, gap, 0]
self.coeffs.append(temp)
self.coeffs = np.array(self.coeffs)
def _evaluate(self,x):
'''
Returns the level of the interpolated function at each value in x. Only
called internally by HARKinterpolator1D.__call__ (etc).
'''
if _isscalar(x):
pos = np.searchsorted(self.x_list,x)
if pos == 0:
y = self.coeffs[0,0] + self.coeffs[0,1]*(x - self.x_list[0])
elif (pos < self.n):
alpha = (x - self.x_list[pos-1])/(self.x_list[pos] - self.x_list[pos-1])
y = self.coeffs[pos,0] + alpha*(self.coeffs[pos,1] + alpha*(self.coeffs[pos,2] + alpha*self.coeffs[pos,3]))
else:
alpha = x - self.x_list[self.n-1]
y = self.coeffs[pos,0] + x*self.coeffs[pos,1] - self.coeffs[pos,2]*np.exp(alpha*self.coeffs[pos,3])
else:
m = len(x)
pos = np.searchsorted(self.x_list,x)
y = np.zeros(m)
if y.size > 0:
out_bot = pos == 0
out_top = pos == self.n
in_bnds = np.logical_not(np.logical_or(out_bot, out_top))
# Do the "in bounds" evaluation points
i = pos[in_bnds]
coeffs_in = self.coeffs[i,:]
alpha = (x[in_bnds] - self.x_list[i-1])/(self.x_list[i] - self.x_list[i-1])
y[in_bnds] = coeffs_in[:,0] + alpha*(coeffs_in[:,1] + alpha*(coeffs_in[:,2] + alpha*coeffs_in[:,3]))
# Do the "out of bounds" evaluation points
y[out_bot] = self.coeffs[0,0] + self.coeffs[0,1]*(x[out_bot] - self.x_list[0])
alpha = x[out_top] - self.x_list[self.n-1]
y[out_top] = self.coeffs[self.n,0] + x[out_top]*self.coeffs[self.n,1] - self.coeffs[self.n,2]*np.exp(alpha*self.coeffs[self.n,3])
return y
def _der(self,x):
'''
Returns the first derivative of the interpolated function at each value
in x. Only called internally by HARKinterpolator1D.derivative (etc).
'''
if _isscalar(x):
pos = np.searchsorted(self.x_list,x)
if pos == 0:
dydx = self.coeffs[0,1]
elif (pos < self.n):
alpha = (x - self.x_list[pos-1])/(self.x_list[pos] - self.x_list[pos-1])
dydx = (self.coeffs[pos,1] + alpha*(2*self.coeffs[pos,2] + alpha*3*self.coeffs[pos,3]))/(self.x_list[pos] - self.x_list[pos-1])
else:
alpha = x - self.x_list[self.n-1]
dydx = self.coeffs[pos,1] - self.coeffs[pos,2]*self.coeffs[pos,3]*np.exp(alpha*self.coeffs[pos,3])
else:
m = len(x)
pos = np.searchsorted(self.x_list,x)
dydx = np.zeros(m)
if dydx.size > 0:
out_bot = pos == 0
out_top = pos == self.n
in_bnds = np.logical_not(np.logical_or(out_bot, out_top))
# Do the "in bounds" evaluation points
i = pos[in_bnds]
coeffs_in = self.coeffs[i,:]
alpha = (x[in_bnds] - self.x_list[i-1])/(self.x_list[i] - self.x_list[i-1])
dydx[in_bnds] = (coeffs_in[:,1] + alpha*(2*coeffs_in[:,2] + alpha*3*coeffs_in[:,3]))/(self.x_list[i] - self.x_list[i-1])
# Do the "out of bounds" evaluation points
dydx[out_bot] = self.coeffs[0,1]
alpha = x[out_top] - self.x_list[self.n-1]
dydx[out_top] = self.coeffs[self.n,1] - self.coeffs[self.n,2]*self.coeffs[self.n,3]*np.exp(alpha*self.coeffs[self.n,3])
return dydx
def _evalAndDer(self,x):
'''
Returns the level and first derivative of the function at each value in
x. Only called internally by HARKinterpolator1D.eval_and_der (etc).
'''
if _isscalar(x):
pos = np.searchsorted(self.x_list,x)
if pos == 0:
y = self.coeffs[0,0] + self.coeffs[0,1]*(x - self.x_list[0])
dydx = self.coeffs[0,1]
elif (pos < self.n):
alpha = (x - self.x_list[pos-1])/(self.x_list[pos] - self.x_list[pos-1])
y = self.coeffs[pos,0] + alpha*(self.coeffs[pos,1] + alpha*(self.coeffs[pos,2] + alpha*self.coeffs[pos,3]))
dydx = (self.coeffs[pos,1] + alpha*(2*self.coeffs[pos,2] + alpha*3*self.coeffs[pos,3]))/(self.x_list[pos] - self.x_list[pos-1])
else:
alpha = x - self.x_list[self.n-1]
y = self.coeffs[pos,0] + x*self.coeffs[pos,1] - self.coeffs[pos,2]*np.exp(alpha*self.coeffs[pos,3])
dydx = self.coeffs[pos,1] - self.coeffs[pos,2]*self.coeffs[pos,3]*np.exp(alpha*self.coeffs[pos,3])
else:
m = len(x)
pos = np.searchsorted(self.x_list,x)
y = np.zeros(m)
dydx = np.zeros(m)
if y.size > 0:
out_bot = pos == 0
out_top = pos == self.n
in_bnds = np.logical_not(np.logical_or(out_bot, out_top))
# Do the "in bounds" evaluation points
i = pos[in_bnds]
coeffs_in = self.coeffs[i,:]
alpha = (x[in_bnds] - self.x_list[i-1])/(self.x_list[i] - self.x_list[i-1])
y[in_bnds] = coeffs_in[:,0] + alpha*(coeffs_in[:,1] + alpha*(coeffs_in[:,2] + alpha*coeffs_in[:,3]))
dydx[in_bnds] = (coeffs_in[:,1] + alpha*(2*coeffs_in[:,2] + alpha*3*coeffs_in[:,3]))/(self.x_list[i] - self.x_list[i-1])
# Do the "out of bounds" evaluation points
y[out_bot] = self.coeffs[0,0] + self.coeffs[0,1]*(x[out_bot] - self.x_list[0])
dydx[out_bot] = self.coeffs[0,1]
alpha = x[out_top] - self.x_list[self.n-1]
y[out_top] = self.coeffs[self.n,0] + x[out_top]*self.coeffs[self.n,1] - self.coeffs[self.n,2]*np.exp(alpha*self.coeffs[self.n,3])
dydx[out_top] = self.coeffs[self.n,1] - self.coeffs[self.n,2]*self.coeffs[self.n,3]*np.exp(alpha*self.coeffs[self.n,3])
return y, dydx
class LinearInterp(HARKinterpolator1D):
'''
A slight extension of scipy.interpolate's UnivariateSpline for linear inter-
polation. Allows for linear or decay extrapolation (approaching a limiting
linear function from below).
'''
def __init__(self,x_list,y_list,intercept_limit=None,slope_limit=None,lower_extrap=False):
'''
The interpolation constructor to make a new linear spline interpolation.
Parameters
----------
x_list : np.array
List of x values composing the grid.
y_list : np.array
List of y values, representing f(x) at the points in x_list.
intercept_limit : float
Intercept of limiting linear function.
slope_limit : float
Slope of limiting linear function.
lower_extrap : boolean
Indicator for whether lower extrapolation is allowed. False means
f(x) = NaN for x < min(x_list); True means linear extrapolation.
Returns
-------
new instance of LinearInterp
NOTE: When no input is given for the limiting linear function, linear
extrapolation is used above the highest gridpoint.
'''
# Make the basic linear spline interpolation
self.x_list = x_list
self.y_list = y_list
self.function = UnivariateSpline(x_list,y_list,k=1,s=0)
self.lower_extrap = lower_extrap
self.distance_criteria = ['x_list','y_list']
# Make a decay extrapolation
if intercept_limit is not None and slope_limit is not None:
slope_at_top = self.function(x_list[-1],1)
level_diff = intercept_limit + slope_limit*x_list[-1] - y_list[-1]
slope_diff = slope_limit - slope_at_top
self.decay_extrap_A = level_diff
self.decay_extrap_B = -slope_diff/level_diff
self.intercept_limit = intercept_limit
self.slope_limit = slope_limit
self.decay_extrap = True
else:
self.decay_extrap = False
def _evaluate(self,x):
'''
Returns the level of the interpolated function at each value in x. Only
called internally by HARKinterpolator1D.__call__ (etc).
'''
out = self.function(x)
if not self.lower_extrap:
below_lower_bound = x < self.function._data[0][0]
out[below_lower_bound] = np.nan
if self.decay_extrap:
above_upper_bound = x > self.function._data[0][-1]
x_temp = x[above_upper_bound] - self.function._data[0][-1]
out[above_upper_bound] = self.intercept_limit + self.slope_limit*x[above_upper_bound] - self.decay_extrap_A*np.exp(-self.decay_extrap_B*x_temp)
return out
def _der(self,x):
'''
Returns the first derivative of the interpolated function at each value
in x. Only called internally by HARKinterpolator1D.derivative (etc).
'''
out = self.function(x,1)
if not self.lower_extrap:
below_lower_bound = x < self.function._data[0][0]
out[below_lower_bound] = np.nan
if self.decay_extrap:
above_upper_bound = x > self.function._data[0][-1]
x_temp = x[above_upper_bound] - self.function._data[0][-1]
out[above_upper_bound] = self.slope_limit + self.decay_extrap_B*self.decay_extrap_A*np.exp(-self.decay_extrap_B*x_temp)
return out
def _evalAndDer(self,x):
'''
Returns the level and first derivative of the function at each value in
x. Only called internally by HARKinterpolator1D.eval_and_der (etc).
'''
out1 = self.function(x)
out2 = self.function(x,1)
if not self.lower_extrap:
below_lower_bound = x < self.function._data[0][0]
out1[below_lower_bound] = np.nan
out2[below_lower_bound] = np.nan
if self.decay_extrap:
above_upper_bound = x > self.function._data[0][-1]
x_temp = x[above_upper_bound] - self.function._data[0][-1]
out1[above_upper_bound] = self.intercept_limit + self.slope_limit*x[above_upper_bound] - self.decay_extrap_A*np.exp(-self.decay_extrap_B*x_temp)
out2[above_upper_bound] = self.slope_limit + self.decay_extrap_B*self.decay_extrap_A*np.exp(-self.decay_extrap_B*x_temp)
return out1, out2
class BilinearInterp(HARKinterpolator2D):
'''
Bilinear full (or tensor) grid interpolation of a function f(x,y).
'''
def __init__(self,f_values,x_list,y_list,xSearchFunc=None,ySearchFunc=None):
'''
Constructor to make a new bilinear interpolation.
Parameters
----------
f_values : numpy.array
An array of size (x_n,y_n) such that f_values[i,j] = f(x_list[i],y_list[j])
x_list : numpy.array
An array of x values, with length designated x_n.
y_list : numpy.array
An array of y values, with length designated y_n.
xSearchFunc : function
An optional function that returns the reference location for x values:
indices = xSearchFunc(x_list,x). Default is np.searchsorted
ySearchFunc : function
An optional function that returns the reference location for y values:
indices = ySearchFunc(y_list,y). Default is np.searchsorted
Returns
-------
new instance of BilinearInterp
'''
self.f_values = f_values
self.x_list = x_list
self.y_list = y_list
self.x_n = x_list.size
self.y_n = y_list.size
if xSearchFunc is None:
xSearchFunc = np.searchsorted
if ySearchFunc is None:
ySearchFunc = np.searchsorted
self.xSearchFunc = xSearchFunc
self.ySearchFunc = ySearchFunc
self.distance_criteria = ['x_list','y_list','f_values']
def _evaluate(self,x,y):
'''
Returns the level of the interpolated function at each value in x,y.
Only called internally by HARKinterpolator2D.__call__ (etc).
'''
if _isscalar(x):
x_pos = max(min(self.xSearchFunc(self.x_list,x),self.x_n-1),1)
y_pos = max(min(self.ySearchFunc(self.y_list,y),self.y_n-1),1)
else:
x_pos = self.xSearchFunc(self.x_list,x)
x_pos[x_pos < 1] = 1
x_pos[x_pos > self.x_n-1] = self.x_n-1
y_pos = self.ySearchFunc(self.y_list,y)
y_pos[y_pos < 1] = 1
y_pos[y_pos > self.y_n-1] = self.y_n-1
alpha = (x - self.x_list[x_pos-1])/(self.x_list[x_pos] - self.x_list[x_pos-1])
beta = (y - self.y_list[y_pos-1])/(self.y_list[y_pos] - self.y_list[y_pos-1])
f = (
(1-alpha)*(1-beta)*self.f_values[x_pos-1,y_pos-1]
+ (1-alpha)*beta*self.f_values[x_pos-1,y_pos]
+ alpha*(1-beta)*self.f_values[x_pos,y_pos-1]
+ alpha*beta*self.f_values[x_pos,y_pos])
return f
def _derX(self,x,y):
'''
Returns the derivative with respect to x of the interpolated function
at each value in x,y. Only called internally by HARKinterpolator2D.derivativeX.
'''
if _isscalar(x):
x_pos = max(min(self.xSearchFunc(self.x_list,x),self.x_n-1),1)
y_pos = max(min(self.ySearchFunc(self.y_list,y),self.y_n-1),1)
else:
x_pos = self.xSearchFunc(self.x_list,x)
x_pos[x_pos < 1] = 1
x_pos[x_pos > self.x_n-1] = self.x_n-1
y_pos = self.ySearchFunc(self.y_list,y)
y_pos[y_pos < 1] = 1
y_pos[y_pos > self.y_n-1] = self.y_n-1
beta = (y - self.y_list[y_pos-1])/(self.y_list[y_pos] - self.y_list[y_pos-1])
dfdx = (
((1-beta)*self.f_values[x_pos,y_pos-1]
+ beta*self.f_values[x_pos,y_pos]) -
((1-beta)*self.f_values[x_pos-1,y_pos-1]
+ beta*self.f_values[x_pos-1,y_pos]))/(self.x_list[x_pos] - self.x_list[x_pos-1])
return dfdx
def _derY(self,x,y):
'''
Returns the derivative with respect to y of the interpolated function
at each value in x,y. Only called internally by HARKinterpolator2D.derivativeY.
'''
if _isscalar(x):
x_pos = max(min(self.xSearchFunc(self.x_list,x),self.x_n-1),1)
y_pos = max(min(self.ySearchFunc(self.y_list,y),self.y_n-1),1)
else:
x_pos = self.xSearchFunc(self.x_list,x)
x_pos[x_pos < 1] = 1
x_pos[x_pos > self.x_n-1] = self.x_n-1
y_pos = self.ySearchFunc(self.y_list,y)
y_pos[y_pos < 1] = 1
y_pos[y_pos > self.y_n-1] = self.y_n-1
alpha = (x - self.x_list[x_pos-1])/(self.x_list[x_pos] - self.x_list[x_pos-1])
dfdy = (
((1-alpha)*self.f_values[x_pos-1,y_pos]
+ alpha*self.f_values[x_pos,y_pos]) -
((1-alpha)*self.f_values[x_pos-1,y_pos]