/
polytemplate.py
688 lines (566 loc) · 21.8 KB
/
polytemplate.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
"""
Template for the Chebyshev and Polynomial classes.
This module houses a Python string module Template object (see, e.g.,
http://docs.python.org/library/string.html#template-strings) used by
the `polynomial` and `chebyshev` modules to implement their respective
`Polynomial` and `Chebyshev` classes. It provides a mechanism for easily
creating additional specific polynomial classes (e.g., Legendre, Jacobi,
etc.) in the future, such that all these classes will have a common API.
"""
import string
import sys
if sys.version_info[0] >= 3:
rel_import = "from . import"
else:
rel_import = "import"
polytemplate = string.Template('''
from __future__ import division
REL_IMPORT polyutils as pu
import numpy as np
class $name(pu.PolyBase) :
"""A $name series class.
Parameters
----------
coef : array_like
$name coefficients, in increasing order. For example,
``(1, 2, 3)`` implies ``P_0 + 2P_1 + 3P_2`` where the
``P_i`` are a graded polynomial basis.
domain : (2,) array_like
Domain to use. The interval ``[domain[0], domain[1]]`` is mapped to
the interval ``$domain`` by shifting and scaling.
Attributes
----------
coef : (N,) array
$name coefficients, from low to high.
domain : (2,) array_like
Domain that is mapped to ``$domain``.
Class Attributes
----------------
maxpower : int
Maximum power allowed, i.e., the largest number ``n`` such that
``p(x)**n`` is allowed. This is to limit runaway polynomial size.
domain : (2,) ndarray
Default domain of the class.
Notes
-----
It is important to specify the domain for many uses of graded polynomial,
for instance in fitting data. This is because many of the important
properties of the polynomial basis only hold in a specified interval and
thus the data must be mapped into that domain in order to benefit.
Examples
--------
"""
# Limit runaway size. T_n^m has degree n*2^m
maxpower = 16
# Default domain
domain = np.array($domain)
# Don't let participate in array operations. Value doesn't matter.
__array_priority__ = 0
def __init__(self, coef, domain=$domain) :
[coef, domain] = pu.as_series([coef, domain], trim=False)
if len(domain) != 2 :
raise ValueError("Domain has wrong number of elements.")
self.coef = coef
self.domain = domain
def __repr__(self):
format = "%s(%s, %s)"
coef = repr(self.coef)[6:-1]
domain = repr(self.domain)[6:-1]
return format % ('$name', coef, domain)
def __str__(self) :
format = "%s(%s, %s)"
return format % ('$nick', str(self.coef), str(self.domain))
# Pickle and copy
def __getstate__(self) :
ret = self.__dict__.copy()
ret['coef'] = self.coef.copy()
ret['domain'] = self.domain.copy()
return ret
def __setstate__(self, dict) :
self.__dict__ = dict
# Call
def __call__(self, arg) :
off, scl = pu.mapparms(self.domain, $domain)
arg = off + scl*arg
return ${nick}val(arg, self.coef)
def __iter__(self) :
return iter(self.coef)
def __len__(self) :
return len(self.coef)
# Numeric properties.
def __neg__(self) :
return self.__class__(-self.coef, self.domain)
def __pos__(self) :
return self
def __add__(self, other) :
"""Returns sum"""
if isinstance(other, self.__class__) :
if np.all(self.domain == other.domain) :
coef = ${nick}add(self.coef, other.coef)
else :
raise PolyDomainError()
else :
try :
coef = ${nick}add(self.coef, other)
except :
return NotImplemented
return self.__class__(coef, self.domain)
def __sub__(self, other) :
"""Returns difference"""
if isinstance(other, self.__class__) :
if np.all(self.domain == other.domain) :
coef = ${nick}sub(self.coef, other.coef)
else :
raise PolyDomainError()
else :
try :
coef = ${nick}sub(self.coef, other)
except :
return NotImplemented
return self.__class__(coef, self.domain)
def __mul__(self, other) :
"""Returns product"""
if isinstance(other, self.__class__) :
if np.all(self.domain == other.domain) :
coef = ${nick}mul(self.coef, other.coef)
else :
raise PolyDomainError()
else :
try :
coef = ${nick}mul(self.coef, other)
except :
return NotImplemented
return self.__class__(coef, self.domain)
def __div__(self, other):
# set to __floordiv__ /.
return self.__floordiv__(other)
def __truediv__(self, other) :
# there is no true divide if the rhs is not a scalar, although it
# could return the first n elements of an infinite series.
# It is hard to see where n would come from, though.
if isinstance(other, self.__class__) :
if len(other.coef) == 1 :
coef = div(self.coef, other.coef)
else :
return NotImplemented
elif np.isscalar(other) :
coef = self.coef/other
else :
return NotImplemented
return self.__class__(coef, self.domain)
def __floordiv__(self, other) :
"""Returns the quotient."""
if isinstance(other, self.__class__) :
if np.all(self.domain == other.domain) :
quo, rem = ${nick}div(self.coef, other.coef)
else :
raise PolyDomainError()
else :
try :
quo, rem = ${nick}div(self.coef, other)
except :
return NotImplemented
return self.__class__(quo, self.domain)
def __mod__(self, other) :
"""Returns the remainder."""
if isinstance(other, self.__class__) :
if np.all(self.domain == other.domain) :
quo, rem = ${nick}div(self.coef, other.coef)
else :
raise PolyDomainError()
else :
try :
quo, rem = ${nick}div(self.coef, other)
except :
return NotImplemented
return self.__class__(rem, self.domain)
def __divmod__(self, other) :
"""Returns quo, remainder"""
if isinstance(other, self.__class__) :
if np.all(self.domain == other.domain) :
quo, rem = ${nick}div(self.coef, other.coef)
else :
raise PolyDomainError()
else :
try :
quo, rem = ${nick}div(self.coef, other)
except :
return NotImplemented
return self.__class__(quo, self.domain), self.__class__(rem, self.domain)
def __pow__(self, other) :
try :
coef = ${nick}pow(self.coef, other, maxpower = self.maxpower)
except :
raise
return self.__class__(coef, self.domain)
def __radd__(self, other) :
try :
coef = ${nick}add(other, self.coef)
except :
return NotImplemented
return self.__class__(coef, self.domain)
def __rsub__(self, other):
try :
coef = ${nick}sub(other, self.coef)
except :
return NotImplemented
return self.__class__(coef, self.domain)
def __rmul__(self, other) :
try :
coef = ${nick}mul(other, self.coef)
except :
return NotImplemented
return self.__class__(coef, self.domain)
def __rdiv__(self, other):
# set to __floordiv__ /.
return self.__rfloordiv__(other)
def __rtruediv__(self, other) :
# there is no true divide if the rhs is not a scalar, although it
# could return the first n elements of an infinite series.
# It is hard to see where n would come from, though.
if len(self.coef) == 1 :
try :
quo, rem = ${nick}div(other, self.coef[0])
except :
return NotImplemented
return self.__class__(quo, self.domain)
def __rfloordiv__(self, other) :
try :
quo, rem = ${nick}div(other, self.coef)
except :
return NotImplemented
return self.__class__(quo, self.domain)
def __rmod__(self, other) :
try :
quo, rem = ${nick}div(other, self.coef)
except :
return NotImplemented
return self.__class__(rem, self.domain)
def __rdivmod__(self, other) :
try :
quo, rem = ${nick}div(other, self.coef)
except :
return NotImplemented
return self.__class__(quo, self.domain), self.__class__(rem, self.domain)
# Enhance me
# some augmented arithmetic operations could be added here
def __eq__(self, other) :
res = isinstance(other, self.__class__) \
and len(self.coef) == len(other.coef) \
and np.all(self.domain == other.domain) \
and np.all(self.coef == other.coef)
return res
def __ne__(self, other) :
return not self.__eq__(other)
#
# Extra numeric functions.
#
def degree(self) :
"""The degree of the series.
Notes
-----
.. versionadded:: 1.5.0
"""
return len(self) - 1
def cutdeg(self, deg) :
"""Truncate series to the given degree.
Reduce the degree of the $name series to `deg` by discarding the
high order terms. If `deg` is greater than the current degree a
copy of the current series is returned. This can be useful in least
squares where the coefficients of the high degree terms may be very
small.
Parameters
----------
deg : non-negative int
The series is reduced to degree `deg` by discarding the high
order terms. The value of `deg` must be a non-negative integer.
Returns
-------
new_instance : $name
New instance of $name with reduced degree.
Notes
-----
.. versionadded:: 1.5.0
"""
return self.truncate(deg + 1)
def convert(self, domain=None, kind=None) :
"""Convert to different class and/or domain.
Parameters
----------
domain : {None, array_like}
The domain of the new series type instance. If the value is is
``None``, then the default domain of `kind` is used.
kind : {None, class}
The polynomial series type class to which the current instance
should be converted. If kind is ``None``, then the class of the
current instance is used.
Returns
-------
new_series_instance : `kind`
The returned class can be of different type than the current
instance and/or have a different domain.
Examples
--------
Notes
-----
Conversion between domains and class types can result in
numerically ill defined series.
"""
if kind is None :
kind = $name
if domain is None :
domain = kind.domain
return self(kind.identity(domain))
def mapparms(self) :
"""Return the mapping parameters.
The returned values define a linear map ``off + scl*x`` that is
applied to the input arguments before the series is evaluated. The
of the map depend on the domain; if the current domain is equal to
the default domain ``$domain`` the resulting map is the identity.
If the coeffients of the ``$name`` instance are to be used
separately, then the linear function must be substituted for the
``x`` in the standard representation of the base polynomials.
Returns
-------
off, scl : floats or complex
The mapping function is defined by ``off + scl*x``.
Notes:
------
If the current domain is the interval ``[l_1, r_1]`` and the default
interval is ``[l_2, r_2]``, then the linear mapping function ``L`` is
defined by the equations:
L(l_1) = l_2
L(r_1) = r_2
"""
return pu.mapparms(self.domain, $domain)
def trim(self, tol=0) :
"""Remove small leading coefficients
Remove leading coefficients until a coefficient is reached whose
absolute value greater than `tol` or the beginning of the series is
reached. If all the coefficients would be removed the series is set to
``[0]``. A new $name instance is returned with the new coefficients.
The current instance remains unchanged.
Parameters
----------
tol : non-negative number.
All trailing coefficients less than `tol` will be removed.
Returns
-------
new_instance : $name
Contains the new set of coefficients.
"""
return self.__class__(pu.trimcoef(self.coef, tol), self.domain)
def truncate(self, size) :
"""Truncate series to length `size`.
Reduce the $name series to length `size` by discarding the high
degree terms. The value of `size` must be a positive integer. This
can be useful in least squares where the coefficients of the
high degree terms may be very small.
Parameters
----------
size : positive int
The series is reduced to length `size` by discarding the high
degree terms. The value of `size` must be a positive integer.
Returns
-------
new_instance : $name
New instance of $name with truncated coefficients.
"""
isize = int(size)
if isize != size or isize < 1 :
raise ValueError("size must be a positive integer")
if isize >= len(self.coef) :
return self.__class__(self.coef, self.domain)
else :
return self.__class__(self.coef[:isize], self.domain)
def copy(self) :
"""Return a copy.
A new instance of $name is returned that has the same
coefficients and domain as the current instance.
Returns
-------
new_instance : $name
New instance of $name with the same coefficients and domain.
"""
return self.__class__(self.coef, self.domain)
def integ(self, m=1, k=[], lbnd=None) :
"""Integrate.
Return an instance of $name that is the definite integral of the
current series. Refer to `${nick}int` for full documentation.
Parameters
----------
m : non-negative int
The number of integrations to perform.
k : array_like
Integration constants. The first constant is applied to the
first integration, the second to the second, and so on. The
list of values must less than or equal to `m` in length and any
missing values are set to zero.
lbnd : Scalar
The lower bound of the definite integral.
Returns
-------
integral : $name
The integral of the series using the same domain.
See Also
--------
`${nick}int` : similar function.
`${nick}der` : similar function for derivative.
"""
off, scl = self.mapparms()
if lbnd is None :
lbnd = 0
else :
lbnd = off + scl*lbnd
coef = ${nick}int(self.coef, m, k, lbnd, 1./scl)
return self.__class__(coef, self.domain)
def deriv(self, m=1):
"""Differentiate.
Return an instance of $name that is the derivative of the current
series. Refer to `${nick}der` for full documentation.
Parameters
----------
m : non-negative int
The number of integrations to perform.
Returns
-------
derivative : $name
The derivative of the series using the same domain.
See Also
--------
`${nick}der` : similar function.
`${nick}int` : similar function for integration.
"""
off, scl = self.mapparms()
coef = ${nick}der(self.coef, m, scl)
return self.__class__(coef, self.domain)
def roots(self) :
"""Return list of roots.
Return ndarray of roots for this series. See `${nick}roots` for
full documentation. Note that the accuracy of the roots is likely to
decrease the further outside the domain they lie.
See Also
--------
`${nick}roots` : similar function
`${nick}fromroots` : function to go generate series from roots.
"""
roots = ${nick}roots(self.coef)
return pu.mapdomain(roots, $domain, self.domain)
def linspace(self, n=100):
"""Return x,y values at equally spaced points in domain.
Returns x, y values at `n` equally spaced points across domain.
Here y is the value of the polynomial at the points x. This is
intended as a plotting aid.
Paramters
---------
n : int, optional
Number of point pairs to return. The default value is 100.
Returns
-------
x, y : ndarrays
``x`` is equal to linspace(self.domain[0], self.domain[1], n)
``y`` is the polynomial evaluated at ``x``.
.. versionadded:: 1.5.0
"""
x = np.linspace(self.domain[0], self.domain[1], n)
y = self(x)
return x, y
@staticmethod
def fit(x, y, deg, domain=None, rcond=None, full=False, w=None) :
"""Least squares fit to data.
Return a `$name` instance that is the least squares fit to the data
`y` sampled at `x`. Unlike ${nick}fit, the domain of the returned
instance can be specified and this will often result in a superior
fit with less chance of ill conditioning. See ${nick}fit for full
documentation of the implementation.
Parameters
----------
x : array_like, shape (M,)
x-coordinates of the M sample points ``(x[i], y[i])``.
y : array_like, shape (M,) or (M, K)
y-coordinates of the sample points. Several data sets of sample
points sharing the same x-coordinates can be fitted at once by
passing in a 2D-array that contains one dataset per column.
deg : int
Degree of the fitting polynomial
domain : {None, [beg, end], []}, optional
Domain to use for the returned $name instance. If ``None``,
then a minimal domain that covers the points `x` is chosen. If
``[]`` the default domain ``$domain`` is used. The default
value is $domain in numpy 1.4.x and ``None`` in later versions.
The ``'[]`` value was added in numpy 1.5.0.
rcond : float, optional
Relative condition number of the fit. Singular values smaller
than this relative to the largest singular value will be
ignored. The default value is len(x)*eps, where eps is the
relative precision of the float type, about 2e-16 in most
cases.
full : bool, optional
Switch determining nature of return value. When it is False
(the default) just the coefficients are returned, when True
diagnostic information from the singular value decomposition is
also returned.
w : array_like, shape (M,), optional
Weights. If not None the contribution of each point
``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
weights are chosen so that the errors of the products
``w[i]*y[i]`` all have the same variance. The default value is
None.
.. versionadded:: 1.5.0
Returns
-------
least_squares_fit : instance of $name
The $name instance is the least squares fit to the data and
has the domain specified in the call.
[residuals, rank, singular_values, rcond] : only if `full` = True
Residuals of the least-squares fit, the effective rank of the
scaled Vandermonde matrix and its singular values, and the
specified value of `rcond`. For more details, see
`linalg.lstsq`.
See Also
--------
${nick}fit : similar function
"""
if domain is None :
domain = pu.getdomain(x)
elif domain == [] :
domain = $domain
xnew = pu.mapdomain(x, domain, $domain)
res = ${nick}fit(xnew, y, deg, w=w, rcond=rcond, full=full)
if full :
[coef, status] = res
return $name(coef, domain=domain), status
else :
coef = res
return $name(coef, domain=domain)
@staticmethod
def fromroots(roots, domain=$domain) :
"""Return $name object with specified roots.
See ${nick}fromroots for full documentation.
See Also
--------
${nick}fromroots : equivalent function
"""
if domain is None :
domain = pu.getdomain(roots)
rnew = pu.mapdomain(roots, domain, $domain)
coef = ${nick}fromroots(rnew)
return $name(coef, domain=domain)
@staticmethod
def identity(domain=$domain) :
"""Identity function.
If ``p`` is the returned $name object, then ``p(x) == x`` for all
values of x.
Parameters:
-----------
domain : array_like
The resulting array must be if the form ``[beg, end]``, where
``beg`` and ``end`` are the endpoints of the domain.
Returns:
--------
identity : $name object
"""
off, scl = pu.mapparms($domain, domain)
coef = ${nick}line(off, scl)
return $name(coef, domain)
'''.replace('REL_IMPORT', rel_import))