From 44de990cbca29ca7688534a172658ea89cb34d15 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Sat, 6 Jul 2019 22:39:05 -0700 Subject: [PATCH 1/2] update config module to use dictionary + module.variable format --- control/config.py | 72 +++++++++++++++++--------------- control/freqplot.py | 79 +++++++++++++++++++----------------- control/matlab/__init__.py | 4 ++ control/statesp.py | 22 ++++++---- control/tests/config_test.py | 25 +++++++----- doc/conventions.rst | 35 ++++++++++------ 6 files changed, 136 insertions(+), 101 deletions(-) diff --git a/control/config.py b/control/config.py index ff0b3d36c..d920ec65f 100644 --- a/control/config.py +++ b/control/config.py @@ -5,58 +5,66 @@ # variables that control the behavior of the control package. # Eventually it will be possible to read and write configuration # files. For now, you can just choose between MATLAB and FBS default -# values. +# values + tweak a few other things. import warnings -# Bode plot defaults -bode_dB = False # Bode plot magnitude units -bode_deg = True # Bode Plot phase units -bode_Hz = False # Bode plot frequency units -bode_number_of_samples = None # Bode plot number of samples -bode_feature_periphery_decade = 1.0 # Bode plot feature periphery in decades +__all__ = ['reset_defaults', 'use_matlab_defaults', 'use_fbs_defaults', + 'use_numpy_matrix'] + +# Dictionary of default values +defaults = { + 'bode.dB':False, 'bode.deg':True, 'bode.Hz':False, 'bode.grid':True, + 'freqplot.feature_periphery_decades':1, 'freqplot.number_of_samples':None, + 'statesp.use_numpy_matrix':True, +} -# State space module variables -_use_numpy_matrix = True # Decide whether to use numpy.marix def reset_defaults(): - """Reset package configuration values to their default values.""" - global bode_dB; bode_dB = False - global bode_deg; bode_deg = True - global bode_Hz; bode_Hz = False - global bode_number_of_samples; bode_number_of_samples = None - global bode_feature_periphery_decade; bode_feature_periphery_decade = 1.0 - global _use_numpy_matrix; _use_numpy_matrix = True + """Reset configuration values to their default values.""" + defaults['bode.dB'] = False + defaults['bode.deg'] = True + defaults['bode.Hz'] = False + defaults['bode.grid'] = True + defaults['freqplot.number_of_samples'] = None + defaults['freqplot.feature_periphery_decades'] = 1.0 + defaults['statesp.use_numpy_matrix'] = True # Set defaults to match MATLAB def use_matlab_defaults(): - """ - Use MATLAB compatible configuration settings + """Use MATLAB compatible configuration settings. The following conventions are used: - * Bode plots plot gain in dB, phase in degrees, frequency in Hertz + * Bode plots plot gain in dB, phase in degrees, frequency in + Hertz, with grids + """ # Bode plot defaults - global bode_dB; bode_dB = True - global bode_deg; bode_deg = True - global bode_Hz; bode_Hz = True - global _use_numpy_matrix; _use_numpy_matrix = True + from .freqplot import bode_plot + defaults['bode.dB'] = True + defaults['bode.deg'] = True + defaults['bode.Hz'] = True + defaults['bode.grid'] = True + defaults['statesp.use_numpy_matrix'] = True # Set defaults to match FBS (Astrom and Murray) def use_fbs_defaults(): - """ - Use `Feedback Systems `_ (FBS) compatible settings + """Use `Feedback Systems `_ (FBS) compatible settings. The following conventions are used: + * Bode plots plot gain in powers of ten, phase in degrees, - frequency in Hertz + frequency in Hertz, no grid + """ # Bode plot defaults - global bode_dB; bode_dB = False - global bode_deg; bode_deg = True - global bode_Hz; bode_Hz = False + from .freqplot import bode_plot + defaults['bode.dB'] = False + defaults['bode.deg'] = True + defaults['bode.Hz'] = False + defaults['bode.grid'] = False # Decide whether to use numpy.matrix for state space operations @@ -68,8 +76,8 @@ def use_numpy_matrix(flag=True, warn=True): flag : bool If flag is `True` (default), use the Numpy (soon to be deprecated) `matrix` class to represent matrices in the `~control.StateSpace` - class and functions. If flat is `False`, then matrices are represnted - by a 2D `ndarray` object. + class and functions. If flat is `False`, then matrices are + represented by a 2D `ndarray` object. warn : bool If flag is `True` (default), issue a warning when turning on the use @@ -80,4 +88,4 @@ class and functions. If flat is `False`, then matrices are represnted if flag and warn: warnings.warn("Return type numpy.matrix is soon to be deprecated.", stacklevel=2) - global _use_numpy_matrix; _use_numpy_matrix = flag + defaults['statesp.use_numpy_matrix'] = flag diff --git a/control/freqplot.py b/control/freqplot.py index 85880740c..2e2ba0bc0 100644 --- a/control/freqplot.py +++ b/control/freqplot.py @@ -48,6 +48,7 @@ from .ctrlutil import unwrap from .bdalg import feedback from .margins import stability_margins +from .config import defaults __all__ = ['bode_plot', 'nyquist_plot', 'gangof4_plot', 'bode', 'nyquist', 'gangof4'] @@ -62,10 +63,10 @@ # Bode plot -def bode_plot(syslist, omega=None, dB=None, Hz=None, deg=None, - Plot=True, omega_limits=None, omega_num=None, margins=None, *args, **kwargs): - """ - Bode plot for a system +def bode_plot(syslist, omega=None, + Plot=True, omega_limits=None, omega_num=None, + margins=None, *args, **kwargs): + """Bode plot for a system Plots a Bode plot for the system over a (optional) frequency range. @@ -76,18 +77,21 @@ def bode_plot(syslist, omega=None, dB=None, Hz=None, deg=None, omega : list List of frequencies in rad/sec to be used for frequency response dB : boolean - If True, plot result in dB + If True, plot result in dB. Defaults to config.defaults['bode.dB']. Hz : boolean - If True, plot frequency in Hz (omega must be provided in rad/sec) + If True, plot frequency in Hz (omega must be provided in rad/sec). + Defaults to config.defaults['bode.Hz'] deg : boolean - If True, plot phase in degrees (else radians) + If True, plot phase in degrees (else radians). Defaults to + config.defaults['bode.deg'] Plot : boolean If True, plot magnitude and phase omega_limits: tuple, list, ... of two values Limits of the to generate frequency vector. If Hz=True the limits are in Hz otherwise in rad/s. omega_num: int - number of samples + Number of samples to plot. Defaults to + config.defaults['freqplot.number_of_samples']. margins : boolean If True, plot gain and phase margin \*args, \**kwargs: @@ -102,6 +106,12 @@ def bode_plot(syslist, omega=None, dB=None, Hz=None, deg=None, omega : array (list if len(syslist) > 1) frequency in rad/sec + Other Parameters + ---------------- + grid : bool + If True, plot grid lines on gain and phase plots. Default is set by + config.defaults['bode.grid']. + Notes ----- 1. Alternatively, you may use the lower-level method (mag, phase, freq) @@ -117,15 +127,13 @@ def bode_plot(syslist, omega=None, dB=None, Hz=None, deg=None, -------- >>> sys = ss("1. -2; 3. -4", "5.; 7", "6. 8", "9.") >>> mag, phase, omega = bode(sys) + """ - # Set default values for options - from . import config - if dB is None: - dB = config.bode_dB - if deg is None: - deg = config.bode_deg - if Hz is None: - Hz = config.bode_Hz + # Set default values for options (and pop from list to allow use in plots) + dB = kwargs.pop('dB', defaults.get('bode.dB', False)) + deg = kwargs.pop('deg', defaults.get('bode.deg', True)) + Hz = kwargs.pop('Hz', defaults.get('bode.Hz', False)) + grid = kwargs.pop('grid', defaults.get('bode.grid', True)) # If argument was a singleton, turn it into a list if not getattr(syslist, '__iter__', False): @@ -235,7 +243,7 @@ def bode_plot(syslist, omega=None, dB=None, Hz=None, deg=None, color=pltline[0].get_color()) # Add a grid to the plot + labeling - ax_mag.grid(False if margins else True, which='both') + ax_mag.grid(grid and not margins, which='both') ax_mag.set_ylabel("Magnitude (dB)" if dB else "Magnitude") # Phase plot @@ -377,7 +385,7 @@ def gen_zero_centered_series(val_min, val_max, period): ylim[1], math.pi / 12.), minor=True) - ax_phase.grid(False if margins else True, which='both') + ax_phase.grid(grid and not margins, which='both') # ax_mag.grid(which='minor', alpha=0.3) # ax_mag.grid(which='major', alpha=0.9) # ax_phase.grid(which='minor', alpha=0.3) @@ -592,7 +600,7 @@ def gangof4_plot(P, C, omega=None): # Compute reasonable defaults for axes def default_frequency_range(syslist, Hz=None, number_of_samples=None, - feature_periphery_decade=None): + feature_periphery_decades=None): """Compute a reasonable default frequency range for frequency domain plots. @@ -603,24 +611,18 @@ def default_frequency_range(syslist, Hz=None, number_of_samples=None, ---------- syslist : list of LTI List of linear input/output systems (single system is OK) - Hz : bool If True, the limits (first and last value) of the frequencies are set to full decades in Hz so it fits plotting with logarithmic scale in Hz otherwise in rad/s. Omega is always returned in rad/sec. - number_of_samples : int, optional - Number of samples to generate. Defaults to ``numpy.logspace`` default - value. - - feature_periphery_decade : float, optional + Number of samples to generate. The default value is read from + ``config.defaults['freqplot.number_of_samples']. If None, then the + default from `numpy.logspace` is used. + feature_periphery_decades : float, optional Defines how many decades shall be included in the frequency range on - both sides of features (poles, zeros). - - Example: If there is a feature, e.g. a pole, at 1 Hz and - feature_periphery_decade=1., then the range of frequencies shall span - 0.1 .. 10 Hz. The default value is read from - ``config.bode_feature_periphery_decade``. + both sides of features (poles, zeros). The default value is read from + ``config.defaults['freqplot.feature_periphery_decades']``. Returns ------- @@ -643,9 +645,10 @@ def default_frequency_range(syslist, Hz=None, number_of_samples=None, # Set default values for options from . import config if number_of_samples is None: - number_of_samples = config.bode_number_of_samples - if feature_periphery_decade is None: - feature_periphery_decade = config.bode_feature_periphery_decade + number_of_samples = config.defaults['freqplot.number_of_samples'] + if feature_periphery_decades is None: + feature_periphery_decades = \ + config.defaults['freqplot.feature_periphery_decades'] # Find the list of all poles and zeros in the systems features = np.array(()) @@ -693,14 +696,14 @@ def default_frequency_range(syslist, Hz=None, number_of_samples=None, if Hz: features /= 2. * math.pi features = np.log10(features) - lsp_min = np.floor(np.min(features) - feature_periphery_decade) - lsp_max = np.ceil(np.max(features) + feature_periphery_decade) + lsp_min = np.floor(np.min(features) - feature_periphery_decades) + lsp_max = np.ceil(np.max(features) + feature_periphery_decades) lsp_min += np.log10(2. * math.pi) lsp_max += np.log10(2. * math.pi) else: features = np.log10(features) - lsp_min = np.floor(np.min(features) - feature_periphery_decade) - lsp_max = np.ceil(np.max(features) + feature_periphery_decade) + lsp_min = np.floor(np.min(features) - feature_periphery_decades) + lsp_max = np.ceil(np.max(features) + feature_periphery_decades) if freq_interesting: lsp_min = min(lsp_min, np.log10(min(freq_interesting))) lsp_max = max(lsp_max, np.log10(max(freq_interesting))) diff --git a/control/matlab/__init__.py b/control/matlab/__init__.py index a13579f90..413dc6d86 100644 --- a/control/matlab/__init__.py +++ b/control/matlab/__init__.py @@ -87,6 +87,10 @@ from .timeresp import * from .wrappers import * +# Set up defaults corresponding to MATLAB conventions +from ..config import * +use_matlab_defaults() + r""" The following tables give an overview of the module ``control.matlab``. They also show the implementation progress and the planned features of the diff --git a/control/statesp.py b/control/statesp.py index 820e40728..3fe6302f7 100644 --- a/control/statesp.py +++ b/control/statesp.py @@ -86,7 +86,7 @@ def _ssmatrix(data, axis=1): """ # Convert the data into an array or matrix, as configured # If data is passed as a string, use (deprecated?) matrix constructor - if config._use_numpy_matrix or isinstance(data, str): + if config.defaults['statesp.use_numpy_matrix'] or isinstance(data, str): arr = np.matrix(data, dtype=float) else: arr = np.array(data, dtype=float) @@ -128,15 +128,21 @@ class StateSpace(LTI): where u is the input, y is the output, and x is the state. The main data members are the A, B, C, and D matrices. The class also - keeps track of the number of states (i.e., the size of A). - - Discrete-time state space system are implemented by using the 'dt' instance - variable and setting it to the sampling period. If 'dt' is not None, - then it must match whenever two state space systems are combined. + keeps track of the number of states (i.e., the size of A). The data + format used to store state space matrices is set using the value of + `config.defaults['use_numpy_matrix']`. If True (default), the state space + elements are stored as `numpy.matrix` objects; otherwise they are + `numpy.ndarray` objects. The :func:`~control.use_numpy_matrix` function + can be used to set the storage type. + + Discrete-time state space system are implemented by using the 'dt' + instance variable and setting it to the sampling period. If 'dt' is not + None, then it must match whenever two state space systems are combined. Setting dt = 0 specifies a continuous system, while leaving dt = None means the system timebase is not specified. If 'dt' is set to True, the - system will be treated as a discrete time system with unspecified - sampling time. + system will be treated as a discrete time system with unspecified sampling + time. + """ # Allow ndarray * StateSpace to give StateSpace._rmul_() priority diff --git a/control/tests/config_test.py b/control/tests/config_test.py index 99b86e9d3..723f36a76 100644 --- a/control/tests/config_test.py +++ b/control/tests/config_test.py @@ -11,6 +11,7 @@ import matplotlib.pyplot as plt from math import pi, log10 + class TestConfig(unittest.TestCase): def setUp(self): # Create a simple second order system to use for testing @@ -109,9 +110,9 @@ def test_matlab_bode(self): ct.reset_defaults() def test_custom_bode_default(self): - ct.bode_dB = True - ct.bode_deg = True - ct.bode_Hz = True + ct.config.defaults['bode.dB'] = True + ct.config.defaults['bode.deg'] = True + ct.config.defaults['bode.Hz'] = True # Generate a Bode plot plt.figure() @@ -137,7 +138,7 @@ def test_bode_number_of_samples(self): self.assertEqual(len(mag_ret), 87) # Change the default number of samples - ct.config.bode_number_of_samples = 76 + ct.config.defaults['freqplot.number_of_samples'] = 76 mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys) self.assertEqual(len(mag_ret), 76) @@ -154,7 +155,7 @@ def test_bode_feature_periphery_decade(self): omega_min, omega_max = omega_ret[[0, -1]] # Reset the periphery decade value (should add one decade on each end) - ct.config.bode_feature_periphery_decade = 2 + ct.config.defaults['freqplot.feature_periphery_decades'] = 2 mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, Hz=False) np.testing.assert_almost_equal(omega_ret[0], omega_min/10) np.testing.assert_almost_equal(omega_ret[-1], omega_max * 10) @@ -162,7 +163,7 @@ def test_bode_feature_periphery_decade(self): # Make sure it also works in rad/sec, in opposite direction mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, Hz=True) omega_min, omega_max = omega_ret[[0, -1]] - ct.config.bode_feature_periphery_decade = 1 + ct.config.defaults['freqplot.feature_periphery_decades'] = 1 mag_ret, phase_ret, omega_ret = ct.bode_plot(self.sys, Hz=True) np.testing.assert_almost_equal(omega_ret[0], omega_min*10) np.testing.assert_almost_equal(omega_ret[-1], omega_max/10) @@ -172,11 +173,13 @@ def test_bode_feature_periphery_decade(self): def test_reset_defaults(self): ct.use_matlab_defaults() ct.reset_defaults() - self.assertEquals(ct.config.bode_dB, False) - self.assertEquals(ct.config.bode_deg, True) - self.assertEquals(ct.config.bode_Hz, False) - self.assertEquals(ct.config.bode_number_of_samples, None) - self.assertEquals(ct.config.bode_feature_periphery_decade, 1.0) + self.assertEqual(ct.config.defaults['bode.dB'], False) + self.assertEqual(ct.config.defaults['bode.deg'], True) + self.assertEqual(ct.config.defaults['bode.Hz'], False) + self.assertEqual( + ct.config.defaults['freqplot.number_of_samples'], None) + self.assertEqual( + ct.config.defaults['freqplot.feature_periphery_decades'], 1.0) def tearDown(self): # Get rid of any figures that we created diff --git a/doc/conventions.rst b/doc/conventions.rst index 0ea0920b5..7dbc49aca 100644 --- a/doc/conventions.rst +++ b/doc/conventions.rst @@ -190,20 +190,31 @@ can be computed like this:: Package configuration ===================== -The python-control library can be customized to allow for different plotting -conventions. The currently configurable options allow the units for Bode -plots to be set as dB for gain, degrees for phase and Hertz for frequency -(MATLAB conventions) or the gain can be given in magnitude units (powers of -10), corresponding to the conventions used in `Feedback Systems -`_ (FBS). +The python-control library can be customized to allow for different default +values for selected parameters. This includes the ability to set the style +for Bode plots and establishing the underlying representation for state space +matrices. + +To set the default value of a configuration variable, set the appropriate +element of the `control.config.defaults` dictionary: + +.. code-block:: python + + control.config.defaults['module.variable'] = value + +There are also +functions available set collections of variables based on standard +configurations. Variables that can be configured, along with their default values: - * bode_dB (False): Bode plot magnitude plotted in dB (otherwise powers of 10) - * bode_deg (True): Bode plot phase plotted in degrees (otherwise radians) - * bode_Hz (False): Bode plot frequency plotted in Hertz (otherwise rad/sec) - * bode_number_of_samples (None): Number of frequency points in Bode plots - * bode_feature_periphery_decade (1.0): How many decades to include in the - frequency range on both sides of features (poles, zeros). + * bode.dB (False): Bode plot magnitude plotted in dB (otherwise powers of 10) + * bode.deg (True): Bode plot phase plotted in degrees (otherwise radians) + * bode.Hz (False): Bode plot frequency plotted in Hertz (otherwise rad/sec) + * freqplot.number_of_samples (None): Number of frequency points in Bode plots + * freqplot.feature_periphery_decade (1.0): How many decades to include in the + frequency range on both sides of features (poles, zeros). + * statesp.use_numpy_matrix: set the return type for state space matrices to + `numpy.matrix` (verus numpy.ndarray) Functions that can be used to set standard configurations: From d66db805a36387b29787e22d3d16f58dc8b0d249 Mon Sep 17 00:00:00 2001 From: Richard Murray Date: Tue, 9 Jul 2019 22:52:06 -0700 Subject: [PATCH 2/2] refactor config module to use local dictionaries + better helper functions --- control/__init__.py | 3 + control/config.py | 127 ++++++++++---- control/freqplot.py | 299 +++++++++++++++++++-------------- control/nichols.py | 11 +- control/pzmap.py | 13 ++ control/rlocus.py | 19 ++- control/statesp.py | 6 + control/tests/config_test.py | 30 ++++ control/tests/freqresp_test.py | 36 ++++ doc/conventions.rst | 34 +++- 10 files changed, 406 insertions(+), 172 deletions(-) diff --git a/control/__init__.py b/control/__init__.py index 31873592a..3dec2c12f 100644 --- a/control/__init__.py +++ b/control/__init__.py @@ -84,3 +84,6 @@ from numpy.testing import Tester test = Tester().test bench = Tester().bench + +# Initialize default parameter values +reset_defaults() diff --git a/control/config.py b/control/config.py index d920ec65f..f61469394 100644 --- a/control/config.py +++ b/control/config.py @@ -9,26 +9,103 @@ import warnings -__all__ = ['reset_defaults', 'use_matlab_defaults', 'use_fbs_defaults', +__all__ = ['defaults', 'set_defaults', 'reset_defaults', + 'use_matlab_defaults', 'use_fbs_defaults', 'use_numpy_matrix'] -# Dictionary of default values -defaults = { - 'bode.dB':False, 'bode.deg':True, 'bode.Hz':False, 'bode.grid':True, - 'freqplot.feature_periphery_decades':1, 'freqplot.number_of_samples':None, - 'statesp.use_numpy_matrix':True, +# Package level default values +_control_defaults = { + # No package level defaults (yet) } +defaults = dict(_control_defaults) + + +def set_defaults(module, **keywords): + """Set default values of parameters for a module. + + The set_defaults() function can be used to modify multiple parameter + values for a module at the same time, using keyword arguments: + + control.set_defaults('module', param1=val, param2=val) + + """ + if not isinstance(module, str): + raise ValueError("module must be a string") + for key, val in keywords.items(): + defaults[module + '.' + key] = val def reset_defaults(): - """Reset configuration values to their default values.""" - defaults['bode.dB'] = False - defaults['bode.deg'] = True - defaults['bode.Hz'] = False - defaults['bode.grid'] = True - defaults['freqplot.number_of_samples'] = None - defaults['freqplot.feature_periphery_decades'] = 1.0 - defaults['statesp.use_numpy_matrix'] = True + """Reset configuration values to their default (initial) values.""" + # System level defaults + defaults.update(_control_defaults) + + from .freqplot import _bode_defaults, _freqplot_defaults + defaults.update(_bode_defaults) + defaults.update(_freqplot_defaults) + + from .nichols import _nichols_defaults + defaults.update(_nichols_defaults) + + from .pzmap import _pzmap_defaults + defaults.update(_pzmap_defaults) + + from .rlocus import _rlocus_defaults + defaults.update(_rlocus_defaults) + + from .statesp import _statesp_defaults + defaults.update(_statesp_defaults) + + +def _get_param(module, param, argval=None, defval=None, pop=False): + """Return the default value for a configuration option. + + The _get_param() function is a utility function used to get the value of a + parameter for a module based on the default parameter settings and any + arguments passed to the function. The precedence order for parameters is + the value passed to the function (as a keyword), the value from the + config.defaults dictionary, and the default value `defval`. + + Parameters + ---------- + module : str + Name of the module whose parameters are being requested. + param : str + Name of the parameter value to be determeind. + argval : object or dict + Value of the parameter as passed to the function. This can either be + an object or a dictionary (i.e. the keyword list from the function + call). Defaults to None. + defval : object + Default value of the parameter to use, if it is not located in the + `config.defaults` dictionary. If a dictionary is provided, then + `module.param` is used to determine the default value. Defaults to + None. + pop : bool + If True and if argval is a dict, then pop the remove the parameter + entry from the argval dict after retreiving it. This allows the use + of a keyword argument list to be passed through to other functions + internal to the function being called. + + """ + + # Make sure that we were passed sensible arguments + if not isinstance(module, str) or not isinstance(param, str): + raise ValueError("module and param must be strings") + + # Construction the name of the key, for later use + key = module + '.' + param + + # If we were passed a dict for the argval, get the param value from there + if isinstance(argval, dict): + argval = argval.pop(param, None) if pop else argval.get(param, None) + + # If we were passed a dict for the defval, get the param value from there + if isinstance(defval, dict): + defval = defval.get(key, None) + + # Return the parameter value to use (argval > defaults > defval) + return argval if argval is not None else defaults.get(key, defval) # Set defaults to match MATLAB @@ -38,15 +115,11 @@ def use_matlab_defaults(): The following conventions are used: * Bode plots plot gain in dB, phase in degrees, frequency in Hertz, with grids + * State space class and functions use Numpy matrix objects """ - # Bode plot defaults - from .freqplot import bode_plot - defaults['bode.dB'] = True - defaults['bode.deg'] = True - defaults['bode.Hz'] = True - defaults['bode.grid'] = True - defaults['statesp.use_numpy_matrix'] = True + set_defaults('bode', dB=True, deg=True, Hz=True, grid=True) + set_defaults('statesp', use_numpy_matrix=True) # Set defaults to match FBS (Astrom and Murray) @@ -54,17 +127,11 @@ def use_fbs_defaults(): """Use `Feedback Systems `_ (FBS) compatible settings. The following conventions are used: - * Bode plots plot gain in powers of ten, phase in degrees, frequency in Hertz, no grid """ - # Bode plot defaults - from .freqplot import bode_plot - defaults['bode.dB'] = False - defaults['bode.deg'] = True - defaults['bode.Hz'] = False - defaults['bode.grid'] = False + set_defaults('bode', dB=False, deg=True, Hz=False, grid=False) # Decide whether to use numpy.matrix for state space operations @@ -87,5 +154,5 @@ class and functions. If flat is `False`, then matrices are """ if flag and warn: warnings.warn("Return type numpy.matrix is soon to be deprecated.", - stacklevel=2) - defaults['statesp.use_numpy_matrix'] = flag + stacklevel=2) + set_defaults('statesp', use_numpy_matrix=flag) diff --git a/control/freqplot.py b/control/freqplot.py index 2e2ba0bc0..0802a084e 100644 --- a/control/freqplot.py +++ b/control/freqplot.py @@ -40,7 +40,7 @@ # SUCH DAMAGE. # # $Id$ -import matplotlib +import matplotlib as mpl import matplotlib.pyplot as plt import scipy as sp import numpy as np @@ -48,11 +48,17 @@ from .ctrlutil import unwrap from .bdalg import feedback from .margins import stability_margins -from .config import defaults +from . import config __all__ = ['bode_plot', 'nyquist_plot', 'gangof4_plot', 'bode', 'nyquist', 'gangof4'] +# Default values for module parameter variables +_freqplot_defaults = { + 'freqplot.feature_periphery_decades': 1, + 'freqplot.number_of_samples': None, +} + # # Main plotting functions # @@ -60,7 +66,17 @@ # frequency domain plots # +# # Bode plot +# + +# Default values for Bode plot configuration variables +_bode_defaults = { + 'bode.dB': False, # Plot gain in dB + 'bode.deg': True, # Plot phase in degrees + 'bode.Hz': False, # Plot frequency in Hertz + 'bode.grid': True, # Turn on grid for gain and phase +} def bode_plot(syslist, omega=None, @@ -76,15 +92,15 @@ def bode_plot(syslist, omega=None, List of linear input/output systems (single system is OK) omega : list List of frequencies in rad/sec to be used for frequency response - dB : boolean - If True, plot result in dB. Defaults to config.defaults['bode.dB']. - Hz : boolean + dB : bool + If True, plot result in dB. Default is false. + Hz : bool If True, plot frequency in Hz (omega must be provided in rad/sec). - Defaults to config.defaults['bode.Hz'] - deg : boolean - If True, plot phase in degrees (else radians). Defaults to + Default value (False) set by config.defaults['bode.Hz'] + deg : bool + If True, plot phase in degrees (else radians). Default value (True) config.defaults['bode.deg'] - Plot : boolean + Plot : bool If True, plot magnitude and phase omega_limits: tuple, list, ... of two values Limits of the to generate frequency vector. @@ -92,8 +108,8 @@ def bode_plot(syslist, omega=None, omega_num: int Number of samples to plot. Defaults to config.defaults['freqplot.number_of_samples']. - margins : boolean - If True, plot gain and phase margin + margins : bool + If True, plot gain and phase margin. \*args, \**kwargs: Additional options to matplotlib (color, linestyle, etc) @@ -112,6 +128,9 @@ def bode_plot(syslist, omega=None, If True, plot grid lines on gain and phase plots. Default is set by config.defaults['bode.grid']. + The default values for Bode plot configuration parameters can be reset + using the `config.defaults` dictionary, with module name 'bode'. + Notes ----- 1. Alternatively, you may use the lower-level method (mag, phase, freq) @@ -129,11 +148,16 @@ def bode_plot(syslist, omega=None, >>> mag, phase, omega = bode(sys) """ - # Set default values for options (and pop from list to allow use in plots) - dB = kwargs.pop('dB', defaults.get('bode.dB', False)) - deg = kwargs.pop('deg', defaults.get('bode.deg', True)) - Hz = kwargs.pop('Hz', defaults.get('bode.Hz', False)) - grid = kwargs.pop('grid', defaults.get('bode.grid', True)) + # Make a copy of the kwargs dictonary since we will modify it + kwargs = dict(kwargs) + + # Get values for params (and pop from list to allow keyword use in plot) + dB = config._get_param('bode', 'dB', kwargs, _bode_defaults, pop=True) + deg = config._get_param('bode', 'deg', kwargs, _bode_defaults, pop=True) + Hz = config._get_param('bode', 'Hz', kwargs, _bode_defaults, pop=True) + grid = config._get_param('bode', 'grid', kwargs, _bode_defaults, pop=True) + Plot = config._get_param('bode', 'grid', Plot, True) + margins = config._get_param('bode', 'margins', margins, False) # If argument was a singleton, turn it into a list if not getattr(syslist, '__iter__', False): @@ -142,26 +166,28 @@ def bode_plot(syslist, omega=None, if omega is None: if omega_limits is None: # Select a default range if none is provided - omega = default_frequency_range(syslist, Hz=Hz, number_of_samples=omega_num) + omega = default_frequency_range(syslist, Hz=Hz, + number_of_samples=omega_num) else: omega_limits = np.array(omega_limits) if Hz: omega_limits *= 2. * math.pi if omega_num: - omega = sp.logspace(np.log10(omega_limits[0]), - np.log10(omega_limits[1]), - num=omega_num, + omega = sp.logspace(np.log10(omega_limits[0]), + np.log10(omega_limits[1]), + num=omega_num, endpoint=True) else: - omega = sp.logspace(np.log10(omega_limits[0]), - np.log10(omega_limits[1]), + omega = sp.logspace(np.log10(omega_limits[0]), + np.log10(omega_limits[1]), endpoint=True) mags, phases, omegas, nyquistfrqs = [], [], [], [] for sys in syslist: if sys.inputs > 1 or sys.outputs > 1: # TODO: Add MIMO bode plots. - raise NotImplementedError("Bode is currently only implemented for SISO systems.") + raise NotImplementedError( + "Bode is currently only implemented for SISO systems.") else: omega_sys = np.array(omega) if sys.isdtime(True): @@ -256,7 +282,8 @@ def bode_plot(syslist, omega=None, # Show the phase and gain margins in the plot if margins: margin = stability_margins(sys) - gm, pm, Wcg, Wcp = margin[0], margin[1], margin[3], margin[4] + gm, pm, Wcg, Wcp = \ + margin[0], margin[1], margin[3], margin[4] # TODO: add some documentation describing why this is here phase_at_cp = phases[0][(np.abs(omegas[0] - Wcp)).argmin()] if phase_at_cp >= 0.: @@ -265,102 +292,106 @@ def bode_plot(syslist, omega=None, phase_limit = -180. if Hz: - Wcg, Wcp = Wcg/(2*math.pi),Wcp/(2*math.pi) + Wcg, Wcp = Wcg/(2*math.pi), Wcp/(2*math.pi) ax_mag.axhline(y=0 if dB else 1, color='k', linestyle=':', zorder=-20) - ax_phase.axhline(y=phase_limit if deg else math.radians(phase_limit), + ax_phase.axhline(y=phase_limit if deg else + math.radians(phase_limit), color='k', linestyle=':', zorder=-20) mag_ylim = ax_mag.get_ylim() phase_ylim = ax_phase.get_ylim() if pm != float('inf') and Wcp != float('nan'): if dB: - ax_mag.semilogx([Wcp, Wcp], [0.,-1e5], - color='k', linestyle=':', - zorder=-20) + ax_mag.semilogx( + [Wcp, Wcp], [0., -1e5], + color='k', linestyle=':', zorder=-20) else: - ax_mag.loglog([Wcp,Wcp], [1.,1e-8],color='k', - linestyle=':', zorder=-20) + ax_mag.loglog( + [Wcp, Wcp], [1., 1e-8], + color='k', linestyle=':', zorder=-20) if deg: - ax_phase.semilogx([Wcp, Wcp], - [1e5, phase_limit+pm], - color='k', linestyle=':', - zorder=-20) - ax_phase.semilogx([Wcp, Wcp], - [phase_limit + pm, phase_limit], - color='k', zorder=-20) + ax_phase.semilogx( + [Wcp, Wcp], [1e5, phase_limit+pm], + color='k', linestyle=':', zorder=-20) + ax_phase.semilogx( + [Wcp, Wcp], [phase_limit + pm, phase_limit], + color='k', zorder=-20) else: - ax_phase.semilogx([Wcp, Wcp], - [1e5, math.radians(phase_limit) + - math.radians(pm)], - color='k', linestyle=':', - zorder=-20) - ax_phase.semilogx([Wcp, Wcp], - [math.radians(phase_limit) + - math.radians(pm), - math.radians(phase_limit)], - color='k', zorder=-20) + ax_phase.semilogx( + [Wcp, Wcp], [1e5, math.radians(phase_limit) + + math.radians(pm)], + color='k', linestyle=':', zorder=-20) + ax_phase.semilogx( + [Wcp, Wcp], [math.radians(phase_limit) + + math.radians(pm), + math.radians(phase_limit)], + color='k', zorder=-20) if gm != float('inf') and Wcg != float('nan'): if dB: - ax_mag.semilogx([Wcg, Wcg], - [-20.*np.log10(gm), -1e5], - color='k', linestyle=':', - zorder=-20) - ax_mag.semilogx([Wcg, Wcg], [0,-20*np.log10(gm)], - color='k', zorder=-20) + ax_mag.semilogx( + [Wcg, Wcg], [-20.*np.log10(gm), -1e5], + color='k', linestyle=':', zorder=-20) + ax_mag.semilogx( + [Wcg, Wcg], [0, -20*np.log10(gm)], + color='k', zorder=-20) else: - ax_mag.loglog([Wcg, Wcg], - [1./gm,1e-8],color='k', - linestyle=':', zorder=-20) - ax_mag.loglog([Wcg, Wcg], - [1.,1./gm],color='k', zorder=-20) + ax_mag.loglog( + [Wcg, Wcg], [1./gm, 1e-8], color='k', + linestyle=':', zorder=-20) + ax_mag.loglog( + [Wcg, Wcg], [1., 1./gm], color='k', zorder=-20) if deg: - ax_phase.semilogx([Wcg, Wcg], [1e-8, phase_limit], - color='k', linestyle=':', - zorder=-20) + ax_phase.semilogx( + [Wcg, Wcg], [1e-8, phase_limit], + color='k', linestyle=':', zorder=-20) else: - ax_phase.semilogx([Wcg, Wcg], - [1e-8, math.radians(phase_limit)], - color='k', linestyle=':', - zorder=-20) + ax_phase.semilogx( + [Wcg, Wcg], [1e-8, math.radians(phase_limit)], + color='k', linestyle=':', zorder=-20) ax_mag.set_ylim(mag_ylim) ax_phase.set_ylim(phase_ylim) if sisotool: - ax_mag.text(0.04, 0.06, - 'G.M.: %.2f %s\nFreq: %.2f %s' % - (20*np.log10(gm) if dB else gm, - 'dB ' if dB else '', - Wcg, 'Hz' if Hz else 'rad/s'), - horizontalalignment='left', - verticalalignment='bottom', - transform=ax_mag.transAxes, - fontsize=8 if int(matplotlib.__version__[0]) == 1 else 6) - ax_phase.text(0.04, 0.06, - 'P.M.: %.2f %s\nFreq: %.2f %s' % - (pm if deg else math.radians(pm), - 'deg' if deg else 'rad', - Wcp, 'Hz' if Hz else 'rad/s'), - horizontalalignment='left', - verticalalignment='bottom', - transform=ax_phase.transAxes, - fontsize=8 if int(matplotlib.__version__[0]) == 1 else 6) + ax_mag.text( + 0.04, 0.06, + 'G.M.: %.2f %s\nFreq: %.2f %s' % + (20*np.log10(gm) if dB else gm, + 'dB ' if dB else '', + Wcg, 'Hz' if Hz else 'rad/s'), + horizontalalignment='left', + verticalalignment='bottom', + transform=ax_mag.transAxes, + fontsize=8 if int(mpl.__version__[0]) == 1 else 6) + ax_phase.text( + 0.04, 0.06, + 'P.M.: %.2f %s\nFreq: %.2f %s' % + (pm if deg else math.radians(pm), + 'deg' if deg else 'rad', + Wcp, 'Hz' if Hz else 'rad/s'), + horizontalalignment='left', + verticalalignment='bottom', + transform=ax_phase.transAxes, + fontsize=8 if int(mpl.__version__[0]) == 1 else 6) else: - plt.suptitle('Gm = %.2f %s(at %.2f %s), Pm = %.2f %s (at %.2f %s)' % - (20*np.log10(gm) if dB else gm, - 'dB ' if dB else '\b', - Wcg, 'Hz' if Hz else 'rad/s', - pm if deg else math.radians(pm), - 'deg' if deg else 'rad', - Wcp, 'Hz' if Hz else 'rad/s')) + plt.suptitle( + "Gm = %.2f %s(at %.2f %s), " + "Pm = %.2f %s (at %.2f %s)" % + (20*np.log10(gm) if dB else gm, + 'dB ' if dB else '\b', + Wcg, 'Hz' if Hz else 'rad/s', + pm if deg else math.radians(pm), + 'deg' if deg else 'rad', + Wcp, 'Hz' if Hz else 'rad/s')) if nyquistfrq_plot: - ax_phase.axvline(nyquistfrq_plot, color=pltline[0].get_color()) + ax_phase.axvline( + nyquistfrq_plot, color=pltline[0].get_color()) # Add a grid to the plot + labeling ax_phase.set_ylabel("Phase (deg)" if deg else "Phase (rad)") @@ -371,20 +402,16 @@ def gen_zero_centered_series(val_min, val_max, period): return np.arange(v1, v2 + 1) * period if deg: ylim = ax_phase.get_ylim() - ax_phase.set_yticks(gen_zero_centered_series(ylim[0], - ylim[1], 45.)) - ax_phase.set_yticks(gen_zero_centered_series(ylim[0], - ylim[1], 15.), - minor=True) + ax_phase.set_yticks(gen_zero_centered_series( + ylim[0], ylim[1], 45.)) + ax_phase.set_yticks(gen_zero_centered_series( + ylim[0], ylim[1], 15.), minor=True) else: ylim = ax_phase.get_ylim() - ax_phase.set_yticks(gen_zero_centered_series(ylim[0], - ylim[1], - math.pi / 4.)) - ax_phase.set_yticks(gen_zero_centered_series(ylim[0], - ylim[1], - math.pi / 12.), - minor=True) + ax_phase.set_yticks(gen_zero_centered_series( + ylim[0], ylim[1], math.pi / 4.)) + ax_phase.set_yticks(gen_zero_centered_series( + ylim[0], ylim[1], math.pi / 12.), minor=True) ax_phase.grid(grid and not margins, which='both') # ax_mag.grid(which='minor', alpha=0.3) # ax_mag.grid(which='major', alpha=0.9) @@ -400,6 +427,9 @@ def gen_zero_centered_series(val_min, val_max, period): else: return mags, phases, omegas +# +# Nyquist plot +# def nyquist_plot(syslist, omega=None, Plot=True, color=None, labelFreq=0, *args, **kwargs): @@ -450,15 +480,16 @@ def nyquist_plot(syslist, omega=None, Plot=True, color=None, elif isinstance(omega, list) or isinstance(omega, tuple): # Only accept tuple or list of length 2 if len(omega) != 2: - raise ValueError("Supported frequency arguments are (wmin,wmax) tuple or list, " - "or frequency vector. ") + raise ValueError("Supported frequency arguments are (wmin,wmax)" + "tuple or list, or frequency vector. ") omega = np.logspace(np.log10(omega[0]), np.log10(omega[1]), num=50, endpoint=True, base=10.0) for sys in syslist: if sys.inputs > 1 or sys.outputs > 1: # TODO: Add MIMO nyquist plots. - raise NotImplementedError("Nyquist is currently only implemented for SISO systems.") + raise NotImplementedError( + "Nyquist is currently only implemented for SISO systems.") else: # Get the magnitude and phase of the system mag_tmp, phase_tmp, omega = sys.freqresp(omega) @@ -479,8 +510,9 @@ def nyquist_plot(syslist, omega=None, Plot=True, color=None, head_width=0.2, head_length=0.2) plt.plot(x, -y, '-', color=c, *args, **kwargs) - ax.arrow(x[-1], -y[-1], (x[-1]-x[-2])/2, (y[-1]-y[-2])/2, fc=c, ec=c, - head_width=0.2, head_length=0.2) + ax.arrow( + x[-1], -y[-1], (x[-1]-x[-2])/2, (y[-1]-y[-2])/2, + fc=c, ec=c, head_width=0.2, head_length=0.2) # Mark the -1 point plt.plot([-1], [0], 'r+') @@ -505,7 +537,8 @@ def nyquist_plot(syslist, omega=None, Plot=True, color=None, # np.round() is used because 0.99... appears # instead of 1.0, and this would otherwise be # truncated to 0. - plt.text(xpt, ypt, ' ' + str(int(np.round(f / 1000 ** pow1000, 0))) + ' ' + + plt.text(xpt, ypt, ' ' + + str(int(np.round(f / 1000 ** pow1000, 0))) + ' ' + prefix + 'Hz') if Plot: @@ -516,6 +549,9 @@ def nyquist_plot(syslist, omega=None, Plot=True, color=None, return x, y, omega +# +# Gang of Four plot +# # TODO: think about how (and whether) to handle lists of systems def gangof4_plot(P, C, omega=None): @@ -537,7 +573,8 @@ def gangof4_plot(P, C, omega=None): """ if P.inputs > 1 or P.outputs > 1 or C.inputs > 1 or C.outputs > 1: # TODO: Add MIMO go4 plots. - raise NotImplementedError("Gang of four is currently only implemented for SISO systems.") + raise NotImplementedError( + "Gang of four is currently only implemented for SISO systems.") else: # Select a default range if none is provided @@ -558,7 +595,8 @@ def gangof4_plot(P, C, omega=None): if label.startswith('control-gangof4-'): key = label[len('control-gangof4-'):] if key not in plot_axes: - raise RuntimeError("unknown gangof4 axis type '{}'".format(label)) + raise RuntimeError( + "unknown gangof4 axis type '{}'".format(label)) plot_axes[key] = ax # if any of the axes are missing, start from scratch @@ -597,9 +635,8 @@ def gangof4_plot(P, C, omega=None): # generating frequency domain plots # - # Compute reasonable defaults for axes -def default_frequency_range(syslist, Hz=None, number_of_samples=None, +def default_frequency_range(syslist, Hz=None, number_of_samples=None, feature_periphery_decades=None): """Compute a reasonable default frequency range for frequency domain plots. @@ -643,12 +680,10 @@ def default_frequency_range(syslist, Hz=None, number_of_samples=None, # are found, it turns logspace(-1, 1) # Set default values for options - from . import config - if number_of_samples is None: - number_of_samples = config.defaults['freqplot.number_of_samples'] - if feature_periphery_decades is None: - feature_periphery_decades = \ - config.defaults['freqplot.feature_periphery_decades'] + number_of_samples = config._get_param( + 'freqplot', 'number_of_samples', number_of_samples) + feature_periphery_decades = config._get_param( + 'freqplot', 'feature_periphery_decades', feature_periphery_decades, 1) # Find the list of all poles and zeros in the systems features = np.array(()) @@ -677,15 +712,18 @@ def default_frequency_range(syslist, Hz=None, number_of_samples=None, # Get rid of poles and zeros # * at the origin and real <= 0 & imag==0: log! # * at 1.: would result in omega=0. (logaritmic plot!) - features_ = features_[(features_.imag != 0.0) | (features_.real > 0.)] - features_ = features_[np.bitwise_not((features_.imag == 0.0) & - (np.abs(features_.real - 1.0) < 1.e-10))] + features_ = features_[ + (features_.imag != 0.0) | (features_.real > 0.)] + features_ = features_[ + np.bitwise_not((features_.imag == 0.0) & + (np.abs(features_.real - 1.0) < 1.e-10))] # TODO: improve features__ = np.abs(np.log(features_) / (1.j * sys.dt)) features = np.concatenate((features, features__)) else: # TODO - raise NotImplementedError('type of system in not implemented now') + raise NotImplementedError( + "type of system in not implemented now") except: pass @@ -713,17 +751,18 @@ def default_frequency_range(syslist, Hz=None, number_of_samples=None, # Set the range to be an order of magnitude beyond any features if number_of_samples: - omega = sp.logspace(lsp_min, lsp_max, num=number_of_samples, endpoint=True) + omega = sp.logspace( + lsp_min, lsp_max, num=number_of_samples, endpoint=True) else: omega = sp.logspace(lsp_min, lsp_max, endpoint=True) return omega - # # KLD 5/23/11: Two functions to create nice looking labels # + def get_pow1000(num): - """Determine the exponent for which the significand of a number is within the + """Determine exponent for which significand of a number is within the range [1, 1000). """ # Based on algorithm from http://www.mail-archive.com/matplotlib-users@lists.sourceforge.net/msg14433.html, accessed 2010/11/7 @@ -744,7 +783,8 @@ def gen_prefix(pow1000): # Prefixes according to Table 5 of [BIPM 2006] (excluding hecto, # deca, deci, and centi). if pow1000 < -8 or pow1000 > 8: - raise ValueError("Value is out of the range covered by the SI prefixes.") + raise ValueError( + "Value is out of the range covered by the SI prefixes.") return ['Y', # yotta (10^24) 'Z', # zetta (10^21) 'E', # exa (10^18) @@ -763,11 +803,12 @@ def gen_prefix(pow1000): 'z', # zepto (10^-21) 'y'][8 - pow1000] # yocto (10^-24) + def find_nearest_omega(omega_list, omega): omega_list = np.asarray(omega_list) - idx = (np.abs(omega_list - omega)).argmin() return omega_list[(np.abs(omega_list - omega)).argmin()] + # Function aliases bode = bode_plot nyquist = nyquist_plot diff --git a/control/nichols.py b/control/nichols.py index a4c5795a4..48abffa0a 100644 --- a/control/nichols.py +++ b/control/nichols.py @@ -54,11 +54,17 @@ import matplotlib.pyplot as plt from .ctrlutil import unwrap from .freqplot import default_frequency_range +from . import config __all__ = ['nichols_plot', 'nichols', 'nichols_grid'] +# Default parameters values for the nichols module +_nichols_defaults = { + 'nichols.grid':True, +} -def nichols_plot(sys_list, omega=None, grid=True): + +def nichols_plot(sys_list, omega=None, grid=None): """Nichols plot for a system Plots a Nichols plot for the system over a (optional) frequency range. @@ -76,6 +82,9 @@ def nichols_plot(sys_list, omega=None, grid=True): ------- None """ + # Get parameter values + grid = config._get_param('nichols', 'grid', grid, True) + # If argument was a singleton, turn it into a list if not getattr(sys_list, '__iter__', False): diff --git a/control/pzmap.py b/control/pzmap.py index 252d10011..5fa777d0c 100644 --- a/control/pzmap.py +++ b/control/pzmap.py @@ -44,9 +44,18 @@ from math import pi from .lti import LTI, isdtime, isctime from .grid import sgrid, zgrid, nogrid +from . import config __all__ = ['pzmap'] + +# Define default parameter values for this module +_pzmap_defaults = { + 'pzmap.grid':False, # Plot omega-damping grid + 'pzmap.Plot':True, # Generate plot using Matplotlib +} + + # TODO: Implement more elegant cross-style axes. See: # http://matplotlib.sourceforge.net/examples/axes_grid/demo_axisline_style.html # http://matplotlib.sourceforge.net/examples/axes_grid/demo_curvelinear_grid.html @@ -71,6 +80,10 @@ def pzmap(sys, Plot=True, grid=False, title='Pole Zero Map'): zeros: array The system's zeros. """ + # Get parameter values + Plot = config._get_param('rlocus', 'Plot', grid, True) + grid = config._get_param('rlocus', 'grid', grid, False) + if not isinstance(sys, LTI): raise TypeError('Argument ``sys``: must be a linear system.') diff --git a/control/rlocus.py b/control/rlocus.py index 8ddd3896f..0c115c26e 100644 --- a/control/rlocus.py +++ b/control/rlocus.py @@ -46,6 +46,7 @@ # $Id$ # Packages used by this module +from functools import partial import numpy as np import matplotlib import matplotlib.pyplot as plt @@ -55,15 +56,22 @@ from .xferfcn import _convert_to_transfer_function from .exception import ControlMIMONotImplemented from .sisotool import _SisotoolUpdate -from functools import partial +from . import config __all__ = ['root_locus', 'rlocus'] +# Default values for module parameters +_rlocus_defaults = { + 'rlocus.grid':True, + 'rlocus.plotstr':'b' if int(matplotlib.__version__[0]) == 1 else 'C0', + 'rlocus.PrintGain':True, + 'rlocus.Plot':True +} + # Main function: compute a root locus diagram def root_locus(sys, kvect=None, xlim=None, ylim=None, - plotstr='b' if int(matplotlib.__version__[0]) == 1 else 'C0', - Plot=True, PrintGain=True, grid=False, **kwargs): + plotstr=None, Plot=True, PrintGain=None, grid=None, **kwargs): """Root locus plot @@ -96,6 +104,11 @@ def root_locus(sys, kvect=None, xlim=None, ylim=None, klist : ndarray or list Gains used. Same as klist keyword argument if provided. """ + # Get parameter values + plotstr = config._get_param('rlocus', 'plotstr', plotstr, _rlocus_defaults) + grid = config._get_param('rlocus', 'grid', grid, _rlocus_defaults) + PrintGain = config._get_param( + 'rlocus', 'PrintGain', PrintGain, _rlocus_defaults) # Convert numerator and denominator to polynomials if they aren't (nump, denp) = _systopoly1d(sys) diff --git a/control/statesp.py b/control/statesp.py index 3fe6302f7..85d48882a 100644 --- a/control/statesp.py +++ b/control/statesp.py @@ -68,6 +68,12 @@ __all__ = ['StateSpace', 'ss', 'rss', 'drss', 'tf2ss', 'ssdata'] +# Define module default parameter values +_statesp_defaults = { + 'statesp.use_numpy_matrix':True, +} + + def _ssmatrix(data, axis=1): """Convert argument to a (possibly empty) state space matrix. diff --git a/control/tests/config_test.py b/control/tests/config_test.py index 723f36a76..c0fc9755b 100644 --- a/control/tests/config_test.py +++ b/control/tests/config_test.py @@ -17,6 +17,36 @@ def setUp(self): # Create a simple second order system to use for testing self.sys = ct.tf([10], [1, 2, 1]) + def test_set_defaults(self): + ct.config.set_defaults('config', test1=1, test2=2, test3=None) + self.assertEqual(ct.config.defaults['config.test1'], 1) + self.assertEqual(ct.config.defaults['config.test2'], 2) + self.assertEqual(ct.config.defaults['config.test3'], None) + + def test_get_param(self): + self.assertEqual( + ct.config._get_param('bode', 'dB'), + ct.config.defaults['bode.dB']) + self.assertEqual(ct.config._get_param('bode', 'dB', 1), 1) + ct.config.defaults['config.test1'] = 1 + self.assertEqual(ct.config._get_param('config', 'test1', None), 1) + self.assertEqual(ct.config._get_param('config', 'test1', None, 1), 1) + + ct.config.defaults['config.test3'] = None + self.assertEqual(ct.config._get_param('config', 'test3'), None) + self.assertEqual(ct.config._get_param('config', 'test3', 1), 1) + self.assertEqual( + ct.config._get_param('config', 'test3', None, 1), None) + + self.assertEqual(ct.config._get_param('config', 'test4'), None) + self.assertEqual(ct.config._get_param('config', 'test4', 1), 1) + self.assertEqual(ct.config._get_param('config', 'test4', 2, 1), 2) + self.assertEqual(ct.config._get_param('config', 'test4', None, 3), 3) + + self.assertEqual( + ct.config._get_param('config', 'test4', {'test4':1}, None), 1) + + def test_fbs_bode(self): ct.use_fbs_defaults(); diff --git a/control/tests/freqresp_test.py b/control/tests/freqresp_test.py index 05247b46b..9c1382d8a 100644 --- a/control/tests/freqresp_test.py +++ b/control/tests/freqresp_test.py @@ -199,6 +199,42 @@ def test_discrete(self): # Calling bode should generate a not implemented error self.assertRaises(NotImplementedError, bode, (sys,)) + def test_options(self): + """Test ability to set parameter values""" + # Generate a Bode plot of a transfer function + sys = ctrl.tf([1000], [1, 25, 100, 0]) + fig1 = plt.figure() + ctrl.bode_plot(sys, dB=False, deg = True, Hz=False) + + # Save the parameter values + left1, right1 = fig1.axes[0].xaxis.get_data_interval() + numpoints1 = len(fig1.axes[0].lines[0].get_data()[0]) + + # Same transfer function, but add a decade on each end + ctrl.config.set_defaults('freqplot', feature_periphery_decades=2) + fig2 = plt.figure() + ctrl.bode_plot(sys, dB=False, deg = True, Hz=False) + left2, right2 = fig2.axes[0].xaxis.get_data_interval() + + # Make sure we got an extra decade on each end + self.assertAlmostEqual(left2, 0.1 * left1) + self.assertAlmostEqual(right2, 10 * right1) + + # Same transfer function, but add more points to the plot + ctrl.config.set_defaults( + 'freqplot', feature_periphery_decades=2, number_of_samples=13) + fig3 = plt.figure() + ctrl.bode_plot(sys, dB=False, deg = True, Hz=False) + numpoints3 = len(fig3.axes[0].lines[0].get_data()[0]) + + # Make sure we got the right number of points + self.assertNotEqual(numpoints1, numpoints3) + self.assertEqual(numpoints3, 13) + + # Reset default parameters to avoid contamination + ctrl.config.reset_defaults() + + def suite(): return unittest.TestLoader().loadTestsFromTestCase(TestTimeresp) diff --git a/doc/conventions.rst b/doc/conventions.rst index 7dbc49aca..56f29fbce 100644 --- a/doc/conventions.rst +++ b/doc/conventions.rst @@ -187,35 +187,51 @@ can be computed like this:: ft = D * U -Package configuration -===================== +Package configuration parameters +================================ The python-control library can be customized to allow for different default values for selected parameters. This includes the ability to set the style -for Bode plots and establishing the underlying representation for state space -matrices. +for various types of plots and establishing the underlying representation for +state space matrices. To set the default value of a configuration variable, set the appropriate element of the `control.config.defaults` dictionary: .. code-block:: python - control.config.defaults['module.variable'] = value + control.config.defaults['module.parameter'] = value -There are also -functions available set collections of variables based on standard -configurations. +The `~control.config.set_defaults` function can also be used to set multiple +configuration parameters at the same time: + +.. code-block:: python + + control.config.set_defaults('module', param1=val1, param2=val2, ...] + +Finally, there are also functions available set collections of variables based +on standard configurations. + +Selected variables that can be configured, along with their default values: -Variables that can be configured, along with their default values: * bode.dB (False): Bode plot magnitude plotted in dB (otherwise powers of 10) + * bode.deg (True): Bode plot phase plotted in degrees (otherwise radians) + * bode.Hz (False): Bode plot frequency plotted in Hertz (otherwise rad/sec) + + * bode.grid (True): Include grids for magnitude and phase plots + * freqplot.number_of_samples (None): Number of frequency points in Bode plots + * freqplot.feature_periphery_decade (1.0): How many decades to include in the frequency range on both sides of features (poles, zeros). + * statesp.use_numpy_matrix: set the return type for state space matrices to `numpy.matrix` (verus numpy.ndarray) +Additional parameter variables are documented in individual functions + Functions that can be used to set standard configurations: .. autosummary::