-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfotf.py
2118 lines (1773 loc) · 70.3 KB
/
fotf.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
#!/usr/bin/env python3
"""
FOTF object class and method definition
derived from the FOTF/FOMCON Matlab toolbox and Control Toolbox Python
---------------------------------------
Ported to python by Tobechukwu Onyedi
Revision date: 12th April 2019
"""
# External function declarations
import traceback
import numpy as np
from numpy import (angle, array, empty, finfo, ndarray, ones,
polyadd, polymul, polyval, roots, sqrt, zeros, squeeze, exp, pi,
where, delete, real, poly, nonzero)
import scipy as sp
from scipy.signal import lti, tf2zpk, zpk2tf, cont2discrete
from copy import deepcopy
from warnings import warn
from control.matlab import *
from lti import LTI
from matplotlib import pyplot as plt
from matplotlib import axes
__all__ = ['FOTransFunc', 'fotf', 'ss2tf', 'tfdata', 'poly2str', 'str2poly', 'freqresp', 'dcgain', 'lsim','newfotf', 'step', 'impulse','fotfparam','g1','g2','g3','loadsets']
EXP_U = -6
EXP_L = -18
EXP_O_UB = 10**EXP_U
EXP_O_LB = 10**EXP_L
EXP_DIFF = round((EXP_U - EXP_L)/2)
X1 = (EXP_O_UB/EXP_O_LB)/10**EXP_DIFF
# X = EXP_O_LB * X1
X = EXP_O_UB / X1
MAX_LAMBDA = 5
MIN_COEF = -1000
MAX_COEF = 1000
MIN_EXPO = 0
MAX_EXPO = 5
class FOTransFunc(LTI):
def __init__(self, *args):
"""FOTransFunc(num, nnum, den, nden[, dt])
Construct a Fractional order TransferFunction.
The default constructor is Fractional order TransferFunction(num, den, nnum, nden), where 'num' and
'den' are lists of arrays containing polynomial coefficients. nnum and nden
are lists of arrays containing exponents of the power of s.
"""
_args = deepcopy(args)
epsi = 0.01
# internal parameters, used to manipulate initial values from user
_num, _nnum, _den, _nden, _dt = None, None, None, None, None
if len(_args) == (0 or None):
pass
elif len(_args) >= 4:
[_num, _nnum, _den, _nden] = args[0:4]
if len(_args) == 5 and isinstance(_args[4], (float,int)):
if _args[4] > 0:
_dt = _args[4]
else:
_dt = 0
elif len(_args) == 1 and isinstance(_args[0],(float,int)):
_num = _args[0]
_nnum = 0
_den = 1.
_nden = 0
_dt = 0
elif len(_args) == 1 and (_args[0] == 's'):
_num = 1.
_nnum = 1.
_den = 1.
_nden = 0.
_dt = 0
elif len(_args) == 1 and isinstance((_args[0]), FOTransFunc):
[_num, _nnum, _den, _nden] = _args[0:4]
if len(_args) == 5:
_dt = _args[4]
elif len(_args) >= 2 and isinstance(_args[0], list) and isinstance(_args[1], list):
_num = _args[0][0]
_nnum = _args[0][1]
_den = _args[1][0]
_nden = _args[1][1]
if len(_args) >= 3 and isinstance(_args[2], (float,int)):
if _args[2] > 0:
_dt = _args[2]
else:
_dt = 0
elif len(_args) >= 2 and isinstance(_args[0], str) and isinstance(_args[1], str):
if len(_args)>= 3 and isinstance(_args[2], (float,int)):
if _args[2] > 0:
_dt = _args[2]
bas = 's'
else:
_dt = 0
bas = 's'
_num,_nnum = str2poly(_args[0], bas)
_den,_nden = str2poly(_args[1], bas)
else:
raise ValueError("fotf.FOTransFunc: Needs 1, 2 , 3 ,4 or 5 string or int or list or ndarray arguments. received {}.".format(len(args)))
_num = _clean_part(_num)
_den = _clean_part(_den)
_nnum = _clean_part(_nnum)
_nden = _clean_part(_nden)
inputs = len(_num[0])
outputs = len(_num)
# Make sure numerator and denominator matrices have consistent sizes
if inputs != len(_den[0]):
raise ValueError("The numerator has %i input(s), but the denominator has "
"%i\ninput(s)." % (inputs, len(_den[0])))
if outputs != len(_den):
raise ValueError("The numerator has %i output(s), but the denominator has "
"%i\noutput(s)." % (outputs, len(_den)))
# Additional checks/updates on structure of the transfer function
for i in range(outputs):
# Make sure that each row has the same number of columns
if len(_num[i]) != inputs:
raise ValueError("Row 0 of the numerator matrix has %i elements, but row "
"%i\nhas %i." % (inputs, i, len(_num[i])))
if len(_den[i]) != inputs:
raise ValueError("Row 0 of the denominator matrix has %i elements, but row "
"%i\nhas %i." % (inputs, i, len(_den[i])))
# Check for zeros in numerator or denominator
# TODO: Right now these checks are only done during construction.
# It might be worthwhile to think of a way to perform checks if the
# user modifies the transfer function after construction.
for j in range(inputs):
# Check that we don't have any zero denominators.
zeroden = True
for k in _den[i][j]:
if k:
zeroden = False
break
if zeroden:
raise ValueError("Input %i, output %i has a zero denominator."
% (j + 1, i + 1))
# If we have zero numerators, set the denominator to 1.
zeronum = True
for k in _num[i][j]:
if k:
zeronum = False
break
if zeronum:
_den[i][j] = ones(1)
LTI.__init__(self, inputs, outputs, dt=_dt)
if EXP_O_LB <= _nnum[0][0][-1] <= EXP_O_UB:
pass #ensures the last coefficent is alwasy 0
else:
_nnum[0][0][-1] = X
if EXP_O_LB <= _nden[0][0][-1] <= EXP_O_UB:
pass #ensures the last coefficent is alwasy 0
else:
_nden[0][0][-1] = X
self.num = _num
self.den = _den
self.nnum = _nnum
self.nden = _nden
self.epsi = epsi
self.numberOfDecimal = 2
self._truncatecoeff()
@property
def MIN_COMM_ORDER(self):
return 10 ** -self.numberOfDecimal
# @MIN_COMM_ORDER.setter
# def MIN_COMM_ORDER(self, value):
# if isinstance(value, np.ndarray):
# self._funcFix = value
def __call__(self, s):
"""Evaluate the system's transfer function for a complex variable
For a SISO transfer function, returns the value of the
transfer function. For a MIMO transfer fuction, returns a
matrix of values evaluated at complex variable s."""
if self.issiso():
# return a scalar
return self.horner(s)[0][0]
else:
# return a matrix
return self.horner(s)
def step(self, t=None, u=None, output=True, plot=True):
"""
:param t: list, ndarray of in secs
:type t: list, ndarray
:param output: bool, used to determine if you want output
:param plot: bool, used to indicate you want plot
:returns t, y:t - time (if 't' is None Step response (y)
"""
tTobereturn = False
if t is None:
t = step_auto_range(self)
tTobereturn = True
elif isinstance(t, (list, ndarray)):
t = np.array(t)
else:
raise ValueError("FOTransFunc.step: variable 't' can only be 'None' or of type 'list', 'numpy.array'")
if u is None:
u = np.ones(t.size)
y = lsim(self, u, t, plot=False)
if output is True and plot is True:
plt.figure()
plt.plot(t, y)
plt.title('Step response')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid()
plt.tight_layout()
plt.show()
# Plot final value if present
# Test DC gain
# myGain = dcgain(self)
# if np.isinf(myGain) or (np.abs(myGain) > finfo(float).resolution):
# pass
# else:
# plt.figure()
# plt.plot([t[0], t[-1]], [myGain, myGain], ':k')
# plt.title('Dc Gain')
# plt.xlabel('Time [s]')
# plt.ylabel('Amplitude')
# plt.grid()
# plt.tight_layout()
# plt.show()
if tTobereturn:
return [t, y]
else:
return y
elif output is False and plot is True:
plt.figure()
plt.plot(t, y)
plt.title('Step response')
plt.xlabel('Time [s]')
plt.ylabel('Amplitude')
plt.grid()
plt.tight_layout()
plt.show()
# Plot final value if present
# Test DC gain
# myGain = dcgain(self)
# if np.isinf(myGain) or (np.abs(myGain) > finfo(float).resolution):
# pass
# else:
# plt.figure()
# plt.plot([t[0], t[-1]], [myGain, myGain], ':k')
# plt.title('Dc Gain')
# plt.xlabel('Time [s]')
# plt.ylabel('Amplitude')
# plt.grid()
# plt.tight_layout()
# plt.show()
elif output is True and plot is False:
if tTobereturn:
return [t, y]
else:
return y
else:
raise ValueError("fotf.step: input for keyword 'output' or 'plot', must be True")
def _truncatecoeff(self):
"""Remove extraneous zero coefficients from num and den.
Check every element of the numerator and denominator matrices, and
truncate leading zeros. For instance, running self._truncatecoeff()
will reduce self.num = [[[0, 0, 1, 2]]] to [[[1, 2]]].
"""
# Beware: this is a shallow copy. This should be okay.
data = [self.num, self.den]
for p in range(len(data)):
for i in range(self.outputs):
for j in range(self.inputs):
# Find the first nontrivial coefficient.
nonzero = None
for k in range(data[p][i][j].size):
if data[p][i][j][k]:
nonzero = k
break
if nonzero is None:
# The array is all zeros.
data[p][i][j] = zeros(1)
else:
# Truncate the trivial coefficients.
data[p][i][j] = data[p][i][j][nonzero:]
[self.num, self.den] = data
ndata = [self.nnum, self.nden]
for p in range(len(data)):
for i in range(self.outputs):
for j in range(self.inputs):
# Find the first nontrivial coefficient.
nonzero = None
for k in range(data[p][i][j].size):
if data[p][i][j][k]:
nonzero = k
break
if nonzero is None:
# The array is all zeros.
data[p][i][j] = zeros(1)
else:
# Truncate the trivial coefficients.
data[p][i][j] = data[p][i][j][nonzero:]
[self.nnum, self.nden] = ndata
def isstable(self, doPlot=True):
"""
:param doPlot: if set to 'True', will create a plot with relevant system poles.
Default is 'False'
:type doPlot: bool
:return K: K - bool, 'True' if system is stable, else 'False'
q - calculated commensurate-order
err - stability assessment error norm
apol - closest poles' absolute imaginary part value to the unstable region
"""
try:
MIN_ORDER = 0.01
if self.MIN_COMM_ORDER < MIN_ORDER:
MIN_COMM_ORDER = MIN_ORDER
else:
MIN_COMM_ORDER = self.MIN_COMM_ORDER
comm_factor = round(MIN_COMM_ORDER ** -1)
if isinstance(self, FOTransFunc):
b = self.den[0][0]
nb = self.nden[0][0]
nb1 = nb * comm_factor
q = comm_order(self, 'den')
newnb = np.array(nb1 / (comm_factor * q), dtype=np.int32)
c = zeros(max(newnb) + 1)
c[newnb] = b
c = np.flip(c)
p = np.roots(c)
if p.size != 0:
absp = p[np.nonzero(np.abs(p) > finfo(float).resolution)] #very important
err = np.linalg.norm(polyval(c, absp))
apol = np.amin(np.abs(np.angle(absp)))
K = apol > q * np.pi * 0.5
# Check if drawing is requested
if doPlot:
# create new figure
#x = plt.figure(dpi=512)
x = plt.figure(dpi=128)
axes.Axes.set_autoscale_on(x, True)
# plt.plot(np.real(p), np.imag(p), '.', markersize=2)
if 0.1 <= q <=1:
plt.plot(np.real(p), np.imag(p), 'x', 0, 0, '.', markersize=4)
elif 0.01 <= q < 0.1:
plt.plot(np.real(p), np.imag(p), 'x', 0, 0, '.', markersize=2)
else:
plt.plot(np.real(p), np.imag(p), 'x', markersize=1)
if K:
plt.legend(['STABLE @ q = {}'.format(q)], loc='lower right')
else:
plt.legend(['UNSTABLE @ q = {}'.format(q)], loc='lower right')
# Get and check x axis limit
left, right = plt.xlim()
if np.imag(p).size <= 1:
right = abs(p.max())
gpi = right * np.tan(q * np.pi * 0.5)
else:
right = max(abs(np.imag(p).max()), abs(np.imag(p).min()))
gpi = right * np.tan(q * np.pi * 0.5)
newright = max(abs(gpi), abs(right))*1.1
plotx = max(abs(gpi), abs(right))*1.05
plt.xlim(-newright, newright)
plt.ylim(-newright, newright)
x_fill = np.array([0, plotx, plotx, 0])
y_fill = np.array([0, gpi, -gpi, 0])
plt.fill_between(x_fill, y_fill, color='red')
plt.tight_layout()
plt.show()
else:
pass
return [K, q, err, apol]
except Exception as excep:
print("\nError occured @ fotf.FOTransfuct.isstable\n")
print(type(excep))
print(excep.args)
def __str__(self, var=None):
"""String representation of the FRACTIONAL Order transfer function."""
mimo = self.inputs > 1 or self.outputs > 1
if var is None:
# ! TODO: replace with standard calls to lti functions
if self.dt is None or self.dt == 0:
var = 's'
else:
var = 's' # var='z'
outstr = ""
for i in range(self.inputs):
for j in range(self.outputs):
if mimo:
outstr += "\nInput {0} to output {1}".format(i + 1, j + 1)
# Convert the numerator and denominator polynomials to strings.
numstr = self.poly2str(self.num[j][i], self.nnum[j][i], var=var)
denstr = self.poly2str(self.den[j][i], self.nden[j][i], var=var)
# Figure out the length of the separating line
dashcount = max(len(numstr), len(denstr))
dashes = '-' * dashcount
if self.dt > 0:
dashes += 'exp({}s)'.format(self.dt * -1)
# Center the numerator or denominator
if len(numstr) < dashcount:
numstr = (' ' * int(round((dashcount - len(numstr)) / 2)) +
numstr)
if len(denstr) < dashcount:
denstr = (' ' * int(round((dashcount - len(denstr)) / 2)) +
denstr)
outstr += "\n" + numstr + "\n" + dashes + "\n" + denstr + "\n"
return outstr
# represent a string, makes display work for IPython
def __repr__(self, ):
return self.__str__()
#TODO: still investigating on this
def _repr_latex_(self, var=None):
"""LaTeX representation of the transfer function, for Jupyter notebook"""
mimo = self.inputs > 1 or self.outputs > 1
if var is None:
# ! TODO: replace with standard calls to lti functions
var = 's' if self.dt is None or self.dt == 0 else 'z'
out = ['$$']
if mimo:
out.append(r"\begin{bmatrix}")
for i in range(self.outputs):
for j in range(self.inputs):
# Convert the numerator and denominator polynomials to strings.
numstr = self.poly2str(self.num[i][j], self.nnum, var=var)
denstr = self.poly2str(self.den[i][j], self.nnum, var=var)
out += [r"\frac{", numstr, "}{", denstr, "}"]
if mimo and j < self.outputs - 1:
out.append("&")
if mimo:
out.append(r"\\")
if mimo:
out.append(r" \end{bmatrix}")
# See if this is a discrete time system with specific sampling time
if not (self.dt is None) and type(self.dt) != bool and self.dt > 0:
out += ["\quad dt = ", str(self.dt)]
out.append("$$")
return ''.join(out)
def __neg__(self):
"""Negate a Fractional order transfer function."""
_num = deepcopy(self.num)
for i in range(self.outputs):
for j in range(self.inputs):
_num[i][j] *= -1
return FOTransFunc(_num, self.nnum, self.den, self.nden, self.dt)
# Not done this yet
def __add__(self, other):
"""Add two FOTransfunc objects ."""
# Convert the second argument to a transfer function.
if not isinstance(other, FOTransFunc) and not isinstance(other, str):
_other = fotf(other)
else:
_other = deepcopy(other)
# Check that the input-output sizes are consistent.
if self.inputs != other.inputs:
raise ValueError("The first summand has %i input(s), but the second has %i."
% (self.inputs, other.inputs))
if self.outputs != other.outputs:
raise ValueError("The first summand has %i output(s), but the second has %i."
% (self.outputs, other.outputs))
# Figure out the sampling time to use
if self.dt == other.dt:
aa = self.den[0][0]
othera = _other.den[0][0]
bb = self.num[0][0]
otherb = _other.num[0][0]
#change denominator shape to 2d
aa = np.reshape(aa, (1, aa.shape[0]))
othera = np.reshape(othera, (1, othera.shape[0]))
# change numerator shape to 2d
bb = np.reshape(bb, (1, bb.shape[0]))
otherb = np.reshape(otherb, (1, otherb.shape[0]))
#use Kron product
a = sp.linalg.kron(aa, othera)
b0 = sp.linalg.kron(aa, otherb)
b1 = sp.linalg.kron(bb, othera)
# revert shapes
a = np.reshape(a, a.size)
b0 = np.reshape(b0, b0.size)
b1 = np.reshape(b1, b1.size)
b = np.concatenate((b0,b1))
na = np.empty(1)
nb = np.empty(1)
for i in self.nden[0][0]:
na = np.append(na, (i + _other.nden[0][0]))
nb = np.append(nb, (i+ _other.nnum[0][0]))
na = np.delete(na, 0)
for j in self.nnum[0][0]:
nb = np.append(nb, (j + _other.nden[0][0]))
nb = np.delete(nb, 0)
return simple(fotf(b,nb,a,na, self.dt))
else:
raise ValueError("Cannot handle different delay times")
# # Preallocate the numerator and denominator of the sum.
# num = [[[] for j in range(self.inputs)] for i in range(self.outputs)]
# den = [[[] for j in range(self.inputs)] for i in range(self.outputs)]
#
# for i in range(self.outputs):
# for j in range(self.inputs):
# num[i][j], den[i][j] = _add_siso(self.num[i][j], self.den[i][j],
# other.num[i][j],
# other.den[i][j])
#
# return FOTransFunc(num, den, dt)
def __radd__(self, other):
"""Right add two LTI objects (parallel connection)."""
return self + other
def __sub__(self, other):
"""Subtract two LTI objects."""
return self + (-other)
def __rsub__(self, other):
"""Right subtract two LTI objects."""
return other + (-self)
def __mul__(self, other):
"""Multiply two FOTransFunc Object (serial connection)."""
# Convert the second argument to a transfer function.
if not isinstance(other, FOTransFunc):
_other = fotf(other)
else:
_other = other
aa = self.num[0][0]
othera = _other.num[0][0]
bb = self.den[0][0]
otherb = _other.den[0][0]
aa = np.reshape(aa,(1,aa.shape[0]))
othera = np.reshape(othera,(1,othera.shape[0]))
bb = np.reshape(bb,(1,bb.shape[0]))
otherb = np.reshape(otherb, (1, otherb.shape[0]))
a = sp.linalg.kron(aa,othera)
b = sp.linalg.kron(bb,otherb)
#revert shapes
a = np.reshape(a, a.size)
b = np.reshape(b, b.size)
na = np.empty(1)
nb = np.empty(1)
for i in self.nnum[0][0]:
na = np.append(na, (i + _other.nnum[0][0]))
na = np.delete(na,0)
for j in self.nden[0][0]:
nb = np.append(nb, (j + _other.nden[0][0]))
nb = np.delete(nb, 0)
return simple(fotf(a,na,b,nb, self.dt + _other.dt))
def __rmul__(self, other):
"""Right multiply two FOTransFunc objects (serial connection)."""
if not isinstance(other, FOTransFunc):
_other = fotf(other)
else:
_other = other
aa = self.num[0][0]
othera = _other.num[0][0]
bb = self.den[0][0]
otherb = _other.den[0][0]
aa = np.reshape(aa,(1,aa.shape[0]))
othera = np.reshape(othera,(1,othera.shape[0]))
bb = np.reshape(bb,(1,bb.shape[0]))
otherb = np.reshape(otherb, (1, otherb.shape[0]))
a = sp.linalg.kron(othera,aa)
b = sp.linalg.kron(otherb, bb)
#revert shapes
a = np.reshape(a, a.size)
b = np.reshape(b, b.size)
na = np.empty(1)
nb = np.empty(1)
for i in self.nnum[0][0]:
na = np.append(na, (i + _other.nnum[0][0]))
na = np.delete(na,0)
for j in self.nden[0][0]:
nb = np.append(nb, (j + _other.nden[0][0]))
nb = np.delete(nb, 0)
return simple(fotf(a,na,b,nb, self.dt + _other.dt))
def __truediv__(self, other):
"""Divide two FOTransFunc objects.
Right division of fractional-order dynamic systems.
Note: if delays in the systems are present, dividing the two systems may
result in positive delays thus the overall delay of the system
will be changed to zero. There with be a warning.
"""
if not isinstance(other, FOTransFunc):
other = newfotf(other)
# Figure out the sampling time to use
if self.dt is None and other.dt != None:
dt = other.dt # use dt from second argument
elif other.dt is None and self.dt != None:
dt = self.dt # use dt from first argument
elif other.dt != None and self.dt != None:
dt = self.dt - other.dt
if dt < 0:
dt = 0
warn("FOTTransFunc.__truedivide__: Resulting FOTransFunc has positive delay: changing to zero")
else:
raise ValueError("Systems have different sampling times")
g = self * other.__invert__()
g.dt = dt
return g
def __rtruediv__(self, other):
"""Right divide two FOTransfunc objects."""
if not isinstance(other, FOTransFunc):
other = newfotf(other)
return other / self
def __rdiv__(self, other):
return FOTransFunc.__rtruediv__(self, other)
def __pow__(self, n):
"""
Computes the self multiplicaiton of object by n-times
:param n: int
:return: self**n
"""
num,nnum,den,nden,dt = fotfparam(self)
if not isinstance(n,int):
raise ValueError("Exponent must be an integer")
elif den.size * num.size == 1 and nden == 0 and nnum ==1:
return FOTransFunc(1,0,1,n) # unity
else:
if n >=0:
y = 1
for i in range(n):
y *=self
else:
a = 1
for i in range(n):
a *=self
y = a.__invert__()
if not isinstance(y,FOTransFunc):
y = fotf(y)
update = simple(y)
update.dt = n * self.dt
return update
def __eq__(self,other):
"""
checks is a transfer function is equal, overides the '==' operator
:param other: A fractional order Transfer function object
:type other: FOTransFunc
:return: True or False
"""
try:
if not isinstance(other,FOTransFunc):
other = FOTransFunc(other)
num, nnum,den, nden, dt = fotfparam(self)
othernum, othernnum, otherden, othernden , otherdt = fotfparam(other)
if num.all() == othernum.all() and nnum.all() ==othernnum.all() and den.all() ==otherden.all() \
and nden.all() == othernden.all() and dt == otherdt:
return True
else:
return False
except:
return False
def __invert__(self):
num, nnum, den,nden, dt = fotfparam(self)
return fotf(den,nden,num,nnum,-dt)
def __getitem__(self, key):
key1, key2 = key
# pre-process
if isinstance(key1, int):
key1 = slice(key1, key1 + 1, 1)
if isinstance(key2, int):
key2 = slice(key2, key2 + 1, 1)
# dim1
start1, stop1, step1 = key1.start, key1.stop, key1.step
if step1 is None:
step1 = 1
if start1 is None:
start1 = 0
if stop1 is None:
stop1 = len(self.num)
# dim1
start2, stop2, step2 = key2.start, key2.stop, key2.step
if step2 is None:
step2 = 1
if start2 is None:
start2 = 0
if stop2 is None:
stop2 = len(self.num[0])
num = []
den = []
for i in range(start1, stop1, step1):
num_i = []
den_i = []
for j in range(start2, stop2, step2):
num_i.append(self.num[i][j])
den_i.append(self.den[i][j])
num.append(num_i)
den.append(den_i)
if self.isctime():
return FOTransFunc(num, den)
else:
return FOTransFunc(num, den, self.dt)
# from control library
def evalfr(self, omega):
"""Evaluate a transfer function at a single angular frequency.
self._evalfr(omega) returns the value of the transfer function
matrix with input value s = i * omega.
"""
warn("TransferFunction.evalfr(omega) will be deprecated in a "
"future release of python-control; use evalfr(sys, omega*1j) "
"instead", PendingDeprecationWarning)
return self._evalfr(omega)
#from control library
def _evalfr(self, omega):
"""Evaluate a transfer function at a single angular frequency."""
# TODO: implement for discrete time systems
if isdtime(self, strict=True):
# Convert the frequency to discrete time
dt = timebase(self)
s = exp(1.j * omega * dt)
if np.any(omega * dt > pi):
warn("_evalfr: frequency evaluation above Nyquist frequency")
else:
s = 1.j * omega
return self.horner(s)
# from control library
def horner(self, s):
"""Evaluate the systems's transfer function for a complex variable
Returns a matrix of values evaluated at complex variable s.
"""
# Preallocate the output.
if getattr(s, '__iter__', False):
out = empty((self.outputs, self.inputs, len(s)), dtype=complex)
else:
out = empty((self.outputs, self.inputs), dtype=complex)
for i in range(self.outputs):
for j in range(self.inputs):
out[i][j] = (polyval(self.num[i][j], s) /
polyval(self.den[i][j], s))
return out
# Method for generating the frequency response of the system
def freqresp(self, minExp=None, maxExp=None, numPts=1000):
"""Frequency response of fractional-order transfer functions.
at which the frequency response must be computed.
:param minExp: minimum exponent of Frequency to compute
:type w: int, float
:param maxExp: maximum exponent of Frequency to compute
:type maxExp: int, float
:param numPts: Number of points within interval minExp and maxExp
:type maxExp: int
:returns :Magnitude (Db), Phase in Degree, w - Frequency
"""
if minExp is None:
minExp = -5
if maxExp is None:
maxExp = 5
if numPts is None:
numPts = 1000
w = np.logspace(minExp, maxExp, numPts)
_num, _nnum, _den, _nden, _dt = fotfparam(self)
jj = 1j
lenW = w.size
r = zeros(lenW, dtype=complex)
for k in range(lenW):
bb = np.power((jj * w[k]), _nnum)
aa = np.power((jj * w[k]), _nden)
P = _num @ bb
Q = _den @ aa
r[k] = P / Q
# Delay
if self.dt > 0:
for k2 in range(lenW):
r[k2] *= np.exp(-jj * w(k2) * self.dt)
rangle = unwrap(np.angle(r))
rangleCalcDeg = np.rad2deg(rangle)
rmagDb = 20 * np.log10(np.absolute(r))
# # from control library, used basically to plot bode. But noticed an error so had to code it myself
# H1 = frd(r,w)
# rmagDb, rangledeg, w = bode(H1, w, dB=True, Plot=True, deg=True)
# plt.show()
plt.figure(dpi=128)
#plt.figure(1)
plt.subplot(2, 1, 1)
plt.semilogx(w, rmagDb, 'g-')
plt.ylabel('Magnitude (Db)')
plt.title('Bode Plot')
plt.grid(True, axis='both', which='both')
plt.subplot(2, 1, 2)
plt.semilogx(w, rangleCalcDeg, 'g-')
plt.xlabel('Frequency (rad/s)')
plt.ylabel('Phase (deg)')
plt.grid(True, axis='both', which='both')
plt.tight_layout()
plt.show()
return [rmagDb, rangleCalcDeg, w]
def Poles(self):
"""Computes the poles of a Fractional Order Transfer function.
:returns absZeros, err: Zeros ,error in calculation of zeros"""
if self.inputs > 1 or self.outputs > 1:
raise NotImplementedError("FOTransFunc.poles is currently only implemented for SISO systems.")
else:
# for now, just give poles of a SISO tf
comm_factor = self.MIN_COMM_ORDER ** -1
b = self.den[0][0]
nb = self.nden[0][0]
nb1 = nb * comm_factor
q = comm_order(self, 'den')
newnb = np.array(nb1 / (comm_factor * q), dtype=np.int32)
c = zeros(newnb[0] + 1)
c[newnb] = b
cslice = c[::-1]
p = roots(cslice)
if p != None:
#resolution Checker
absZeros = np.array(p * (np.abs(p) > finfo(float).resolution))
err = np.linalg.norm(polyval(cslice, absZeros))
return absZeros, err
def Zeros(self):
"""Computes the Zeros of a Fractional-Order Transfer function.
:returns absZeros, err: poles ,error in calculation of poles"""
if self.inputs > 1 or self.outputs > 1:
raise NotImplementedError("FOTransFunc.zeros is currently only implemented for SISO systems.")
else:
# for now, just give zeros of a SISO tf
comm_factor = self.MIN_COMM_ORDER ** -1
a = self.num[0][0]
na = self.num[0][0]
na1 = na * comm_factor
q = comm_order(self, 'den')
newna = np.array(na1 / (comm_factor * q), dtype=np.int32)
c = zeros(newna[0] + 1)
c[newna] = a
cslice = c[::-1]
p = roots(cslice)
if p != None:
# resolution Checker
absZeros = np.array(p * (np.abs(p) > finfo(float).resolution))
err = np.linalg.norm(polyval(cslice, absZeros))
return absZeros, err
def feedback(self, other, sign=-1):
"""Feedback connection of two input/output fractional-order transfer functions.
M = G.feedback(H) computes a closed-loop model for the feedback loop:
u --->O---->[ G ]---------> y
^ |
| |
------[ H ]<-----
"""
if not isinstance(other, FOTransFunc):
other = newfotf(other)
if self.dt == other.dt:
aa = self.den[0][0]
othera = other.den[0][0]
bb = self.num[0][0]
otherb = other.num[0][0]
# change denominator shape to 2d
aa = np.reshape(aa, (1, aa.shape[0]))
othera = np.reshape(othera, (1, othera.shape[0]))
# change numerator shape to 2d
bb = np.reshape(bb, (1, bb.shape[0]))
otherb = np.reshape(otherb, (1, otherb.shape[0]))
# use Kron product
b = sp.linalg.kron(bb, othera)
a0 = sp.linalg.kron(bb, otherb)
a1 = sp.linalg.kron(aa, othera)