/
function.py
4720 lines (3811 loc) · 160 KB
/
function.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
# Copyright (c) 2014 Evalf
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
The function module defines the :class:`Evaluable` class and derived objects,
commonly referred to as nutils functions. They represent mappings from a
:mod:`nutils.topology` onto Python space. The notabe class of :class:`Array`
objects map onto the space of Numpy arrays of predefined dimension and shape.
Most functions used in nutils applicatons are of this latter type, including the
geometry and function bases for analysis.
Nutils functions are essentially postponed python functions, stored in a tree
structure of input/output dependencies. Many :class:`Array` objects have
directly recognizable numpy equivalents, such as :class:`Sin` or
:class:`Inverse`. By not evaluating directly but merely stacking operations,
complex operations can be defined prior to entering a quadrature loop, allowing
for a higher level style programming. It also allows for automatic
differentiation and code optimization.
It is important to realize that nutils functions do not map for a physical
xy-domain but from a topology, where a point is characterized by the combination
of an element and its local coordinate. This is a natural fit for typical finite
element operations such as quadrature. Evaluation from physical coordinates is
possible only via inverting of the geometry function, which is a fundamentally
expensive and currently unsupported operation.
"""
from . import util, types, numpy, numeric, cache, transform, transformseq, expression, warnings, _
import sys, itertools, functools, operator, inspect, numbers, builtins, re, types as builtin_types, abc, collections.abc, math, treelog as log
isevaluable = lambda arg: isinstance(arg, Evaluable)
def strictevaluable(value):
if not isinstance(value, Evaluable):
raise ValueError('expected an object of type {!r} but got {!r} with type {!r}'.format(Evaluable.__qualname__, value, type(value).__qualname__))
return value
def simplified(value):
return strictevaluable(value).simplified
asdtype = lambda arg: arg if any(arg is dtype for dtype in (bool, int, float, complex)) else {'f': float, 'i': int, 'b': bool, 'c': complex}[numpy.dtype(arg).kind]
asarray = lambda arg: arg if isarray(arg) else Constant(arg) if numeric.isarray(arg) or numpy.asarray(arg).dtype != object else stack(arg, axis=0)
asarrays = types.tuple[asarray]
def as_canonical_length(value):
if isarray(value):
if value.ndim != 0 or value.dtype != int:
raise ValueError('length should be an `int` or `Array` with zero dimensions and dtype `int`, got {!r}'.format(value))
value = value.simplified
if value.isconstant:
value = int(value.eval()) # Ensure this is an `int`, not `numpy.int64`.
elif numeric.isint(value):
value = int(value) # Ensure this is an `int`, not `numpy.int64`.
else:
raise ValueError('length should be an `int` or `Array` with zero dimensions and dtype `int`, got {!r}'.format(value))
return value
asshape = types.tuple[as_canonical_length]
class ExpensiveEvaluationWarning(Warning): pass
class Evaluable(types.Singleton):
'Base class'
__slots__ = '__args',
__cache__ = 'dependencies', 'ordereddeps', 'dependencytree', 'simplified', 'prepare_eval', 'optimized_for_numpy'
@types.apply_annotations
def __init__(self, args:types.tuple[strictevaluable]):
super().__init__()
self.__args = args
def evalf(self, *args):
raise NotImplementedError('Evaluable derivatives should implement the evalf method')
@property
def dependencies(self):
'''collection of all function arguments'''
deps = list(self.__args)
for func in self.__args:
deps.extend(func.dependencies)
return frozenset(deps)
@property
def isconstant(self):
return EVALARGS not in self.dependencies
@property
def ordereddeps(self):
'''collection of all function arguments such that the arguments to
dependencies[i] can be found in dependencies[:i]'''
return tuple([EVALARGS] + sorted(self.dependencies - {EVALARGS}, key=lambda f: len(f.dependencies)))
@property
def dependencytree(self):
'''lookup table of function arguments into ordereddeps, such that
ordereddeps[i].__args[j] == ordereddeps[dependencytree[i][j]], and
self.__args[j] == ordereddeps[dependencytree[-1][j]]'''
args = self.ordereddeps
return tuple(tuple(map(args.index, func.__args)) for func in args+(self,))
@property
def serialized(self):
return zip(self.ordereddeps[1:]+(self,), self.dependencytree[1:])
def asciitree(self, richoutput=False):
'string representation'
if richoutput:
select = '├ ', '└ '
bridge = '│ ', ' '
else:
select = ': ', ': '
bridge = '| ', ' '
lines = []
ordereddeps = list(self.ordereddeps) + [self]
pool = [('', len(ordereddeps)-1)] # prefix, object tuples
while pool:
prefix, n = pool.pop()
s = '%{}'.format(n)
if prefix:
s = prefix[:-2] + select[bridge.index(prefix[-2:])] + s # locally change prefix into selector
if ordereddeps[n] is not None:
s += ' = ' + ordereddeps[n]._asciitree_str()
pool.extend((prefix + bridge[i==0], arg) for i, arg in enumerate(reversed(self.dependencytree[n])))
ordereddeps[n] = None
lines.append(s)
return '\n'.join(lines)
def _asciitree_str(self):
return str(self)
def __str__(self):
return self.__class__.__name__
def eval(self, **evalargs):
values = [evalargs]
for op, indices in self.serialized:
try:
args = [values[i] for i in indices]
retval = op.evalf(*args)
except KeyboardInterrupt:
raise
except:
etype, evalue, traceback = sys.exc_info()
excargs = etype, evalue, self, values
raise EvaluationError(*excargs).with_traceback(traceback)
values.append(retval)
return values[-1]
@log.withcontext
def graphviz(self, dotpath='dot', imgtype='png'):
'create function graph'
import os, subprocess
lines = []
lines.append('digraph {')
lines.append('graph [dpi=72];')
lines.extend('{0:} [label="{0:}. {1:}"];'.format(i, name._asciitree_str()) for i, name in enumerate(self.ordereddeps+(self,)))
lines.extend('{} -> {};'.format(j, i) for i, indices in enumerate(self.dependencytree) for j in indices)
lines.append('}')
with log.infofile('dot.'+imgtype, 'wb') as img:
status = subprocess.run([dotpath,'-T'+imgtype], input='\n'.join(lines).encode(), stdout=subprocess.PIPE)
if status.returncode:
log.warning('graphviz failed for error code', status.returncode)
img.write(status.stdout)
def stackstr(self, nlines=-1):
'print stack'
lines = [' %0 = EVALARGS']
for op, indices in self.serialized:
args = ['%{}'.format(idx) for idx in indices]
try:
code = op.evalf.__code__
offset = 1 if getattr(op.evalf, '__self__', None) is not None else 0
names = code.co_varnames[offset:code.co_argcount]
names += tuple('{}[{}]'.format(code.co_varnames[code.co_argcount], n) for n in range(len(indices) - len(names)))
args = ['{}={}'.format(*item) for item in zip(names, args)]
except:
pass
lines.append(' %{} = {}({})'.format(len(lines), op._asciitree_str(), ', '.join(args)))
if len(lines) == nlines+1:
break
return '\n'.join(lines)
@property
def simplified(self):
return self.edit(lambda arg: arg.simplified if isevaluable(arg) else arg)
@property
def optimized_for_numpy(self):
return self.edit(lambda arg: arg.optimized_for_numpy if isevaluable(arg) else arg)
@util.positional_only
def prepare_eval(self, kwargs=...):
'''
Return a function tree suitable for evaluation.
'''
return self.edit(lambda arg: arg.prepare_eval(**kwargs) if isevaluable(arg) else arg)
class EvaluationError(Exception):
'evaluation error'
def __init__(self, etype, evalue, evaluable, values):
'constructor'
self.etype = etype
self.evalue = evalue
self.evaluable = evaluable
self.values = values
def __repr__(self):
return 'EvaluationError{}'.format(self)
def __str__(self):
'string representation'
return '\n{} --> {}: {}'.format(self.evaluable.stackstr(nlines=len(self.values)), self.etype.__name__, self.evalue)
EVALARGS = Evaluable(args=())
class Points(Evaluable):
__slots__ = ()
def __init__(self):
super().__init__(args=[EVALARGS])
def evalf(self, evalargs):
points = evalargs['_points']
assert numeric.isarray(points) and points.ndim == 2
return types.frozenarray(points)
POINTS = Points()
class Tuple(Evaluable):
__slots__ = 'items', 'indices'
__cache__ = 'simplified',
@types.apply_annotations
def __init__(self, items:tuple): # FIXME: shouldn't all items be Evaluable?
self.items = items
args = []
indices = []
for i, item in enumerate(self.items):
if isevaluable(item):
args.append(item)
indices.append(i)
self.indices = tuple(indices)
super().__init__(args)
@property
def simplified(self):
return Tuple([item.simplified if isevaluable(item) else item for item in self.items])
def edit(self, op):
return Tuple([op(item) for item in self.items])
def evalf(self, *items):
'evaluate'
T = list(self.items)
for index, item in zip(self.indices, items):
T[index] = item
return tuple(T)
def __iter__(self):
'iterate'
return iter(self.items)
def __len__(self):
'length'
return len(self.items)
def __getitem__(self, item):
'get item'
return self.items[item]
def __add__(self, other):
'add'
return Tuple(self.items + tuple(other))
def __radd__(self, other):
'add'
return Tuple(tuple(other) + self.items)
# TRANSFORMCHAIN
class TransformChain(Evaluable):
'''Chain of affine transformations.
Evaluates to a tuple of :class:`nutils.transform.TransformItem` objects.
'''
__slots__ = 'todims',
@types.apply_annotations
def __init__(self, args:types.tuple[strictevaluable], todims:types.strictint=None):
self.todims = todims
super().__init__(args)
class SelectChain(TransformChain):
__slots__ = 'n'
@types.apply_annotations
def __init__(self, n:types.strictint=0):
self.n = n
super().__init__(args=[EVALARGS])
def evalf(self, evalargs):
trans = evalargs['_transforms'][self.n]
assert isinstance(trans, tuple)
return trans
@util.positional_only
def prepare_eval(self, *, opposite=False, kwargs=...):
return SelectChain(1-self.n) if opposite else self
TRANS = SelectChain()
class PopHead(TransformChain):
__slots__ = 'trans',
@types.apply_annotations
def __init__(self, todims:types.strictint, trans=TRANS):
self.trans = trans
super().__init__(args=[self.trans], todims=todims)
def evalf(self, trans):
assert trans[0].fromdims == self.todims
return trans[1:]
class SelectBifurcation(TransformChain):
__slots__ = 'trans', 'first'
@types.apply_annotations
def __init__(self, trans:strictevaluable, first:bool, todims:types.strictint=None):
self.trans = trans
self.first = first
super().__init__(args=[trans], todims=todims)
def evalf(self, trans):
assert isinstance(trans, tuple)
bf = trans[0]
assert isinstance(bf, transform.Bifurcate)
selected = bf.trans1 if self.first else bf.trans2
return selected + trans[1:]
class TransformChainFromTuple(TransformChain):
__slots__ = 'index',
def __init__(self, values:strictevaluable, index:types.strictint, todims:types.strictint=None):
assert 0 <= index < len(values)
self.index = index
super().__init__(args=[values], todims=todims)
def evalf(self, values):
return values[self.index]
class TransformsIndexWithTail(Evaluable):
__slots__ = '_transforms'
@types.apply_annotations
def __init__(self, transforms, trans:types.strict[TransformChain]):
self._transforms = transforms
super().__init__(args=[trans])
def evalf(self, trans):
index, tail = self._transforms.index_with_tail(trans)
return numpy.array(index)[None], tail
def __len__(self):
return 2
@property
def index(self):
return ArrayFromTuple(self, index=0, shape=(), dtype=int)
@property
def tail(self):
return TransformChainFromTuple(self, index=1, todims=self._transforms.fromdims)
def __iter__(self):
yield self.index
yield self.tail
# ARRAYFUNC
#
# The main evaluable. Closely mimics a numpy array.
def add(a, b):
a, b = _numpy_align(a, b)
return Add([a, b])
def multiply(a, b):
a, b = _numpy_align(a, b)
return Multiply([a, b])
def sum(arg, axis=None):
arg = asarray(arg)
if axis is None:
axis = numpy.arange(arg.ndim)
elif numeric.isint(axis):
axis = numeric.normdim(arg.ndim, axis),
else:
axis = _norm_and_sort(arg.ndim, axis)
assert numpy.greater(numpy.diff(axis), 0).all(), 'duplicate axes in sum'
summed = arg
for ax in reversed(axis):
summed = Sum(summed, ax)
return summed
def product(arg, axis):
arg = asarray(arg)
axis = numeric.normdim(arg.ndim, axis)
shape = arg.shape[:axis] + arg.shape[axis+1:]
trans = [i for i in range(arg.ndim) if i != axis] + [axis]
return Product(transpose(arg, trans))
def power(arg, n):
arg, n = _numpy_align(arg, n)
return Power(arg, n)
def dot(a, b, axes=None):
'''
Contract ``a`` and ``b`` along ``axes``.
'''
if axes is None:
a = asarray(a)
b = asarray(b)
assert b.ndim == 1 and b.shape[0] == a.shape[0]
for idim in range(1, a.ndim):
b = insertaxis(b, idim, a.shape[idim])
axes = 0,
return multiply(a, b).sum(axes)
def transpose(arg, trans=None):
arg = asarray(arg)
if trans is None:
normtrans = range(arg.ndim-1, -1, -1)
else:
normtrans = _normdims(arg.ndim, trans)
assert sorted(normtrans) == list(range(arg.ndim))
return Transpose(arg, normtrans)
def swapaxes(arg, axis1, axis2):
arg = asarray(arg)
trans = numpy.arange(arg.ndim)
trans[axis1], trans[axis2] = trans[axis2], trans[axis1]
return transpose(arg, trans)
class Array(Evaluable):
'''
Base class for array valued functions.
Attributes
----------
shape : :class:`tuple` of :class:`int`\\s
The shape of this array function.
ndim : :class:`int`
The number of dimensions of this array array function. Equal to
``len(shape)``.
dtype : :class:`int`, :class:`float`
The dtype of the array elements.
'''
__slots__ = 'shape', 'ndim', 'dtype'
__cache__ = 'optimized_for_numpy'
__array_priority__ = 1. # http://stackoverflow.com/questions/7042496/numpy-coercion-problem-for-left-sided-binary-operator/7057530#7057530
@types.apply_annotations
def __init__(self, args:types.tuple[strictevaluable], shape:asshape, dtype:asdtype):
self.shape = shape
self.ndim = len(shape)
self.dtype = dtype
super().__init__(args=args)
def __getitem__(self, item):
if not isinstance(item, tuple):
item = item,
iell = None
nx = self.ndim - len(item)
for i, it in enumerate(item):
if it is ...:
assert iell is None, 'at most one ellipsis allowed'
iell = i
elif it is _:
nx += 1
array = self
axis = 0
for it in item + (slice(None),)*nx if iell is None else item[:iell] + (slice(None),)*(nx+1) + item[iell+1:]:
if numeric.isint(it):
array = get(array, axis, item=it)
elif it is _:
array = expand_dims(array, axis)
axis += 1
elif it == slice(None):
axis += 1
elif isinstance(it, slice):
assert it.step == None or it.step == 1
start = 0 if it.start is None else it.start if it.start >= 0 else it.start + array.shape[axis]
stop = array.shape[axis] if it.stop is None else it.stop if it.stop >= 0 else it.stop + array.shape[axis]
array = take(array, index=Range(stop-start, start), axis=axis)
axis += 1
else:
array = take(array, index=it, axis=axis)
axis += 1
assert axis == array.ndim
return array
def __len__(self):
if self.ndim == 0:
raise TypeError('len() of unsized object')
return self.shape[0]
def __iter__(self):
if not self.shape:
raise TypeError('iteration over a 0-d array')
return (self[i,...] for i in range(self.shape[0]))
size = property(lambda self: util.product(self.shape) if self.ndim else 1)
T = property(lambda self: transpose(self))
__add__ = __radd__ = add
__sub__ = lambda self, other: subtract(self, other)
__rsub__ = lambda self, other: subtract(other, self)
__mul__ = __rmul__ = multiply
__truediv__ = lambda self, other: divide(self, other)
__rtruediv__ = lambda self, other: divide(other, self)
__pos__ = lambda self: self
__neg__ = lambda self: negative(self)
__pow__ = power
__abs__ = lambda self: abs(self)
__mod__ = lambda self, other: mod(self, other)
__str__ = __repr__ = lambda self: 'Array<{}>'.format(','.join(map(str, self.shape)) if hasattr(self, 'shape') else '?')
sum = sum
prod = product
dot = dot
normalized = lambda self, axis=-1: normalized(self, axis)
normal = lambda self, exterior=False: normal(self, exterior)
curvature = lambda self, ndims=-1: curvature(self, ndims)
swapaxes = swapaxes
transpose = transpose
grad = lambda self, geom, ndims=0: grad(self, geom, ndims)
laplace = lambda self, geom, ndims=0: grad(self, geom, ndims).div(geom, ndims)
add_T = lambda self, axes=(-2,-1): add_T(self, axes)
symgrad = lambda self, geom, ndims=0: symgrad(self, geom, ndims)
div = lambda self, geom, ndims=0: div(self, geom, ndims)
dotnorm = lambda self, geom, axis=-1: dotnorm(self, geom, axis)
tangent = lambda self, vec: tangent(self, vec)
ngrad = lambda self, geom, ndims=0: ngrad(self, geom, ndims)
nsymgrad = lambda self, geom, ndims=0: nsymgrad(self, geom, ndims)
def vector(self, ndims):
if self.ndim != 1:
raise Exception('only a scalar basis van be vectorized')
return ravel(diagonalize(insertaxis(self, 1, ndims), 1, 2), 0)
@property
def blocks(self):
return [(tuple(Range(n) for n in self.shape), self)]
def _asciitree_str(self):
return '{}({})'.format(type(self).__name__, ','.join(['?' if isarray(sh) else str(sh) for sh in self.shape]))
# simplifications
_multiply = lambda self, other: None
_transpose = lambda self, axes: None
_insertaxis = lambda self, axis, length: None
_get = lambda self, i, item: None
_power = lambda self, n: None
_add = lambda self, other: None
_sum = lambda self, axis: None
_take = lambda self, index, axis: None
_determinant = lambda self: None
_inverse = lambda self: None
_takediag = lambda self, axis, rmaxis: None
_diagonalize = lambda self, axis, newaxis: None
_product = lambda self: None
_sign = lambda self: None
_eig = lambda self, symmetric: None
_inflate = lambda self, dofmap, length, axis: None
_mask = lambda self, maskvec, axis: None
_unravel = lambda self, axis, shape: None
_ravel = lambda self, axis: None
_kronecker = lambda self, axis, length, pos: None
_inserted_axes = ()
@property
def optimized_for_numpy(self):
if self.isconstant:
const, = self.eval()
return Constant(const)
return super().optimized_for_numpy
def _derivative(self, var, seen):
if self.dtype in (bool, int) or var not in self.dependencies:
return Zeros(self.shape + var.shape, dtype=self.dtype)
raise NotImplementedError('derivative not defined for {}'.format(self.__class__.__name__))
class Normal(Array):
'normal'
__slots__ = 'lgrad',
@types.apply_annotations
def __init__(self, lgrad:asarray):
assert lgrad.ndim == 2 and lgrad.shape[0] == lgrad.shape[1]
self.lgrad = lgrad
super().__init__(args=[lgrad], shape=(len(lgrad),), dtype=float)
def evalf(self, lgrad):
n = lgrad[...,-1]
if n.shape[-1] == 1: # geom is 1D
return numpy.sign(n)
# orthonormalize n to G
G = lgrad[...,:-1]
GG = numeric.contract(G[:,:,_,:], G[:,:,:,_], axis=1)
v1 = numeric.contract(G, n[:,:,_], axis=1)
v2 = numpy.linalg.solve(GG, v1)
v3 = numeric.contract(G, v2[:,_,:], axis=2)
return numeric.normalize(n - v3)
def _derivative(self, var, seen):
if len(self) == 1:
return zeros(self.shape + var.shape)
G = self.lgrad[...,:-1]
GG = matmat(G.T, G)
Gder = derivative(G, var, seen)
nGder = matmat(self, Gder)
return -matmat(G, inverse(GG), nGder)
class Constant(Array):
__slots__ = 'value',
__cache__ = 'simplified', '_isunit'
@types.apply_annotations
def __init__(self, value:types.frozenarray):
self.value = value
super().__init__(args=[], shape=value.shape, dtype=value.dtype)
@property
def simplified(self):
if not self.value.any():
return zeros_like(self)
# Find and replace invariant axes with InsertAxis.
value = self.value
invariant = []
for i in reversed(range(self.ndim)):
# Since `self.value.any()` is False for arrays with a zero-length axis,
# we can arrive here only if all axes have at least length one, hence the
# following statement should work.
first = numeric.get(value, i, 0)
if all(numpy.equal(first, numeric.get(value, i, j)).all() for j in range(1, value.shape[i])):
invariant.append(i)
value = first
if invariant:
value = Constant(value)
for i in reversed(invariant):
value = InsertAxis(value, i, self.shape[i])
return value.simplified
return self
def evalf(self):
return self.value[_]
@property
def _isunit(self):
return numpy.equal(self.value, 1).all()
def _transpose(self, axes):
return Constant(self.value.transpose(axes))
def _sum(self, axis):
return Constant(numpy.sum(self.value, axis))
def _get(self, i, item):
if item.isconstant:
item, = item.eval()
return Constant(numeric.get(self.value, i, item))
def _add(self, other):
if isinstance(other, Constant):
return Constant(numpy.add(self.value, other.value))
def _inverse(self):
return Constant(numpy.linalg.inv(self.value))
def _product(self):
return Constant(self.value.prod(-1))
def _multiply(self, other):
if self._isunit:
return other
if isinstance(other, Constant):
return Constant(numpy.multiply(self.value, other.value))
def _takediag(self, axis, rmaxis):
return Constant(numeric.takediag(self.value, axis, rmaxis))
def _take(self, index, axis):
if isinstance(index, Constant):
return Constant(self.value.take(index.value, axis))
def _power(self, n):
if isinstance(n, Constant):
return Constant(numeric.power(self.value, n.value))
def _eig(self, symmetric):
eigval, eigvec = (numpy.linalg.eigh if symmetric else numpy.linalg.eig)(self.value)
return Tuple((Constant(eigval), Constant(eigvec)))
def _sign(self):
return Constant(numeric.sign(self.value))
def _unravel(self, axis, shape):
shape = self.value.shape[:axis] + shape + self.value.shape[axis+1:]
return Constant(self.value.reshape(shape))
def _mask(self, maskvec, axis):
return Constant(self.value[(slice(None),)*axis+(numpy.asarray(maskvec),)])
def _determinant(self):
# NOTE: numpy <= 1.12 cannot compute the determinant of an array with shape [...,0,0]
return Constant(numpy.linalg.det(self.value) if self.value.shape[-1] else numpy.ones(self.value.shape[:-2]))
class InsertAxis(Array):
__slots__ = 'func', 'axis', 'length'
__cache__ = 'simplified', 'blocks'
@types.apply_annotations
def __init__(self, func:asarray, axis:types.strictint, length:asarray):
assert length.ndim == 0 and length.dtype == int
assert 0 <= axis <= func.ndim
self.func = func
self.axis = axis
self.length = length
super().__init__(args=[func, length], shape=func.shape[:axis]+(length,)+func.shape[axis:], dtype=func.dtype)
@property
def simplified(self):
func = self.func.simplified
retval = func._insertaxis(self.axis, self.length)
if retval is not None:
assert retval.shape == self.shape
return retval.simplified
return InsertAxis(func, self.axis, self.length)
def evalf(self, func, length):
# We would like to return an array with stride zero for the inserted axis,
# but this appears to be *slower* (checked with examples/cylinderflow.py)
# than the implementation below.
length, = length
func = numpy.asarray(func)[(slice(None),)*(self.axis+1)+(None,)]
if length != 1:
func = numpy.repeat(func, length, self.axis+1)
return func
def _derivative(self, var, seen):
return insertaxis(derivative(self.func, var, seen), self.axis, self.length)
def _get(self, i, item):
if i == self.axis:
if item.isconstant and self.length.isconstant:
assert item.eval()[0] < self.length.eval()[0]
return self.func
return InsertAxis(Get(self.func, i-(i>self.axis), item), self.axis-(i<self.axis), self.length)
def _sum(self, i):
if i == self.axis:
return Multiply([self.func, _inflate_scalar(self.length, self.func.shape)])
return InsertAxis(Sum(self.func, i-(i>self.axis)), self.axis-(i<self.axis), self.length)
def _product(self):
if self.axis == self.ndim-1:
return Power(self.func, _inflate_scalar(self.length, self.func.shape))
return InsertAxis(Product(self.func), self.axis, self.length)
def _power(self, n):
for axis in n._inserted_axes:
if axis in self._inserted_axes:
return InsertAxis(Power(self._uninsert(axis), n._uninsert(axis)), axis, self.shape[axis])
def _add(self, other):
for axis in other._inserted_axes:
if axis in self._inserted_axes:
return InsertAxis(Add([self._uninsert(axis), other._uninsert(axis)]), axis, self.shape[axis])
def _multiply(self, other):
for axis in other._inserted_axes:
if axis in self._inserted_axes:
return InsertAxis(Multiply([self._uninsert(axis), other._uninsert(axis)]), axis, self.shape[axis])
def _insertaxis(self, axis, length):
if (not length.isconstant, axis) < (not self.length.isconstant, self.axis):
return InsertAxis(InsertAxis(self.func, axis-(axis>self.axis), length), self.axis+(axis<=self.axis), self.length)
def _take(self, index, axis):
if axis == self.axis:
return InsertAxis(self.func, self.axis, index.shape[0])
return InsertAxis(Take(self.func, index, axis-(axis>self.axis)), self.axis, self.length)
def _takediag(self, axis, rmaxis):
if self.axis == rmaxis:
return self.func
elif self.axis == axis:
return Transpose(self.func, list(range(axis))+[rmaxis-1]+list(range(axis, rmaxis-1))+list(range(rmaxis, self.func.ndim)))
else:
return InsertAxis(TakeDiag(self.func, axis-(self.axis<axis), rmaxis-(self.axis<rmaxis)), self.axis-(self.axis>rmaxis), self.length)
def _mask(self, maskvec, axis):
if axis == self.axis:
assert len(maskvec) == self.shape[self.axis]
return InsertAxis(self.func, self.axis, maskvec.sum())
return InsertAxis(Mask(self.func, maskvec, axis-(self.axis<axis)), self.axis, self.length)
def _transpose(self, axes):
i = axes.index(self.axis)
return InsertAxis(Transpose(self.func, [ax-(ax>self.axis) for ax in axes[:i]+axes[i+1:]]), i, self.length)
def _unravel(self, axis, shape):
if axis == self.axis:
return InsertAxis(InsertAxis(self.func, self.axis, shape[1]), self.axis, shape[0])
else:
return InsertAxis(Unravel(self.func, axis-(axis>self.axis), shape), self.axis+(axis<self.axis), self.length)
@property
def _inserted_axes(self):
return tuple([self.axis] + [axis + (axis>=self.axis) for axis in self.func._inserted_axes])
def _uninsert(self, axis):
return self.func if axis == self.axis else InsertAxis(self.func._uninsert(axis-(axis>self.axis)), self.axis-(axis<self.axis), self.length)
def _sign(self):
return InsertAxis(Sign(self.func), self.axis, self.length)
def _inverse(self):
if self.axis < self.ndim-2:
return InsertAxis(Inverse(self.func), self.axis, self.length)
def _determinant(self):
if self.axis < self.ndim-2:
return InsertAxis(Determinant(self.func), self.axis, self.length)
@property
def blocks(self):
return tuple((ind[:self.axis]+(Range(self.length),)+ind[self.axis:], InsertAxis(f, self.axis, self.length)) for ind, f in self.func.blocks)
class Transpose(Array):
__slots__ = 'func', 'axes'
__cache__ = 'simplified', 'blocks'
@types.apply_annotations
def __init__(self, func:asarray, axes:types.tuple[types.strictint]):
assert sorted(axes) == list(range(func.ndim))
self.func = func
self.axes = axes
super().__init__(args=[func], shape=[func.shape[n] for n in axes], dtype=func.dtype)
@property
def simplified(self):
func = self.func.simplified
if self.axes == tuple(range(self.ndim)):
return func
retval = func._transpose(self.axes)
if retval is not None:
assert retval.shape == self.shape
return retval.simplified
return Transpose(func, self.axes)
def evalf(self, arr):
return arr.transpose([0] + [n+1 for n in self.axes])
def _transpose(self, axes):
newaxes = [self.axes[i] for i in axes]
return Transpose(self.func, newaxes)
def _takediag(self, axis, rmaxis):
if self.axes[axis] < self.axes[rmaxis]:
axes = self.axes
else:
axes = list(self.axes)
axes[axis], axes[rmaxis] = axes[rmaxis], axes[axis]
assert axes[axis] < axes[rmaxis]
return Transpose(TakeDiag(self.func, axes[axis], axes[rmaxis]), [ax-(ax>axes[rmaxis]) for ax in axes[:rmaxis]+axes[rmaxis+1:]])
def _get(self, i, item):
axis = self.axes[i]
axes = [ax-(ax>axis) for ax in self.axes if ax != axis]
return Transpose(Get(self.func, axis, item), axes)
def _sum(self, i):
axis = self.axes[i]
axes = [ax-(ax>axis) for ax in self.axes if ax != axis]
return Transpose(Sum(self.func, axis), axes)
def _derivative(self, var, seen):
return transpose(derivative(self.func, var, seen), self.axes+tuple(range(self.ndim, self.ndim+var.ndim)))
def _multiply(self, other):
other_trans = other._transpose(_invtrans(self.axes))
if other_trans is not None:
return Transpose(Multiply([self.func, other_trans]), self.axes)
def _add(self, other):
if isinstance(other, Transpose) and self.axes == other.axes:
return Transpose(Add([self.func, other.func]), self.axes)
other_trans = other._transpose(_invtrans(self.axes))
if other_trans is not None:
return Transpose(Add([self.func, other_trans]), self.axes)
def _take(self, indices, axis):
return Transpose(Take(self.func, indices, self.axes[axis]), self.axes)
def _mask(self, maskvec, axis):
return Transpose(Mask(self.func, maskvec, self.axes[axis]), self.axes)
def _power(self, n):
n_trans = n._transpose(_invtrans(self.axes))
return Transpose(Power(self.func, n_trans), self.axes)
def _sign(self):
return Transpose(Sign(self.func), self.axes)
def _unravel(self, axis, shape):
orig_axis = self.axes[axis]
axes = [ax + (ax>orig_axis) for ax in self.axes]
axes.insert(axis+1, orig_axis+1)
return Transpose(Unravel(self.func, orig_axis, shape), axes)
def _product(self):
if self.axes[-1] == self.ndim-1:
return Transpose(Product(self.func), self.axes[:-1])
def _determinant(self):
if sorted(self.axes[-2:]) == [self.ndim-2, self.ndim-1]:
return Transpose(Determinant(self.func), self.axes[:-2])
def _inverse(self):
if sorted(self.axes[-2:]) == [self.ndim-2, self.ndim-1]:
return Transpose(Inverse(self.func), self.axes)
@property
def blocks(self):
return tuple((tuple(ind[n] for n in self.axes), Transpose(f, self.axes)) for ind, f in self.func.blocks)
class Get(Array):
__slots__ = 'func', 'axis', 'item'
__cache__ = 'simplified',
@types.apply_annotations
def __init__(self, func:asarray, axis:types.strictint, item:asarray):
assert item.ndim == 0 and item.dtype == int
self.func = func
self.axis = axis
self.item = item
assert 0 <= axis < func.ndim, 'axis is out of bounds'
if item.isconstant and numeric.isint(func.shape[axis]):
assert 0 <= item.eval()[0] < func.shape[axis], 'item is out of bounds'
super().__init__(args=[func, item], shape=func.shape[:axis]+func.shape[axis+1:], dtype=func.dtype)
@property
def simplified(self):
func = self.func.simplified
item = self.item.simplified