-
Notifications
You must be signed in to change notification settings - Fork 33
/
rbfopt_utils.py
1752 lines (1401 loc) · 53.8 KB
/
rbfopt_utils.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
"""Utility functions.
This module contains a number of subroutines that are used by the
other modules. In particular it contains most of the subroutines that
do the calculations using numpy, as well as utility functions for
various modules.
Licensed under Revised BSD license, see LICENSE.
(C) Copyright Singapore University of Technology and Design 2014.
(C) Copyright International Business Machines Corporation 2017.
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
import sys
import os
import math
import itertools
import warnings
import collections
import logging
import numpy as np
import scipy.spatial as ss
import scipy.linalg as la
from scipy.special import xlogy
from rbfopt.rbfopt_settings import RbfoptSettings
def get_rbf_function(settings):
"""Return a radial basis function.
Return the radial basis function appropriate function as indicated
by the settings.
Parameters
----------
settings : :class:`rbfopt_settings.RbfoptSettings`
Global and algorithmic settings.
Returns
---
Callable[numpy.ndarray]
A callable radial basis function that can be applied on floats
and numpy.ndarray.
"""
assert(isinstance(settings, RbfoptSettings))
if (settings.rbf == 'cubic'):
return _cubic
elif (settings.rbf == 'thin_plate_spline'):
return _thin_plate_spline
elif (settings.rbf == 'linear'):
return _linear
elif (settings.rbf == 'multiquadric'):
mq = _MultiquadricRbf(settings.rbf_shape_parameter)
return mq._multiquadric
elif (settings.rbf == 'gaussian'):
gauss = _GaussianRbf(settings.rbf_shape_parameter)
return gauss._gaussian
# -- List of radial basis functions
def _cubic(r):
"""Cubic RBF: :math: `f(x) = x^3`"""
return r*r*r
def _thin_plate_spline(r):
"""Thin plate spline RBF: :math: `f(x) = x^2 \log x`"""
return r*r*xlogy(np.sign(r), r)
def _linear(r):
"""Linear RBF: :math: `f(x) = x`"""
return r
class _MultiquadricRbf:
def __init__(self, gamma):
self._gamma_sq = gamma*gamma
def _multiquadric(self, r):
return (r*r + self._gamma_sq)**0.5
# -- end class
class _GaussianRbf:
def __init__(self, gamma):
self._gamma = gamma
def _gaussian(self, r):
return np.exp(-self._gamma * r * r)
# -- end class
# -- end list of radial basis functions
def get_degree_polynomial(settings):
"""Compute the degree of the polynomial for the interpolant.
Return the degree of the polynomial that should be used in the RBF
expression to ensure unisolvence and convergence of the
optimization method.
Parameters
----------
settings : :class:`rbfopt_settings.RbfoptSettings`
Global and algorithmic settings.
Returns
-------
int
Degree of the polynomial
Raises
------
ValueError
If the matrix type is not implemented.
"""
assert(isinstance(settings, RbfoptSettings))
if (settings.rbf == 'cubic' or settings.rbf == 'thin_plate_spline'):
return 1
elif (settings.rbf == 'linear' or settings.rbf == 'multiquadric'):
return 0
elif (settings.rbf == 'gaussian'):
return -1
raise ValueError('Rbf "' + settings.rbf + '" not implemented yet')
# -- end function
def get_size_P_matrix(settings, n):
"""Compute size of the P part of the RBF matrix.
Return the number of columns in the P part of the matrix [\Phi P;
P^T 0] that is used through the algorithm.
Parameters
----------
settings : :class:`rbfopt_settings.RbfoptSettings`
Global and algorithmic settings.
n : int
Dimension of the problem, i.e. number of variables.
Returns
-------
int
Number of columns in the matrix
Raises
------
ValueError
If the matrix type is not implemented.
"""
assert(isinstance(settings, RbfoptSettings))
if (settings.rbf == 'cubic' or settings.rbf == 'thin_plate_spline'):
return n+1
elif (settings.rbf == 'linear' or settings.rbf == 'multiquadric'):
return 1
elif (settings.rbf == 'gaussian'):
return 0
raise ValueError('Rbf "' + settings.rbf + '" not implemented yet')
# -- end function
def get_all_corners(var_lower, var_upper):
"""Compute all corner points of a box.
Compute and return all the corner points of the given box. Note
that this number is exponential in the dimension of the problem.
Parameters
----------
var_lower : 1D numpy.ndarray[float]
List of lower bounds of the variables.
var_upper : 1D numpy.ndarray[float]
List of upper bounds of the variables.
Returns
-------
2D numpy.ndarray[float]
All the corner points.
"""
assert(isinstance(var_lower, np.ndarray))
assert(isinstance(var_upper, np.ndarray))
assert(len(var_lower) == len(var_upper))
n = len(var_lower)
node_pos = np.empty([2**n, n], np.float_)
i = 0
# Generate all corners
for corner in itertools.product('lu', repeat=len(var_lower)):
for (j, bound) in enumerate(corner):
if bound == 'l':
node_pos[i, j] = var_lower[j]
else:
node_pos[i, j] = var_upper[j]
i += 1
return node_pos
# -- end function
def get_lower_corners(var_lower, var_upper):
"""Compute the lower corner points of a box.
Compute a list of (n+1) corner points of the given box, where n is
the dimension of the space. The selected points are the bottom
left (i.e. corresponding to the origin in the 0-1 hypercube) and
the n adjacent ones.
Parameters
----------
var_lower : 1D numpy.ndarray[float]
List of lower bounds of the variables.
var_upper : 1D numpy.ndarray[float]
List of upper bounds of the variables.
Returns
-------
2D numpy.ndarray[float]
The lower corner points.
"""
assert(isinstance(var_lower, np.ndarray))
assert(isinstance(var_upper, np.ndarray))
assert(len(var_lower) == len(var_upper))
n = len(var_lower)
# Make sure we copy the object instead of copying just a reference
node_pos = np.tile(var_lower, (n + 1, 1))
# Generate adjacent corners
for i in range(n):
node_pos[i + 1, i] = var_upper[i]
return node_pos
# -- end function
def get_random_corners(var_lower, var_upper):
"""Compute some randomly selected corner points of the box.
Compute a list of (n+1) corner points of the given box, where n is
the dimension of the space. The selected points are picked
randomly.
Parameters
----------
var_lower : 1D numpy.ndarray[float]
List of lower bounds of the variables.
var_upper : 1D numpy.ndarray[float]
List of upper bounds of the variables.
Returns
-------
2D numpy.ndarray[float]
A List of random corner points.
"""
assert(isinstance(var_lower, np.ndarray))
assert(isinstance(var_upper, np.ndarray))
assert(len(var_lower) == len(var_upper))
n = len(var_lower)
limits = np.vstack((var_upper, var_lower))
node_pos = np.atleast_2d(limits[np.random.randint(2, size=n),
np.arange(n)])
while (len(node_pos) < n+1):
point = limits[np.random.randint(2, size=n), np.arange(n)]
if (get_min_distance(point, node_pos) > 0):
node_pos = np.vstack((node_pos, point))
return np.array(node_pos, np.float_)
# -- end function
def get_uniform_lhs(n, num_samples):
"""Generate random Latin Hypercube samples.
Generate points using Latin Hypercube sampling from the uniform
distribution in the unit hypercube.
Parameters
----------
n : int
Dimension of the space, i.e. number of variables.
num_samples : num_samples
Number of samples to be generated.
Returns
-------
2D numpy.ndarray[float]
A list of n-dimensional points in the unit hypercube.
"""
assert(n >= 0)
assert(num_samples >= 0)
# Generate integer LH in [0, num_samples]
int_lh = np.array([np.random.permutation(num_samples)
for i in range(n)], np.float_).T
# Map integer LH back to unit hypercube, and perturb points so that
# they are uniformly distributed in the corresponding intervals
lhs = (np.random.rand(num_samples, n) + int_lh) / num_samples
return lhs
# -- end function
def get_lhd_maximin_points(var_lower, var_upper, sample_size, num_trials=50):
"""Compute a latin hypercube design with maximin distance.
Compute an array of points in the given box, where n is the
dimension of the space. The selected points are picked according
to a random latin hypercube design with maximin distance
criterion.
Parameters
----------
var_lower : 1D numpy.ndarray[float]
List of lower bounds of the variables.
var_upper : 1D numpy.ndarray[float]
List of upper bounds of the variables.
sample_size : int
Number of points to sample.
num_trials : int
Maximum number of generated LHs to choose from.
Returns
-------
2D numpy.ndarray[float]
List of points in the latin hypercube design.
"""
assert(isinstance(var_lower, np.ndarray))
assert(isinstance(var_upper, np.ndarray))
assert(len(var_lower) == len(var_upper))
n = len(var_lower)
if (n == 1):
# For unidimensional problems, simply take the two endpoints
# of the interval as starting points
return np.vstack((var_lower, var_upper))
# Otherwise, generate a bunch of Latin Hypercubes, and rank them
lhs = [get_uniform_lhs(n, sample_size) for i in range(num_trials)]
# Indices of upper triangular matrix (without the diagonal)
indices = np.triu_indices(sample_size, 1)
# Compute distance matrix of points to themselves, get upper
# triangular part of the matrix, and get minimum
dist_values = [np.amin(ss.distance.cdist(mat, mat)[indices])
for mat in lhs]
lhd = lhs[dist_values.index(max(dist_values))]
node_pos = lhd * (var_upper-var_lower) + var_lower
return node_pos
# -- end function
def get_lhd_corr_points(var_lower, var_upper, sample_size, num_trials=50):
"""Compute a latin hypercube design with min correlation.
Compute a list of points in the given box, where n is the
dimension of the space. The selected points are picked according
to a random latin hypercube design with minimum correlation
criterion.
Parameters
----------
var_lower : 1D numpy.ndarray[float]
List of lower bounds of the variables.
var_upper : 1D numpy.ndarray[float]
List of upper bounds of the variables.
sample_size : int
Number of points to sample.
num_trials : int
Maximum number of generated LHs to choose from.
Returns
-------
2D numpy.ndarray[float]
List of points in the latin hypercube design.
"""
assert(isinstance(var_lower, np.ndarray))
assert(isinstance(var_upper, np.ndarray))
assert(len(var_lower) == len(var_upper))
n = len(var_lower)
if (n == 1):
# For unidimensional problems, simply take the two endpoints
# of the interval as starting points
return np.vstack((var_lower, var_upper))
# Otherwise, generate a bunch of Latin Hypercubes, and rank them
lhs = [get_uniform_lhs(n, sample_size) for i in range(num_trials)]
# Indices of upper triangular matrix (without the diagonal)
indices = np.triu_indices(n, 1)
# Compute correlation matrix of points to themselves, get upper
# triangular part of the matrix, and get minimum
corr_values = [abs(np.amax(np.corrcoef(mat, rowvar = 0)[indices]))
for mat in lhs]
lhd = lhs[corr_values.index(min(corr_values))]
node_pos = lhd * (var_upper-var_lower) + var_lower
return node_pos
# -- end function
def initialize_nodes(settings, var_lower, var_upper, integer_vars):
"""Compute the initial sample points.
Compute an initial list of nodes using the initialization strategy
indicated in the algorithmic settings.
Parameters
----------
settings : :class:`rbfopt_settings.RbfoptSettings`
Global and algorithmic settings.
var_lower : 1D numpy.ndarray[float]
List of lower bounds of the variables.
var_upper : 1D numpy.ndarray[float]
List of upper bounds of the variables.
integer_vars : 1D numpy.ndarray[int]
A List containing the indices of the integrality constrained
variables. If empty, all variables are assumed to be
continuous.
Returns
-------
2D numpy.ndarray[float]
Matrix containing at least n+1 corner points, one for each
row, where n is the dimension of the space. The number and
position of points depends on the chosen strategy.
Raises
------
RuntimeError
If a set of feasible and linearly independent sample points
cannot be computed within the prescribed number of iterations.
"""
assert(isinstance(settings, RbfoptSettings))
assert(isinstance(var_lower, np.ndarray))
assert(isinstance(var_upper, np.ndarray))
assert(isinstance(integer_vars, np.ndarray))
assert(len(var_lower) == len(var_upper))
sample_size = max(2, round((len(var_lower) + 1) *
settings.init_sample_fraction))
if (settings.init_include_midpoint):
midpoint = (var_lower + var_upper)/2
midpoint[integer_vars] = np.around(midpoint[integer_vars])
# We must make sure points are linearly independent; if they are
# not, we perform a given number of iterations
dependent = True
itercount = 0
while (dependent and itercount < settings.max_random_init):
itercount += 1
if (settings.init_strategy == 'all_corners'):
nodes = get_all_corners(var_lower, var_upper)
elif (settings.init_strategy == 'lower_corners'):
nodes = get_lower_corners(var_lower, var_upper)
elif (settings.init_strategy == 'rand_corners'):
nodes = get_random_corners(var_lower, var_upper)
elif (settings.init_strategy == 'lhd_maximin'):
nodes = get_lhd_maximin_points(var_lower, var_upper, sample_size)
elif (settings.init_strategy == 'lhd_corr'):
nodes = get_lhd_corr_points(var_lower, var_upper, sample_size)
if (len(integer_vars)):
nodes[:, integer_vars] = np.around(nodes[:, integer_vars])
if (settings.init_include_midpoint and
get_min_distance(midpoint, nodes) > settings.min_dist):
nodes = np.vstack((nodes, midpoint))
norms = la.norm(nodes, axis=1)
U, s, V = np.linalg.svd(nodes[norms > settings.eps_zero])
if (min(s) > settings.eps_linear_dependence):
dependent = False
if (itercount == settings.max_random_init):
raise RuntimeError('Exceeded number of random initializations')
return nodes
# -- end function
def round_integer_vars(point, integer_vars):
"""Round a point to the closest integer.
Round the values of the integer-constrained variables to the
closest integer value. The values are rounded in-place.
Parameters
----------
point : 1D numpy.ndarray[float]
The point to be rounded.
integer_vars : 1D numpy.ndarray[int]
A list of indices of integer variables.
"""
assert(isinstance(point, np.ndarray))
assert(isinstance(integer_vars, np.ndarray))
if (len(integer_vars)):
point[integer_vars] = np.around(point[integer_vars])
# -- end function
def round_integer_bounds(var_lower, var_upper, integer_vars):
"""Round the variable bounds to integer values.
Round the values of the integer-constrained variable bounds, in
the usual way: lower bounds are rounded up, upper bounds are
rounded down.
Parameters
----------
var_lower : 1D numpy.ndarray[float]
List of lower bounds of the variables.
var_upper : 1D numpy.ndarray[float]
List of upper bounds of the variables.
integer_vars : 1D numpy.ndarray[int]
A list containing the indices of the integrality constrained
variables. If empty, all variables are assumed to be
continuous.
"""
assert (isinstance(var_lower, np.ndarray))
assert (isinstance(var_upper, np.ndarray))
assert (isinstance(integer_vars, np.ndarray))
if (len(integer_vars)):
assert(len(var_lower) == len(var_upper))
assert(max(integer_vars) < len(var_lower))
var_lower[integer_vars] = np.floor(var_lower[integer_vars])
var_upper[integer_vars] = np.ceil(var_upper[integer_vars])
# -- end function
def norm(p):
"""Compute the L2-norm of a vector
Compute the L2 (Euclidean) norm.
Parameters
----------
p : 1D numpy.ndarray[float]
The point whose norm should be computed.
Returns
-------
float
The norm of the point.
"""
assert(isinstance(p, np.ndarray))
return np.sqrt(np.dot(p, p))
# -- end function
def distance(p1, p2):
"""Compute Euclidean distance between two points.
Compute Euclidean distance between two points.
Parameters
----------
p1 : 1D numpy.ndarray[float]
First point.
p2 : 1D numpy.ndarray[float]
Second point.
Returns
-------
float
Euclidean distance.
"""
assert(isinstance(p1, np.ndarray))
assert(isinstance(p2, np.ndarray))
assert(len(p1) == len(p2))
p = p1 - p2
return np.sqrt(np.dot(p, p))
# -- end function
def get_min_distance(point, other_points):
"""Compute minimum distance from a set of points.
Compute the minimum Euclidean distance between a given point and a
list of points.
Parameters
----------
point : 1D numpy.ndarray[float]
The point we compute the distances from.
other_points : 2D numpy.ndarray[float]
The list of points we want to compute the distances to.
Returns
-------
float
Minimum distance between point and the other_points.
"""
assert(isinstance(point, np.ndarray))
assert(isinstance(other_points, np.ndarray))
assert(point.size)
assert(other_points.size)
# Create distance matrix
dist = ss.distance.cdist(np.atleast_2d(point), other_points)
return np.amin(dist, 1)
# -- end function
def get_min_distance_and_index(point, other_points):
"""Compute the distance and index of the point with minimum distance.
Compute the distance value and the index of the point in a matrix
that achieves minimum Euclidean distance to a given point.
Parameters
----------
point : 1D numpy.ndarray[float]
The point we compute the distances from.
other_points : 2D numpy.ndarray[float]
The list of points we want to compute the distances to.
Returns
-------
(float, int)
The distance value and the index of the point in other_points
that achieved minimum distance from point.
"""
assert (isinstance(point, np.ndarray))
assert (isinstance(other_points, np.ndarray))
assert(point.size)
assert(other_points.size)
dist = ss.distance.cdist(np.atleast_2d(point), other_points)
index = np.argmin(dist, 1)[0]
return (dist[0, index], index)
# -- end function
def bulk_get_min_distance(points, other_points):
"""Get the minimum distances between two sets of points.
Compute the minimum distance of each point in the first set to the
points in the second set. This is faster than using
get_min_distance repeatedly, for large sets of points.
Parameters
----------
points : 2D numpy.ndarray[float]
The points in R^n that we compute the distances from.
other_points : 2D numpy.ndarray[float]
The list of points we want to compute the distances to.
Returns
-------
1D numpy.ndarray[float]
Minimum distance between each point in points and the
other_points.
See also
--------
get_min_distance()
"""
assert(isinstance(points, np.ndarray))
assert(isinstance(other_points, np.ndarray))
assert(points.size)
assert(other_points.size)
assert(len(points[0]) == len(other_points[0]))
# Create distance matrix
dist = ss.distance.cdist(points, other_points)
return np.amin(dist, 1)
# -- end function
def get_rbf_matrix(settings, n, k, node_pos):
"""Compute the matrix for the RBF system.
Compute the matrix A = [Phi P; P^T 0] of equation (3) in the paper
by Costa and Nannicini.
Parameters
----------
settings : :class:`rbfopt_settings.RbfoptSettings`.
Global and algorithmic settings.
n : int
Dimension of the problem, i.e. the size of the space.
k : int
Number of interpolation nodes.
node_pos : 2D numpy.ndarray[float]
List of coordinates of the nodes.
Returns
-------
numpy.matrix
The matrix A = [Phi P; P^T 0].
Raises
------
ValueError
If the type of RBF function is not supported.
"""
assert(isinstance(node_pos, np.ndarray))
assert(len(node_pos) == k)
assert(isinstance(settings, RbfoptSettings))
rbf = get_rbf_function(settings)
p = get_size_P_matrix(settings, n)
# Create matrix P.
if (p == n + 1):
# Keep the node coordinates and append a 1.
# P is ((k) x (n+1)), PTr is its transpose
P = np.insert(node_pos, n, 1, axis=1)
PTr = P.T
elif (p == 1):
# P is an all-one vector of size ((k) x (1))
P = np.ones([k, 1])
PTr = P.T
elif (p == 0):
pass
else:
raise ValueError('Rbf "' + settings.rbf + '" not implemented yet')
# Now create matrix Phi. Phi is ((k) x (k))
dist = ss.distance.cdist(node_pos, node_pos)
Phi = rbf(dist)
# Put together to obtain [Phi P; P^T 0].
if (p > 0):
A = np.vstack((np.hstack((Phi, P)),
np.hstack((PTr, np.zeros((p, p))))))
else:
A = Phi
Amat = np.matrix(A)
# Zero out tiny elements
Amat[np.abs(Amat) < settings.eps_zero] = 0
return Amat
# -- end function
def get_matrix_inverse(settings, Amat):
"""Compute the inverse of a matrix.
Compute the inverse of a given matrix, zeroing out small
coefficients to improve sparsity.
Parameters
----------
settings : :class:`rbfopt_settings.RbfoptSettings`
Global and algorithmic settings.
Amat : numpy.matrix
The matrix to invert.
Returns
-------
numpy.matrix
The matrix Amat^{-1}.
Raises
------
numpy.linalg.LinAlgError
If the matrix cannot be inverted for numerical reasons.
"""
assert(isinstance(settings, RbfoptSettings))
assert(isinstance(Amat, np.matrix))
try:
Amatinv = Amat.getI()
except np.linalg.LinAlgError as e:
if (settings.debug):
print('Exception raised trying to invert the RBF matrix',
file=sys.stderr)
print(e, file=sys.stderr)
raise e
# Zero out tiny elements of the inverse -- this is potentially
# dangerous as the product between Amat and Amatinv may not be the
# identity, but if the zero tolerance is chosen not too large,
# this should help the optimization process
Amatinv[np.abs(Amatinv) < settings.eps_zero] = 0
return Amatinv
# -- end function
def get_rbf_coefficients(settings, n, k, Amat, node_val):
"""Compute the coefficients of the RBF interpolant.
Solve a linear system to compute the coefficients of the RBF
interpolant.
Parameters
----------
settings : :class:`rbfopt_settings.RbfoptSettings`.
Global and algorithmic settings.
n : int
Dimension of the problem, i.e. the size of the space.
k : int
Number of interpolation nodes.
Amat : numpy.matrix
Matrix [Phi P; P^T 0] defining the linear system. Must be a
square matrix of appropriate size.
node_val : 1D numpy.ndarray[float]
List of values of the function at the nodes.
Returns
-------
(1D numpy.ndarray[float], 1D numpy.ndarray[float])
Lambda coefficients (for the radial basis functions), and h
coefficients (for the polynomial).
"""
assert(len(np.atleast_1d(node_val)) == k)
assert(isinstance(settings, RbfoptSettings))
assert(isinstance(Amat, np.matrix))
assert(isinstance(node_val, np.ndarray))
p = get_size_P_matrix(settings, n)
assert(Amat.shape == (k+p, k+p))
rhs = np.append(node_val, np.zeros(p))
try:
solution = np.linalg.solve(Amat, rhs)
except np.linalg.LinAlgError as e:
if (settings.debug):
print('Exception raised in the solution of the RBF linear system',
file=sys.stderr)
print('Exception details:', file=sys.stderr)
print(e, file=sys.stderr)
raise e
return (solution[0:k], solution[k:])
# -- end function
def get_rbf_coefficients_underdet(settings, n, k, Amat, node_val):
"""Compute coefficients of RBF interpolant (underdetermined).
Solve an underdetermined linear system to compute the coefficients
of the RBF interpolant.
Parameters
----------
settings : :class:`rbfopt_settings.RbfoptSettings`.
Global and algorithmic settings.
n : int
Dimension of the problem, i.e. the size of the space.
k : int
Number of interpolation nodes.
Amat : numpy.matrix
Matrix [Phi P; P^T 0] defining the linear system. Must be a
square matrix of appropriate size.
node_val : 1D numpy.ndarray[float]
List of values of the function at the nodes.
Returns
-------
(1D numpy.ndarray[float], 1D numpy.ndarray[float])
Lambda coefficients (for the radial basis functions), and h
coefficients (for the polynomial).
"""
assert(len(np.atleast_1d(node_val)) == k)
assert(isinstance(settings, RbfoptSettings))
assert(isinstance(Amat, np.matrix))
assert(isinstance(node_val, np.ndarray))
p = get_size_P_matrix(settings, n)
assert(Amat.shape == (k+p, k+p))
rhs = np.append(node_val, np.zeros(p))
try:
solution, res, rank, svd = np.linalg.lstsq(Amat, rhs, rcond=-1)
except np.linalg.LinAlgError as e:
if (settings.debug):
print('Exception raised in the solution of the RBF linear system',
file=sys.stderr)
print('Exception details:', file=sys.stderr)
print(e, file=sys.stderr)
raise e
return (solution[0:k], solution[k:])
# -- end function
def evaluate_rbf(settings, point, n, k, node_pos, rbf_lambda, rbf_h):
"""Evaluate the RBF interpolant at a given point.
Evaluate the RBF interpolant at a given point.
Parameters
----------
settings : :class:`rbfopt_settings.RbfoptSettings`.
Global and algorithmic settings.
point : 1D numpy.ndarray[float]
The point in R^n where we want to evaluate the interpolant.
n : int
Dimension of the problem, i.e. the size of the space.
k : int
Number of interpolation nodes.
node_pos : 2D numpy.ndarray[float]
List of coordinates of the interpolation points.
rbf_lambda : 1D numpy.ndarray[float]
The lambda coefficients of the RBF interpolant, corresponding
to the radial basis functions. List of dimension k.
rbf_h : 1D numpy.ndarray[float]
The h coefficients of the RBF interpolant, corresponding to he
polynomial. List of dimension given by get_size_P_matrix().
Returns
-------
float
Value of the RBF interpolant at the given point.
"""
assert(isinstance(point, np.ndarray))
assert(isinstance(node_pos, np.ndarray))
assert(isinstance(rbf_lambda, np.ndarray))
assert(isinstance(rbf_h, np.ndarray))
assert(len(point) == n)
assert(len(rbf_lambda) == k)
assert(len(node_pos) == k)
assert(isinstance(settings, RbfoptSettings))
p = get_size_P_matrix(settings, n)
assert(len(rbf_h) == p)
rbf_function = get_rbf_function(settings)
# Formula:
# \sum_{i=1}^k \lambda_i \phi(\|x - x_i\|) + h^T (x 1)
part1 = math.fsum(rbf_lambda[i] *
rbf_function(distance(point, node_pos[i]))
for i in range(k))
part2 = math.fsum(rbf_h[i]*point[i] for i in range(p-1))
return math.fsum([part1, part2, rbf_h[-1] if (p > 0) else 0.0])
# -- end function
def bulk_evaluate_rbf(settings, points, n, k, node_pos, rbf_lambda, rbf_h,
return_distances='no'):
"""Evaluate the RBF interpolant at all points in a given list.
Evaluate the RBF interpolant at all points in a given list. This
version uses numpy and should be faster than individually
evaluating the RBF at each single point, provided that the list of
points is large enough. It also computes the distance or the
minimum distance of each point from the interpolation nodes, if
requested, since this comes almost for free.
Parameters
----------
settings : :class:`rbfopt_settings.RbfoptSettings`.