-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathiosys.py
More file actions
1371 lines (1144 loc) · 49.7 KB
/
iosys.py
File metadata and controls
1371 lines (1144 loc) · 49.7 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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# iosys.py - I/O system class and helper functions
# RMM, 13 Mar 2022
"""I/O system class and helper functions.
This module implements the `InputOutputSystem` class, which is used as a
parent class for `LTI`, `StateSpace`, `TransferFunction`,
`NonlinearIOSystem`, class:`FrequencyResponseData`, `InterconnectedSystem`
and other similar classes that allow naming of signals.
"""
import re
from copy import deepcopy
import numpy as np
from . import config
from .exception import ControlIndexError
__all__ = ['InputOutputSystem', 'NamedSignal', 'issiso', 'timebase',
'common_timebase', 'isdtime', 'isctime', 'iosys_repr']
# Define module default parameter values
_iosys_defaults = {
'iosys.state_name_delim': '_',
'iosys.duplicate_system_name_prefix': '',
'iosys.duplicate_system_name_suffix': '$copy',
'iosys.linearized_system_name_prefix': '',
'iosys.linearized_system_name_suffix': '$linearized',
'iosys.sampled_system_name_prefix': '',
'iosys.sampled_system_name_suffix': '$sampled',
'iosys.indexed_system_name_prefix': '',
'iosys.indexed_system_name_suffix': '$indexed',
'iosys.converted_system_name_prefix': '',
'iosys.converted_system_name_suffix': '$converted',
'iosys.repr_format': 'eval',
'iosys.repr_show_count': True,
}
# Named signal class
class NamedSignal(np.ndarray):
"""Named signal with label-based access.
This class modifies the `numpy.ndarray` class and allows signals to
be accessed using the signal name in addition to indices and slices.
Signals can be either a 2D array, index by signal and time, or a 3D
array, indexed by signal, trace, and time.
Attributes
----------
signal_labels : list of str
Label names for each of the signal elements in the signal.
trace_labels : list of str, optional
Label names for each of the traces in the signal (if multi-trace).
Examples
--------
>>> sys = ct.rss(
... states=['p1', 'p2', 'p3'], inputs=['u1', 'u2'], outputs=['y'])
>>> resp = ct.step_response(sys)
>>> resp.states['p1', 'u1'] # Step response from u1 to p1
NamedSignal(...)
"""
def __new__(cls, input_array, signal_labels=None, trace_labels=None):
# See https://numpy.org/doc/stable/user/basics.subclassing.html
obj = np.asarray(input_array).view(cls) # Cast to our class type
obj.signal_labels = signal_labels # Save signal labels
obj.trace_labels = trace_labels # Save trace labels
obj.data_shape = input_array.shape # Save data shape
return obj # Return new object
def __array_finalize__(self, obj):
# See https://numpy.org/doc/stable/user/basics.subclassing.html
if obj is None:
return
self.signal_labels = getattr(obj, 'signal_labels', None)
self.trace_labels = getattr(obj, 'trace_labels', None)
self.data_shape = getattr(obj, 'data_shape', None)
def _parse_key(self, key, labels=None, level=0):
if labels is None:
labels = self.signal_labels
try:
if isinstance(key, str):
key = labels.index(item := key)
if level == 0 and len(self.data_shape) < 2:
# This is the only signal => use it
return ()
elif isinstance(key, list):
keylist = []
for item in key: # use for loop to save item for error
keylist.append(
self._parse_key(item, labels=labels, level=level+1))
if level == 0 and key != keylist and len(self.data_shape) < 2:
raise ControlIndexError
key = keylist
elif isinstance(key, tuple) and len(key) > 0:
keylist = []
keylist.append(
self._parse_key(
item := key[0], labels=self.signal_labels,
level=level+1))
if len(key) > 1:
keylist.append(
self._parse_key(
item := key[1], labels=self.trace_labels,
level=level+1))
if level == 0 and key[:len(keylist)] != tuple(keylist) \
and len(keylist) > len(self.data_shape) - 1:
raise ControlIndexError
for i in range(2, len(key)):
keylist.append(key[i]) # pass on remaining elements
key = tuple(keylist)
except ValueError:
raise ValueError(f"unknown signal name '{item}'")
except ControlIndexError:
raise ControlIndexError(
"signal name(s) not valid for squeezed data")
return key
def __getitem__(self, key):
return super().__getitem__(self._parse_key(key))
def __repr__(self):
out = "NamedSignal(\n"
out += repr(np.array(self)) # NamedSignal -> array
if self.signal_labels is not None:
out += f",\nsignal_labels={self.signal_labels}"
if self.trace_labels is not None:
out += f",\ntrace_labels={self.trace_labels}"
out += ")"
return out
class InputOutputSystem():
"""Base class for input/output systems.
The `InputOutputSystem` class allows (possibly nonlinear) input/output
systems to be represented in Python. It is used as a parent class for
a set of subclasses that are used to implement specific structures and
operations for different types of input/output dynamical systems.
The timebase for the system, `dt`, is used to specify whether the system
is operating in continuous or discrete time. It can have the following
values:
* `dt` = None: No timebase specified
* `dt` = 0: Continuous time system
* `dt` > 0: Discrete time system with sampling time dt
* `dt` = True: Discrete time system with unspecified sampling time
Parameters
----------
inputs : int, list of str, or None
Description of the system inputs. This can be given as an integer
count or a list of strings that name the individual signals. If an
integer count is specified, the names of the signal will be of the
form 's[i]' (where 's' is given by the `input_prefix` parameter and
has default value 'u'). If this parameter is not given or given as
None, the relevant quantity will be determined when possible
based on other information provided to functions using the system.
outputs : int, list of str, or None
Description of the system outputs. Same format as `inputs`, with
the prefix given by `output_prefix` (defaults to 'y').
states : int, list of str, or None
Description of the system states. Same format as `inputs`, with
the prefix given by `state_prefix` (defaults to 'x').
dt : None, True or float, optional
System timebase. 0 (default) indicates continuous time, True
indicates discrete time with unspecified sampling time, positive
number is discrete time with specified sampling time, None indicates
unspecified timebase (either continuous or discrete time).
name : string, optional
System name (used for specifying signals). If unspecified, a generic
name 'sys[id]' is generated with a unique integer id.
params : dict, optional
Parameter values for the system. Passed to the evaluation functions
for the system as default values, overriding internal defaults.
Attributes
----------
ninputs, noutputs, nstates : int
Number of input, output, and state variables.
input_index, output_index, state_index : dict
Dictionary of signal names for the inputs, outputs, and states and
the index of the corresponding array.
input_labels, output_labels, state_labels : list of str
List of signal names for inputs, outputs, and states.
shape : tuple
2-tuple of I/O system dimension, (noutputs, ninputs).
Other Parameters
----------------
input_prefix : string, optional
Set the prefix for input signals. Default = 'u'.
output_prefix : string, optional
Set the prefix for output signals. Default = 'y'.
state_prefix : string, optional
Set the prefix for state signals. Default = 'x'.
repr_format : str
String representation format. See `control.iosys_repr`.
"""
# Allow ndarray * IOSystem to give IOSystem._rmul_() priority
# https://docs.scipy.org/doc/numpy/reference/arrays.classes.html
__array_priority__ = 20
def __init__(
self, name=None, inputs=None, outputs=None, states=None,
input_prefix='u', output_prefix='y', state_prefix='x', **kwargs):
# system name
self.name = self._name_or_default(name)
# Parse and store the number of inputs and outputs
self.set_inputs(inputs, prefix=input_prefix)
self.set_outputs(outputs, prefix=output_prefix)
self.set_states(states, prefix=state_prefix)
# Process timebase: if not given use default, but allow None as value
self.dt = _process_dt_keyword(kwargs)
self._repr_format = kwargs.pop('repr_format', None)
# Make sure there were no other keywords
if kwargs:
raise TypeError("unrecognized keywords: ", str(kwargs))
# Keep track of the keywords that we recognize
_kwargs_list = [
'name', 'inputs', 'outputs', 'states', 'input_prefix',
'output_prefix', 'state_prefix', 'dt']
#
# Functions to manipulate the system name
#
_idCounter = 0 # Counter for creating generic system name
# Return system name
def _name_or_default(self, name=None, prefix_suffix_name=None):
if name is None:
name = "sys[{}]".format(InputOutputSystem._idCounter)
InputOutputSystem._idCounter += 1
elif re.match(r".*\..*", name):
raise ValueError(f"invalid system name '{name}' ('.' not allowed)")
prefix = "" if prefix_suffix_name is None else config.defaults[
'iosys.' + prefix_suffix_name + '_system_name_prefix']
suffix = "" if prefix_suffix_name is None else config.defaults[
'iosys.' + prefix_suffix_name + '_system_name_suffix']
return prefix + name + suffix
# Check if system name is generic
def _generic_name_check(self):
return re.match(r'^sys\[\d*\]$', self.name) is not None
#
# Class attributes
#
# These attributes are defined as class attributes so that they are
# documented properly. They are "overwritten" in __init__.
#
#: Number of system inputs.
#:
#: :meta hide-value:
ninputs = None
#: Number of system outputs.
#:
#: :meta hide-value:
noutputs = None
#: Number of system states.
#:
#: :meta hide-value:
nstates = None
#: System timebase.
#:
#: :meta hide-value:
dt = None
#
# System representation
#
def __str__(self):
"""String representation of an input/output object"""
out = f"<{self.__class__.__name__}>: {self.name}"
out += f"\nInputs ({self.ninputs}): {self.input_labels}"
out += f"\nOutputs ({self.noutputs}): {self.output_labels}"
if self.nstates is not None:
out += f"\nStates ({self.nstates}): {self.state_labels}"
out += self._dt_repr(separator="\n", space=" ")
return out
def __repr__(self):
return iosys_repr(self, format=self.repr_format)
def _repr_info_(self, html=False):
out = f"<{self.__class__.__name__} {self.name}: " + \
f"{list(self.input_labels)} -> {list(self.output_labels)}"
out += self._dt_repr(separator=", ", space="") + ">"
if html:
# Replace symbols that might be interpreted by HTML processing
# TODO: replace -> with right arrow (later)
escape_chars = {
'$': r'\$',
'<': '<',
'>': '>',
}
return "".join([c if c not in escape_chars else
escape_chars[c] for c in out])
else:
return out
def _repr_eval_(self):
# Defaults to _repr_info_; override in subclasses
return self._repr_info_()
def _repr_latex_(self):
# Defaults to using __repr__; override in subclasses
return None
def _repr_html_(self):
# Defaults to using __repr__; override in subclasses
return None
def _repr_markdown_(self):
return self._repr_html_()
@property
def repr_format(self):
"""String representation format.
Format used in creating the representation for the system:
* 'info' : <IOSystemType sysname: [inputs] -> [outputs]>
* 'eval' : system specific, loadable representation
* 'latex' : HTML/LaTeX representation of the object
The default representation for an input/output is set to 'eval'.
This value can be changed for an individual system by setting the
`repr_format` parameter when the system is created or by setting
the `repr_format` property after system creation. Set
`config.defaults['iosys.repr_format']` to change for all I/O systems
or use the `repr_format` parameter/attribute for a single system.
"""
return self._repr_format if self._repr_format is not None \
else config.defaults['iosys.repr_format']
@repr_format.setter
def repr_format(self, value):
self._repr_format = value
def _label_repr(self, show_count=None):
show_count = config._get_param(
'iosys', 'repr_show_count', show_count, True)
out, count = "", 0
# Include the system name if not generic
if not self._generic_name_check():
name_spec = f"name='{self.name}'"
count += len(name_spec)
out += name_spec
# Include the state, output, and input names if not generic
for sig_name, sig_default, sig_labels in zip(
['states', 'outputs', 'inputs'],
['x', 'y', 'u'], # TODO: replace with defaults
[self.state_labels, self.output_labels, self.input_labels]):
if sig_name == 'states' and self.nstates is None:
continue
# Check if the signal labels are generic
if any([re.match(r'^' + sig_default + r'\[\d*\]$', label) is None
for label in sig_labels]):
spec = f"{sig_name}={sig_labels}"
elif show_count:
spec = f"{sig_name}={len(sig_labels)}"
else:
spec = ""
# Append the specification string to the output, with wrapping
if count == 0:
count = len(spec) # no system name => suppress comma
elif count + len(spec) > 72:
# TODO: check to make sure a single line is enough (minor)
out += ",\n"
count = len(spec)
elif len(spec) > 0:
out += ", "
count += len(spec) + 2
out += spec
return out
def _dt_repr(self, separator="\n", space=""):
if config.defaults['control.default_dt'] != self.dt:
return "{separator}dt{space}={space}{dt}".format(
separator=separator, space=space,
dt='None' if self.dt is None else self.dt)
else:
return ""
# Find a list of signals by name, index, or pattern
def _find_signals(self, name_list, sigdict):
if not isinstance(name_list, (list, tuple)):
name_list = [name_list]
index_list = []
for name in name_list:
# Look for signal ranges (slice-like or base name)
ms = re.match(r'([\w$]+)\[([\d]*):([\d]*)\]$', name) # slice
mb = re.match(r'([\w$]+)$', name) # base
if ms:
base = ms.group(1)
start = None if ms.group(2) == '' else int(ms.group(2))
stop = None if ms.group(3) == '' else int(ms.group(3))
for var in sigdict:
# Find variables that match
msig = re.match(r'([\w$]+)\[([\d]+)\]$', var)
if msig and msig.group(1) == base and \
(start is None or int(msig.group(2)) >= start) and \
(stop is None or int(msig.group(2)) < stop):
index_list.append(sigdict.get(var))
elif mb and sigdict.get(name, None) is None:
# Try to use name as a base name
for var in sigdict:
msig = re.match(name + r'\[([\d]+)\]$', var)
if msig:
index_list.append(sigdict.get(var))
else:
index_list.append(sigdict.get(name, None))
return None if len(index_list) == 0 or \
any([idx is None for idx in index_list]) else index_list
def _copy_names(self, sys, prefix="", suffix="", prefix_suffix_name=None):
"""copy the signal and system name of sys. Name is given as a keyword
in case a specific name (e.g. append 'linearized') is desired. """
# Figure out the system name and assign it
self.name = _extended_system_name(
sys.name, prefix, suffix, prefix_suffix_name)
# Name the inputs, outputs, and states
self.input_index = sys.input_index.copy()
self.output_index = sys.output_index.copy()
if self.nstates and sys.nstates:
# only copy state names for state space systems
self.state_index = sys.state_index.copy()
def copy(self, name=None, use_prefix_suffix=True):
"""Make a copy of an input/output system.
A copy of the system is made, with a new name. The `name` keyword
can be used to specify a specific name for the system. If no name
is given and `use_prefix_suffix` is True, the name is constructed
by prepending `config.defaults['iosys.duplicate_system_name_prefix']`
and appending `config.defaults['iosys.duplicate_system_name_suffix']`.
Otherwise, a generic system name of the form 'sys[<id>]' is used,
where '<id>' is based on an internal counter.
Parameters
----------
name : str, optional
Name of the newly created system.
use_prefix_suffix : bool, optional
If True and `name` is None, set the name of the new system
to the name of the original system with prefix
`config.defaults['duplicate_system_name_prefix']` and
suffix `config.defaults['duplicate_system_name_suffix']`.
Returns
-------
`InputOutputSystem`
"""
# Create a copy of the system
newsys = deepcopy(self)
# Update the system name
if name is None and use_prefix_suffix:
# Get the default prefix and suffix to use
newsys.name = self._name_or_default(
self.name, prefix_suffix_name='duplicate')
else:
newsys.name = self._name_or_default(name)
return newsys
def set_inputs(self, inputs, prefix='u'):
"""Set the number/names of the system inputs.
Parameters
----------
inputs : int, list of str, or None
Description of the system inputs. This can be given as an integer
count or as a list of strings that name the individual signals.
If an integer count is specified, the names of the signal will be
of the form 'u[i]' (where the prefix 'u' can be changed using the
optional prefix parameter).
prefix : string, optional
If `inputs` is an integer, create the names of the states using
the given prefix (default = 'u'). The names of the input will be
of the form 'prefix[i]'.
"""
self.ninputs, self.input_index = \
_process_signal_list(inputs, prefix=prefix)
def find_input(self, name):
"""Find the index for an input given its name (None if not found).
Parameters
----------
name : str
Signal name for the desired input.
Returns
-------
int
Index of the named input.
"""
return self.input_index.get(name, None)
def find_inputs(self, name_list):
"""Return list of indices matching input spec (None if not found).
Parameters
----------
name_list : str or list of str
List of signal specifications for the desired inputs. A
signal can be described by its name or by a slice-like
description of the form 'start:end` where 'start' and
'end' are signal names. If either is omitted, it is taken
as the first or last signal, respectively.
Returns
-------
list of int
List of indices for the specified inputs.
"""
return self._find_signals(name_list, self.input_index)
# Property for getting and setting list of input signals
input_labels = property(
lambda self: list(self.input_index.keys()), # getter
set_inputs, # setter
doc="List of labels for the input signals.")
def set_outputs(self, outputs, prefix='y'):
"""Set the number/names of the system outputs.
Parameters
----------
outputs : int, list of str, or None
Description of the system outputs. This can be given as an
integer count or as a list of strings that name the individual
signals. If an integer count is specified, the names of the
signal will be of the form 'y[i]' (where the prefix 'y' can be
changed using the optional prefix parameter).
prefix : string, optional
If `outputs` is an integer, create the names of the states using
the given prefix (default = 'y'). The names of the input will be
of the form 'prefix[i]'.
"""
self.noutputs, self.output_index = \
_process_signal_list(outputs, prefix=prefix)
def find_output(self, name):
"""Find the index for a output given its name (None if not found).
Parameters
----------
name : str
Signal name for the desired output.
Returns
-------
int
Index of the named output.
"""
return self.output_index.get(name, None)
def find_outputs(self, name_list):
"""Return list of indices matching output spec (None if not found).
Parameters
----------
name_list : str or list of str
List of signal specifications for the desired outputs. A
signal can be described by its name or by a slice-like
description of the form 'start:end` where 'start' and
'end' are signal names. If either is omitted, it is taken
as the first or last signal, respectively.
Returns
-------
list of int
List of indices for the specified outputs.
"""
return self._find_signals(name_list, self.output_index)
# Property for getting and setting list of output signals
output_labels = property(
lambda self: list(self.output_index.keys()), # getter
set_outputs, # setter
doc="List of labels for the output signals.")
def set_states(self, states, prefix='x'):
"""Set the number/names of the system states.
Parameters
----------
states : int, list of str, or None
Description of the system states. This can be given as an integer
count or as a list of strings that name the individual signals.
If an integer count is specified, the names of the signal will be
of the form 'x[i]' (where the prefix 'x' can be changed using the
optional prefix parameter).
prefix : string, optional
If `states` is an integer, create the names of the states using
the given prefix (default = 'x'). The names of the input will be
of the form 'prefix[i]'.
"""
self.nstates, self.state_index = \
_process_signal_list(states, prefix=prefix, allow_dot=True)
def find_state(self, name):
"""Find the index for a state given its name (None if not found).
Parameters
----------
name : str
Signal name for the desired state.
Returns
-------
int
Index of the named state.
"""
return self.state_index.get(name, None)
def find_states(self, name_list):
"""Return list of indices matching state spec (None if not found).
Parameters
----------
name_list : str or list of str
List of signal specifications for the desired states. A
signal can be described by its name or by a slice-like
description of the form 'start:end` where 'start' and
'end' are signal names. If either is omitted, it is taken
as the first or last signal, respectively.
Returns
-------
list of int
List of indices for the specified states..
"""
return self._find_signals(name_list, self.state_index)
# Property for getting and setting list of state signals
state_labels = property(
lambda self: list(self.state_index.keys()), # getter
set_states, # setter
doc="List of labels for the state signals.")
@property
def shape(self):
"""2-tuple of I/O system dimension, (noutputs, ninputs)."""
return (self.noutputs, self.ninputs)
# TODO: add dict as a means to selective change names? [GH #1019]
def update_names(self, **kwargs):
"""update_names([name, inputs, outputs, states])
Update signal and system names for an I/O system.
Parameters
----------
name : str, optional
New system name.
inputs : list of str, int, or None, optional
List of strings that name the individual input signals. If
given as an integer or None, signal names default to the form
'u[i]'. See `InputOutputSystem` for more information.
outputs : list of str, int, or None, optional
Description of output signals; defaults to 'y[i]'.
states : int, list of str, int, or None, optional
Description of system states; defaults to 'x[i]'.
input_prefix : string, optional
Set the prefix for input signals. Default = 'u'.
output_prefix : string, optional
Set the prefix for output signals. Default = 'y'.
state_prefix : string, optional
Set the prefix for state signals. Default = 'x'.
"""
self.name = kwargs.pop('name', self.name)
if 'inputs' in kwargs:
ninputs, input_index = _process_signal_list(
kwargs.pop('inputs'), prefix=kwargs.pop('input_prefix', 'u'))
if self.ninputs and self.ninputs != ninputs:
raise ValueError("number of inputs does not match system size")
self.input_index = input_index
if 'outputs' in kwargs:
noutputs, output_index = _process_signal_list(
kwargs.pop('outputs'), prefix=kwargs.pop('output_prefix', 'y'))
if self.noutputs and self.noutputs != noutputs:
raise ValueError("number of outputs does not match system size")
self.output_index = output_index
if 'states' in kwargs:
nstates, state_index = _process_signal_list(
kwargs.pop('states'), prefix=kwargs.pop('state_prefix', 'x'))
if self.nstates != nstates:
raise ValueError("number of states does not match system size")
self.state_index = state_index
# Make sure we processed all of the arguments
if kwargs:
raise TypeError("unrecognized keywords: ", str(kwargs))
def isctime(self, strict=False):
"""
Check to see if a system is a continuous-time system.
Parameters
----------
strict : bool, optional
If strict is True, make sure that timebase is not None. Default
is False.
"""
# If no timebase is given, answer depends on strict flag
if self.dt is None:
return True if not strict else False
return self.dt == 0
def isdtime(self, strict=False):
"""
Check to see if a system is a discrete-time system.
Parameters
----------
strict : bool, optional
If strict is True, make sure that timebase is not None. Default
is False.
"""
# If no timebase is given, answer depends on strict flag
if self.dt == None:
return True if not strict else False
# Look for dt > 0 (also works if dt = True)
return self.dt > 0
def issiso(self):
"""Check to see if a system is single input, single output."""
return self.ninputs == 1 and self.noutputs == 1
# Test to see if a system is SISO
def issiso(sys, strict=False):
"""
Check to see if a system is single input, single output.
Parameters
----------
sys : I/O or LTI system
System to be checked.
strict : bool (default = False)
If strict is True, do not treat scalars as SISO.
"""
if isinstance(sys, (int, float, complex, np.number)) and not strict:
return True
elif not isinstance(sys, InputOutputSystem):
raise ValueError("Object is not an I/O or LTI system")
# Done with the tricky stuff...
return sys.issiso()
# Return the timebase (with conversion if unspecified)
def timebase(sys, strict=True):
"""Return the timebase for a system.
dt = timebase(sys)
returns the timebase for a system 'sys'. If the strict option is
set to True, `dt` = True will be returned as 1.
Parameters
----------
sys : `InputOutputSystem` or float
System whose timebase is to be determined.
strict : bool, optional
Whether to implement strict checking. If set to True (default),
a float will always be returned (`dt` = True will be returned as 1).
Returns
-------
dt : timebase
Timebase for the system (0 = continuous time, None = unspecified).
"""
# System needs to be either a constant or an I/O or LTI system
if isinstance(sys, (int, float, complex, np.number)):
return None
elif not isinstance(sys, InputOutputSystem):
raise ValueError("Timebase not defined")
# Return the sample time, with conversion to float if strict is false
if sys.dt == None:
return None
elif strict:
return float(sys.dt)
return sys.dt
def common_timebase(dt1, dt2):
"""
Find the common timebase when interconnecting systems.
Parameters
----------
dt1, dt2 : `InputOutputSystem` or float
Number or system with a 'dt' attribute (e.g. `TransferFunction`
or `StateSpace` system).
Returns
-------
dt : number
The common timebase of dt1 and dt2, as specified in
:ref:`conventions-ref`.
Raises
------
ValueError
When no compatible time base can be found.
"""
# explanation:
# if either dt is None, they are compatible with anything
# if either dt is True (discrete with unspecified time base),
# use the timebase of the other, if it is also discrete
# otherwise both dt's must be equal
if hasattr(dt1, 'dt'):
dt1 = dt1.dt
if hasattr(dt2, 'dt'):
dt2 = dt2.dt
if dt1 is None:
return dt2
elif dt2 is None:
return dt1
elif dt1 is True:
if dt2 > 0:
return dt2
else:
raise ValueError("Systems have incompatible timebases")
elif dt2 is True:
if dt1 > 0:
return dt1
else:
raise ValueError("Systems have incompatible timebases")
elif np.isclose(dt1, dt2):
return dt1
else:
raise ValueError("Systems have incompatible timebases")
# Check to see if a system is a discrete-time system
def isdtime(sys=None, strict=False, dt=None):
"""
Check to see if a system is a discrete-time system.
Parameters
----------
sys : I/O system, optional
System to be checked.
dt : None or number, optional
Timebase to be checked.
strict : bool, default=False
If strict is True, make sure that timebase is not None.
"""
# See if we were passed a timebase instead of a system
if sys is None:
if dt is None:
return True if not strict else False
else:
return dt > 0
elif dt is not None:
raise TypeError("passing both system and timebase not allowed")
# Check timebase of the system
if isinstance(sys, (int, float, complex, np.number)):
# Constants OK as long as strict checking is off
return True if not strict else False
else:
return sys.isdtime(strict)
# Check to see if a system is a continuous-time system
def isctime(sys=None, dt=None, strict=False):
"""
Check to see if a system is a continuous-time system.
Parameters
----------
sys : I/O system, optional
System to be checked.
dt : None or number, optional
Timebase to be checked.
strict : bool (default = False)
If strict is True, make sure that timebase is not None.
"""
# See if we were passed a timebase instead of a system
if sys is None:
if dt is None:
return True if not strict else False
else:
return dt == 0
elif dt is not None:
raise TypeError("passing both system and timebase not allowed")
# Check timebase of the system
if isinstance(sys, (int, float, complex, np.number)):
# Constants OK as long as strict checking is off
return True if not strict else False
else:
return sys.isctime(strict)
def iosys_repr(sys, format=None):
"""Return representation of an I/O system.
Parameters
----------
sys : `InputOutputSystem`
System for which the representation is generated.
format : str
Format to use in creating the representation:
* 'info' : <IOSystemType sysname: [inputs] -> [outputs]>
* 'eval' : system specific, loadable representation
* 'latex' : HTML/LaTeX representation of the object
Returns
-------
str
String representing the input/output system.
Notes
-----
By default, the representation for an input/output is set to 'eval'.
Set `config.defaults['iosys.repr_format']` to change for all I/O systems
or use the `repr_format` parameter for a single system.
Jupyter will automatically use the 'latex' representation for I/O
systems, when available.
"""
format = config.defaults['iosys.repr_format'] if format is None else format
match format:
case 'info':
return sys._repr_info_()
case 'eval':
return sys._repr_eval_()
case 'latex':
return sys._repr_html_()
case _:
raise ValueError(f"format '{format}' unknown")
# Utility function to parse iosys keywords
def _process_iosys_keywords(
keywords={}, defaults={}, static=False, end=False):
"""Process iosys specification.
This function processes the standard keywords used in initializing an