Coverage for /usr/local/lib/python3.10/dist-packages/Adifpy/visualize/graph_function.py: 96%

27 statements  

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

1"""Implements visualization of the function and its derivative""" 

2 

3import matplotlib.pyplot as plt 

4import numpy as np 

5 

6from Adifpy.differentiate.evaluator import Evaluator 

7 

8 

9def draw(func, x_range, y_range = None, save_path = None): 

10 """Graph a function 

11 

12 Args: 

13 func (Callable): a function on which to evaluate 

14 pt (float): the point at which to evaluate 

15 x_range (list, optional): x range on which to plot the values 

16 save_path (str): path on which to save the image, or None to display 

17 y_range (list, optional): y range on which to plot the values 

18 """ 

19 assert type(x_range) in [list, tuple] and len(x_range) == 2, \ 

20 'Argument x_range must be a two-length list of tuple like [min, max]' 

21 

22 x_values = np.arange(x_range[0], x_range[1], step=0.01) 

23 y_values = [] 

24 dx_values = [] 

25 

26 evaluator = Evaluator(fn=func) 

27 

28 for x in x_values: 

29 y, dx = evaluator.eval(x) 

30 

31 y_values.append(y) 

32 dx_values.append(dx) 

33 

34 plt.plot(x_values, y_values, label="f(x)") 

35 plt.plot(x_values, dx_values, label="f'(x)") 

36 plt.title('f(x) and f\'(x)') 

37 

38 plt.xlim(x_range) 

39 

40 if y_range is not None: 

41 assert type(y_range) in [list, tuple] and len(y_range) == 2, \ 

42 'Argument y_range must be a two-length list of tuple like [min, max]' 

43 plt.ylim(y_range) 

44 

45 plt.legend() 

46 plt.grid() 

47 

48 if save_path is not None: 

49 plt.savefig(save_path) 

50 else: 

51 plt.show() 

52 

53 

54def plot_evaluator(eval: Evaluator, x_range, y_range = None, save_path = None): 

55 """Plot an evaluator's function over a range""" 

56 draw(eval.fn, x_range, y_range, save_path)