Coverage for /usr/local/lib/python3.10/dist-packages/Adifpy/differentiate/reverse_mode.py: 100%

8 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2022-12-07 00:47 -0500

1from Adifpy.differentiate.node import Node 

2 

3 

4def reverse_mode(func, pt, seed_vector): 

5 """Compute the value and directional derivative at a point, for a given function. 

6 

7 Reverse mode AD calculates the derivative of a function at point 

8 with respect to some seed vector, at machine precision. 

9 

10 Args: 

11 func (Callable): the function on which to evaluate 

12 pt (float | ndarray): the point at which to evaluate 

13 seed_vector (ndarray): the direction in which to evaluate 

14 defaults to 1 when the function's input space is R 

15 

16 Returns: 

17 If the function's output space is R, a tuple of the value and directional derivative 

18 Otherwise, a tuple of two lists: the values and directional derivatives for each component 

19 

20 >>> f = lambda x: x**2 + 3*x 

21 >>> reverse_mode(f, 1, seed_vector=1) 

22 (4, 5.0) 

23 """ 

24 

25 # Forward pass 

26 input_node = Node(pt) 

27 output_node = func(input_node) 

28 

29 # Account for functions that are in some way "disconnected" from the input 

30 if type(output_node) != Node: 

31 return float(output_node), 0.0 

32 

33 # Initialize value of last node adjoint to 1 

34 output_node.node_adjoint = 1 

35 

36 # Reverse pass 

37 return float(output_node.value), float(input_node.reverse_pass())