-
Notifications
You must be signed in to change notification settings - Fork 19
/
_classes.py
3443 lines (2903 loc) · 132 KB
/
_classes.py
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
import numpy as np
import warnings
from numpy import zeros_like, kron, ndarray, zeros, exp, convolve, spacing
from numpy.random import rand, choice
from scipy.linalg import (eigvals, svdvals, block_diag, qz, norm, solve, expm,
inv, LinAlgError)
from scipy.linalg.decomp import _asarray_validated
from scipy.stats import ortho_group
from tabulate import tabulate
from itertools import zip_longest, chain
from ._polynomial_ops import (haroldpoly, haroldpolyadd, haroldpolydiv,
haroldpolymul, haroldcompanion, haroldlcm)
from ._array_validators import _assert_square
from ._aux_linalg import haroldsvd
from ._global_constants import _KnownDiscretizationMethods
from copy import deepcopy
__all__ = ['Transfer', 'State', 'state_to_transfer', 'transfer_to_state',
'transmission_zeros', 'random_state_model',
'concatenate_state_matrices']
class Transfer:
"""
A class for creating Transfer functions.
"""
def __init__(self, num, den=None, dt=None):
"""
For SISO models, 1D lists or 1D numpy arrays are expected, e.g.,::
>>> G = Transfer(1,[1,2,1])
For MIMO systems, the array like objects are expected to be inside the
appropriate shaped list of lists ::
>>> G = Transfer([[ [1,3,2], [1,3] ],
... [ [1] , [1,0] ]],# end of num
... [[ [1,2,1] , [1,3,3] ],
... [ [1,0,0] , [1,2,3,4] ]])
If the denominator is common then the denominator can be given as a
single array like object.
>>> G = Transfer([[ [1,3,2], [1,3] ],
... [ [1] , [1,0] ]],# end of num
... [1, 2, 3, 4, 5]) # common den
Setting ``SamplingPeriod`` property to ``'None'`` will make the
system continuous time again and relevant properties are reset
to continuous-time properties. However the numerical data will still
be the same.
"""
# Initialization Switch and Variable Defaults
self._isgain = False
self._isSISO = False
self._isstable = False
self._DiscretizedWith = None
self._DiscretizationMatrix = None
self._PrewarpFrequency = 0.
self._dt = False
(self._num, self._den,
self._shape, self._isgain) = self.validate_arguments(num, den)
self._p, self._m = self._shape
if self._shape == (1, 1):
self._isSISO = True
self.SamplingPeriod = dt
self._isdiscrete = False if dt is None else True
self._recalc()
@property
def num(self):
"""
If this property is called ``G.num`` then returns the numerator data.
Alternatively, if this property is set then the provided value is
first validated with the existing denominator shape and causality.
"""
return self._num
@property
def den(self):
"""
If this property is called ``G.den`` then returns the numerator data.
Alternatively, if this property is set then the provided value is
first validated with the existing numerator shape and causality.
"""
return self._den
@property
def SamplingPeriod(self):
"""
If this property is called ``G.SamplingPeriod`` then returns the
sampling period data. If this property is set to ``False``, the model
is assumed to be a continuous model. Otherwise, a discrete time model
is assumed. Upon changing this value, relevant system properties are
recalculated.
"""
return self._dt
@property
def SamplingSet(self):
"""
If this property is called ``G.SamplingSet`` then returns the
set ``Z`` or ``R`` for discrete and continuous models respectively.
This is a read only property and cannot be set. Instead an appropriate
setting should be given to the ``SamplingPeriod`` property.
"""
return self._rz
@property
def NumberOfInputs(self):
"""
A read only property that holds the number of inputs.
"""
return self._m
@property
def NumberOfOutputs(self):
"""
A read only property that holds the number of outputs.
"""
return self._p
@property
def shape(self):
"""
A read only property that holds the shape of the system as a tuple
such that the result is ``(# of outputs, # of inputs)``.
"""
return self._shape
@property
def polynomials(self):
"""
A read only property that returns the model numerator and the
denominator as the outputs.
"""
return self._num, self._den
@property
def DiscretizedWith(self):
"""
This property is used internally to keep track of (if applicable)
the original method used for discretization. It is used by the
``undiscretize()`` function to reach back to the continuous model that
would hopefully minimize the discretization errors. It is also
possible to manually set this property such that ``undiscretize``
uses the provided method.
"""
if self.SamplingSet == 'R' or self._DiscretizedWith is None:
return None
else:
return self._DiscretizedWith
@property
def DiscretizationMatrix(self):
"""
This 2x2 matrix denoted with ``q`` is used internally to represent
the upper linear fractional transformation of the operation
:math:`\\frac{1}{s} I = \\frac{1}{z} I \\star Q`.
The available methods (and their aliases) can be accessed via the
internal ``_KnownDiscretizationMethods`` variable.
.. note:: The common discretization techniques can be selected with
a keyword argument and this matrix business can safely be
avoided. This is a rather technical issue and it is best to
be used sparingly. For the experts, I have to note that
the transformation is currently not tested for well-posedness.
.. note:: SciPy actually uses a variant of this LFT
representation as given in the paper of `Zhang et al.
<http://dx.doi.org/10.1080/00207170802247728>`_
"""
if self.SamplingSet == 'R' or not self.DiscretizedWith == 'lft':
return None
else:
return self._DiscretizationMatrix
@property
def PrewarpFrequency(self):
"""
If the discretization method is ``tustin`` then a frequency warping
correction might be required the match of the discrete time system
response at the frequency band of interest. Via this property, the
prewarp frequency can be provided.
"""
if self.SamplingSet == 'R' or self.DiscretizedWith \
not in ('tustin', 'bilinear', 'trapezoidal'):
return None
else:
return self._PrewarpFrequency
@SamplingPeriod.setter
def SamplingPeriod(self, value):
if value is not None:
value = float(value)
if value <= 0.:
raise ValueError('SamplingPeriod must be a real positive '
'scalar. But looks like a \"{0}\" is '
'given.'.format(type(value).__name__))
self._dt = value
self._rz = 'Z'
self._isdiscrete = True
else:
self._rz = 'R'
self._dt = None
self._isdiscrete = False
@num.setter
def num(self, value):
user_num, _, user_shape = self.validate_arguments(value, self._den)[:3]
if not user_shape == self._shape:
raise IndexError('Once created, the shape of the transfer '
'function \ncannot be changed. I have '
'received a numerator with shape {0}x{1} \nbut '
'the system has {2}x{3}.'
''.format(*user_shape+self._shape))
else:
self._num = user_num
self._recalc()
@den.setter
def den(self, value):
user_den, user_shape = self.validate_arguments(self._num, value)[1:3]
if not user_shape == self._shape:
raise IndexError('Once created, the shape of the transfer '
'function \ncannot be changed. I have '
'received a denominator with shape {0}x{1} \nbut '
'the system has {2}x{3}.'
''.format(*user_shape+self._shape))
else:
self._den = user_den
self._recalc()
@DiscretizedWith.setter
def DiscretizedWith(self, value):
if value in _KnownDiscretizationMethods:
if self.SamplingSet == 'R':
raise ValueError('This model is not discretized yet '
'hence you cannot define a method for'
' it. Discretize the model first via '
'"discretize" function.')
else:
self._DiscretizedWith = value
else:
raise ValueError('The {} method is unknown.'.format(value))
@DiscretizationMatrix.setter
def DiscretizationMatrix(self, value):
if self._DiscretizedWith == 'lft':
value = np.atleast_2d(np.asarray(value, dtype=float))
if value.ndim > 2 or value.shape != (2, 2):
raise ValueError('The interconnection array needs to be a'
' 2x2 real-valued array.')
self._DiscretizationMatrix = value
else:
raise ValueError('If the discretization method is not '
'\"lft\" then this property is not set.')
@PrewarpFrequency.setter
def PrewarpFrequency(self, value):
if self._DiscretizedWith not in ('tustin', 'bilinear', 'trapezoidal'):
raise ValueError('If the discretization method is not tustin (or '
'its aliases) then this property is not set.')
else:
if value > 1/(2*self._dt):
raise ValueError('Prewarping Frequency is beyond '
'the Nyquist rate.\nIt has to '
'satisfy 0 < w < 1/(2*dt) and dt '
'being the sampling\nperiod in '
'seconds (dt={0} is provided, '
'hence the max\nallowed is '
'{1} Hz.'.format(self._dt, 1/(2*self._dt)))
else:
self._PrewarpFrequency = value
def _recalc(self):
"""
Internal bookkeeping routine to readjust the class properties
"""
if self._isgain:
self.poles = np.array([])
self.zeros = np.array([])
else:
if self._isSISO:
self.poles = eigvals(haroldcompanion(self._den))
if self._num.size == 1:
self.zeros = np.array([])
else:
self.zeros = eigvals(haroldcompanion(self._num))
else:
# Create a dummy statespace and check the zeros there
zzz = transfer_to_state((self._num, self._den),
output='matrices')
if zzz[0].size == 0:
# Oops, its static gain in disguise with exact cancellation
# reset numerator and copy poles to zeros
zzz = transfer_to_state(([[1]*self._m]*self._p,
self._den),
output='matrices')
self.poles = eigvals(zzz[0])
self.zeros = self.poles.copy()
else:
self.zeros = transmission_zeros(*zzz)
self.poles = eigvals(zzz[0])
self._set_stability()
self._set_representation()
def _set_stability(self):
if self._rz == 'Z':
self._isstable = all(1 > abs(self.poles))
else:
self._isstable = all(0 > np.real(self.poles))
def _set_representation(self):
self._repr_type = 'Transfer'
# %% Transfer class arithmetic methods
# Overwrite numpy array ufuncs
__array_ufunc__ = None
def __neg__(self):
if not self._isSISO:
newnum = [[None]*self._m for n in range(self._p)]
for i in range(self._p):
for j in range(self._m):
newnum[i][j] = -self._num[i][j]
else:
newnum = -1*self._num
return Transfer(newnum, self._den, self._dt)
def __add__(self, other):
"""
Addition method
Notice that in case SISO + MIMO, it is broadcasted to a ones matrix
not an identity (Given a 3x3 system + 5) adds 5*np.ones([3,3]).
"""
if isinstance(other, State):
# We still follow the generic rule, State wins over Transfer
# representations.
if not self._dt == other._dt:
raise ValueError('The sampling periods don\'t match '
'so I cannot add these models.')
gainflag = sum([self._isgain, other._isgain])
# If both are static gains
if gainflag == 2:
try:
return State(self.to_array()+other.to_array(), dt=self._dt)
except ValueError:
raise ValueError('Shapes are not compatible for '
'addition. Model shapes are {0} and'
' {1}'.format(self._shape, other.shape))
# If one of them is a static gain
elif gainflag == 1:
if self._isgain:
return other + self.to_array()
else:
return transfer_to_state(self) + other.to_array()
# No static gains, carry on
else:
pass
sisoflag = sum([self._isSISO, other._isSISO])
if sisoflag == 0 and self.shape != other.shape:
raise ValueError('Shapes are not compatible for '
'addition. Transfer shape is {0}'
' but the State shape is {1}.'
''.format(self._shape, other.shape))
else:
# In case one of them is SISO and will be broadcasted in the
# next arrival
return other + transfer_to_state(self)
elif isinstance(other, Transfer):
if not self._dt == other._dt:
raise ValueError('The sampling periods don\'t match '
'so I cannot multiply these systems.')
gainflag = sum([self._isgain, other._isgain])
# If both are static gains
if gainflag == 2:
try:
return Transfer(self.to_array() + other.to_array(),
dt=self._dt)
except ValueError:
raise ValueError('Shapes are not compatible for '
'addition. Model shapes are {0} and'
' {1}'.format(self._shape, other.shape))
else:
pass
sisoflag = sum([self._isSISO, other._isSISO])
# Both SISO or both MIMO
if sisoflag in [0, 2]:
# Create empty num and den holders.
newnum = [[None]*self._m for n in range(self._p)]
newden = [[None]*self._m for n in range(self._p)]
nonzero_num = np.zeros(self._shape, dtype=bool)
# in case both are siso wrap the entries into list of lists
if self._isSISO:
snum, sden = [[self._num]], [[self._den]]
onum, oden = [[other.num]], [[other.den]]
else:
snum, sden = self._num, self._den
onum, oden = other.num, other.den
# over all rows/cols, SISO is included with p, m = 1
for row in range(self._p):
for col in range(self._m):
# in case the denominators are not monic
c0, c1 = sden[row][col][0, 0], oden[row][col][0, 0]
lcm, mults = haroldlcm(sden[row][col], oden[row][col])
newnum[row][col] = np.atleast_2d(haroldpolyadd(
convolve(snum[row][col].flatten(), mults[0]*c1),
convolve(onum[row][col].flatten(), mults[1]*c0)))
newden[row][col] = lcm*c0*c1
# Test whether we have at least one numerator entry
# that is nonzero. Otherwise return a zero MIMO tf
if np.count_nonzero(newnum[row][col]) != 0:
nonzero_num[row, col] = True
# If SISO, unpack the list of lists
if self._isSISO:
newnum, newden = newnum[0][0], newden[0][0]
if any(nonzero_num.ravel()):
return Transfer(newnum, newden, dt=self._dt)
else:
# Numerators all cancelled to zero hence 0-gain SISO/MIMO
return Transfer(np.zeros(self._shape).tolist(),
dt=self._dt)
# One of them is SISO and will be broadcasted here
else:
if self._isSISO:
return other +\
Transfer([[self._num]*other.m for n in range(other.p)],
[[self._den]*other.m for n in range(other.p)],
self._dt)
else:
return self +\
Transfer([[other.num]*other.m for n in range(other.p)],
[[other.den]*other.m for n in range(other.p)],
self._dt)
# Regularize arrays and scalars and consistency checks
elif isinstance(other, (int, float, np.ndarray)):
# Complex dtype does not immediately mean complex numbers,
# check and forgive
if np.iscomplexobj(other) and np.any(other.imag):
raise ValueError('Complex valued representations are not '
'supported.')
if isinstance(other, np.ndarray):
if other.ndim == 1:
if other.size == 1:
s = float(other)
else:
s = np.atleast_2d(other.real)
else:
s = other.real
else:
s = float(other)
# Self is, # other is
# isgain 1- scalar
# 2- ndarray
# isSISO 3- scalar
# 4- ndarray
# isMIMO 5- scalar
# 6- ndarray
if self._isgain:
try:
# 1, 2
mat = self.to_array() + s
except ValueError:
raise ValueError('Shapes are not compatible for '
'broadcasted addition. Transfer '
'shape is {0} but the array shape is {1}.'
''.format(self._shape, other.shape))
return Transfer(mat, dt=self._dt)
elif self._isSISO:
# 3
if isinstance(s, float):
return self + Transfer(s, dt=self._dt)
# 4
else:
# Broadcast and send to MIMO TF + TF above
return (self * np.ones(s.shape)) + Transfer(s.tolist(),
dt=self._dt)
else:
# 5
if isinstance(s, float):
return self + Transfer(np.ones(self.shape)*s, dt=self._dt)
# 6
if self.shape != other.shape:
raise ValueError('Shapes are not compatible for '
'addition. Transfer shape is {0}'
' but the array shape is {1}.'
''.format(self._shape, other.shape))
return self + Transfer(other.tolist(), dt=self._dt)
else:
raise ValueError('I don\'t know how to add a {0} to a '
'Transfer representation (yet).'
''.format(type(other).__qualname__))
def __radd__(self, other): return self + other
def __sub__(self, other): return self + (-other)
def __rsub__(self, other): return -self + other
def __mul__(self, other):
# TODO: There are a few repeated code segments. Refactor!
if isinstance(other, (int, float)):
if self._isSISO:
if other == 0.:
return Transfer(0, 1, dt=self.SamplingPeriod)
else:
return Transfer(other*self._num,
self._den,
dt=self._dt)
else:
# Manually multiply each numerator
t_p = self._p
t_m = self._m
newnum = [[None]*t_m for n in range(t_p)]
newden = [[None]*t_m for n in range(t_p)]
for row in range(t_p):
for col in range(t_m):
if other == 0.:
newnum[row][col] = np.array([[0.]])
newden[row][col] = np.array([[1.]])
else:
newnum[row][col] = other*self._num[row][col]
newden[row][col] = self._den[row][col]
return Transfer(newnum, newden, dt=self._dt)
elif isinstance(other, np.ndarray):
# Complex dtype does not immediately mean complex numbers,
# check and forgive
if np.iscomplexobj(other) and np.any(other.imag):
raise ValueError('Complex valued representations are not '
'supported.')
# It still might be a scalar inside an array
if other.size == 1:
return float(other) * self
if other.ndim == 1:
arr = np.atleast_2d(other.real)
else:
arr = other.real
t_p, t_m = arr.shape
newnum = [[None]*t_m for n in range(t_p)]
newden = [[None]*t_m for n in range(t_p)]
# if an array multiplied with SISO Transfer, elementwise multiply
if self._isSISO:
# Manually multiply numerator
for row in range(t_p):
for col in range(t_m):
# If identically zero, empty out num/den
if arr[row, col] == 0.:
newnum[row][col] = np.array([[0.]])
newden[row][col] = np.array([[1.]])
else:
newnum[row][col] = arr[row, col]*self._num
newden[row][col] = self._den
return Transfer(newnum, newden, dt=self._dt)
# Reminder: This is elementwise multiplication not __matmul__!!
elif self._shape == arr.shape:
# Manually multiply each numerator
for r in range(t_p):
for c in range(t_m):
# If identically zero, empty out num/den
if arr[r, c] == 0.:
newnum[r][c] = np.array([[0.]])
newden[r][c] = np.array([[1.]])
else:
newnum[r][c] = arr[r, c]*self._num[r][c]
newden[r][c] = self._den[r][c]
return Transfer(newnum, newden, dt=self._dt)
else:
raise ValueError('Multiplication of systems requires their '
'shape to match but the system shapes '
'I got are {0} vs. {1}'
''.format(self._shape, other.shape))
elif isinstance(other, State):
# State representations win over the typecasting
if not self._dt == other._dt:
raise ValueError('The sampling periods don\'t match '
'so I cannot multiply these systems. ')
return other*transfer_to_state(self)
elif isinstance(other, Transfer):
if not self._dt == other._dt:
raise ValueError('The sampling periods don\'t match '
'so I cannot multiply these systems.')
# Get SISO and static gain out of the way
# For gain, convert to ndarray and let previous case handle it
if self._isgain:
if self._isSISO:
return other * float(self._num)
else:
# recast as a numpy array and multiply
# if denominator has non unity entries
# rescale numerator
mult_arr = np.empty((self._p, self._m))
for r in range(self._p):
for c in range(self._m):
mult_arr[r, c] = self._num[r][c] \
if self._den[r][c] == 1. else \
self._num[r][c]/self._den[r][c]
return other*mult_arr
elif self._isSISO and other._isSISO:
if not np.any(self._num) or not np.any(other.num):
return Transfer(0, 1, dt=self.SamplingPeriod)
return Transfer(haroldpolymul(self._num, other.num),
haroldpolymul(self._den, other.den),
dt=self.SamplingPeriod)
elif other._isSISO or self._isSISO:
# Which one is MIMO
snum = self._num if self._isSISO else other.num
sden = self._den if self._isSISO else other.den
mnum = other.num if self._isSISO else self._num
mden = other.den if self._isSISO else self._den
t_p, t_m = other.shape if self._isSISO else self._shape
newnum = [[None]*t_m for n in range(t_p)]
newden = [[None]*t_m for n in range(t_p)]
for r in range(t_p):
for c in range(t_m):
if not np.any(snum) or not np.any(mnum[r][c]):
newnum[r][c] = np.array([[0.]])
newden[r][c] = np.array([[1.]])
else:
newnum[r][c] = haroldpolymul(snum, mnum[r][c])
newden[r][c] = haroldpolymul(sden, mden[r][c])
return Transfer(newnum, newden, dt=self.SamplingPeriod)
else:
# Both MIMO
if not self._shape == other.shape:
raise ValueError('Cannot multiply Transfer with {0} '
' shape with {1} with {2} shape.'
''.format(self._shape,
type(other).__qualname__,
other.shape)
)
t_p, t_m = self._shape
newnum = [[None]*t_m for n in range(t_p)]
newden = [[None]*t_m for n in range(t_p)]
sn = self._num
sd = self._den
on = other.num
od = other.den
for r in range(t_p):
for c in range(t_m):
if not np.any(sn[r][c]) or not np.any(on[r][c]):
newnum[r][c] = np.array([[0.]])
newden[r][c] = np.array([[1.]])
else:
newnum[r][c] = haroldpolymul(sn[r][c], on[r][c])
newden[r][c] = haroldpolymul(sd[r][c], od[r][c])
return Transfer(newnum, newden, dt=self.SamplingPeriod)
else:
raise ValueError('I don\'t know how to multiply a '
'{0} with a Transfer representation '
'(yet).'.format(type(other).__name__))
def __rmul__(self, other):
# *-multiplication means elementwise multiplication in Python
# and order doesn't matter so pass it to mul, only because
# I wrote that one first
return self * other
def __truediv__(self, other):
"""Support for G / ...
"""
# For convenience of scaling the system via G/5 and so on.
return self @ (1/other)
def __rtruediv__(self, other):
""" Support for division .../G
"""
if self._isSISO:
numdeg, dendeg = self.num.size, self.den.size
if numdeg != dendeg:
raise ValueError('Inverse of the system is noncausal which '
'is not supported.')
else:
return other * Transfer(self.den, self.num, dt=self._dt)
if not np.equal(*self._shape):
raise ValueError('Nonsquare systems cannot be inverted')
a, b, c, d = transfer_to_state((self._num, self._den),
output='matrices')
if np.any(svdvals(d) < np.spacing(1.)):
raise LinAlgError('The feedthrough term of the system is not'
' invertible.')
else:
# A-BD^{-1}C | BD^{-1}
# -----------|--------
# -D^{-1}C | D^{-1}
if self._isgain:
ai, bi, ci = a, b, c
else:
ai = a - b @ solve(d, c)
bi = (solve(d.T, b.T)).T
ci = -solve(d, c)
di = inv(d)
num_inv, den_inv = state_to_transfer((ai, bi, ci, di),
output='polynomials')
return other * Transfer(num_inv, den_inv, dt=self._dt)
def __matmul__(self, other):
# @-multiplication has the following rationale, first two items
# are for user-convenience in case @ is used for *
# 1. self is SISO --> whatever other is treat as *-mult --> __mul__
# 2. self is MIMO and other is SISO, same as item 1.
# 3. self is MIMO and other is np.ndarray --> Matrix mult
# 4. self is MIMO and other is MIMO --> Matrix mult
# 1.
if isinstance(other, (int, float)) or self._isSISO:
return self * other
# 3.
if isinstance(other, (np.ndarray)):
if np.iscomplexobj(other) and np.any(other.imag):
raise ValueError('Complex valued representations are not '
'supported.')
# It still might be a scalar inside an array
if other.size == 1:
return self*float(other)
if other.ndim == 1:
arr = np.atleast_2d(other.real).astype(float)
else:
arr = other.real.astype(float)
if not self._m == arr.shape[0]:
raise ValueError('Size mismatch: Transfer representation '
f'has {self._m} inputs but array has '
f'{arr.shape[0]} rows.')
# If self is gain, this is just matrix multiplication
if self._isgain:
return Transfer(self.to_array() @ arr, dt=self._dt)
tp, tm = self._shape[0], arr.shape[1]
newnum = [[None]*tm for n in range(tp)]
newden = [[None]*tm for n in range(tp)]
for r in range(tp):
for c in range(tm):
t_G = Transfer(0, 1, dt=self._dt)
for ind in range(self._m):
t_G += self[r, ind] * other[ind, [c]]
newnum[r][c] = t_G.num
newden[r][c] = t_G.den
if (tp, tm) == (1, 1):
newnum = newnum[0][0]
newden = newden[0][0]
return Transfer(newnum, newden, dt=self.SamplingPeriod)
# 4.
if isinstance(other, (State, Transfer)):
if not self._dt == other._dt:
raise ValueError('The sampling periods don\'t match '
'so I cannot multiply these systems.')
if isinstance(other, State):
return transfer_to_state(self) @ State
# 2.
if other._isSISO:
return self * other
if self._shape[1] != other.shape[0]:
raise ValueError(f'Size mismatch: Left Transfer '
f'has {self._m} inputs but right Transfer '
f'has {other.shape[0]} outputs.')
tp, tm = self._shape[0], other.shape[1]
# TODO : unoptimized and too careful
# Take out the SIMO * MISO case resulting with SISO.
if (tp, tm) == (1, 1):
t_G = Transfer(0, 1, dt=self._dt)
for ind in range(self._m):
t_G += self[0, ind] * other[ind, 0]
return t_G
else:
newnum = [[None]*tm for n in range(tp)]
newden = [[None]*tm for n in range(tp)]
for r in range(tp):
for c in range(tm):
t_G = Transfer(0, 1, dt=self._dt)
for ind in range(self._m):
t_G += self[r, ind] * other[ind, c]
newnum[r][c] = t_G.num
newden[r][c] = t_G.den
return Transfer(newnum, newden, dt=self._dt)
else:
raise ValueError('I don\'t know how to multiply a '
'{0} with a Transfer representation '
'(yet).'.format(type(other).__name__))
def __rmatmul__(self, other):
# If other is a State or Transfer, it will be handled
# by other's __matmul__() method. Hence we only take care of the
# right multiplication with the scalars and arrays. Otherwise
# rejection is executed
if isinstance(other, np.ndarray):
if np.iscomplexobj(other) and np.any(other.imag):
raise ValueError('Complex valued representations are not '
'supported.')
# It still might be a scalar inside an array
if other.size == 1:
return self*float(other)
if other.ndim == 1:
arr = np.atleast_2d(other.real)
else:
arr = other.real
return Transfer(arr.tolist(), self._dt) @ self
elif isinstance(other, (int, float)):
return self * other
else:
raise ValueError('I don\'t know how to multiply a '
'{0} with a Transfer representation '
'(yet).'.format(type(other).__name__))
def __getitem__(self, num_or_slice):
# Check if a double subscript or not
if isinstance(num_or_slice, tuple):
rows_of_c, cols_of_b = num_or_slice
else:
rows_of_c, cols_of_b = num_or_slice, slice(None, None, None)
# Eliminate all slices and colons but only indices
rc = np.arange(self.NumberOfOutputs)[rows_of_c].tolist()
cb = np.arange(self.NumberOfInputs)[cols_of_b].tolist()
# if a SISO is sliced only [0,0] will pass, then return self
if self._isSISO:
return self
# Is the result goint to be SISO ?
if isinstance(rc, int) and isinstance(cb, int):
return Transfer(self.num[rc][cb], self.den[rc][cb],
dt=self._dt)
else:
# Nope, release the MIMO bracket hell
rc = [rc] if isinstance(rc, int) else rc
cb = [cb] if isinstance(cb, int) else cb
return Transfer([[self.num[x][y] for y in cb] for x in rc],
[[self.den[x][y] for y in cb] for x in rc],
dt=self._dt)
def __setitem__(self, *args):
raise ValueError('To change the data of a subsystem, set directly\n'
'the relevant num, den attributes.')
# ================================================================
# __repr__ and __str__ to provide meaningful info about the system
# The ascii art of matlab for tf won't be implemented.
# Either proper image with proper superscripts or numbers.
# ================================================================
def __repr__(self):
p, m = self.NumberOfOutputs, self.NumberOfInputs
if self.SamplingSet == 'R':
desc_text = 'Continuous-Time Transfer function\n'
else:
desc_text = ('Discrete-Time Transfer function with '
'sampling time: {0:.3f} ({1:.3f} Hz.)\n'
''.format(float(self.SamplingPeriod),
1/float(self.SamplingPeriod)))
if self._isgain:
desc_text += '\n{}x{} Static Gain\n'.format(p, m)
else:
desc_text += ' {0} input{2} and {1} output{3}\n'\
''.format(m, p, 's' if m > 1 else '',
's' if p > 1 else '')
pole_zero_table = zip_longest(np.real(self.poles),
np.imag(self.poles),
np.real(self.zeros),
np.imag(self.zeros)
)
desc_text += '\n' + tabulate(pole_zero_table,
headers=['Poles(real)',
'Poles(imag)',
'Zeros(real)',
'Zeros(imag)']
)
desc_text += '\n\n'
return desc_text
def pole_properties(self, output_data=False):
'''
The resulting array holds the poles in the first column, natural
frequencies in the second and damping ratios in the third. For
static gain representations None is returned.
# TODO : Will be implemented!!!
The result is an array whose first column is the one of the complex
pair or the real pole. When tabulated the complex pair is represented
as "<num> ± <num>j" using single entry. However the data is kept as
a valid complex number for convenience. If output_data is set to
True the numerical values will be returned instead of the string
type tabulars.
'''
return _pole_properties(self.poles,
self.SamplingPeriod,
output_data=output_data)
def to_array(self):
'''
If a Transfer representation is a static gain, this method returns
a regular 2D-ndarray.
'''
if self._isgain:
if self._isSISO:
return self._num/self._den
else:
num_arr = np.empty((self._p * self._m,))