-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathutpm.py
3385 lines (2536 loc) · 93.2 KB
/
utpm.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
"""
Implementation of the univariate matrix polynomial.
The algebraic class is
M[t]/<t^D>
where M is the ring of matrices and t an external parameter
"""
import math
import numpy.linalg
import numpy
import scipy.linalg
from ..base_type import Ring
from .._npversion import NumpyVersion
from .algorithms import RawAlgorithmsMixIn, broadcast_arrays_shape
import operator
from algopy import nthderiv
import algopy.utils
if NumpyVersion(numpy.version.version) >= '1.6.0':
def workaround_strides_function(x, y, fun):
"""
peform the operation fun(x,y)
where fun = operator.iadd, operator.imul, operator.setitem, etc.
workaround for the bug
https://github.com/numpy/numpy/issues/2705
Replace this function once the bug has been fixed.
This function assumes that x and y have the same shape.
Parameters
------------
x: UTPM instance
y: UTPM instance
fun: function from the module operator
"""
if x.shape != y.shape:
raise ValueError('x.shape != y.shape')
if x.ndim == 0:
fun(x, y)
else:
for i in range(x.shape[0]):
workaround_strides_function(x[i, ...], y[i, ...], fun)
else:
def workaround_strides_function(x, y, fun):
fun(x, y)
class UTPM(Ring, RawAlgorithmsMixIn):
r"""
UTPM == Univariate Taylor Polynomial of Matrices
This class implements univariate Taylor arithmetic on matrices, i.e.
[A]_D = \sum_{d=0}^{D-1} A_d T^d
Input:
in the most general form, the input is a 4-tensor.
We use the notation:
D: degree of the Taylor series
P: number of directions
N: number of rows of A_0
M: number of cols of A_0
shape([A]) = (D,P,N,M)
The reason for this choice is that the (N,M) matrix is the elementary type,
so that memory should be contiguous.
Then, at each operation, the code performed to compute
v_d has to be repeated for every direction.
E.g. a multiplication
[w] = [u]*[v] =
[[u_11, ..., u_1Ndir],
...
[u_D1, ..., u_DNdir]] +
[[v11, ..., v_1Ndir],
...
[v_D1, ..., v_DNdir]] =
[[ u_11 + v_11, ..., u_1Ndir + v_1Ndir],
...
[[ u_D1 + v_D1, ..., u_DNdir + v_DNdir]]
For ufuncs this arrangement is advantageous, because in this order,
memory chunks of size Ndir are used and the operation on each element is the
same. This is desireable to avoid cache misses.
See for example __mul__: there, operations of
self.data[:d+1,:,:,:]* rhs.data[d::-1,:,:,:]
has to be performed.
One can see, that contiguous memory blocks are used for such operations.
A disadvantage of this arrangement is: it seems unnatural.
It is easier to regard each direction separately.
"""
__array_priority__ = 2
def __init__(self, X):
"""
INPUT:
shape([X]) = (D,P,N,M)
"""
Ndim = numpy.ndim(X)
if Ndim >= 2:
self.data = numpy.asarray(X)
self.data = self.data
else:
raise NotImplementedError()
def __getitem__(self, sl):
if not isinstance(sl, tuple):
sl = (sl,)
tmp = self.data.__getitem__((slice(None),slice(None)) + sl)
return self.__class__(tmp)
def __setitem__(self, sl, rhs):
if isinstance(rhs, UTPM):
if type(sl) == int or sl == Ellipsis or isinstance(sl, slice):
sl = (sl,)
x_data, y_data = UTPM._broadcast_arrays(self.data.__getitem__((slice(None),slice(None)) + sl), rhs.data)
return x_data.__setitem__(Ellipsis, y_data)
else:
if type(sl) == int or sl == Ellipsis or isinstance(sl, slice):
sl = (sl,)
self.data.__setitem__((slice(1,None),slice(None)) + sl, 0)
return self.data.__setitem__((0,slice(None)) + sl, rhs)
@property
def dtype(self):
return self.data.dtype
@classmethod
def pb___getitem__(cls, ybar, x, sl, y, out = None):
"""
y = getitem(x, sl)
Warning:
this includes a workaround for tuples, e.g. for Q,R = qr(A)
where A,Q,R are Function objects
"""
if out is None:
raise NotImplementedError('I\'m not sure that this makes sense')
# workaround for qr and eigh
if isinstance( out[0], tuple):
tmp = list(out[0])
tmp[sl] += ybar
# usual workflow
else:
# print 'out=\n', out[0][sl]
# print 'ybar=\n',ybar
out[0][sl] = ybar
return out
@classmethod
def pb_getitem(cls, ybar, x, sl, y, out = None):
# print 'ybar=\n',ybar
retval = cls.pb___getitem__(ybar, x, sl, y, out = out)
# print 'retval=\n',retval[0]
return retval
@classmethod
def as_utpm(cls, x):
""" tries to convert a container (e.g. list or numpy.array) with UTPM elements as instances to a UTPM instance"""
x_shp = numpy.shape(x)
xr = numpy.ravel(x)
# print 'x=', x
# print 'xr=',xr
# print 'x.dtype', x.dtype
D,P = xr[0].data.shape[:2]
shp = xr[0].data.shape[2:]
if not isinstance(shp, tuple): shp = (shp,)
if not isinstance(x_shp, tuple): x_shp = (x_shp,)
y = UTPM(numpy.zeros((D,P) + x_shp + shp))
yr = UTPM( y.data.reshape((D,P) + (numpy.prod(x_shp, dtype=int),) + shp))
# print yr.shape
# print yr.data.shape
for n in range(len(xr)):
# print yr[n].shape
# print xr[n].shape
yr[n] = xr[n]
return y
def get_flat(self):
return UTPM(self.data.reshape(self.data.shape[:2] + (numpy.prod(self.data.shape[2:]),) ))
flat = property(get_flat)
def coeff_op(self, sl, shp):
"""
operation to extract UTP coefficients of x
defined by the slice sl creates a new
UTPM instance where the coefficients have the shape as defined
by shp
Parameters
----------
x: UTPM instance
sl: tuple of slice instance
shp: tuple
Returns
-------
UTPM instance
"""
tmp = self.data.__getitem__(sl)
tmp = tmp.reshape(shp)
return self.__class__(tmp)
@classmethod
def pb_coeff_op(cls, ybar, x, sl, shp, out = None):
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar = out[0]
# step 1: revert reshape
old_shp = x.data.__getitem__(sl).shape
tmp_data = ybar.data.reshape(old_shp)
# print('tmp_data.shape=',tmp_data.shape)
# step 2: revert getitem
tmp2 = xbar.data[::-1].__getitem__(sl)
tmp2 += tmp_data[::-1,...]
return xbar
@classmethod
def pb___setitem__(cls, y, sl, x, out = None):
"""
y.__setitem(sl,x)
"""
if out is None:
raise NotImplementedError('I\'m not sure if this makes sense')
ybar, dummy, xbar = out
# print 'xbar =', xbar
# print 'ybar =', ybar
xbar += ybar[sl]
ybar[sl].data[...] = 0.
# print 'funcargs=',funcargs
# print y[funcargs[0]]
@classmethod
def pb_setitem(cls, y, sl, x, out = None):
return cls.pb___setitem__(y, sl, x, out = out)
def __add__(self,rhs):
if numpy.isscalar(rhs):
dtype = numpy.promote_types(self.data.dtype, type(rhs))
retval = UTPM(numpy.zeros(self.data.shape, dtype=dtype))
retval.data[...] = self.data
retval.data[0,:] += rhs
return retval
elif isinstance(rhs,numpy.ndarray) and rhs.dtype == object:
if not isinstance(rhs.flatten()[0], UTPM):
err_str = 'you are trying to perform an operation involving 1) a UTPM instance and 2)a numpy.ndarray with elements of type %s\n'%type(rhs.flatten()[0])
err_str+= 'this operation is not supported!\n'
raise NotImplementedError(err_str)
else:
err_str = 'binary operations between UTPM instances and object arrays are not supported'
raise NotImplementedError(err_str)
elif isinstance(rhs, numpy.ndarray):
rhs_shape = rhs.shape
if numpy.isscalar(rhs_shape):
rhs_shape = (rhs_shape,)
x_data, y_data = UTPM._broadcast_arrays(self.data, rhs.reshape((1,1)+rhs_shape))
dtype = numpy.promote_types(x_data.dtype, y_data.dtype)
z_data = numpy.zeros(x_data.shape, dtype=dtype)
z_data[...] = x_data
z_data[0] += y_data[0]
return UTPM(z_data)
else:
x_data, y_data = UTPM._broadcast_arrays(self.data, rhs.data)
return UTPM(x_data + y_data)
def __sub__(self,rhs):
if numpy.isscalar(rhs):
dtype = numpy.promote_types(self.data.dtype, type(rhs))
retval = UTPM(numpy.zeros(self.data.shape, dtype=dtype))
retval.data[...] = self.data
retval.data[0,:] -= rhs
return retval
elif isinstance(rhs,numpy.ndarray) and rhs.dtype == object:
if not isinstance(rhs.flatten()[0], UTPM):
err_str = 'you are trying to perform an operation involving 1) a UTPM instance and 2)a numpy.ndarray with elements of type %s\n'%type(rhs.flatten()[0])
err_str+= 'this operation is not supported!\n'
raise NotImplementedError(err_str)
else:
err_str = 'binary operations between UTPM instances and object arrays are not supported'
raise NotImplementedError(err_str)
elif isinstance(rhs, numpy.ndarray):
rhs_shape = rhs.shape
if numpy.isscalar(rhs_shape):
rhs_shape = (rhs_shape,)
x_data, y_data = UTPM._broadcast_arrays(self.data, rhs.reshape((1,1)+rhs_shape))
dtype = numpy.promote_types(x_data.dtype, y_data.dtype)
z_data = numpy.zeros(x_data.shape, dtype=dtype)
z_data[...] = x_data
z_data[0] -= y_data[0]
return UTPM(z_data)
else:
x_data, y_data = UTPM._broadcast_arrays(self.data, rhs.data)
return UTPM(x_data - y_data)
def __mul__(self,rhs):
if numpy.isscalar(rhs):
return UTPM( self.data * rhs)
elif isinstance(rhs,numpy.ndarray) and rhs.dtype == object:
if not isinstance(rhs.flatten()[0], UTPM):
err_str = 'you are trying to perform an operation involving 1) a UTPM instance and 2)a numpy.ndarray with elements of type %s\n'%type(rhs.flatten()[0])
err_str+= 'this operation is not supported!\n'
raise NotImplementedError(err_str)
else:
err_str = 'binary operations between UTPM instances and object arrays are not supported'
raise NotImplementedError(err_str)
elif isinstance(rhs,numpy.ndarray):
rhs_shape = rhs.shape
if numpy.isscalar(rhs_shape):
rhs_shape = (rhs_shape,)
x_data, y_data = UTPM._broadcast_arrays(self.data, rhs.reshape((1,1)+rhs_shape))
return UTPM(x_data * y_data)
x_data, y_data = UTPM._broadcast_arrays(self.data, rhs.data)
dtype = numpy.promote_types(x_data.dtype, y_data.dtype)
z_data = numpy.zeros(x_data.shape, dtype=dtype)
self._mul(x_data, y_data, z_data)
return self.__class__(z_data)
def __truediv__(self,rhs):
if numpy.isscalar(rhs):
return UTPM( self.data/rhs)
elif isinstance(rhs,numpy.ndarray) and rhs.dtype == object:
if not isinstance(rhs.flatten()[0], UTPM):
err_str = 'you are trying to perform an operation involving 1) a UTPM instance and 2)a numpy.ndarray with elements of type %s\n'%type(rhs.flatten()[0])
err_str+= 'this operation is not supported!\n'
raise NotImplementedError(err_str)
else:
err_str = 'binary operations between UTPM instances and object arrays are not supported'
raise NotImplementedError(err_str)
elif isinstance(rhs,numpy.ndarray):
rhs_shape = rhs.shape
if numpy.isscalar(rhs_shape):
rhs_shape = (rhs_shape,)
x_data, y_data = UTPM._broadcast_arrays(self.data, rhs.reshape((1,1)+rhs_shape))
return UTPM(x_data / y_data)
x_data, y_data = UTPM._broadcast_arrays(self.data, rhs.data)
dtype = numpy.promote_types(x_data.dtype, y_data.dtype)
z_data = numpy.zeros(x_data.shape, dtype=dtype)
self._truediv(x_data, y_data, z_data)
return self.__class__(z_data)
def __floordiv__(self, rhs):
"""
self // rhs
use L'Hopital's rule
"""
x_data, y_data = UTPM._broadcast_arrays(self.data, rhs.data)
dtype = numpy.promote_types(x_data.dtype, y_data.dtype)
z_data = numpy.zeros(x_data.shape, dtype=dtype)
self._floordiv(x_data, y_data, z_data)
return self.__class__(z_data)
def __pow__(self,r):
if isinstance(r, UTPM):
return UTPM.exp(UTPM.log(self)*r)
else:
x_data = self.data
y_data = numpy.zeros_like(x_data)
self._pow_real(x_data, r, y_data)
return self.__class__(y_data)
def __rpow__(self,r):
return UTPM.exp(numpy.log(r)*self)
@classmethod
def pb___pow__(cls, ybar, x, r, y, out = None):
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar = out[0]
if isinstance(r, cls):
raise NotImplementedError('r must be int or float, or use the identity x**y = exp(log(x)*y)')
cls._pb_pow_real(ybar.data, x.data, r, y.data, out = xbar.data)
return xbar
@classmethod
def pb_pow(cls, ybar, x, r, y, out = None):
retval = cls.pb___pow__(ybar, x, r, y, out = out)
return retval
def __radd__(self,rhs):
return self + rhs
def __rsub__(self, other):
return -self + other
def __rmul__(self,rhs):
return self * rhs
def __rtruediv__(self, rhs):
tmp = self.zeros_like()
tmp.data[0,...] = rhs
return tmp/self
def __iadd__(self,rhs):
if isinstance(rhs,numpy.ndarray) and rhs.dtype == object:
raise NotImplementedError('should implement that')
elif numpy.isscalar(rhs) or isinstance(rhs,numpy.ndarray):
self.data[0,...] += rhs
else:
self_data, rhs_data = UTPM._broadcast_arrays(self.data, rhs.data)
# self_data[...] += rhs_data[...]
numpy.add(self_data, rhs_data, out=self_data, casting="unsafe")
return self
def __isub__(self,rhs):
if isinstance(rhs,numpy.ndarray) and rhs.dtype == object:
raise NotImplementedError('should implement that')
elif numpy.isscalar(rhs) or isinstance(rhs,numpy.ndarray):
self.data[0,...] -= rhs
else:
self_data, rhs_data = UTPM._broadcast_arrays(self.data, rhs.data)
self_data[...] -= rhs_data[...]
return self
def __imul__(self,rhs):
(D,P) = self.data.shape[:2]
if isinstance(rhs,numpy.ndarray) and rhs.dtype == object:
raise NotImplementedError('should implement that')
elif numpy.isscalar(rhs) or isinstance(rhs,numpy.ndarray):
for d in range(D):
for p in range(P):
self.data[d,p,...] *= rhs
else:
for d in range(D)[::-1]:
for p in range(P):
self.data[d,p,...] *= rhs.data[0,p,...]
for c in range(d):
self.data[d,p,...] += self.data[c,p,...] * rhs.data[d-c,p,...]
return self
def __itruediv__(self,rhs):
(D,P) = self.data.shape[:2]
if isinstance(rhs,numpy.ndarray) and rhs.dtype == object:
raise NotImplementedError('should implement that')
elif numpy.isscalar(rhs) or isinstance(rhs,numpy.ndarray):
self.data[...] /= rhs
else:
retval = self.clone()
for d in range(D):
retval.data[d,:,...] = 1./ rhs.data[0,:,...] * ( self.data[d,:,...] - numpy.sum(retval.data[:d,:,...] * rhs.data[d:0:-1,:,...], axis=0))
self.data[...] = retval.data[...]
return self
__div__ = __truediv__
__idiv__ = __itruediv__
__rdiv__ = __rtruediv__
def sqrt(self):
retval = self.clone()
self._sqrt(self.data, out = retval.data)
return retval
@classmethod
def pb_sqrt(cls, ybar, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
cls._pb_sqrt(ybar.data, x.data, y.data, out = xbar.data)
return out
def exp(self):
""" computes y = exp(x) in UTP arithmetic"""
retval = self.clone()
self._exp(self.data, out = retval.data)
return retval
@classmethod
def pb_exp(cls, ybar, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
cls._pb_exp(ybar.data, x.data, y.data, out = xbar.data)
return out
def expm1(self):
""" computes y = expm1(x) in UTP arithmetic"""
retval = self.clone()
self._expm1(self.data, out = retval.data)
return retval
@classmethod
def pb_expm1(cls, ybar, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
cls._pb_expm1(ybar.data, x.data, y.data, out = xbar.data)
return out
def log(self):
""" computes y = log(x) in UTP arithmetic"""
retval = self.clone()
self._log(self.data, out = retval.data)
return retval
@classmethod
def pb_log(cls, ybar, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
cls._pb_log(ybar.data, x.data, y.data, out = xbar.data)
return xbar
def log1p(self):
""" computes y = log1p(x) in UTP arithmetic"""
retval = self.clone()
self._log1p(self.data, out = retval.data)
return retval
@classmethod
def pb_log1p(cls, ybar, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
cls._pb_log1p(ybar.data, x.data, y.data, out = xbar.data)
return out
def sincos(self):
""" simultanteously computes s = sin(x) and c = cos(x) in UTP arithmetic"""
retsin = self.clone()
retcos = self.clone()
self._sincos(self.data, out = (retsin.data, retcos.data))
return retsin, retcos
def sin(self):
retval = self.clone()
tmp = self.clone()
self._sincos(self.data, out = (retval.data, tmp.data))
return retval
@classmethod
def pb_sin(cls, sbar, x, s, out = None):
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
c = x.cos()
cbar = x.zeros_like()
cls._pb_sincos(sbar.data, cbar.data, x.data, s.data, c.data, out = xbar.data)
return out
def cos(self):
retval = self.clone()
tmp = self.clone()
self._sincos(self.data, out = (tmp.data, retval.data))
return retval
@classmethod
def pb_cos(cls, cbar, x, c, out = None):
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
s = x.sin()
sbar = x.zeros_like()
cls._pb_sincos(sbar.data, cbar.data, x.data, s.data, c.data, out = xbar.data)
return out
def tansec2(self):
""" computes simultaneously y = tan(x) and z = sec^2(x) in UTP arithmetic"""
rettan = self.clone()
retsec = self.clone()
self._tansec2(self.data, out = (rettan.data, retsec.data))
return rettan, retset
def tan(self):
retval = self.zeros_like()
tmp = self.zeros_like()
self._tansec2(self.data, out = (retval.data, tmp.data))
return retval
@classmethod
def pb_tan(cls, ybar, x, y, out = None):
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
z = 1./x.cos(); z = z * z
zbar = x.zeros_like()
cls._pb_tansec(ybar.data, zbar.data, x.data, y.data, z.data, out = xbar.data)
return out
@classmethod
def dpm_hyp1f1(cls, a, b, x):
""" computes y = hyp1f1(a, b, x) in UTP arithmetic"""
retval = x.clone()
cls._dpm_hyp1f1(a, b, x.data, out = retval.data)
return retval
@classmethod
def pb_dpm_hyp1f1(cls, ybar, a, b, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
# out = (abar, bbar, xbar)
xbar = out[2]
cls._pb_dpm_hyp1f1(ybar.data, a, b, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def hyp1f1(cls, a, b, x):
""" computes y = hyp1f1(a, b, x) in UTP arithmetic"""
retval = x.clone()
cls._hyp1f1(a, b, x.data, out = retval.data)
return retval
@classmethod
def pb_hyp1f1(cls, ybar, a, b, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
# out = (abar, bbar, xbar)
xbar = out[2]
cls._pb_hyp1f1(ybar.data, a, b, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def hyperu(cls, a, b, x):
""" computes y = hyperu(a, b, x) in UTP arithmetic"""
retval = x.clone()
cls._hyperu(a, b, x.data, out = retval.data)
return retval
@classmethod
def pb_hyperu(cls, ybar, a, b, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
# out = (abar, bbar, xbar)
xbar = out[2]
cls._pb_hyperu(ybar.data, a, b, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def botched_clip(cls, a_min, a_max, x):
""" computes y = botched_clip(a_min, a_max, x) in UTP arithmetic"""
retval = x.clone()
cls._botched_clip(a_min, a_max, x.data, out = retval.data)
return retval
@classmethod
def pb_botched_clip(cls, ybar, a_min, a_max, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
# out = (aminbar, amaxbar, xbar)
xbar = out[2]
cls._pb_botched_clip(
ybar.data, a_min, a_max, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def dpm_hyp2f0(cls, a1, a2, x):
""" computes y = hyp2f0(a1, a2, x) in UTP arithmetic"""
retval = x.clone()
cls._dpm_hyp2f0(a1, a2, x.data, out = retval.data)
return retval
@classmethod
def pb_dpm_hyp2f0(cls, ybar, a1, a2, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
# out = (a1bar, a2bar, xbar)
xbar = out[2]
cls._pb_dpm_hyp2f0(ybar.data, a1, a2, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def hyp2f0(cls, a1, a2, x):
""" computes y = hyp2f0(a1, a2, x) in UTP arithmetic"""
retval = x.clone()
cls._hyp2f0(a1, a2, x.data, out = retval.data)
return retval
@classmethod
def pb_hyp2f0(cls, ybar, a1, a2, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
# out = (a1bar, a2bar, xbar)
xbar = out[2]
cls._pb_hyp2f0(ybar.data, a1, a2, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def hyp0f1(cls, b, x):
""" computes y = hyp0f1(b, x) in UTP arithmetic"""
retval = x.clone()
cls._hyp0f1(b, x.data, out = retval.data)
return retval
@classmethod
def pb_hyp0f1(cls, ybar, b, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
# out = (bbar, xbar)
xbar = out[1]
cls._pb_hyp0f1(ybar.data, b, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def polygamma(cls, n, x):
""" computes y = polygamma(n, x) in UTP arithmetic"""
retval = x.clone()
cls._polygamma(n, x.data, out = retval.data)
return retval
@classmethod
def pb_polygamma(cls, ybar, n, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
# out = (nbar, xbar)
xbar = out[1]
cls._pb_polygamma(ybar.data, n, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def psi(cls, x):
""" computes y = psi(x) in UTP arithmetic"""
retval = x.clone()
cls._psi(x.data, out = retval.data)
return retval
@classmethod
def pb_psi(cls, ybar, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
cls._pb_psi(ybar.data, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def reciprocal(cls, x):
""" computes y = reciprocal(x) in UTP arithmetic"""
retval = x.clone()
cls._reciprocal(x.data, out = retval.data)
return retval
@classmethod
def pb_reciprocal(cls, ybar, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
cls._pb_reciprocal(ybar.data, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def gammaln(cls, x):
""" computes y = gammaln(x) in UTP arithmetic"""
retval = x.clone()
cls._gammaln(x.data, out = retval.data)
return retval
@classmethod
def pb_gammaln(cls, ybar, x, y, out=None):
""" computes bar y dy = bar x dx in UTP arithmetic"""
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
cls._pb_gammaln(ybar.data, x.data, y.data, out = xbar.data)
return xbar
@classmethod
def minimum(cls, x, y):
# FIXME: this typechecking is probably not flexible enough
# FIXME: also add pullback
if isinstance(x, UTPM) and isinstance(y, UTPM):
return UTPM(cls._minimum(x.data, y.data))
elif isinstance(x, numpy.ndarray) and isinstance(y, numpy.ndarray):
return numpy.minimum(x, y)
else:
raise NotImplementedError(
'this combination of types is not yet implemented')
@classmethod
def maximum(cls, x, y):
# FIXME: this typechecking is probably not flexible enough
# FIXME: also add pullback
if isinstance(x, UTPM) and isinstance(y, UTPM):
return UTPM(cls._maximum(x.data, y.data))
elif isinstance(x, numpy.ndarray) and isinstance(y, numpy.ndarray):
return numpy.maximum(x, y)
else:
raise NotImplementedError(
'this combination of types is not yet implemented')
@classmethod
def real(cls, x):
""" UTPM equivalent to numpy.real """
return cls(x.data.real)
@classmethod
def pb_real(cls, ybar, x, y, out=None):
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
xbar.data.real = ybar.data
@classmethod
def imag(cls, x):
""" UTPM equivalent to numpy.imag """
return cls(x.data.imag)
@classmethod
def pb_imag(cls, ybar, x, y, out=None):
if out is None:
D,P = x.data.shape[:2]
xbar = x.zeros_like()
else:
xbar, = out
xbar.data.imag = -ybar.data
@classmethod
def absolute(cls, x):
""" computes y = absolute(x) in UTP arithmetic"""