-
Notifications
You must be signed in to change notification settings - Fork 458
Expand file tree
/
Copy pathfreqplot_test.py
More file actions
419 lines (349 loc) · 15.1 KB
/
Copy pathfreqplot_test.py
File metadata and controls
419 lines (349 loc) · 15.1 KB
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
# freqplot_test.py - test out frequency response plots
# RMM, 23 Jun 2023
import pytest
import control as ct
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from control.tests.conftest import slycotonly
pytestmark = pytest.mark.usefixtures("mplcleanup")
#
# Define a system for testing out different sharing options
#
omega = np.logspace(-2, 2, 5)
fresp1 = np.array([10 + 0j, 5 - 5j, 1 - 1j, 0.5 - 1j, -.1j])
fresp2 = np.array([1j, 0.5 - 0.5j, -0.5, 0.1 - 0.1j, -.05j]) * 0.1
fresp3 = np.array([10 + 0j, -20j, -10, 2j, 1])
fresp4 = np.array([10 + 0j, 5 - 5j, 1 - 1j, 0.5 - 1j, -.1j]) * 0.01
fresp = np.empty((2, 2, omega.size), dtype=complex)
fresp[0, 0] = fresp1
fresp[0, 1] = fresp2
fresp[1, 0] = fresp3
fresp[1, 1] = fresp4
manual_response = ct.FrequencyResponseData(
fresp, omega, sysname="Manual Response")
@pytest.mark.parametrize(
"sys", [
ct.tf([1], [1, 2, 1], name='System 1'), # SISO
manual_response, # simple MIMO
])
# @pytest.mark.parametrize("pltmag", [True, False])
# @pytest.mark.parametrize("pltphs", [True, False])
# @pytest.mark.parametrize("shrmag", ['row', 'all', False, None])
# @pytest.mark.parametrize("shrphs", ['row', 'all', False, None])
# @pytest.mark.parametrize("shrfrq", ['col', 'all', False, None])
# @pytest.mark.parametrize("secsys", [False, True])
@pytest.mark.parametrize( # combinatorial-style test (faster)
"pltmag, pltphs, shrmag, shrphs, shrfrq, ovlout, ovlinp, secsys",
[(True, True, None, None, None, False, False, False),
(True, False, None, None, None, True, False, False),
(False, True, None, None, None, False, True, False),
(True, True, None, None, None, False, False, True),
(True, True, 'row', 'row', 'col', False, False, False),
(True, True, 'row', 'row', 'all', False, False, True),
(True, True, 'all', 'row', None, False, False, False),
(True, True, 'row', 'all', None, False, False, True),
(True, True, 'none', 'none', None, False, False, True),
(True, False, 'all', 'row', None, False, False, False),
(True, True, True, 'row', None, False, False, True),
(True, True, None, 'row', True, False, False, False),
(True, True, 'row', None, None, False, False, True),
])
def test_response_plots(
sys, pltmag, pltphs, shrmag, shrphs, shrfrq, secsys,
ovlout, ovlinp, clear=True):
# Save up the keyword arguments
kwargs = dict(
plot_magnitude=pltmag, plot_phase=pltphs,
share_magnitude=shrmag, share_phase=shrphs, share_frequency=shrfrq,
overlay_outputs=ovlout, overlay_inputs=ovlinp
)
# Create the response
if isinstance(sys, ct.FrequencyResponseData):
response = sys
else:
response = ct.frequency_response(sys)
# Look for cases where there are no data to plot
if not pltmag and not pltphs:
return None
# Plot the frequency response
plt.figure()
out = response.plot(**kwargs)
# Check the shape
if ovlout and ovlinp:
assert out.shape == (pltmag + pltphs, 1)
elif ovlout:
assert out.shape == (pltmag + pltphs, sys.ninputs)
elif ovlinp:
assert out.shape == (sys.noutputs * (pltmag + pltphs), 1)
else:
assert out.shape == (sys.noutputs * (pltmag + pltphs), sys.ninputs)
# Make sure all of the outputs are of the right type
nlines_plotted = 0
for ax_lines in np.nditer(out, flags=["refs_ok"]):
for line in ax_lines.item() or []:
assert isinstance(line, mpl.lines.Line2D)
nlines_plotted += 1
# Make sure number of plots is correct
nlines_expected = response.ninputs * response.noutputs * \
(2 if pltmag and pltphs else 1)
assert nlines_plotted == nlines_expected
# Save the old axes to compare later
old_axes = plt.gcf().get_axes()
# Add additional data (and provide info in the title)
if secsys:
newsys = ct.rss(
4, sys.noutputs, sys.ninputs, strictly_proper=True)
ct.frequency_response(newsys).plot(**kwargs)
# Make sure we have the same axes
new_axes = plt.gcf().get_axes()
assert new_axes == old_axes
# Make sure every axes has multiple lines
for ax in new_axes:
assert len(ax.get_lines()) > 1
# Update the title so we can see what is going on
fig = out[0, 0][0].axes.figure
fig.suptitle(
fig._suptitle._text +
f" [{sys.noutputs}x{sys.ninputs}, pm={pltmag}, pp={pltphs},"
f" sm={shrmag}, sp={shrphs}, sf={shrfrq}]", # TODO: ", "
# f"oo={ovlout}, oi={ovlinp}, ss={secsys}]", # TODO: add back
fontsize='small')
# Get rid of the figure to free up memory
if clear:
plt.close('.Figure')
# Use the manaul response to verify that different settings are working
def test_manual_response_limits():
# Default response: limits should be the same across rows
out = manual_response.plot()
axs = ct.get_plot_axes(out)
for i in range(manual_response.noutputs):
for j in range(1, manual_response.ninputs):
# Everything in the same row should have the same limits
assert axs[i*2, 0].get_ylim() == axs[i*2, j].get_ylim()
assert axs[i*2 + 1, 0].get_ylim() == axs[i*2 + 1, j].get_ylim()
# Different rows have different limits
assert axs[0, 0].get_ylim() != axs[2, 0].get_ylim()
assert axs[1, 0].get_ylim() != axs[3, 0].get_ylim()
@pytest.mark.parametrize(
"plt_fcn", [ct.bode_plot, ct.nichols_plot, ct.singular_values_plot])
def test_line_styles(plt_fcn):
# Define a couple of systems for testing
sys1 = ct.tf([1], [1, 2, 1], name='sys1')
sys2 = ct.tf([1, 0.2], [1, 1, 3, 1, 1], name='sys2')
sys3 = ct.tf([0.2, 0.1], [1, 0.1, 0.3, 0.1, 0.1], name='sys3')
# Create a plot for the first system, with custom styles
lines_default = plt_fcn(sys1)
# Now create a plot using *fmt customization
lines_fmt = plt_fcn(sys2, None, 'r--')
assert lines_fmt.reshape(-1)[0][0].get_color() == 'r'
assert lines_fmt.reshape(-1)[0][0].get_linestyle() == '--'
# Add a third plot using keyword customization
lines_kwargs = plt_fcn(sys3, color='g', linestyle=':')
assert lines_kwargs.reshape(-1)[0][0].get_color() == 'g'
assert lines_kwargs.reshape(-1)[0][0].get_linestyle() == ':'
def test_basic_freq_plots(savefigs=False):
# Basic SISO Bode plot
plt.figure()
# ct.frequency_response(sys_siso).plot()
sys1 = ct.tf([1], [1, 2, 1], name='sys1')
sys2 = ct.tf([1, 0.2], [1, 1, 3, 1, 1], name='sys2')
response = ct.frequency_response([sys1, sys2])
ct.bode_plot(response, initial_phase=0)
if savefigs:
plt.savefig('freqplot-siso_bode-default.png')
# Basic MIMO Bode plot
plt.figure()
sys_mimo = ct.tf(
[[[1], [0.1]], [[0.2], [1]]],
[[[1, 0.6, 1], [1, 1, 1]], [[1, 0.4, 1], [1, 2, 1]]], name="sys_mimo")
ct.frequency_response(sys_mimo).plot()
if savefigs:
plt.savefig('freqplot-mimo_bode-default.png')
# Magnitude only plot, with overlayed inputs and outputs
plt.figure()
ct.frequency_response(sys_mimo).plot(
plot_phase=False, overlay_inputs=True, overlay_outputs=True)
if savefigs:
plt.savefig('freqplot-mimo_bode-magonly.png')
# Phase only plot
plt.figure()
ct.frequency_response(sys_mimo).plot(plot_magnitude=False)
# Singular values plot
plt.figure()
ct.singular_values_response(sys_mimo).plot()
if savefigs:
plt.savefig('freqplot-mimo_svplot-default.png')
# Nichols chart
plt.figure()
ct.nichols_plot(response)
if savefigs:
plt.savefig('freqplot-siso_nichols-default.png')
def test_gangof4_plots(savefigs=False):
proc = ct.tf([1], [1, 1, 1], name="process")
ctrl = ct.tf([100], [1, 5], name="control")
plt.figure()
ct.gangof4_plot(proc, ctrl)
if savefigs:
plt.savefig('freqplot-gangof4.png')
@pytest.mark.parametrize("response_cmd, return_type", [
(ct.frequency_response, ct.FrequencyResponseData),
(ct.nyquist_response, ct.freqplot.NyquistResponseData),
(ct.singular_values_response, ct.FrequencyResponseData),
])
def test_first_arg_listable(response_cmd, return_type):
sys = ct.rss(2, 1, 1)
# If we pass a single system, should get back a single system
result = response_cmd(sys)
assert isinstance(result, return_type)
# Save the results from a single plot
lines_single = result.plot()
# If we pass a list of systems, we should get back a list
result = response_cmd([sys, sys, sys])
assert isinstance(result, list)
assert len(result) == 3
assert all([isinstance(item, return_type) for item in result])
# Make sure that plot works
lines_list = result.plot()
if response_cmd == ct.frequency_response:
assert lines_list.shape == lines_single.shape
assert len(lines_list.reshape(-1)[0]) == \
3 * len(lines_single.reshape(-1)[0])
else:
assert lines_list.shape[0] == 3 * lines_single.shape[0]
# If we pass a singleton list, we should get back a list
result = response_cmd([sys])
assert isinstance(result, list)
assert len(result) == 1
assert isinstance(result[0], return_type)
def test_bode_share_options():
# Default sharing should share along rows and cols for mag and phase
lines = ct.bode_plot(manual_response)
axs = ct.get_plot_axes(lines)
for i in range(axs.shape[0]):
for j in range(axs.shape[1]):
# Share y limits along rows
assert axs[i, j].get_ylim() == axs[i, 0].get_ylim()
# Share x limits along columns
assert axs[i, j].get_xlim() == axs[-1, j].get_xlim()
# Sharing along y axis for mag but not phase
plt.figure()
lines = ct.bode_plot(manual_response, share_phase='none')
axs = ct.get_plot_axes(lines)
for i in range(int(axs.shape[0] / 2)):
for j in range(axs.shape[1]):
if i != 0:
# Different rows are different
assert axs[i*2 + 1, 0].get_ylim() != axs[1, 0].get_ylim()
elif j != 0:
# Different columns are different
assert axs[i*2 + 1, j].get_ylim() != axs[i*2 + 1, 0].get_ylim()
# Turn off sharing for magnitude and phase
plt.figure()
lines = ct.bode_plot(manual_response, sharey='none')
axs = ct.get_plot_axes(lines)
for i in range(int(axs.shape[0] / 2)):
for j in range(axs.shape[1]):
if i != 0:
# Different rows are different
assert axs[i*2, 0].get_ylim() != axs[0, 0].get_ylim()
assert axs[i*2 + 1, 0].get_ylim() != axs[1, 0].get_ylim()
elif j != 0:
# Different columns are different
assert axs[i*2, j].get_ylim() != axs[i*2, 0].get_ylim()
assert axs[i*2 + 1, j].get_ylim() != axs[i*2 + 1, 0].get_ylim()
# Turn off sharing in x axes
plt.figure()
lines = ct.bode_plot(manual_response, sharex='none')
# TODO: figure out what to check
@pytest.mark.parametrize("plot_type", ['bode', 'svplot', 'nichols'])
def test_freqplot_plot_type(plot_type):
if plot_type == 'svplot':
response = ct.singular_values_response(ct.rss(2, 1, 1))
else:
response = ct.frequency_response(ct.rss(2, 1, 1))
lines = response.plot(plot_type=plot_type)
if plot_type == 'bode':
assert lines.shape == (2, 1)
else:
assert lines.shape == (1, )
@pytest.mark.parametrize("plt_fcn", [ct.bode_plot, ct.singular_values_plot])
def test_freqplot_omega_limits(plt_fcn):
# Utility function to check visible limits
def _get_visible_limits(ax):
xticks = np.array(ax.get_xticks())
limits = ax.get_xlim()
return np.array([min(xticks[xticks >= limits[0]]),
max(xticks[xticks <= limits[1]])])
# Generate a test response with a fixed set of limits
response = ct.singular_values_response(
ct.tf([1], [1, 2, 1]), np.logspace(-1, 1))
# Generate a plot without overridding the limits
lines = plt_fcn(response)
ax = ct.get_plot_axes(lines)
np.testing.assert_allclose(
_get_visible_limits(ax.reshape(-1)[0]), np.array([0.1, 10]))
# Now reset the limits
lines = plt_fcn(response, omega_limits=(1, 100))
ax = ct.get_plot_axes(lines)
np.testing.assert_allclose(
_get_visible_limits(ax.reshape(-1)[0]), np.array([1, 100]))
@pytest.mark.parametrize("plt_fcn", [ct.bode_plot, ct.singular_values_plot])
def test_freqplot_errors(plt_fcn):
if plt_fcn == ct.bode_plot:
# Turning off both magnitude and phase
with pytest.raises(ValueError, match="no data to plot"):
ct.bode_plot(
manual_response, plot_magnitude=False, plot_phase=False)
# Specifying frequency parameters with response data
response = ct.singular_values_response(ct.rss(2, 1, 1))
with pytest.warns(UserWarning, match="`omega_num` ignored "):
plt_fcn(response, omega_num=100)
with pytest.warns(UserWarning, match="`omega` ignored "):
plt_fcn(response, omega=np.logspace(-2, 2))
# Bad frequency limits
with pytest.raises(ValueError, match="invalid limits"):
plt_fcn(response, omega_limits=[1e2, 1e-2])
if __name__ == "__main__":
#
# Interactive mode: generate plots for manual viewing
#
# Running this script in python (or better ipython) will show a
# collection of figures that should all look OK on the screeen.
#
# In interactive mode, turn on ipython interactive graphics
plt.ion()
# Start by clearing existing figures
plt.close('all')
# Define a set of systems to test
sys_siso = ct.tf([1], [1, 2, 1], name="SISO")
sys_mimo = ct.tf(
[[[1], [0.1]], [[0.2], [1]]],
[[[1, 0.6, 1], [1, 1, 1]], [[1, 0.4, 1], [1, 2, 1]]], name="MIMO")
sys_test = manual_response
# Run through a large number of test cases
test_cases = [
# sys pltmag pltphs shrmag shrphs shrfrq secsys
(sys_siso, True, True, None, None, None, False),
(sys_siso, True, True, None, None, None, True),
(sys_mimo, True, True, 'row', 'row', 'col', False),
(sys_mimo, True, True, 'row', 'row', 'col', True),
(sys_test, True, True, 'row', 'row', 'col', False),
(sys_test, True, True, 'row', 'row', 'col', True),
(sys_test, True, True, 'none', 'none', 'col', True),
(sys_test, True, True, 'all', 'row', 'col', False),
(sys_test, True, True, 'row', 'all', 'col', True),
(sys_test, True, True, None, 'row', 'col', False),
(sys_test, True, True, 'row', None, 'col', True),
]
for args in test_cases:
test_response_plots(*args, ovlinp=False, ovlout=False, clear=False)
# Define and run a selected set of interesting tests
# TODO: TBD (see timeplot_test.py for format)
test_basic_freq_plots(savefigs=True)
test_gangof4_plots(savefigs=True)
#
# Run a few more special cases to show off capabilities (and save some
# of them for use in the documentation).
#
pass