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
« 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"""
3import matplotlib.pyplot as plt
4import numpy as np
6from Adifpy.differentiate.evaluator import Evaluator
9def draw(func, x_range, y_range = None, save_path = None):
10 """Graph a function
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]'
22 x_values = np.arange(x_range[0], x_range[1], step=0.01)
23 y_values = []
24 dx_values = []
26 evaluator = Evaluator(fn=func)
28 for x in x_values:
29 y, dx = evaluator.eval(x)
31 y_values.append(y)
32 dx_values.append(dx)
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)')
38 plt.xlim(x_range)
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)
45 plt.legend()
46 plt.grid()
48 if save_path is not None:
49 plt.savefig(save_path)
50 else:
51 plt.show()
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)