Coverage for src/fad/Matrices.py: 23%

# Coverage for src/fad/Matrices.py : 23%

## 52 statements

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1#!/usr/bin/env python3

2

3 import numpy as np

4 from FADiff import FADiff

5

6

7 class Vect:

8 def __init__(self, vect, der=None, parents=[], name=None, new_input=False):

9 self._val = np.array(vect)

10 if new_input:

11 self._der = {}

12 for vec_var in FADiff._fadvect_inputs:

13 self._der[vec_var] = 0

14 vec_var._der[self] = 0

15 self._der[self] = der * np.identity(len(vect))

16 FADiff._fadvect_inputs.append(self)

17 else:

18 self._der = der

19 self._name = name # TODO: Utilize if have time?

20 self._parents = parents

21

22 def __sub__(self, other):

23 try:

24 der = {}

25 for var, part_der in self._der.items():

26 der[var] = part_der - other._der.get(var)

27 parents = self._set_parents(self, other)

28 return Vect(self._val - other._val, der, parents)

29 except AttributeError:

30 parents = self._set_parents(self)

31 return Vect(self._val - other, self._der, parents)

32

33 def __rsub__(self, other):

34 return self.__sub__(other)

35

36 @property

37 def val(self):

38 return [self._val]

39

40 @property

41 def der(self):

42 '''Returns partial derivatives wrt all root input vars used'''

43 parents = []

44 for var, part_der in self._der.items():

45 if var in self._parents:

46 parents.append(part_der)

47 if parents: # For output vars

48 return parents

49 elif self in FADiff._fadvect_inputs: # For input vars (no parents)

50 return [self._der[self]]

51

52 @staticmethod

53 def _set_parents(var1, var2=None):

54 '''Sets parent/grandparent vars used (including root input vars)'''

55 parents = []

56 parents.append(var1)

57 for parent in var1._parents:

58 parents.append(parent)

59 if var2:

60 parents.append(var2)

61 for parent in var2._parents:

62 parents.append(parent)

63 parents = list(set(parents))

64 return parents