forked from alchemyst/Skogestad-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
2852 lines (2281 loc) · 79.2 KB
/
utils.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
# -*- coding: utf-8 -*-
"""
Created on Jan 27, 2012
@author: Carl Sandrock
"""
from __future__ import division
from __future__ import print_function
import numpy # do not abbreviate this module as np in utils.py
import scipy
import sympy # do not abbreviate this module as sp in utils.py
from scipy import optimize, signal
import scipy.linalg as sc_linalg
from functools import reduce
import itertools
def astf(maybetf):
"""
:param maybetf: something which could be a tf
:return: a transfer function object
>>> G = tf( 1, [ 1, 1])
>>> astf(G)
tf([1.], [1. 1.])
>>> astf(1)
tf([1.], [1.])
>>> astf(numpy.matrix([[G, 1.], [0., G]]))
matrix([[tf([1.], [1. 1.]), tf([1.], [1.])],
[tf([0.], [1]), tf([1.], [1. 1.])]], dtype=object)
"""
if isinstance(maybetf, (tf, mimotf)):
return maybetf
elif numpy.isscalar(maybetf):
return tf(maybetf)
else: # Assume we have an array-like object
return numpy.asmatrix(arrayfun(astf, numpy.asarray(maybetf)))
class tf(object):
"""
Very basic transfer function object
Construct with a numerator and denominator:
>>> G = tf(1, [1, 1])
>>> G
tf([1.], [1. 1.])
>>> G2 = tf(1, [2, 1])
The object knows how to do:
addition
>>> G + G2
tf([1.5 1. ], [1. 1.5 0.5])
>>> G + G # check for simplification
tf([2.], [1. 1.])
multiplication
>>> G * G2
tf([0.5], [1. 1.5 0.5])
division
>>> G / G2
tf([2. 1.], [1. 1.])
Deadtime is supported:
>>> G3 = tf(1, [1, 1], deadtime=2)
>>> G3
tf([1.], [1. 1.], deadtime=2)
Note we can't add transfer functions with different deadtime:
>>> G2 + G3
Traceback (most recent call last):
...
ValueError: Transfer functions can only be added if their deadtimes are the same. self=tf([0.5], [1. 0.5]), other=tf([1.], [1. 1.], deadtime=2)
Although we can add a zero-gain tf to anything
>>> G2 + 0*G3
tf([0.5], [1. 0.5])
>>> 0*G2 + G3
tf([1.], [1. 1.], deadtime=2)
It is sometimes useful to define
>>> s = tf([1, 0])
>>> 1 + s
tf([1. 1.], [1.])
>>> 1/(s + 1)
tf([1.], [1. 1.])
"""
def __init__(self, numerator, denominator=1, deadtime=0, name='',
u='', y='', prec=3):
"""
Initialize the transfer function from a
numerator and denominator polynomial
"""
# TODO: poly1d should be replaced by np.polynomial.Polynomial
self.numerator = numpy.poly1d(numerator)
self.denominator = numpy.poly1d(denominator)
self.deadtime = deadtime
self.zerogain = False
self.name = name
self.u = u
self.y = y
self.simplify(dec=prec)
def inverse(self):
"""
Inverse of the transfer function
"""
return tf(self.denominator, self.numerator, -self.deadtime)
def step(self, *args):
""" Step response """
return signal.lti(self.numerator, self.denominator).step(*args)
def lsim(self, *args):
""" Negative step response """
return signal.lsim(signal.lti(self.numerator, self.denominator), *args)
def simplify(self, dec=3):
# Polynomial simplification
k = self.numerator[self.numerator.order] / \
self.denominator[self.denominator.order]
ps = self.poles().tolist()
zs = self.zeros().tolist()
ps_to_canc_ind, zs_to_canc_ind = common_roots_ind(ps, zs)
cancelled = cancel_by_ind(ps, ps_to_canc_ind)
places = 10
if cancelled > 0:
cancel_by_ind(zs, zs_to_canc_ind)
places = dec
self.numerator = numpy.poly1d(
[round(i.real, places) for i in k*numpy.poly1d(zs, True)])
self.denominator = numpy.poly1d(
[round(i.real, places) for i in 1*numpy.poly1d(ps, True)])
# Zero-gain transfer functions are special. They effectively have no
# dead time and can be simplified to a unity denominator
if self.numerator == numpy.poly1d([0]):
self.zerogain = True
self.deadtime = 0
self.denominator = numpy.poly1d([1])
def poles(self):
return self.denominator.r
def zeros(self):
return self.numerator.r
def exp(self):
""" If this is basically "D*s" defined as tf([D, 0], 1),
return dead time
>>> s = tf([1, 0], 1)
>>> numpy.exp(-2*s)
tf([1.], [1.], deadtime=2.0)
"""
# Check that denominator is 1:
if self.denominator != numpy.poly1d([1]):
raise ValueError(
'Can only exponentiate multiples of s, not {}'.format(self))
s = tf([1, 0], 1)
ratio = -self/s
if len(ratio.numerator.coeffs) != 1:
raise ValueError(
'Can not determine dead time associated with {}'.format(self))
D = ratio.numerator.coeffs[0]
return tf(1, 1, deadtime=D)
def __repr__(self):
if self.name:
r = str(self.name) + "\n"
else:
r = ''
r += "tf(" + str(self.numerator.coeffs) + ", " \
+ str(self.denominator.coeffs)
if self.deadtime:
r += ", deadtime=" + str(self.deadtime)
if self.u:
r += ", u='" + self.u + "'"
if self.y:
r += ", y=': " + self.y + "'"
r += ")"
return r
def __call__(self, s):
"""
This allows the transfer function to be evaluated at
particular values of s.
Effectively, this makes a tf object behave just like a function of s.
>>> G = tf(1, [1, 1])
>>> G(0)
1.0
"""
return (numpy.polyval(self.numerator, s) /
numpy.polyval(self.denominator, s) *
numpy.exp(-s * self.deadtime))
def __add__(self, other):
other = astf(other)
if isinstance(other, numpy.matrix):
return other.__add__(self)
# Zero-gain functions are special
dterrormsg = "Transfer functions can only be added if " \
"their deadtimes are the same. self={}, other={}"
if self.deadtime != other.deadtime and not (
self.zerogain or other.zerogain):
raise ValueError(dterrormsg.format(self, other))
gcd = self.denominator * other.denominator
return tf(self.numerator*other.denominator +
other.numerator*self.denominator, gcd, self.deadtime +
other.deadtime)
def __radd__(self, other):
return self + other
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return other + (-self)
def __mul__(self, other):
other = astf(other)
if isinstance(other, numpy.matrix):
return numpy.dot(other, self)
elif isinstance(other, mimotf):
return mimotf(numpy.dot(other.matrix, self))
return tf(self.numerator*other.numerator,
self.denominator*other.denominator,
self.deadtime + other.deadtime)
def __rmul__(self, other):
return self * other
def __truediv__(self, other):
if not isinstance(other, tf):
other = tf(other)
return self * other.inverse()
def __rtruediv__(self, other):
return tf(other)/self
def __div__(self, other):
if not isinstance(other, tf):
other = tf(other)
return self * other.inverse()
def __rdiv__(self, other):
return tf(other)/self
def __neg__(self):
return tf(-self.numerator, self.denominator, self.deadtime)
def __pow__(self, other):
r = self
for k in range(other-1):
r = r * self
return r
# TODO: Concatenate tf objects into MIMO structure
def RHPonly(x, round_precision=2):
return list(
set(numpy.round(xi, round_precision) for xi in x if xi.real > 0))
@numpy.vectorize
def evalfr(G, s):
return G(s)
def matrix_as_scalar(M):
"""
Return a scalar from a 1x1 matrix
:param M: matrix
:return: scalar part of matrix if it is 1x1 else just a matrix
"""
if M.shape == (1, 1):
return M[0, 0]
else:
return M
class mimotf(object):
""" Represents MIMO transfer function matrix
This is a pretty basic wrapper around the numpy.matrix class which deals
with most of the heavy lifting.
You can construct the object from siso tf objects similarly to calling
numpy.matrix:
>>> G11 = G12 = G21 = G22 = tf(1, [1, 1])
>>> G = mimotf([[G11, G12], [G21, G22]])
>>> G
mimotf([[tf([1.], [1. 1.]) tf([1.], [1. 1.])]
[tf([1.], [1. 1.]) tf([1.], [1. 1.])]])
Some coersion will take place on the elements:
>>> mimotf([[1]])
mimotf([[tf([1.], [1.])]])
The object knows how to do:
addition
>>> G + G
mimotf([[tf([2.], [1. 1.]) tf([2.], [1. 1.])]
[tf([2.], [1. 1.]) tf([2.], [1. 1.])]])
>>> 0 + G
mimotf([[tf([1.], [1. 1.]) tf([1.], [1. 1.])]
[tf([1.], [1. 1.]) tf([1.], [1. 1.])]])
>>> G + 0
mimotf([[tf([1.], [1. 1.]) tf([1.], [1. 1.])]
[tf([1.], [1. 1.]) tf([1.], [1. 1.])]])
multiplication
>>> G * G
mimotf([[tf([2.], [1. 2. 1.]) tf([2.], [1. 2. 1.])]
[tf([2.], [1. 2. 1.]) tf([2.], [1. 2. 1.])]])
>>> 1*G
mimotf([[tf([1.], [1. 1.]) tf([1.], [1. 1.])]
[tf([1.], [1. 1.]) tf([1.], [1. 1.])]])
>>> G*1
mimotf([[tf([1.], [1. 1.]) tf([1.], [1. 1.])]
[tf([1.], [1. 1.]) tf([1.], [1. 1.])]])
>>> G*tf(1)
mimotf([[tf([1.], [1. 1.]) tf([1.], [1. 1.])]
[tf([1.], [1. 1.]) tf([1.], [1. 1.])]])
>>> tf(1)*G
mimotf([[tf([1.], [1. 1.]) tf([1.], [1. 1.])]
[tf([1.], [1. 1.]) tf([1.], [1. 1.])]])
exponentiation with positive integer constants
>>> G**2
mimotf([[tf([2.], [1. 2. 1.]) tf([2.], [1. 2. 1.])]
[tf([2.], [1. 2. 1.]) tf([2.], [1. 2. 1.])]])
"""
def __init__(self, matrix):
# First coerce whatever we have into a matrix
self.matrix = astf(numpy.asmatrix(matrix))
# We only support matrices of transfer functions
self.shape = self.matrix.shape
def mimotf_slice(self, rows, cols):
nRows = len(rows)
nCols = len(cols)
result = [[] for r in range(nRows)]
for r in range(nRows):
for c in range(nCols):
result[r].append(tf(list(self[rows[r], cols[c]].numerator.coeffs),
list(self[rows[r], cols[c]].denominator.coeffs)))
return mimotf(result)
def det(self):
return det(self.matrix)
def poles(self):
""" Calculate poles
>>> s = tf([1, 0], [1])
>>> G = mimotf([[(s - 1) / (s + 2), 4 / (s + 2)],
... [4.5 / (s + 2), 2 * (s - 1) / (s + 2)]])
>>> G.poles()
array([-2.])
"""
return poles(self)
def zeros(self):
return zeros(self)
def cofactor_mat(self):
A = self.matrix
m = A.shape[0]
n = A.shape[1]
C = numpy.zeros((m, n), dtype=object)
for i in range(m):
for j in range(n):
minorij = det(
numpy.delete(numpy.delete(A, i, axis=0), j, axis=1))
C[i, j] = (-1.)**(i+1+j+1)*minorij
return C
def inverse(self):
""" Calculate inverse of mimotf object
>>> s = tf([1, 0], 1)
>>> G = mimotf([[(s - 1) / (s + 2), 4 / (s + 2)],
... [4.5 / (s + 2), 2 * (s - 1) / (s + 2)]])
>>> G.inverse()
matrix([[tf([ 1. -1.], [ 1. -4.]), tf([-2.], [ 1. -4.])],
[tf([-2.25], [ 1. -4.]), tf([ 0.5 -0.5], [ 1. -4.])]],
dtype=object)
>>> G.inverse()*G.matrix
matrix([[tf([1.], [1.]), tf([0.], [1])],
[tf([0.], [1]), tf([1.], [1.])]], dtype=object)
"""
detA = det(self.matrix)
C_T = self.cofactor_mat().T
inv = (1./detA)*C_T
return inv
def __call__(self, s):
"""
>>> G = mimotf([[1]])
>>> G(0)
matrix([[1.]])
>>> firstorder= tf(1, [1, 1])
>>> G = mimotf(firstorder)
>>> G(0)
matrix([[1.]])
>>> G2 = mimotf([[firstorder]*2]*2)
>>> G2(0)
matrix([[1., 1.],
[1., 1.]])
"""
return evalfr(self.matrix, s)
def __repr__(self):
return "mimotf({})".format(str(self.matrix))
def __add__(self, other):
left = self.matrix
if not isinstance(other, mimotf):
if hasattr(other, 'shape'):
right = mimotf(other).matrix
else:
right = tf(other)
else:
right = other.matrix
return mimotf(left + right)
def __radd__(self, other):
return self + other
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return other + (-self)
def __mul__(self, other):
left = matrix_as_scalar(self.matrix)
if not isinstance(other, mimotf):
other = mimotf(other)
right = matrix_as_scalar(other.matrix)
return mimotf(left*right)
def __rmul__(self, other):
right = matrix_as_scalar(self.matrix)
if not isinstance(other, mimotf):
other = mimotf(other)
left = matrix_as_scalar(other.matrix)
return mimotf(left*right)
def __div__(self, other):
raise NotImplemented("Division doesn't make sense on matrices")
def __neg__(self):
return mimotf(-self.matrix)
def __pow__(self, other):
r = self
for k in range(other-1):
r = r * self
return r
def __getitem__(self, item):
result = mimotf(self.matrix.__getitem__(item))
if result.shape == (1, 1):
return result.matrix[0, 0]
else:
return result
def __slice__(self, i, j):
result = mimotf(self.matrix[i, j])
if result.shape == (1, 1):
return result.matrix[0, 0]
else:
return result
def scaling(G_hat, e, u, input_type='symbolic', Gd_hat=None, d=None):
"""
Receives symbolic matrix of plant and disturbance transfer functions
as well as array of maximum deviations, scales plant variables according
to eq () and ()
Parameters
-----------
G_hat : matrix of plant WITHOUT deadtime
e : array of maximum plant output variable deviations
in same order as G matrix plant outputs
u : array of maximum plant input variable deviations
in same order as G matrix plant inputs
input_type : specifies whether input is symbolic matrix or utils mimotf
Gd_hat : optional
matrix of plant disturbance model WITHOUT deadtime
d : optional
array of maximum plant disturbance variable deviations
in same order as Gd matrix plant disturbances
Returns
----------
G_scaled : scaled plant function
Gd_scaled : scaled plant disturbance function
Example
-------
>>> s = sympy.Symbol("s")
>>> G_hat = sympy.Matrix([[1/(s + 2), s/(s**2 - 1)],
... [5*s/(s - 1), 1/(s + 5)]])
>>> e = numpy.array([1,2])
>>> u = numpy.array([3,4])
>>> scaling(G_hat,e,u,input_type='symbolic')
Matrix([
[ 3.0/(s + 2), 4.0*s/(s**2 - 1)],
[7.5*s/(s - 1), 2.0/(s + 5)]])
"""
De = numpy.diag(e)
De_inv = numpy.linalg.inv(De)
Du = numpy.diag(u)
if Gd_hat is not None and d is not None:
Dd = numpy.diag(d)
if input_type == 'symbolic':
G_scaled = De_inv*(G_hat)*(Du)
if Gd_hat is not None and d is not None:
Dd = numpy.diag(d)
Gd_scaled = De_inv*(Gd_hat)*(Dd)
if G_hat.shape == (1, 1):
return G_scaled[0, 0], Gd_scaled[0, 0]
else:
return G_scaled, Gd_scaled
else:
if G_hat.shape == (1, 1):
return G_scaled[0, 0]
else:
return G_scaled
elif input_type == 'mimotf':
De_inv_utils = [[] for r in range(De_inv.shape[0])]
Du_utils = [[] for r in range(Du.shape[0])]
for r in range(De_inv.shape[0]):
for c in range(De_inv.shape[1]):
De_inv_utils[r].append(tf([De_inv[r, c]]))
for r in range(Du.shape[0]):
for c in range(Du.shape[1]):
Du_utils[r].append(tf([Du[r, c]]))
De_inv_mimo = mimotf(De_inv_utils)
Du_mimo = mimotf(Du_utils)
G_scaled = De_inv_mimo*(G_hat)*(Du_mimo)
if Gd_hat is not None and d is not None:
Dd_utils = [[] for r in range(Dd.shape[0])]
for r in range(Dd.shape[0]):
for c in range(Dd.shape[1]):
Dd_utils[r].append(tf([Dd[r, c]]))
Dd_mimo = mimotf(Dd_utils)
Gd_scaled = De_inv_mimo*(Gd_hat)*(Dd_mimo)
if G_hat.shape == (1, 1):
return G_scaled[0, 0], Gd_scaled[0, 0]
else:
return G_scaled, Gd_scaled
else:
if G_hat.shape == (1, 1):
return G_scaled[0, 0]
else:
return G_scaled
else:
raise ValueError('No input type specified')
def tf_step(G, t_end=10, initial_val=0, points=1000,
constraint=None, Y=None, method='numeric'):
"""
Validate the step response data of a transfer function by considering dead
time and constraints. A unit step response is generated.
Parameters
----------
G : tf
Transfer function (input[u] or output[y]) to evauate step response.
Y : tf
Transfer function output[y] to evaluate constrain step response
(optional) (required if constraint is specified).
t_end : integer
length of time to evaluate step response (optional).
initial_val : integer
starting value to evalaute step response (optional).
points : integer
number of iteration that will be calculated (optional).
constraint : real
The upper limit the step response cannot exceed. Is only calculated
if a value is specified (optional).
method : ['numeric','analytic']
The method that is used to calculate a constrainted response. A
constraint value is required (optional).
Returns
-------
timedata : array
Array of floating time values.
process : array (1 or 2 dim)
1 or 2 dimensional array of floating process values.
"""
# Surpress the complex casting error
import warnings
warnings.simplefilter("ignore")
timedata = numpy.linspace(0, t_end, points)
if constraint is None:
deadtime = G.deadtime
[timedata, processdata] = numpy.real(G.step(initial_val, timedata))
t_stepsize = max(timedata)/(timedata.size-1)
t_startindex = int(max(0, numpy.round(deadtime/t_stepsize, 0)))
processdata = numpy.roll(processdata, t_startindex)
processdata[0:t_startindex] = initial_val
else:
if method == 'numeric':
A1, B1, C1, D1 = signal.tf2ss(G.numerator, G.denominator)
# adjust the shape for complex state space functions
x1 = numpy.zeros((numpy.shape(A1)[1], numpy.shape(B1)[1]))
if constraint is not None:
A2, B2, C2, D2 = signal.tf2ss(Y.numerator, Y.denominator)
x2 = numpy.zeros((numpy.shape(A2)[1], numpy.shape(B2)[1]))
dt = timedata[1]
processdata1 = []
processdata2 = []
bconst = False
u = 1
for t in timedata:
dxdt1 = A1*x1 + B1*u
y1 = C1*x1 + D1*u
if constraint is not None:
if (y1[0, 0] > constraint) or bconst:
y1[0, 0] = constraint
# once constraint the system is oversaturated
bconst = True
# TODO : incorrect, find the correct switch condition
u = 0
dxdt2 = A2*x2 + B2*u
y2 = C2*x2 + D2*u
x2 = x2 + dxdt2 * dt
processdata2.append(y2[0, 0])
x1 = x1 + dxdt1 * dt
processdata1.append(y1[0, 0])
if constraint:
processdata = [processdata1, processdata2]
else:
processdata = processdata1
elif method == 'analytic':
# TODO: calculate intercept of step and constraint line
timedata, processdata = [0, 0]
else:
raise ValueError('Invalid function parameters')
# TODO: calculate time response
return timedata, processdata
def circle(cx, cy, r):
"""
Return the coordinates of a circle
Parameters
----------
cx : float
Center x coordinate.
cy : float
Center y coordinate.
r : float
Radius.
Returns
-------
x, y : float
Circle coordinates.
"""
npoints = 100
theta = numpy.linspace(0, 2*numpy.pi, npoints)
y = cy + numpy.sin(theta)*r
x = cx + numpy.cos(theta)*r
return x, y
def common_roots_ind(a, b, dec=3):
#Returns the indices of common (approximately equal) roots
#of two polynomials
a_ind = [] # Contains index of common roots
b_ind = []
for i in range(len(a)):
for j in range(len(b)):
if abs(a[i]-b[j]) < 10**-dec:
if j not in b_ind:
b_ind.append(j)
a_ind.append(i)
break
return a_ind, b_ind
def cancel_by_ind(a, a_ind):
#Removes roots by index, returns number of roots
#that have been removed
cancelled = 0 # Number of roots cancelled
for i in a_ind:
del a[i - cancelled]
cancelled += 1
return cancelled
def polygcd(a, b):
"""
Find the approximate Greatest Common Divisor of two polynomials
>>> a = numpy.poly1d([1, 1]) * numpy.poly1d([1, 2])
>>> b = numpy.poly1d([1, 1]) * numpy.poly1d([1, 3])
>>> polygcd(a, b)
poly1d([1., 1.])
>>> polygcd(numpy.poly1d([1, 1]), numpy.poly1d([1]))
poly1d([1.])
"""
a_roots = a.r.tolist()
b_roots = b.r.tolist()
a_common, b_common = common_roots_ind(a_roots, b_roots)
gcd_roots = []
for i in range(len(a_common)):
gcd_roots.append((a_roots[a_common[i]]+b_roots[b_common[i]])/2)
return numpy.poly1d(gcd_roots, True)
def polylcm(a, b):
#Finds the approximate lowest common multiple of
#two polynomials
a_roots = a.r.tolist()
b_roots = b.r.tolist()
a_common, b_common = common_roots_ind(a_roots, b_roots)
cancelled = cancel_by_ind(a_roots, a_common)
if cancelled > 0: #some roots in common
gcd = polygcd(a, b)
cancelled = cancel_by_ind(b_roots, b_common)
lcm_roots = a_roots + b_roots
return numpy.polymul(gcd, numpy.poly1d(lcm_roots, True))
else: #no roots in common
lcm_roots = a_roots + b_roots
return numpy.poly1d(lcm_roots, True)
def multi_polylcm(P):
roots_list = [i.r.tolist() for i in P]
roots_by_mult = []
lcm_roots_by_mult = []
for roots in roots_list:
root_builder = []
for root in roots:
repeated = False
for i in range(len(root_builder)):
if abs(root_builder[i][0]-root) < 10**-3:
root_builder[i][1] += 1
repeated = True
break
if not repeated:
root_builder.append([root, 1])
for i in root_builder:
roots_by_mult.append(i)
for i in range(len(roots_by_mult)):
in_lcm = False
for j in range(len(lcm_roots_by_mult)):
if abs(roots_by_mult[i][0] - lcm_roots_by_mult[j][0]) < 10**-3:
in_lcm = True
if lcm_roots_by_mult[j][1] < roots_by_mult[i][1]:
lcm_roots_by_mult[j][1] = roots_by_mult[i][1]
break
if not in_lcm:
lcm_roots_by_mult.append(roots_by_mult[i])
lcm_roots = []
for i in lcm_roots_by_mult:
for j in range(i[1]):
lcm_roots.append(i[0])
return numpy.poly1d(lcm_roots, True)
def arrayfun(f, A):
"""
Recurses down to scalar elements in A, then applies f, returning lists
containing the result.
Parameters
----------
A : array
f : function
Returns
-------
arrayfun : list
>>> def f(x):
... return 1.
>>> arrayfun(f, numpy.array([1, 2, 3]))
[1.0, 1.0, 1.0]
>>> arrayfun(f, numpy.array([[1, 2, 3], [1, 2, 3]]))
[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
>>> arrayfun(f, 1)
1.0
"""
if not hasattr(A, 'shape') or numpy.isscalar(A):
return f(A)
else:
return [arrayfun(f, b) for b in A]
def listify(A):
"""
Transform a gain value into a transfer function.
Parameters
----------
K : float
Gain.
Returns
-------
gaintf : tf
Transfer function.
"""
return [A]
def det(A):
"""
Calculate determinant via elementary operations
:param A: Array-like object
:return: determinant
>>> det(2.)
2.0
>>> A = [[1., 2.],
... [1., 2.]]
>>> det(A)
0.0
>>> B = [[1., 2.],
... [3., 4.]]
>>> det(B)
-2.0
>>> C = [[1., 2., 3.],
... [1., 3., 2.],
... [3., 2., 1.]]
>>> det(C)
-12.0
# Can handle matrices of tf objects
>>> G11 = tf([1], [1, 2])
>>> G = mimotf([[G11, G11], [G11, G11]])
>>> det(G)
tf([0.], [1])
>>> G = mimotf([[G11, 2*G11], [G11**2, 3*G11]])
>>> det(G)
tf([ 3. 16. 28. 16.], [ 1. 10. 40. 80. 80. 32.])
"""
if type(A) is tf or type(A) is mimotf:
A = A.matrix
A = numpy.asmatrix(A)
assert A.shape[0] == A.shape[1], "Matrix must be square for determinant " \
"to exist"
# Base case, if matrix is 1x1, return value
if A.shape == (1, 1):
return A[0, 0]
# We expand by columns
sign = 1
result = 0
cols = rows = list(range(A.shape[1]))
for i in cols:
submatrix = A[numpy.ix_(cols[1:], list(cols[:i]) + list(cols[i+1:]))]
result += sign*A[0, i]*det(submatrix)
sign *= -1
return result
###############################################################################
# Chapter 2 #
###############################################################################
def gaintf(K):
"""
Transform a gain value into a transfer function.
Parameters
----------
K : float
Gain.
Returns
-------
gaintf : tf
Transfer function.
"""
r = tf(arrayfun(listify, K), arrayfun(listify, numpy.ones_like(K)))
return r
def findst(G, K):
"""
Find S and T given a value for G and K.
Parameters
----------
G : numpy array
Matrix of transfer functions.
K : numpy array
Matrix of controller functions.
Returns
-------
S : numpy array
Matrix of sensitivities.
T : numpy array
Matrix of complementary sensitivities.
"""
L = G*K
I = numpy.eye(G.outputs, G.inputs)
S = numpy.linalg.inv(I + L)