/
basis.py
2235 lines (1731 loc) · 84.9 KB
/
basis.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
"""Module for functional data manipulation in a basis system.
Defines functional data object in a basis function system representation and
the corresponding basis classes.
"""
import copy
from abc import ABC, abstractmethod
import matplotlib.pyplot
import numpy
import scipy.integrate
import scipy.interpolate
import scipy.linalg
from numpy import polyder, polyint, polymul, polyval
from scipy.interpolate import PPoly
from scipy.special import binom
from . import grid
from .functional_data import FData, _list_of_arrays
from .lfd import Lfd
__author__ = "Miguel Carbajo Berrocal"
__email__ = "miguel.carbajo@estudiante.uam.es"
MIN_EVAL_SAMPLES = 201
# aux functions
def _polypow(p, n=2):
if n > 2:
return polymul(p, _polypow(p, n - 1))
if n == 2:
return polymul(p, p)
elif n == 1:
return p
elif n == 0:
return [1]
else:
raise ValueError("n must be greater than 0.")
def _check_domain(domain_range):
for domain in domain_range:
if len(domain) != 2 or domain[0] >= domain[1]:
raise ValueError(f"The interval {domain} is not well-defined.")
def _same_domain(one_domain_range, other_domain_range):
return numpy.array_equal(one_domain_range, other_domain_range)
class Basis(ABC):
"""Defines the structure of a basis function system.
Attributes:
domain_range (tuple): a tuple of length 2 containing the initial and
end values of the interval over which the basis can be evaluated.
nbasis (int): number of functions in the basis.
"""
def __init__(self, domain_range=(0, 1), nbasis=1):
"""Basis constructor.
Args:
domain_range (tuple or list of tuples, optional): Definition of the
interval where the basis defines a space. Defaults to (0,1).
nbasis: Number of functions that form the basis. Defaults to 1.
"""
# TODO: Allow multiple dimensions
domain_range = _list_of_arrays(domain_range)
# Some checks
_check_domain(domain_range)
if nbasis < 1:
raise ValueError("The number of basis has to be strictly "
"possitive.")
self.domain_range = domain_range
self.nbasis = nbasis
self._drop_index_lst = []
super().__init__()
@abstractmethod
def _compute_matrix(self, eval_points, derivative=0):
"""Compute the basis or its derivatives given a list of values.
Args:
eval_points (array_like): List of points where the basis is
evaluated.
derivative (int, optional): Order of the derivative. Defaults to 0.
Returns:
(:obj:`numpy.darray`): Matrix whose rows are the values of the each
basis function or its derivatives at the values specified in
eval_points.
"""
pass
@abstractmethod
def _ndegenerated(self, penalty_degree):
"""Return number of 0 or nearly 0 eigenvalues of the penalty matrix.
Args:
penalty_degree (int): Degree of the derivative used in the
calculation of the penalty matrix.
Returns:
int: number of close to 0 eigenvalues.
"""
pass
def evaluate(self, eval_points, derivative=0):
"""Evaluate Basis objects and its derivatives.
Evaluates the basis function system or its derivatives at a list of
given values.
Args:
eval_points (array_like): List of points where the basis is
evaluated.
derivative (int, optional): Order of the derivative. Defaults to 0.
Returns:
(numpy.darray): Matrix whose rows are the values of the each
basis function or its derivatives at the values specified in
eval_points.
"""
eval_points = numpy.asarray(eval_points)
if numpy.any(numpy.isnan(eval_points)):
raise ValueError("The list of points where the function is "
"evaluated can not contain nan values.")
return self._compute_matrix(eval_points, derivative)
def plot(self, chart=None, *, derivative=0, **kwargs):
"""Plot the basis object or its derivatives.
Args:
chart (figure object, axe or list of axes, optional): figure over
with the graphs are plotted or axis over where the graphs are
plotted.
derivative (int or tuple, optional): Order of derivative to be
plotted. Defaults 0.
**kwargs: keyword arguments to be passed to the fdata.plot function.
Returns:
fig (figure object): figure object in which the graphs are plotted.
ax (axes object): axes in which the graphs are plotted.
"""
self.to_basis().plot(chart=chart, derivative=derivative, **kwargs)
def _evaluate_single_basis_coefficients(self, coefficients, basis_index, x,
cache):
"""Evaluate a differential operator over one of the basis.
Computes the result of evaluating a the result of applying a
differential operator over one of the basis functions. It also admits a
"cache" dictionary to store the results for the other basis not
returned because they are evaluated by the function and may be needed
later.
Args:
coefficients (list): List of coefficients representing a
differential operator. An iterable indicating
coefficients of derivatives (which can be functions). For
instance the tuple (1, 0, numpy.sin) means :math:`1
+ sin(x)D^{2}`.
basis_index (int): index in self.basis of the basis that is
evaluated.
x (number): Point of evaluation.
cache (dict): Dictionary with the values of previous evaluation
for all the basis function and where the results of the
evalaution are stored. This is done because later evaluation
of the same differential operator and same x may be needed
for other of the basis functions.
"""
if x not in cache:
res = numpy.zeros(self.nbasis)
for i, k in enumerate(coefficients):
if callable(k):
res += k(x) * self._compute_matrix([x], i)[:, 0]
else:
res += k * self._compute_matrix([x], i)[:, 0]
cache[x] = res
return cache[x][basis_index]
def _numerical_penalty(self, coefficients):
"""Return a penalty matrix using a numerical approach.
See :func:`~basis.Basis.penalty`.
Args:
coefficients (list): List of coefficients representing a
differential operator. An iterable indicating
coefficients of derivatives (which can be functions). For
instance the tuple (1, 0, numpy.sin) means :math:`1
+ sin(x)D^{2}`.
"""
# Range of first dimension
domain_range = self.domain_range[0]
penalty_matrix = numpy.zeros((self.nbasis, self.nbasis))
cache = {}
for i in range(self.nbasis):
penalty_matrix[i, i] = scipy.integrate.quad(
lambda x: (self._evaluate_single_basis_coefficients(
coefficients, i, x, cache) ** 2),
domain_range[0], domain_range[1]
)[0]
for j in range(i + 1, self.nbasis):
penalty_matrix[i, j] = scipy.integrate.quad(
lambda x: (self._evaluate_single_basis_coefficients(
coefficients, i, x, cache)
* self._evaluate_single_basis_coefficients(
coefficients, j, x, cache)),
domain_range[0], domain_range[1]
)[0]
penalty_matrix[j, i] = penalty_matrix[i, j]
return penalty_matrix
@abstractmethod
def penalty(self, derivative_degree=None, coefficients=None):
r"""Return a penalty matrix given a differential operator.
The differential operator can be either a derivative of a certain
degree or a more complex operator.
The penalty matrix is defined as [RS05-5-6-2]_:
.. math::
R_{ij} = \int L\phi_i(s) L\phi_j(s) ds
where :math:`\phi_i(s)` for :math:`i=1, 2, ..., n` are the basis
functions and :math:`L` is a differential operator.
Args:
derivative_degree (int): Integer indicating the order of the
derivative or . For instance 2 means that the differential
operator is :math:`f''(x)`.
coefficients (list): List of coefficients representing a
differential operator. An iterable indicating
coefficients of derivatives (which can be functions). For
instance the tuple (1, 0, numpy.sin) means :math:`1
+ sin(x)D^{2}`. Only used if derivative degree is None.
Returns:
numpy.array: Penalty matrix.
References:
.. [RS05-5-6-2] Ramsay, J., Silverman, B. W. (2005). Specifying the
roughness penalty. In *Functional Data Analysis* (pp. 106-107).
Springer.
"""
pass
@abstractmethod
def basis_of_product(self, other):
pass
@abstractmethod
def rbasis_of_product(self, other):
pass
@staticmethod
def default_basis_of_product(one, other):
"""Default multiplication for a pair of basis"""
if not _same_domain(one.domain_range, other.domain_range):
raise ValueError("Ranges are not equal.")
norder = min(8, one.nbasis + other.nbasis)
nbasis = max(one.nbasis + other.nbasis, norder + 1)
return BSpline(one.domain_range, nbasis, norder)
def rescale(self, domain_range=None):
r"""Return a copy of the basis with a new domain range, with the
corresponding values rescaled to the new bounds.
Args:
domain_range (tuple, optional): Definition of the interval where
the basis defines a space. Defaults uses the same as the
original basis.
"""
if domain_range is None:
domain_range = self.domain_range
return type(self)(domain_range, self.nbasis)
def same_domain(self, other):
r"""Returns if two basis are defined on the same domain range.
Args:
other (Basis): Basis to check the domain range definition
"""
return _same_domain(self.domain_range, other.domain_range)
def copy(self):
"""Basis copy"""
return copy.deepcopy(self)
def to_basis(self):
return FDataBasis(self.copy(), numpy.identity(self.nbasis))
def _list_to_R(self, knots):
retstring = "c("
for i in range(0, len(knots)):
retstring = retstring + str(knots[i]) + ", "
return retstring[0:len(retstring) - 2] + ")"
def _to_R(self):
raise NotImplementedError
def inner_product(self, other):
return numpy.transpose(other.inner_product(self.to_basis()))
def __repr__(self):
"""Representation of a Basis object."""
return (f"{self.__class__.__name__}(domain_range={self.domain_range}, "
f"nbasis={self.nbasis})")
def __eq__(self, other):
"""Equality of Basis"""
return type(self) == type(other) and _same_domain(self.domain_range, other.domain_range) and self.nbasis == other.nbasis
class Constant(Basis):
"""Constant basis.
Basis for constant functions
Attributes:
domain_range (tuple): a tuple of length 2 containing the initial and
end values of the interval over which the basis can be evaluated.
Examples:
Defines a contant base over the interval :math:`[0, 5]` consisting
on the constant function 1 on :math:`[0, 5]`.
>>> bs_cons = Constant((0,5))
"""
def __init__(self, domain_range=(0, 1)):
"""Constant basis constructor.
Args:
domain_range (tuple): Tuple defining the domain over which the
function is defined.
"""
super().__init__(domain_range, 1)
def _ndegenerated(self, penalty_degree):
"""Return number of 0 or nearly 0 eigenvalues of the penalty matrix.
Args:
penalty_degree (int): Degree of the derivative used in the
calculation of the penalty matrix.
Returns:
int: number of close to 0 eigenvalues.
"""
return penalty_degree
def _compute_matrix(self, eval_points, derivative=0):
"""Compute the basis or its derivatives given a list of values.
For each of the basis computes its value for each of the points in
the list passed as argument to the method.
Args:
eval_points (array_like): List of points where the basis is
evaluated.
derivative (int, optional): Order of the derivative. Defaults to 0.
Returns:
(:obj:`numpy.darray`): Matrix whose rows are the values of the each
basis function or its derivatives at the values specified in
eval_points.
"""
return numpy.ones((1, len(eval_points))) if derivative == 0 else numpy.zeros((1, len(eval_points)))
def penalty(self, derivative_degree=None, coefficients=None):
r"""Return a penalty matrix given a differential operator.
The differential operator can be either a derivative of a certain
degree or a more complex operator.
The penalty matrix is defined as [RS05-5-6-2]_:
.. math::
R_{ij} = \int L\phi_i(s) L\phi_j(s) ds
where :math:`\phi_i(s)` for :math:`i=1, 2, ..., n` are the basis
functions and :math:`L` is a differential operator.
Args:
derivative_degree (int): Integer indicating the order of the
derivative or . For instance 2 means that the differential
operator is :math:`f''(x)`.
coefficients (list): List of coefficients representing a
differential operator. An iterable indicating
coefficients of derivatives (which can be functions). For
instance the tuple (1, 0, numpy.sin) means :math:`1
+ sin(x)D^{2}`. Only used if derivative degree is None.
Returns:
numpy.array: Penalty matrix.
Examples:
>>> Constant((0,5)).penalty(0)
array([[5]])
>>> Constant().penalty(1)
array([[ 0.]])
References:
.. [RS05-5-6-2] Ramsay, J., Silverman, B. W. (2005). Specifying the
roughness penalty. In *Functional Data Analysis* (pp. 106-107).
Springer.
"""
if derivative_degree is None:
return self._numerical_penalty(coefficients)
return (numpy.full((1, 1), (self.domain_range[0][1] - self.domain_range[0][0]))
if derivative_degree == 0 else numpy.zeros((1, 1)))
def basis_of_product(self, other):
"""Multiplication of a Constant Basis with other Basis"""
if not _same_domain(self.domain_range, other.domain_range):
raise ValueError("Ranges are not equal.")
return other.copy()
def rbasis_of_product(self, other):
"""Multiplication of a Constant Basis with other Basis"""
return other.copy()
def _to_R(self):
drange = self.domain_range[0]
return "create.constant.basis(rangeval = c(" + str(drange[0]) + "," +\
str(drange[1]) + "))"
class Monomial(Basis):
"""Monomial basis.
Basis formed by powers of the argument :math:`t`:
.. math::
1, t, t^2, t^3...
Attributes:
domain_range (tuple): a tuple of length 2 containing the initial and
end values of the interval over which the basis can be evaluated.
nbasis (int): number of functions in the basis.
Examples:
Defines a monomial base over the interval :math:`[0, 5]` consisting
on the first 3 powers of :math:`t`: :math:`1, t, t^2`.
>>> bs_mon = Monomial((0,5), nbasis=3)
And evaluates all the functions in the basis in a list of descrete
values.
>>> bs_mon.evaluate([0, 1, 2])
array([[ 1., 1., 1.],
[ 0., 1., 2.],
[ 0., 1., 4.]])
And also evaluates its derivatives
>>> bs_mon.evaluate([0, 1, 2], derivative=1)
array([[ 0., 0., 0.],
[ 1., 1., 1.],
[ 0., 2., 4.]])
>>> bs_mon.evaluate([0, 1, 2], derivative=2)
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 2., 2., 2.]])
"""
def _ndegenerated(self, penalty_degree):
"""Return number of 0 or nearly 0 eigenvalues of the penalty matrix.
Args:
penalty_degree (int): Degree of the derivative used in the
calculation of the penalty matrix.
Returns:
int: number of close to 0 eigenvalues.
"""
return penalty_degree
def _compute_matrix(self, eval_points, derivative=0):
"""Compute the basis or its derivatives given a list of values.
For each of the basis computes its value for each of the points in
the list passed as argument to the method.
Args:
eval_points (array_like): List of points where the basis is
evaluated.
derivative (int, optional): Order of the derivative. Defaults to 0.
Returns:
(:obj:`numpy.darray`): Matrix whose rows are the values of the each
basis function or its derivatives at the values specified in
eval_points.
"""
# Initialise empty matrix
mat = numpy.zeros((self.nbasis, len(eval_points)))
# For each basis computes its value for each evaluation
if derivative == 0:
for i in range(self.nbasis):
mat[i] = eval_points ** i
else:
for i in range(self.nbasis):
if derivative <= i:
factor = i
for j in range(2, derivative + 1):
factor *= (i - j + 1)
mat[i] = factor * eval_points ** (i - derivative)
return mat
def penalty(self, derivative_degree=None, coefficients=None):
r"""Return a penalty matrix given a differential operator.
The differential operator can be either a derivative of a certain
degree or a more complex operator.
The penalty matrix is defined as [RS05-5-6-2]_:
.. math::
R_{ij} = \int L\phi_i(s) L\phi_j(s) ds
where :math:`\phi_i(s)` for :math:`i=1, 2, ..., n` are the basis
functions and :math:`L` is a differential operator.
Args:
derivative_degree (int): Integer indicating the order of the
derivative or . For instance 2 means that the differential
operator is :math:`f''(x)`.
coefficients (list): List of coefficients representing a
differential operator. An iterable indicating
coefficients of derivatives (which can be functions). For
instance the tuple (1, 0, numpy.sin) means :math:`1
+ sin(x)D^{2}`. Only used if derivative degree is None.
Returns:
numpy.array: Penalty matrix.
Examples:
>>> Monomial(nbasis=4).penalty(2)
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 4., 6.],
[ 0., 0., 6., 12.]])
References:
.. [RS05-5-6-2] Ramsay, J., Silverman, B. W. (2005). Specifying the
roughness penalty. In *Functional Data Analysis* (pp. 106-107).
Springer.
"""
if derivative_degree is None:
return self._numerical_penalty(coefficients)
integration_domain = self.domain_range[0]
# initialize penalty matrix as all zeros
penalty_matrix = numpy.zeros((self.nbasis, self.nbasis))
# iterate over the cartesion product of the basis system with itself
for ibasis in range(self.nbasis):
# notice that the index ibasis it is also the exponent of the
# monomial
# ifac is the factor resulting of deriving the monomial as many
# times as indicates de differential operator
if derivative_degree > 0:
ifac = ibasis
for k in range(2, derivative_degree + 1):
ifac *= ibasis - k + 1
else:
ifac = 1
for jbasis in range(self.nbasis):
# notice that the index jbasis it is also the exponent of the
# monomial
# jfac is the factor resulting of deriving the monomial as
# many times as indicates de differential operator
if derivative_degree > 0:
jfac = jbasis
for k in range(2, derivative_degree + 1):
jfac *= jbasis - k + 1
else:
jfac = 1
# if any of the two monomial has lower degree than the order of
# the derivative indicated by the differential operator that
# factor equals 0, so no calculation are needed
if (ibasis >= derivative_degree
and jbasis >= derivative_degree):
# Calculates exactly the result of the integral
# Exponent after applying the differential operator and
# integrating
ipow = ibasis + jbasis - 2 * derivative_degree + 1
# coefficient after integrating
penalty_matrix[ibasis, jbasis] = (
(integration_domain[1] ** ipow
- integration_domain[0] ** ipow)
* ifac * jfac / ipow)
penalty_matrix[jbasis, ibasis] = penalty_matrix[ibasis,
jbasis]
return penalty_matrix
def basis_of_product(self, other):
"""Multiplication of a Monomial Basis with other Basis"""
if not _same_domain(self.domain_range, other.domain_range):
raise ValueError("Ranges are not equal.")
if isinstance(other, Monomial):
return Monomial(self.domain_range, self.nbasis + other.nbasis)
return other.rbasis_of_product(self)
def rbasis_of_product(self, other):
"""Multiplication of a Monomial Basis with other Basis"""
return Basis.default_basis_of_product(self, other)
def _to_R(self):
drange = self.domain_range[0]
return "create.monomial.basis(rangeval = c(" + str(drange[0]) + "," +\
str(drange[1]) + "), nbasis = " + str(self.nbasis) + ")"
class BSpline(Basis):
r"""BSpline basis.
BSpline basis elements are defined recursively as:
.. math::
B_{i, 1}(x) = 1 \quad \text{if } t_i \le x < t_{i+1},
\quad 0 \text{ otherwise}
.. math::
B_{i, k}(x) = \frac{x - t_i}{t_{i+k} - t_i} B_{i, k-1}(x)
+ \frac{t_{i+k+1} - x}{t_{i+k+1} - t_{i+1}} B_{i+1, k-1}(x)
Where k indicates the order of the spline.
Implementation details: In order to allow a discontinuous behaviour at
the boundaries of the domain it is necessary to placing m knots at the
boundaries [RS05]_. This is automatically done so that the user only has to
specify a single knot at the boundaries.
Attributes:
domain_range (tuple): A tuple of length 2 containing the initial and
end values of the interval over which the basis can be evaluated.
nbasis (int): Number of functions in the basis.
order (int): Order of the splines. One greather than their degree.
knots (list): List of knots of the spline functions.
Examples:
Constructs specifying number of basis and order.
>>> bss = BSpline(nbasis=8, order=4)
If no order is specified defaults to 4 because cubic splines are
the most used. So the previous example is the same as:
>>> bss = BSpline(nbasis=8)
It is also possible to create a BSpline basis specifying the knots.
>>> bss = BSpline(knots=[0, 0.2, 0.4, 0.6, 0.8, 1])
Once we create a basis we can evaluate each of its functions at a
set of points.
>>> bss = BSpline(nbasis=3, order=3)
>>> bss.evaluate([0, 0.5, 1])
array([[ 1. , 0.25, 0. ],
[ 0. , 0.5 , 0. ],
[ 0. , 0.25, 1. ]])
And evaluates first derivative
>>> bss.evaluate([0, 0.5, 1], derivative=1)
array([[-2., -1., 0.],
[ 2., 0., -2.],
[ 0., 1., 2.]])
References:
.. [RS05] Ramsay, J., Silverman, B. W. (2005). *Functional Data
Analysis*. Springer. 50-51.
"""
def __init__(self, domain_range=None, nbasis=None, order=4, knots=None):
"""Bspline basis constructor.
Args:
domain_range (tuple, optional): Definition of the interval where
the basis defines a space. Defaults to (0,1) if knots are not
specified. If knots are specified defaults to the first and
last element of the knots.
nbasis (int, optional): Number of splines that form the basis.
order (int, optional): Order of the splines. One greater that
their degree. Defaults to 4 which mean cubic splines.
knots (array_like): List of knots of the splines. If domain_range
is specified the first and last elements of the knots have to
match with it.
"""
if domain_range is not None:
domain_range = _list_of_arrays(domain_range)
if len(domain_range) != 1:
raise ValueError("Domain range should be unidimensional.")
domain_range = domain_range[0]
# Knots default to equally space points in the domain_range
if knots is None:
if nbasis is None:
raise ValueError("Must provide either a list of knots or the"
"number of basis.")
if domain_range is None:
domain_range = (0, 1)
knots = list(numpy.linspace(*domain_range, nbasis - order + 2))
else:
knots = list(knots)
knots.sort()
if domain_range is None:
domain_range = (knots[0], knots[-1])
# nbasis default to number of knots + order of the splines - 2
if nbasis is None:
nbasis = len(knots) + order - 2
if domain_range is None:
domain_range = (knots[0], knots[-1])
if (nbasis - order + 2) < 2:
raise ValueError(f"The number of basis ({nbasis}) minus the order "
f"of the bspline ({order}) should be greater than "
f"3.")
if domain_range[0] != knots[0] or domain_range[1] != knots[-1]:
raise ValueError("The ends of the knots must be the same as "
"the domain_range.")
# Checks
if nbasis != order + len(knots) - 2:
raise ValueError("The number of basis has to equal the order "
"plus the number of knots minus 2.")
self.order = order
self.knots = list(knots)
super().__init__(domain_range, nbasis)
def _ndegenerated(self, penalty_degree):
"""Return number of 0 or nearly to 0 eigenvalues of the penalty matrix.
Args:
penalty_degree (int): Degree of the derivative used in the
calculation of the penalty matrix.
Returns:
int: number of close to 0 eigenvalues.
"""
return penalty_degree
def _compute_matrix(self, eval_points, derivative=0):
"""Compute the basis or its derivatives given a list of values.
It uses the scipy implementation of BSplines to compute the values
for each element of the basis.
Args:
eval_points (array_like): List of points where the basis system is
evaluated.
derivative (int, optional): Order of the derivative. Defaults to 0.
Returns:
(:obj:`numpy.darray`): Matrix whose rows are the values of the each
basis function or its derivatives at the values specified in
eval_points.
Implementation details: In order to allow a discontinuous behaviour at
the boundaries of the domain it is necessary to placing m knots at the
boundaries [RS05]_. This is automatically done so that the user only
has to specify a single knot at the boundaries.
References:
.. [RS05] Ramsay, J., Silverman, B. W. (2005). *Functional Data
Analysis*. Springer. 50-51.
"""
# Places m knots at the boundaries
knots = numpy.array([self.knots[0]] * (self.order - 1) + self.knots
+ [self.knots[-1]] * (self.order - 1))
# c is used the select which spline the function splev below computes
c = numpy.zeros(len(knots))
# Initialise empty matrix
mat = numpy.empty((self.nbasis, len(eval_points)))
# For each basis computes its value for each evaluation point
for i in range(self.nbasis):
# write a 1 in c in the position of the spline calculated in each
# iteration
c[i] = 1
# compute the spline
mat[i] = scipy.interpolate.splev(eval_points, (knots, c,
self.order - 1),
der=derivative)
c[i] = 0
return mat
def penalty(self, derivative_degree=None, coefficients=None):
r"""Return a penalty matrix given a differential operator.
The differential operator can be either a derivative of a certain
degree or a more complex operator.
The penalty matrix is defined as [RS05-5-6-2]_:
.. math::
R_{ij} = \int L\phi_i(s) L\phi_j(s) ds
where :math:`\phi_i(s)` for :math:`i=1, 2, ..., n` are the basis
functions and :math:`L` is a differential operator.
Args:
derivative_degree (int): Integer indicating the order of the
derivative or . For instance 2 means that the differential
operator is :math:`f''(x)`.
coefficients (list): List of coefficients representing a
differential operator. An iterable indicating
coefficients of derivatives (which can be functions). For
instance the tuple (1, 0, numpy.sin) means :math:`1
+ sin(x)D^{2}`. Only used if derivative degree is None.
Returns:
numpy.array: Penalty matrix.
References:
.. [RS05-5-6-2] Ramsay, J., Silverman, B. W. (2005). Specifying the
roughness penalty. In *Functional Data Analysis* (pp. 106-107).
Springer.
"""
if derivative_degree is not None:
if derivative_degree >= self.order:
raise ValueError(f"Penalty matrix cannot be evaluated for "
f"derivative of order {derivative_degree} for "
f"B-splines of order {self.order}")
if derivative_degree == self.order - 1:
# The derivative of the bsplines are constant in the intervals
# defined between knots
knots = numpy.array(self.knots)
mid_inter = (knots[1:] + knots[:-1]) / 2
constants = self.evaluate(mid_inter,
derivative=derivative_degree).T
knots_intervals = numpy.diff(self.knots)
# Integration of product of constants
return constants.T @ numpy.diag(knots_intervals) @ constants
if numpy.all(numpy.diff(self.knots) != 0):
# Compute exactly using the piecewise polynomial
# representation of splines
# Places m knots at the boundaries
knots = numpy.array(
[self.knots[0]] * (self.order - 1) + self.knots
+ [self.knots[-1]] * (self.order - 1))
# c is used the select which spline the function
# PPoly.from_spline below computes
c = numpy.zeros(len(knots))
# Initialise empty list to store the piecewise polynomials
ppoly_lst = []
no_0_intervals = numpy.where(numpy.diff(knots) > 0)[0]
# For each basis gets its piecewise polynomial representation
for i in range(self.nbasis):
# write a 1 in c in the position of the spline
# transformed in each iteration
c[i] = 1
# gets the piecewise polynomial representation and gets
# only the positions for no zero length intervals
# This polynomial are defined relatively to the knots
# meaning that the column i corresponds to the ith knot.
# Let the ith not be a
# Then f(x) = pp(x - a)
pp = (PPoly.from_spline((knots, c, self.order - 1))
.c[:, no_0_intervals])
# We need the actual coefficients of f, not pp. So we
# just recursively calculate the new coefficients
coeffs = pp.copy()
for j in range(self.order - 1):
coeffs[j + 1:] += (
(binom(self.order - j - 1,
range(1, self.order - j))
* numpy.vstack([(-a) ** numpy.array(
range(1, self.order - j)) for a in
self.knots[:-1]])
).T * pp[j])
ppoly_lst.append(coeffs)
c[i] = 0
# Now for each pair of basis computes the inner product after
# applying the linear differential operator
penalty_matrix = numpy.zeros((self.nbasis, self.nbasis))
for interval in range(len(no_0_intervals)):
for i in range(self.nbasis):
poly_i = numpy.trim_zeros(ppoly_lst[i][:,
interval], 'f')
if len(poly_i) <= derivative_degree:
# if the order of the polynomial is lesser or
# equal to the derivative the result of the
# integral will be 0
continue
# indefinite integral
integral = polyint(_polypow(polyder(
poly_i, derivative_degree), 2))
# definite integral
penalty_matrix[i, i] += numpy.diff(polyval(
integral, self.knots[interval: interval + 2]))[0]
for j in range(i + 1, self.nbasis):
poly_j = numpy.trim_zeros(ppoly_lst[j][:,
interval], 'f')
if len(poly_j) <= derivative_degree:
# if the order of the polynomial is lesser
# or equal to the derivative the result of
# the integral will be 0
continue
# indefinite integral
integral = polyint(
polymul(polyder(poly_i, derivative_degree),
polyder(poly_j, derivative_degree)))
# definite integral
penalty_matrix[i, j] += numpy.diff(polyval(
integral, self.knots[interval: interval + 2])
)[0]
penalty_matrix[j, i] = penalty_matrix[i, j]
return penalty_matrix
else:
# if the order of the derivative is greater or equal to the order
# of the bspline minus 1
if len(coefficients) >= self.order:
raise ValueError(f"Penalty matrix cannot be evaluated for "
f"derivative of order {len(coefficients) - 1} "
f"for B-splines of order {self.order}")
# compute using the inner product
return self._numerical_penalty(coefficients)
def rescale(self, domain_range=None):
r"""Return a copy of the basis with a new domain range, with the
corresponding values rescaled to the new bounds.
The knots of the BSpline will be rescaled in the new interval.
Args:
domain_range (tuple, optional): Definition of the interval where
the basis defines a space. Defaults uses the same as the
original basis.
"""
knots = numpy.array(self.knots, dtype=numpy.dtype('float'))
if domain_range is not None: # Rescales the knots