applied-ai-018 commited on
Commit
f727435
·
verified ·
1 Parent(s): 12532a1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ckpts/universal/global_step120/zero/11.mlp.dense_h_to_4h.weight/fp32.pt +3 -0
  2. ckpts/universal/global_step120/zero/12.attention.query_key_value.weight/fp32.pt +3 -0
  3. ckpts/universal/global_step80/mp_rank_00_model_states.pt +3 -0
  4. ckpts/universal/global_step80/mp_rank_01_model_states.pt +3 -0
  5. ckpts/universal/global_step80/mp_rank_02_model_states.pt +3 -0
  6. ckpts/universal/global_step80/mp_rank_03_model_states.pt +3 -0
  7. ckpts/universal/global_step80/mp_rank_04_model_states.pt +3 -0
  8. ckpts/universal/global_step80/mp_rank_05_model_states.pt +3 -0
  9. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__init__.py +5 -0
  10. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-310.pyc +0 -0
  11. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc +0 -0
  12. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/truss.cpython-310.pyc +0 -0
  13. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/beam.py +0 -0
  14. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__init__.py +0 -0
  15. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  16. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-310.pyc +0 -0
  17. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_truss.cpython-310.pyc +0 -0
  18. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_beam.py +782 -0
  19. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_truss.py +108 -0
  20. venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/truss.py +735 -0
  21. venv/lib/python3.10/site-packages/sympy/physics/control/__init__.py +15 -0
  22. venv/lib/python3.10/site-packages/sympy/physics/control/__pycache__/__init__.cpython-310.pyc +0 -0
  23. venv/lib/python3.10/site-packages/sympy/physics/control/__pycache__/control_plots.cpython-310.pyc +0 -0
  24. venv/lib/python3.10/site-packages/sympy/physics/control/__pycache__/lti.cpython-310.pyc +0 -0
  25. venv/lib/python3.10/site-packages/sympy/physics/control/control_plots.py +961 -0
  26. venv/lib/python3.10/site-packages/sympy/physics/control/lti.py +0 -0
  27. venv/lib/python3.10/site-packages/sympy/physics/control/tests/__init__.py +0 -0
  28. venv/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  29. venv/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_control_plots.cpython-310.pyc +0 -0
  30. venv/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_lti.cpython-310.pyc +0 -0
  31. venv/lib/python3.10/site-packages/sympy/physics/control/tests/test_control_plots.py +300 -0
  32. venv/lib/python3.10/site-packages/sympy/physics/control/tests/test_lti.py +1245 -0
  33. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/__init__.cpython-310.pyc +0 -0
  34. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/body.cpython-310.pyc +0 -0
  35. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/functions.cpython-310.pyc +0 -0
  36. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/joint.cpython-310.pyc +0 -0
  37. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/jointsmethod.cpython-310.pyc +0 -0
  38. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/kane.cpython-310.pyc +0 -0
  39. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/lagrange.cpython-310.pyc +0 -0
  40. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/linearize.cpython-310.pyc +0 -0
  41. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/method.cpython-310.pyc +0 -0
  42. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/models.cpython-310.pyc +0 -0
  43. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/particle.cpython-310.pyc +0 -0
  44. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/rigidbody.cpython-310.pyc +0 -0
  45. venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/system.cpython-310.pyc +0 -0
  46. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange2.cpython-310.pyc +0 -0
  47. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_linearize.cpython-310.pyc +0 -0
  48. venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_models.cpython-310.pyc +0 -0
  49. venv/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/circuitutils.cpython-310.pyc +0 -0
  50. venv/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/matrixutils.cpython-310.pyc +0 -0
ckpts/universal/global_step120/zero/11.mlp.dense_h_to_4h.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07d16433be54a452375dd99d0b20bec743f3f0efe29d5e756db03197319518ed
3
+ size 33555533
ckpts/universal/global_step120/zero/12.attention.query_key_value.weight/fp32.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d0062767ad6350ea8bae409af5fef764a96e09255127c18d2320e73672a910e1
3
+ size 50332749
ckpts/universal/global_step80/mp_rank_00_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:248c3bfb4d9333f29546bd0b9afaa0d6cec817dc341c7cecc8b6daec507db488
3
+ size 4230084
ckpts/universal/global_step80/mp_rank_01_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6338497930be280426064cc7abbbaf23608fce81285136bee6cee9579d29c3c7
3
+ size 4230020
ckpts/universal/global_step80/mp_rank_02_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1ee99d500a1ab28ba1a9c1410096e9446535d2af2e6670616c1f0ef518c3b631
3
+ size 4230020
ckpts/universal/global_step80/mp_rank_03_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5bdcf353c80c6ee0b2f296b4123df1444b6ee988fcc7039676e30366d2ae1a92
3
+ size 4230020
ckpts/universal/global_step80/mp_rank_04_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2d10e30f538d9e1b2fb52e0d99c9e49e70d5d27d63cf8cd50157878fc1bf3eff
3
+ size 4230084
ckpts/universal/global_step80/mp_rank_05_model_states.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c28b496aa07ce8ce02014956f88e30108446d183cd34a4914a1fac4a20546f4b
3
+ size 4230084
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ __all__ = ['Beam',
2
+ 'Truss']
3
+
4
+ from .beam import Beam
5
+ from .truss import Truss
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (302 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc ADDED
Binary file (120 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/truss.cpython-310.pyc ADDED
Binary file (22.6 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/beam.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (207 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_beam.cpython-310.pyc ADDED
Binary file (21.3 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/__pycache__/test_truss.cpython-310.pyc ADDED
Binary file (2.65 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_beam.py ADDED
@@ -0,0 +1,782 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.function import expand
2
+ from sympy.core.numbers import (Rational, pi)
3
+ from sympy.core.singleton import S
4
+ from sympy.core.symbol import (Symbol, symbols)
5
+ from sympy.sets.sets import Interval
6
+ from sympy.simplify.simplify import simplify
7
+ from sympy.physics.continuum_mechanics.beam import Beam
8
+ from sympy.functions import SingularityFunction, Piecewise, meijerg, Abs, log
9
+ from sympy.testing.pytest import raises
10
+ from sympy.physics.units import meter, newton, kilo, giga, milli
11
+ from sympy.physics.continuum_mechanics.beam import Beam3D
12
+ from sympy.geometry import Circle, Polygon, Point2D, Triangle
13
+ from sympy.core.sympify import sympify
14
+
15
+ x = Symbol('x')
16
+ y = Symbol('y')
17
+ R1, R2 = symbols('R1, R2')
18
+
19
+
20
+ def test_Beam():
21
+ E = Symbol('E')
22
+ E_1 = Symbol('E_1')
23
+ I = Symbol('I')
24
+ I_1 = Symbol('I_1')
25
+ A = Symbol('A')
26
+
27
+ b = Beam(1, E, I)
28
+ assert b.length == 1
29
+ assert b.elastic_modulus == E
30
+ assert b.second_moment == I
31
+ assert b.variable == x
32
+
33
+ # Test the length setter
34
+ b.length = 4
35
+ assert b.length == 4
36
+
37
+ # Test the E setter
38
+ b.elastic_modulus = E_1
39
+ assert b.elastic_modulus == E_1
40
+
41
+ # Test the I setter
42
+ b.second_moment = I_1
43
+ assert b.second_moment is I_1
44
+
45
+ # Test the variable setter
46
+ b.variable = y
47
+ assert b.variable is y
48
+
49
+ # Test for all boundary conditions.
50
+ b.bc_deflection = [(0, 2)]
51
+ b.bc_slope = [(0, 1)]
52
+ assert b.boundary_conditions == {'deflection': [(0, 2)], 'slope': [(0, 1)]}
53
+
54
+ # Test for slope boundary condition method
55
+ b.bc_slope.extend([(4, 3), (5, 0)])
56
+ s_bcs = b.bc_slope
57
+ assert s_bcs == [(0, 1), (4, 3), (5, 0)]
58
+
59
+ # Test for deflection boundary condition method
60
+ b.bc_deflection.extend([(4, 3), (5, 0)])
61
+ d_bcs = b.bc_deflection
62
+ assert d_bcs == [(0, 2), (4, 3), (5, 0)]
63
+
64
+ # Test for updated boundary conditions
65
+ bcs_new = b.boundary_conditions
66
+ assert bcs_new == {
67
+ 'deflection': [(0, 2), (4, 3), (5, 0)],
68
+ 'slope': [(0, 1), (4, 3), (5, 0)]}
69
+
70
+ b1 = Beam(30, E, I)
71
+ b1.apply_load(-8, 0, -1)
72
+ b1.apply_load(R1, 10, -1)
73
+ b1.apply_load(R2, 30, -1)
74
+ b1.apply_load(120, 30, -2)
75
+ b1.bc_deflection = [(10, 0), (30, 0)]
76
+ b1.solve_for_reaction_loads(R1, R2)
77
+
78
+ # Test for finding reaction forces
79
+ p = b1.reaction_loads
80
+ q = {R1: 6, R2: 2}
81
+ assert p == q
82
+
83
+ # Test for load distribution function.
84
+ p = b1.load
85
+ q = -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) \
86
+ + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1)
87
+ assert p == q
88
+
89
+ # Test for shear force distribution function
90
+ p = b1.shear_force()
91
+ q = 8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) \
92
+ - 120*SingularityFunction(x, 30, -1) - 2*SingularityFunction(x, 30, 0)
93
+ assert p == q
94
+
95
+ # Test for shear stress distribution function
96
+ p = b1.shear_stress()
97
+ q = (8*SingularityFunction(x, 0, 0) - 6*SingularityFunction(x, 10, 0) \
98
+ - 120*SingularityFunction(x, 30, -1) \
99
+ - 2*SingularityFunction(x, 30, 0))/A
100
+ assert p==q
101
+
102
+ # Test for bending moment distribution function
103
+ p = b1.bending_moment()
104
+ q = 8*SingularityFunction(x, 0, 1) - 6*SingularityFunction(x, 10, 1) \
105
+ - 120*SingularityFunction(x, 30, 0) - 2*SingularityFunction(x, 30, 1)
106
+ assert p == q
107
+
108
+ # Test for slope distribution function
109
+ p = b1.slope()
110
+ q = -4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) \
111
+ + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) \
112
+ + Rational(4000, 3)
113
+ assert p == q/(E*I)
114
+
115
+ # Test for deflection distribution function
116
+ p = b1.deflection()
117
+ q = x*Rational(4000, 3) - 4*SingularityFunction(x, 0, 3)/3 \
118
+ + SingularityFunction(x, 10, 3) + 60*SingularityFunction(x, 30, 2) \
119
+ + SingularityFunction(x, 30, 3)/3 - 12000
120
+ assert p == q/(E*I)
121
+
122
+ # Test using symbols
123
+ l = Symbol('l')
124
+ w0 = Symbol('w0')
125
+ w2 = Symbol('w2')
126
+ a1 = Symbol('a1')
127
+ c = Symbol('c')
128
+ c1 = Symbol('c1')
129
+ d = Symbol('d')
130
+ e = Symbol('e')
131
+ f = Symbol('f')
132
+
133
+ b2 = Beam(l, E, I)
134
+
135
+ b2.apply_load(w0, a1, 1)
136
+ b2.apply_load(w2, c1, -1)
137
+
138
+ b2.bc_deflection = [(c, d)]
139
+ b2.bc_slope = [(e, f)]
140
+
141
+ # Test for load distribution function.
142
+ p = b2.load
143
+ q = w0*SingularityFunction(x, a1, 1) + w2*SingularityFunction(x, c1, -1)
144
+ assert p == q
145
+
146
+ # Test for shear force distribution function
147
+ p = b2.shear_force()
148
+ q = -w0*SingularityFunction(x, a1, 2)/2 \
149
+ - w2*SingularityFunction(x, c1, 0)
150
+ assert p == q
151
+
152
+ # Test for shear stress distribution function
153
+ p = b2.shear_stress()
154
+ q = (-w0*SingularityFunction(x, a1, 2)/2 \
155
+ - w2*SingularityFunction(x, c1, 0))/A
156
+ assert p == q
157
+
158
+ # Test for bending moment distribution function
159
+ p = b2.bending_moment()
160
+ q = -w0*SingularityFunction(x, a1, 3)/6 - w2*SingularityFunction(x, c1, 1)
161
+ assert p == q
162
+
163
+ # Test for slope distribution function
164
+ p = b2.slope()
165
+ q = (w0*SingularityFunction(x, a1, 4)/24 + w2*SingularityFunction(x, c1, 2)/2)/(E*I) + (E*I*f - w0*SingularityFunction(e, a1, 4)/24 - w2*SingularityFunction(e, c1, 2)/2)/(E*I)
166
+ assert expand(p) == expand(q)
167
+
168
+ # Test for deflection distribution function
169
+ p = b2.deflection()
170
+ q = x*(E*I*f - w0*SingularityFunction(e, a1, 4)/24 \
171
+ - w2*SingularityFunction(e, c1, 2)/2)/(E*I) \
172
+ + (w0*SingularityFunction(x, a1, 5)/120 \
173
+ + w2*SingularityFunction(x, c1, 3)/6)/(E*I) \
174
+ + (E*I*(-c*f + d) + c*w0*SingularityFunction(e, a1, 4)/24 \
175
+ + c*w2*SingularityFunction(e, c1, 2)/2 \
176
+ - w0*SingularityFunction(c, a1, 5)/120 \
177
+ - w2*SingularityFunction(c, c1, 3)/6)/(E*I)
178
+ assert simplify(p - q) == 0
179
+
180
+ b3 = Beam(9, E, I, 2)
181
+ b3.apply_load(value=-2, start=2, order=2, end=3)
182
+ b3.bc_slope.append((0, 2))
183
+ C3 = symbols('C3')
184
+ C4 = symbols('C4')
185
+
186
+ p = b3.load
187
+ q = -2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) \
188
+ + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
189
+ assert p == q
190
+
191
+ p = b3.shear_force()
192
+ q = 2*SingularityFunction(x, 2, 3)/3 - 2*SingularityFunction(x, 3, 1) \
193
+ - 2*SingularityFunction(x, 3, 2) - 2*SingularityFunction(x, 3, 3)/3
194
+ assert p == q
195
+
196
+ p = b3.shear_stress()
197
+ q = SingularityFunction(x, 2, 3)/3 - 1*SingularityFunction(x, 3, 1) \
198
+ - 1*SingularityFunction(x, 3, 2) - 1*SingularityFunction(x, 3, 3)/3
199
+ assert p == q
200
+
201
+ p = b3.slope()
202
+ q = 2 - (SingularityFunction(x, 2, 5)/30 - SingularityFunction(x, 3, 3)/3 \
203
+ - SingularityFunction(x, 3, 4)/6 - SingularityFunction(x, 3, 5)/30)/(E*I)
204
+ assert p == q
205
+
206
+ p = b3.deflection()
207
+ q = 2*x - (SingularityFunction(x, 2, 6)/180 \
208
+ - SingularityFunction(x, 3, 4)/12 - SingularityFunction(x, 3, 5)/30 \
209
+ - SingularityFunction(x, 3, 6)/180)/(E*I)
210
+ assert p == q + C4
211
+
212
+ b4 = Beam(4, E, I, 3)
213
+ b4.apply_load(-3, 0, 0, end=3)
214
+
215
+ p = b4.load
216
+ q = -3*SingularityFunction(x, 0, 0) + 3*SingularityFunction(x, 3, 0)
217
+ assert p == q
218
+
219
+ p = b4.shear_force()
220
+ q = 3*SingularityFunction(x, 0, 1) \
221
+ - 3*SingularityFunction(x, 3, 1)
222
+ assert p == q
223
+
224
+ p = b4.shear_stress()
225
+ q = SingularityFunction(x, 0, 1) - SingularityFunction(x, 3, 1)
226
+ assert p == q
227
+
228
+ p = b4.slope()
229
+ q = -3*SingularityFunction(x, 0, 3)/6 + 3*SingularityFunction(x, 3, 3)/6
230
+ assert p == q/(E*I) + C3
231
+
232
+ p = b4.deflection()
233
+ q = -3*SingularityFunction(x, 0, 4)/24 + 3*SingularityFunction(x, 3, 4)/24
234
+ assert p == q/(E*I) + C3*x + C4
235
+
236
+ # can't use end with point loads
237
+ raises(ValueError, lambda: b4.apply_load(-3, 0, -1, end=3))
238
+ with raises(TypeError):
239
+ b4.variable = 1
240
+
241
+
242
+ def test_insufficient_bconditions():
243
+ # Test cases when required number of boundary conditions
244
+ # are not provided to solve the integration constants.
245
+ L = symbols('L', positive=True)
246
+ E, I, P, a3, a4 = symbols('E I P a3 a4')
247
+
248
+ b = Beam(L, E, I, base_char='a')
249
+ b.apply_load(R2, L, -1)
250
+ b.apply_load(R1, 0, -1)
251
+ b.apply_load(-P, L/2, -1)
252
+ b.solve_for_reaction_loads(R1, R2)
253
+
254
+ p = b.slope()
255
+ q = P*SingularityFunction(x, 0, 2)/4 - P*SingularityFunction(x, L/2, 2)/2 + P*SingularityFunction(x, L, 2)/4
256
+ assert p == q/(E*I) + a3
257
+
258
+ p = b.deflection()
259
+ q = P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
260
+ assert p == q/(E*I) + a3*x + a4
261
+
262
+ b.bc_deflection = [(0, 0)]
263
+ p = b.deflection()
264
+ q = a3*x + P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
265
+ assert p == q/(E*I)
266
+
267
+ b.bc_deflection = [(0, 0), (L, 0)]
268
+ p = b.deflection()
269
+ q = -L**2*P*x/16 + P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
270
+ assert p == q/(E*I)
271
+
272
+
273
+ def test_statically_indeterminate():
274
+ E = Symbol('E')
275
+ I = Symbol('I')
276
+ M1, M2 = symbols('M1, M2')
277
+ F = Symbol('F')
278
+ l = Symbol('l', positive=True)
279
+
280
+ b5 = Beam(l, E, I)
281
+ b5.bc_deflection = [(0, 0),(l, 0)]
282
+ b5.bc_slope = [(0, 0),(l, 0)]
283
+
284
+ b5.apply_load(R1, 0, -1)
285
+ b5.apply_load(M1, 0, -2)
286
+ b5.apply_load(R2, l, -1)
287
+ b5.apply_load(M2, l, -2)
288
+ b5.apply_load(-F, l/2, -1)
289
+
290
+ b5.solve_for_reaction_loads(R1, R2, M1, M2)
291
+ p = b5.reaction_loads
292
+ q = {R1: F/2, R2: F/2, M1: -F*l/8, M2: F*l/8}
293
+ assert p == q
294
+
295
+
296
+ def test_beam_units():
297
+ E = Symbol('E')
298
+ I = Symbol('I')
299
+ R1, R2 = symbols('R1, R2')
300
+
301
+ kN = kilo*newton
302
+ gN = giga*newton
303
+
304
+ b = Beam(8*meter, 200*gN/meter**2, 400*1000000*(milli*meter)**4)
305
+ b.apply_load(5*kN, 2*meter, -1)
306
+ b.apply_load(R1, 0*meter, -1)
307
+ b.apply_load(R2, 8*meter, -1)
308
+ b.apply_load(10*kN/meter, 4*meter, 0, end=8*meter)
309
+ b.bc_deflection = [(0*meter, 0*meter), (8*meter, 0*meter)]
310
+ b.solve_for_reaction_loads(R1, R2)
311
+ assert b.reaction_loads == {R1: -13750*newton, R2: -31250*newton}
312
+
313
+ b = Beam(3*meter, E*newton/meter**2, I*meter**4)
314
+ b.apply_load(8*kN, 1*meter, -1)
315
+ b.apply_load(R1, 0*meter, -1)
316
+ b.apply_load(R2, 3*meter, -1)
317
+ b.apply_load(12*kN*meter, 2*meter, -2)
318
+ b.bc_deflection = [(0*meter, 0*meter), (3*meter, 0*meter)]
319
+ b.solve_for_reaction_loads(R1, R2)
320
+ assert b.reaction_loads == {R1: newton*Rational(-28000, 3), R2: newton*Rational(4000, 3)}
321
+ assert b.deflection().subs(x, 1*meter) == 62000*meter/(9*E*I)
322
+
323
+
324
+ def test_variable_moment():
325
+ E = Symbol('E')
326
+ I = Symbol('I')
327
+
328
+ b = Beam(4, E, 2*(4 - x))
329
+ b.apply_load(20, 4, -1)
330
+ R, M = symbols('R, M')
331
+ b.apply_load(R, 0, -1)
332
+ b.apply_load(M, 0, -2)
333
+ b.bc_deflection = [(0, 0)]
334
+ b.bc_slope = [(0, 0)]
335
+ b.solve_for_reaction_loads(R, M)
336
+ assert b.slope().expand() == ((10*x*SingularityFunction(x, 0, 0)
337
+ - 10*(x - 4)*SingularityFunction(x, 4, 0))/E).expand()
338
+ assert b.deflection().expand() == ((5*x**2*SingularityFunction(x, 0, 0)
339
+ - 10*Piecewise((0, Abs(x)/4 < 1), (16*meijerg(((3, 1), ()), ((), (2, 0)), x/4), True))
340
+ + 40*SingularityFunction(x, 4, 1))/E).expand()
341
+
342
+ b = Beam(4, E - x, I)
343
+ b.apply_load(20, 4, -1)
344
+ R, M = symbols('R, M')
345
+ b.apply_load(R, 0, -1)
346
+ b.apply_load(M, 0, -2)
347
+ b.bc_deflection = [(0, 0)]
348
+ b.bc_slope = [(0, 0)]
349
+ b.solve_for_reaction_loads(R, M)
350
+ assert b.slope().expand() == ((-80*(-log(-E) + log(-E + x))*SingularityFunction(x, 0, 0)
351
+ + 80*(-log(-E + 4) + log(-E + x))*SingularityFunction(x, 4, 0) + 20*(-E*log(-E)
352
+ + E*log(-E + x) + x)*SingularityFunction(x, 0, 0) - 20*(-E*log(-E + 4) + E*log(-E + x)
353
+ + x - 4)*SingularityFunction(x, 4, 0))/I).expand()
354
+
355
+
356
+ def test_composite_beam():
357
+ E = Symbol('E')
358
+ I = Symbol('I')
359
+ b1 = Beam(2, E, 1.5*I)
360
+ b2 = Beam(2, E, I)
361
+ b = b1.join(b2, "fixed")
362
+ b.apply_load(-20, 0, -1)
363
+ b.apply_load(80, 0, -2)
364
+ b.apply_load(20, 4, -1)
365
+ b.bc_slope = [(0, 0)]
366
+ b.bc_deflection = [(0, 0)]
367
+ assert b.length == 4
368
+ assert b.second_moment == Piecewise((1.5*I, x <= 2), (I, x <= 4))
369
+ assert b.slope().subs(x, 4) == 120.0/(E*I)
370
+ assert b.slope().subs(x, 2) == 80.0/(E*I)
371
+ assert int(b.deflection().subs(x, 4).args[0]) == -302 # Coefficient of 1/(E*I)
372
+
373
+ l = symbols('l', positive=True)
374
+ R1, M1, R2, R3, P = symbols('R1 M1 R2 R3 P')
375
+ b1 = Beam(2*l, E, I)
376
+ b2 = Beam(2*l, E, I)
377
+ b = b1.join(b2,"hinge")
378
+ b.apply_load(M1, 0, -2)
379
+ b.apply_load(R1, 0, -1)
380
+ b.apply_load(R2, l, -1)
381
+ b.apply_load(R3, 4*l, -1)
382
+ b.apply_load(P, 3*l, -1)
383
+ b.bc_slope = [(0, 0)]
384
+ b.bc_deflection = [(0, 0), (l, 0), (4*l, 0)]
385
+ b.solve_for_reaction_loads(M1, R1, R2, R3)
386
+ assert b.reaction_loads == {R3: -P/2, R2: P*Rational(-5, 4), M1: -P*l/4, R1: P*Rational(3, 4)}
387
+ assert b.slope().subs(x, 3*l) == -7*P*l**2/(48*E*I)
388
+ assert b.deflection().subs(x, 2*l) == 7*P*l**3/(24*E*I)
389
+ assert b.deflection().subs(x, 3*l) == 5*P*l**3/(16*E*I)
390
+
391
+ # When beams having same second moment are joined.
392
+ b1 = Beam(2, 500, 10)
393
+ b2 = Beam(2, 500, 10)
394
+ b = b1.join(b2, "fixed")
395
+ b.apply_load(M1, 0, -2)
396
+ b.apply_load(R1, 0, -1)
397
+ b.apply_load(R2, 1, -1)
398
+ b.apply_load(R3, 4, -1)
399
+ b.apply_load(10, 3, -1)
400
+ b.bc_slope = [(0, 0)]
401
+ b.bc_deflection = [(0, 0), (1, 0), (4, 0)]
402
+ b.solve_for_reaction_loads(M1, R1, R2, R3)
403
+ assert b.slope() == -2*SingularityFunction(x, 0, 1)/5625 + SingularityFunction(x, 0, 2)/1875\
404
+ - 133*SingularityFunction(x, 1, 2)/135000 + SingularityFunction(x, 3, 2)/1000\
405
+ - 37*SingularityFunction(x, 4, 2)/67500
406
+ assert b.deflection() == -SingularityFunction(x, 0, 2)/5625 + SingularityFunction(x, 0, 3)/5625\
407
+ - 133*SingularityFunction(x, 1, 3)/405000 + SingularityFunction(x, 3, 3)/3000\
408
+ - 37*SingularityFunction(x, 4, 3)/202500
409
+
410
+
411
+ def test_point_cflexure():
412
+ E = Symbol('E')
413
+ I = Symbol('I')
414
+ b = Beam(10, E, I)
415
+ b.apply_load(-4, 0, -1)
416
+ b.apply_load(-46, 6, -1)
417
+ b.apply_load(10, 2, -1)
418
+ b.apply_load(20, 4, -1)
419
+ b.apply_load(3, 6, 0)
420
+ assert b.point_cflexure() == [Rational(10, 3)]
421
+
422
+
423
+ def test_remove_load():
424
+ E = Symbol('E')
425
+ I = Symbol('I')
426
+ b = Beam(4, E, I)
427
+
428
+ try:
429
+ b.remove_load(2, 1, -1)
430
+ # As no load is applied on beam, ValueError should be returned.
431
+ except ValueError:
432
+ assert True
433
+ else:
434
+ assert False
435
+
436
+ b.apply_load(-3, 0, -2)
437
+ b.apply_load(4, 2, -1)
438
+ b.apply_load(-2, 2, 2, end = 3)
439
+ b.remove_load(-2, 2, 2, end = 3)
440
+ assert b.load == -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1)
441
+ assert b.applied_loads == [(-3, 0, -2, None), (4, 2, -1, None)]
442
+
443
+ try:
444
+ b.remove_load(1, 2, -1)
445
+ # As load of this magnitude was never applied at
446
+ # this position, method should return a ValueError.
447
+ except ValueError:
448
+ assert True
449
+ else:
450
+ assert False
451
+
452
+ b.remove_load(-3, 0, -2)
453
+ b.remove_load(4, 2, -1)
454
+ assert b.load == 0
455
+ assert b.applied_loads == []
456
+
457
+
458
+ def test_apply_support():
459
+ E = Symbol('E')
460
+ I = Symbol('I')
461
+
462
+ b = Beam(4, E, I)
463
+ b.apply_support(0, "cantilever")
464
+ b.apply_load(20, 4, -1)
465
+ M_0, R_0 = symbols('M_0, R_0')
466
+ b.solve_for_reaction_loads(R_0, M_0)
467
+ assert simplify(b.slope()) == simplify((80*SingularityFunction(x, 0, 1) - 10*SingularityFunction(x, 0, 2)
468
+ + 10*SingularityFunction(x, 4, 2))/(E*I))
469
+ assert simplify(b.deflection()) == simplify((40*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 0, 3)/3
470
+ + 10*SingularityFunction(x, 4, 3)/3)/(E*I))
471
+
472
+ b = Beam(30, E, I)
473
+ b.apply_support(10, "pin")
474
+ b.apply_support(30, "roller")
475
+ b.apply_load(-8, 0, -1)
476
+ b.apply_load(120, 30, -2)
477
+ R_10, R_30 = symbols('R_10, R_30')
478
+ b.solve_for_reaction_loads(R_10, R_30)
479
+ assert b.slope() == (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2)
480
+ + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + Rational(4000, 3))/(E*I)
481
+ assert b.deflection() == (x*Rational(4000, 3) - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3)
482
+ + 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I)
483
+
484
+ P = Symbol('P', positive=True)
485
+ L = Symbol('L', positive=True)
486
+ b = Beam(L, E, I)
487
+ b.apply_support(0, type='fixed')
488
+ b.apply_support(L, type='fixed')
489
+ b.apply_load(-P, L/2, -1)
490
+ R_0, R_L, M_0, M_L = symbols('R_0, R_L, M_0, M_L')
491
+ b.solve_for_reaction_loads(R_0, R_L, M_0, M_L)
492
+ assert b.reaction_loads == {R_0: P/2, R_L: P/2, M_0: -L*P/8, M_L: L*P/8}
493
+
494
+
495
+ def test_max_shear_force():
496
+ E = Symbol('E')
497
+ I = Symbol('I')
498
+
499
+ b = Beam(3, E, I)
500
+ R, M = symbols('R, M')
501
+ b.apply_load(R, 0, -1)
502
+ b.apply_load(M, 0, -2)
503
+ b.apply_load(2, 3, -1)
504
+ b.apply_load(4, 2, -1)
505
+ b.apply_load(2, 2, 0, end=3)
506
+ b.solve_for_reaction_loads(R, M)
507
+ assert b.max_shear_force() == (Interval(0, 2), 8)
508
+
509
+ l = symbols('l', positive=True)
510
+ P = Symbol('P')
511
+ b = Beam(l, E, I)
512
+ R1, R2 = symbols('R1, R2')
513
+ b.apply_load(R1, 0, -1)
514
+ b.apply_load(R2, l, -1)
515
+ b.apply_load(P, 0, 0, end=l)
516
+ b.solve_for_reaction_loads(R1, R2)
517
+ assert b.max_shear_force() == (0, l*Abs(P)/2)
518
+
519
+
520
+ def test_max_bmoment():
521
+ E = Symbol('E')
522
+ I = Symbol('I')
523
+ l, P = symbols('l, P', positive=True)
524
+
525
+ b = Beam(l, E, I)
526
+ R1, R2 = symbols('R1, R2')
527
+ b.apply_load(R1, 0, -1)
528
+ b.apply_load(R2, l, -1)
529
+ b.apply_load(P, l/2, -1)
530
+ b.solve_for_reaction_loads(R1, R2)
531
+ b.reaction_loads
532
+ assert b.max_bmoment() == (l/2, P*l/4)
533
+
534
+ b = Beam(l, E, I)
535
+ R1, R2 = symbols('R1, R2')
536
+ b.apply_load(R1, 0, -1)
537
+ b.apply_load(R2, l, -1)
538
+ b.apply_load(P, 0, 0, end=l)
539
+ b.solve_for_reaction_loads(R1, R2)
540
+ assert b.max_bmoment() == (l/2, P*l**2/8)
541
+
542
+
543
+ def test_max_deflection():
544
+ E, I, l, F = symbols('E, I, l, F', positive=True)
545
+ b = Beam(l, E, I)
546
+ b.bc_deflection = [(0, 0),(l, 0)]
547
+ b.bc_slope = [(0, 0),(l, 0)]
548
+ b.apply_load(F/2, 0, -1)
549
+ b.apply_load(-F*l/8, 0, -2)
550
+ b.apply_load(F/2, l, -1)
551
+ b.apply_load(F*l/8, l, -2)
552
+ b.apply_load(-F, l/2, -1)
553
+ assert b.max_deflection() == (l/2, F*l**3/(192*E*I))
554
+
555
+
556
+ def test_Beam3D():
557
+ l, E, G, I, A = symbols('l, E, G, I, A')
558
+ R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
559
+
560
+ b = Beam3D(l, E, G, I, A)
561
+ m, q = symbols('m, q')
562
+ b.apply_load(q, 0, 0, dir="y")
563
+ b.apply_moment_load(m, 0, 0, dir="z")
564
+ b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])]
565
+ b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])]
566
+ b.solve_slope_deflection()
567
+
568
+ assert b.polar_moment() == 2*I
569
+ assert b.shear_force() == [0, -q*x, 0]
570
+ assert b.shear_stress() == [0, -q*x/A, 0]
571
+ assert b.axial_stress() == 0
572
+ assert b.bending_moment() == [0, 0, -m*x + q*x**2/2]
573
+ expected_deflection = (x*(A*G*q*x**3/4 + A*G*x**2*(-l*(A*G*l*(l*q - 2*m) +
574
+ 12*E*I*q)/(A*G*l**2 + 12*E*I)/2 - m) + 3*E*I*l*(A*G*l*(l*q - 2*m) +
575
+ 12*E*I*q)/(A*G*l**2 + 12*E*I) + x*(-A*G*l**2*q/2 +
576
+ 3*A*G*l**2*(A*G*l*(l*q - 2*m) + 12*E*I*q)/(A*G*l**2 + 12*E*I)/4 +
577
+ A*G*l*m*Rational(3, 2) - 3*E*I*q))/(6*A*E*G*I))
578
+ dx, dy, dz = b.deflection()
579
+ assert dx == dz == 0
580
+ assert simplify(dy - expected_deflection) == 0
581
+
582
+ b2 = Beam3D(30, E, G, I, A, x)
583
+ b2.apply_load(50, start=0, order=0, dir="y")
584
+ b2.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])]
585
+ b2.apply_load(R1, start=0, order=-1, dir="y")
586
+ b2.apply_load(R2, start=30, order=-1, dir="y")
587
+ b2.solve_for_reaction_loads(R1, R2)
588
+ assert b2.reaction_loads == {R1: -750, R2: -750}
589
+
590
+ b2.solve_slope_deflection()
591
+ assert b2.slope() == [0, 0, 25*x**3/(3*E*I) - 375*x**2/(E*I) + 3750*x/(E*I)]
592
+ expected_deflection = 25*x**4/(12*E*I) - 125*x**3/(E*I) + 1875*x**2/(E*I) - \
593
+ 25*x**2/(A*G) + 750*x/(A*G)
594
+ dx, dy, dz = b2.deflection()
595
+ assert dx == dz == 0
596
+ assert dy == expected_deflection
597
+
598
+ # Test for solve_for_reaction_loads
599
+ b3 = Beam3D(30, E, G, I, A, x)
600
+ b3.apply_load(8, start=0, order=0, dir="y")
601
+ b3.apply_load(9*x, start=0, order=0, dir="z")
602
+ b3.apply_load(R1, start=0, order=-1, dir="y")
603
+ b3.apply_load(R2, start=30, order=-1, dir="y")
604
+ b3.apply_load(R3, start=0, order=-1, dir="z")
605
+ b3.apply_load(R4, start=30, order=-1, dir="z")
606
+ b3.solve_for_reaction_loads(R1, R2, R3, R4)
607
+ assert b3.reaction_loads == {R1: -120, R2: -120, R3: -1350, R4: -2700}
608
+
609
+
610
+ def test_polar_moment_Beam3D():
611
+ l, E, G, A, I1, I2 = symbols('l, E, G, A, I1, I2')
612
+ I = [I1, I2]
613
+
614
+ b = Beam3D(l, E, G, I, A)
615
+ assert b.polar_moment() == I1 + I2
616
+
617
+
618
+ def test_parabolic_loads():
619
+
620
+ E, I, L = symbols('E, I, L', positive=True, real=True)
621
+ R, M, P = symbols('R, M, P', real=True)
622
+
623
+ # cantilever beam fixed at x=0 and parabolic distributed loading across
624
+ # length of beam
625
+ beam = Beam(L, E, I)
626
+
627
+ beam.bc_deflection.append((0, 0))
628
+ beam.bc_slope.append((0, 0))
629
+ beam.apply_load(R, 0, -1)
630
+ beam.apply_load(M, 0, -2)
631
+
632
+ # parabolic load
633
+ beam.apply_load(1, 0, 2)
634
+
635
+ beam.solve_for_reaction_loads(R, M)
636
+
637
+ assert beam.reaction_loads[R] == -L**3/3
638
+
639
+ # cantilever beam fixed at x=0 and parabolic distributed loading across
640
+ # first half of beam
641
+ beam = Beam(2*L, E, I)
642
+
643
+ beam.bc_deflection.append((0, 0))
644
+ beam.bc_slope.append((0, 0))
645
+ beam.apply_load(R, 0, -1)
646
+ beam.apply_load(M, 0, -2)
647
+
648
+ # parabolic load from x=0 to x=L
649
+ beam.apply_load(1, 0, 2, end=L)
650
+
651
+ beam.solve_for_reaction_loads(R, M)
652
+
653
+ # result should be the same as the prior example
654
+ assert beam.reaction_loads[R] == -L**3/3
655
+
656
+ # check constant load
657
+ beam = Beam(2*L, E, I)
658
+ beam.apply_load(P, 0, 0, end=L)
659
+ loading = beam.load.xreplace({L: 10, E: 20, I: 30, P: 40})
660
+ assert loading.xreplace({x: 5}) == 40
661
+ assert loading.xreplace({x: 15}) == 0
662
+
663
+ # check ramp load
664
+ beam = Beam(2*L, E, I)
665
+ beam.apply_load(P, 0, 1, end=L)
666
+ assert beam.load == (P*SingularityFunction(x, 0, 1) -
667
+ P*SingularityFunction(x, L, 1) -
668
+ P*L*SingularityFunction(x, L, 0))
669
+
670
+ # check higher order load: x**8 load from x=0 to x=L
671
+ beam = Beam(2*L, E, I)
672
+ beam.apply_load(P, 0, 8, end=L)
673
+ loading = beam.load.xreplace({L: 10, E: 20, I: 30, P: 40})
674
+ assert loading.xreplace({x: 5}) == 40*5**8
675
+ assert loading.xreplace({x: 15}) == 0
676
+
677
+
678
+ def test_cross_section():
679
+ I = Symbol('I')
680
+ l = Symbol('l')
681
+ E = Symbol('E')
682
+ C3, C4 = symbols('C3, C4')
683
+ a, c, g, h, r, n = symbols('a, c, g, h, r, n')
684
+
685
+ # test for second_moment and cross_section setter
686
+ b0 = Beam(l, E, I)
687
+ assert b0.second_moment == I
688
+ assert b0.cross_section == None
689
+ b0.cross_section = Circle((0, 0), 5)
690
+ assert b0.second_moment == pi*Rational(625, 4)
691
+ assert b0.cross_section == Circle((0, 0), 5)
692
+ b0.second_moment = 2*n - 6
693
+ assert b0.second_moment == 2*n-6
694
+ assert b0.cross_section == None
695
+ with raises(ValueError):
696
+ b0.second_moment = Circle((0, 0), 5)
697
+
698
+ # beam with a circular cross-section
699
+ b1 = Beam(50, E, Circle((0, 0), r))
700
+ assert b1.cross_section == Circle((0, 0), r)
701
+ assert b1.second_moment == pi*r*Abs(r)**3/4
702
+
703
+ b1.apply_load(-10, 0, -1)
704
+ b1.apply_load(R1, 5, -1)
705
+ b1.apply_load(R2, 50, -1)
706
+ b1.apply_load(90, 45, -2)
707
+ b1.solve_for_reaction_loads(R1, R2)
708
+ assert b1.load == (-10*SingularityFunction(x, 0, -1) + 82*SingularityFunction(x, 5, -1)/S(9)
709
+ + 90*SingularityFunction(x, 45, -2) + 8*SingularityFunction(x, 50, -1)/9)
710
+ assert b1.bending_moment() == (10*SingularityFunction(x, 0, 1) - 82*SingularityFunction(x, 5, 1)/9
711
+ - 90*SingularityFunction(x, 45, 0) - 8*SingularityFunction(x, 50, 1)/9)
712
+ q = (-5*SingularityFunction(x, 0, 2) + 41*SingularityFunction(x, 5, 2)/S(9)
713
+ + 90*SingularityFunction(x, 45, 1) + 4*SingularityFunction(x, 50, 2)/S(9))/(pi*E*r*Abs(r)**3)
714
+ assert b1.slope() == C3 + 4*q
715
+ q = (-5*SingularityFunction(x, 0, 3)/3 + 41*SingularityFunction(x, 5, 3)/27 + 45*SingularityFunction(x, 45, 2)
716
+ + 4*SingularityFunction(x, 50, 3)/27)/(pi*E*r*Abs(r)**3)
717
+ assert b1.deflection() == C3*x + C4 + 4*q
718
+
719
+ # beam with a recatangular cross-section
720
+ b2 = Beam(20, E, Polygon((0, 0), (a, 0), (a, c), (0, c)))
721
+ assert b2.cross_section == Polygon((0, 0), (a, 0), (a, c), (0, c))
722
+ assert b2.second_moment == a*c**3/12
723
+ # beam with a triangular cross-section
724
+ b3 = Beam(15, E, Triangle((0, 0), (g, 0), (g/2, h)))
725
+ assert b3.cross_section == Triangle(Point2D(0, 0), Point2D(g, 0), Point2D(g/2, h))
726
+ assert b3.second_moment == g*h**3/36
727
+
728
+ # composite beam
729
+ b = b2.join(b3, "fixed")
730
+ b.apply_load(-30, 0, -1)
731
+ b.apply_load(65, 0, -2)
732
+ b.apply_load(40, 0, -1)
733
+ b.bc_slope = [(0, 0)]
734
+ b.bc_deflection = [(0, 0)]
735
+
736
+ assert b.second_moment == Piecewise((a*c**3/12, x <= 20), (g*h**3/36, x <= 35))
737
+ assert b.cross_section == None
738
+ assert b.length == 35
739
+ assert b.slope().subs(x, 7) == 8400/(E*a*c**3)
740
+ assert b.slope().subs(x, 25) == 52200/(E*g*h**3) + 39600/(E*a*c**3)
741
+ assert b.deflection().subs(x, 30) == -537000/(E*g*h**3) - 712000/(E*a*c**3)
742
+
743
+ def test_max_shear_force_Beam3D():
744
+ x = symbols('x')
745
+ b = Beam3D(20, 40, 21, 100, 25)
746
+ b.apply_load(15, start=0, order=0, dir="z")
747
+ b.apply_load(12*x, start=0, order=0, dir="y")
748
+ b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
749
+ assert b.max_shear_force() == [(0, 0), (20, 2400), (20, 300)]
750
+
751
+ def test_max_bending_moment_Beam3D():
752
+ x = symbols('x')
753
+ b = Beam3D(20, 40, 21, 100, 25)
754
+ b.apply_load(15, start=0, order=0, dir="z")
755
+ b.apply_load(12*x, start=0, order=0, dir="y")
756
+ b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
757
+ assert b.max_bmoment() == [(0, 0), (20, 3000), (20, 16000)]
758
+
759
+ def test_max_deflection_Beam3D():
760
+ x = symbols('x')
761
+ b = Beam3D(20, 40, 21, 100, 25)
762
+ b.apply_load(15, start=0, order=0, dir="z")
763
+ b.apply_load(12*x, start=0, order=0, dir="y")
764
+ b.bc_deflection = [(0, [0, 0, 0]), (20, [0, 0, 0])]
765
+ b.solve_slope_deflection()
766
+ c = sympify("495/14")
767
+ p = sympify("-10 + 10*sqrt(10793)/43")
768
+ q = sympify("(10 - 10*sqrt(10793)/43)**3/160 - 20/7 + (10 - 10*sqrt(10793)/43)**4/6400 + 20*sqrt(10793)/301 + 27*(10 - 10*sqrt(10793)/43)**2/560")
769
+ assert b.max_deflection() == [(0, 0), (10, c), (p, q)]
770
+
771
+ def test_torsion_Beam3D():
772
+ x = symbols('x')
773
+ b = Beam3D(20, 40, 21, 100, 25)
774
+ b.apply_moment_load(15, 5, -2, dir='x')
775
+ b.apply_moment_load(25, 10, -2, dir='x')
776
+ b.apply_moment_load(-5, 20, -2, dir='x')
777
+ b.solve_for_torsion()
778
+ assert b.angular_deflection().subs(x, 3) == sympify("1/40")
779
+ assert b.angular_deflection().subs(x, 9) == sympify("17/280")
780
+ assert b.angular_deflection().subs(x, 12) == sympify("53/840")
781
+ assert b.angular_deflection().subs(x, 17) == sympify("2/35")
782
+ assert b.angular_deflection().subs(x, 20) == sympify("3/56")
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/tests/test_truss.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.symbol import Symbol, symbols
2
+ from sympy.physics.continuum_mechanics.truss import Truss
3
+ from sympy import sqrt
4
+
5
+
6
+ def test_truss():
7
+ A = Symbol('A')
8
+ B = Symbol('B')
9
+ C = Symbol('C')
10
+ AB, BC, AC = symbols('AB, BC, AC')
11
+ P = Symbol('P')
12
+
13
+ t = Truss()
14
+ assert t.nodes == []
15
+ assert t.node_labels == []
16
+ assert t.node_positions == []
17
+ assert t.members == {}
18
+ assert t.loads == {}
19
+ assert t.supports == {}
20
+ assert t.reaction_loads == {}
21
+ assert t.internal_forces == {}
22
+
23
+ # testing the add_node method
24
+ t.add_node(A, 0, 0)
25
+ t.add_node(B, 2, 2)
26
+ t.add_node(C, 3, 0)
27
+ assert t.nodes == [(A, 0, 0), (B, 2, 2), (C, 3, 0)]
28
+ assert t.node_labels == [A, B, C]
29
+ assert t.node_positions == [(0, 0), (2, 2), (3, 0)]
30
+ assert t.loads == {}
31
+ assert t.supports == {}
32
+ assert t.reaction_loads == {}
33
+
34
+ # testing the remove_node method
35
+ t.remove_node(C)
36
+ assert t.nodes == [(A, 0, 0), (B, 2, 2)]
37
+ assert t.node_labels == [A, B]
38
+ assert t.node_positions == [(0, 0), (2, 2)]
39
+ assert t.loads == {}
40
+ assert t.supports == {}
41
+
42
+ t.add_node(C, 3, 0)
43
+
44
+ # testing the add_member method
45
+ t.add_member(AB, A, B)
46
+ t.add_member(BC, B, C)
47
+ t.add_member(AC, A, C)
48
+ assert t.members == {AB: [A, B], BC: [B, C], AC: [A, C]}
49
+ assert t.internal_forces == {AB: 0, BC: 0, AC: 0}
50
+
51
+ # testing the remove_member method
52
+ t.remove_member(BC)
53
+ assert t.members == {AB: [A, B], AC: [A, C]}
54
+ assert t.internal_forces == {AB: 0, AC: 0}
55
+
56
+ t.add_member(BC, B, C)
57
+
58
+ D, CD = symbols('D, CD')
59
+
60
+ # testing the change_label methods
61
+ t.change_node_label(B, D)
62
+ assert t.nodes == [(A, 0, 0), (D, 2, 2), (C, 3, 0)]
63
+ assert t.node_labels == [A, D, C]
64
+ assert t.loads == {}
65
+ assert t.supports == {}
66
+ assert t.members == {AB: [A, D], BC: [D, C], AC: [A, C]}
67
+
68
+ t.change_member_label(BC, CD)
69
+ assert t.members == {AB: [A, D], CD: [D, C], AC: [A, C]}
70
+ assert t.internal_forces == {AB: 0, CD: 0, AC: 0}
71
+
72
+
73
+ # testing the apply_load method
74
+ t.apply_load(A, P, 90)
75
+ t.apply_load(A, P/4, 90)
76
+ t.apply_load(A, 2*P,45)
77
+ t.apply_load(D, P/2, 90)
78
+ assert t.loads == {A: [[P, 90], [P/4, 90], [2*P, 45]], D: [[P/2, 90]]}
79
+ assert t.loads[A] == [[P, 90], [P/4, 90], [2*P, 45]]
80
+
81
+ # testing the remove_load method
82
+ t.remove_load(A, P/4, 90)
83
+ assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90]]}
84
+ assert t.loads[A] == [[P, 90], [2*P, 45]]
85
+
86
+ # testing the apply_support method
87
+ t.apply_support(A, "pinned")
88
+ t.apply_support(D, "roller")
89
+ assert t.supports == {A: 'pinned', D: 'roller'}
90
+ assert t.reaction_loads == {}
91
+ assert t.loads == {A: [[P, 90], [2*P, 45], [Symbol('R_A_x'), 0], [Symbol('R_A_y'), 90]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]}
92
+
93
+ # testing the remove_support method
94
+ t.remove_support(A)
95
+ assert t.supports == {D: 'roller'}
96
+ assert t.reaction_loads == {}
97
+ assert t.loads == {A: [[P, 90], [2*P, 45]], D: [[P/2, 90], [Symbol('R_D_y'), 90]]}
98
+
99
+ t.apply_support(A, "pinned")
100
+
101
+ # testing the solve method
102
+ t.solve()
103
+ assert t.reaction_loads['R_A_x'] == -sqrt(2)*P
104
+ assert t.reaction_loads['R_A_y'] == -sqrt(2)*P - P
105
+ assert t.reaction_loads['R_D_y'] == -P/2
106
+ assert t.internal_forces[AB]/P == 0
107
+ assert t.internal_forces[CD] == 0
108
+ assert t.internal_forces[AC] == 0
venv/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/truss.py ADDED
@@ -0,0 +1,735 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module can be used to solve problems related
3
+ to 2D Trusses.
4
+ """
5
+
6
+ from cmath import inf
7
+ from sympy.core.add import Add
8
+ from sympy.core.mul import Mul
9
+ from sympy.core.symbol import Symbol
10
+ from sympy.core.sympify import sympify
11
+ from sympy import Matrix, pi
12
+ from sympy.functions.elementary.miscellaneous import sqrt
13
+ from sympy.matrices.dense import zeros
14
+ from sympy import sin, cos
15
+
16
+
17
+
18
+ class Truss:
19
+ """
20
+ A Truss is an assembly of members such as beams,
21
+ connected by nodes, that create a rigid structure.
22
+ In engineering, a truss is a structure that
23
+ consists of two-force members only.
24
+
25
+ Trusses are extremely important in engineering applications
26
+ and can be seen in numerous real-world applications like bridges.
27
+
28
+ Examples
29
+ ========
30
+
31
+ There is a Truss consisting of four nodes and five
32
+ members connecting the nodes. A force P acts
33
+ downward on the node D and there also exist pinned
34
+ and roller joints on the nodes A and B respectively.
35
+
36
+ .. image:: truss_example.png
37
+
38
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
39
+ >>> t = Truss()
40
+ >>> t.add_node("node_1", 0, 0)
41
+ >>> t.add_node("node_2", 6, 0)
42
+ >>> t.add_node("node_3", 2, 2)
43
+ >>> t.add_node("node_4", 2, 0)
44
+ >>> t.add_member("member_1", "node_1", "node_4")
45
+ >>> t.add_member("member_2", "node_2", "node_4")
46
+ >>> t.add_member("member_3", "node_1", "node_3")
47
+ >>> t.add_member("member_4", "node_2", "node_3")
48
+ >>> t.add_member("member_5", "node_3", "node_4")
49
+ >>> t.apply_load("node_4", magnitude=10, direction=270)
50
+ >>> t.apply_support("node_1", type="fixed")
51
+ >>> t.apply_support("node_2", type="roller")
52
+ """
53
+
54
+ def __init__(self):
55
+ """
56
+ Initializes the class
57
+ """
58
+ self._nodes = []
59
+ self._members = {}
60
+ self._loads = {}
61
+ self._supports = {}
62
+ self._node_labels = []
63
+ self._node_positions = []
64
+ self._node_position_x = []
65
+ self._node_position_y = []
66
+ self._nodes_occupied = {}
67
+ self._reaction_loads = {}
68
+ self._internal_forces = {}
69
+ self._node_coordinates = {}
70
+
71
+ @property
72
+ def nodes(self):
73
+ """
74
+ Returns the nodes of the truss along with their positions.
75
+ """
76
+ return self._nodes
77
+
78
+ @property
79
+ def node_labels(self):
80
+ """
81
+ Returns the node labels of the truss.
82
+ """
83
+ return self._node_labels
84
+
85
+ @property
86
+ def node_positions(self):
87
+ """
88
+ Returns the positions of the nodes of the truss.
89
+ """
90
+ return self._node_positions
91
+
92
+ @property
93
+ def members(self):
94
+ """
95
+ Returns the members of the truss along with the start and end points.
96
+ """
97
+ return self._members
98
+
99
+ @property
100
+ def member_labels(self):
101
+ """
102
+ Returns the members of the truss along with the start and end points.
103
+ """
104
+ return self._member_labels
105
+
106
+ @property
107
+ def supports(self):
108
+ """
109
+ Returns the nodes with provided supports along with the kind of support provided i.e.
110
+ pinned or roller.
111
+ """
112
+ return self._supports
113
+
114
+ @property
115
+ def loads(self):
116
+ """
117
+ Returns the loads acting on the truss.
118
+ """
119
+ return self._loads
120
+
121
+ @property
122
+ def reaction_loads(self):
123
+ """
124
+ Returns the reaction forces for all supports which are all initialized to 0.
125
+ """
126
+ return self._reaction_loads
127
+
128
+ @property
129
+ def internal_forces(self):
130
+ """
131
+ Returns the internal forces for all members which are all initialized to 0.
132
+ """
133
+ return self._internal_forces
134
+
135
+ def add_node(self, label, x, y):
136
+ """
137
+ This method adds a node to the truss along with its name/label and its location.
138
+
139
+ Parameters
140
+ ==========
141
+ label: String or a Symbol
142
+ The label for a node. It is the only way to identify a particular node.
143
+
144
+ x: Sympifyable
145
+ The x-coordinate of the position of the node.
146
+
147
+ y: Sympifyable
148
+ The y-coordinate of the position of the node.
149
+
150
+ Examples
151
+ ========
152
+
153
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
154
+ >>> t = Truss()
155
+ >>> t.add_node('A', 0, 0)
156
+ >>> t.nodes
157
+ [('A', 0, 0)]
158
+ >>> t.add_node('B', 3, 0)
159
+ >>> t.nodes
160
+ [('A', 0, 0), ('B', 3, 0)]
161
+ """
162
+ x = sympify(x)
163
+ y = sympify(y)
164
+
165
+ if label in self._node_labels:
166
+ raise ValueError("Node needs to have a unique label")
167
+
168
+ elif x in self._node_position_x and y in self._node_position_y and self._node_position_x.index(x)==self._node_position_y.index(y):
169
+ raise ValueError("A node already exists at the given position")
170
+
171
+ else :
172
+ self._nodes.append((label, x, y))
173
+ self._node_labels.append(label)
174
+ self._node_positions.append((x, y))
175
+ self._node_position_x.append(x)
176
+ self._node_position_y.append(y)
177
+ self._node_coordinates[label] = [x, y]
178
+
179
+ def remove_node(self, label):
180
+ """
181
+ This method removes a node from the truss.
182
+
183
+ Parameters
184
+ ==========
185
+ label: String or Symbol
186
+ The label of the node to be removed.
187
+
188
+ Examples
189
+ ========
190
+
191
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
192
+ >>> t = Truss()
193
+ >>> t.add_node('A', 0, 0)
194
+ >>> t.nodes
195
+ [('A', 0, 0)]
196
+ >>> t.add_node('B', 3, 0)
197
+ >>> t.nodes
198
+ [('A', 0, 0), ('B', 3, 0)]
199
+ >>> t.remove_node('A')
200
+ >>> t.nodes
201
+ [('B', 3, 0)]
202
+ """
203
+ for i in range(len(self.nodes)):
204
+ if self._node_labels[i] == label:
205
+ x = self._node_position_x[i]
206
+ y = self._node_position_y[i]
207
+
208
+ if label not in self._node_labels:
209
+ raise ValueError("No such node exists in the truss")
210
+
211
+ else:
212
+ members_duplicate = self._members.copy()
213
+ for member in members_duplicate:
214
+ if label == self._members[member][0] or label == self._members[member][1]:
215
+ raise ValueError("The node given has members already attached to it")
216
+ self._nodes.remove((label, x, y))
217
+ self._node_labels.remove(label)
218
+ self._node_positions.remove((x, y))
219
+ self._node_position_x.remove(x)
220
+ self._node_position_y.remove(y)
221
+ if label in list(self._loads):
222
+ self._loads.pop(label)
223
+ if label in list(self._supports):
224
+ self._supports.pop(label)
225
+ self._node_coordinates.pop(label)
226
+
227
+ def add_member(self, label, start, end):
228
+ """
229
+ This method adds a member between any two nodes in the given truss.
230
+
231
+ Parameters
232
+ ==========
233
+ label: String or Symbol
234
+ The label for a member. It is the only way to identify a particular member.
235
+
236
+ start: String or Symbol
237
+ The label of the starting point/node of the member.
238
+
239
+ end: String or Symbol
240
+ The label of the ending point/node of the member.
241
+
242
+ Examples
243
+ ========
244
+
245
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
246
+ >>> t = Truss()
247
+ >>> t.add_node('A', 0, 0)
248
+ >>> t.add_node('B', 3, 0)
249
+ >>> t.add_node('C', 2, 2)
250
+ >>> t.add_member('AB', 'A', 'B')
251
+ >>> t.members
252
+ {'AB': ['A', 'B']}
253
+ """
254
+
255
+ if start not in self._node_labels or end not in self._node_labels or start==end:
256
+ raise ValueError("The start and end points of the member must be unique nodes")
257
+
258
+ elif label in list(self._members):
259
+ raise ValueError("A member with the same label already exists for the truss")
260
+
261
+ elif self._nodes_occupied.get((start, end)):
262
+ raise ValueError("A member already exists between the two nodes")
263
+
264
+ else:
265
+ self._members[label] = [start, end]
266
+ self._nodes_occupied[start, end] = True
267
+ self._nodes_occupied[end, start] = True
268
+ self._internal_forces[label] = 0
269
+
270
+ def remove_member(self, label):
271
+ """
272
+ This method removes a member from the given truss.
273
+
274
+ Parameters
275
+ ==========
276
+ label: String or Symbol
277
+ The label for the member to be removed.
278
+
279
+ Examples
280
+ ========
281
+
282
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
283
+ >>> t = Truss()
284
+ >>> t.add_node('A', 0, 0)
285
+ >>> t.add_node('B', 3, 0)
286
+ >>> t.add_node('C', 2, 2)
287
+ >>> t.add_member('AB', 'A', 'B')
288
+ >>> t.add_member('AC', 'A', 'C')
289
+ >>> t.add_member('BC', 'B', 'C')
290
+ >>> t.members
291
+ {'AB': ['A', 'B'], 'AC': ['A', 'C'], 'BC': ['B', 'C']}
292
+ >>> t.remove_member('AC')
293
+ >>> t.members
294
+ {'AB': ['A', 'B'], 'BC': ['B', 'C']}
295
+ """
296
+ if label not in list(self._members):
297
+ raise ValueError("No such member exists in the Truss")
298
+
299
+ else:
300
+ self._nodes_occupied.pop((self._members[label][0], self._members[label][1]))
301
+ self._nodes_occupied.pop((self._members[label][1], self._members[label][0]))
302
+ self._members.pop(label)
303
+ self._internal_forces.pop(label)
304
+
305
+ def change_node_label(self, label, new_label):
306
+ """
307
+ This method changes the label of a node.
308
+
309
+ Parameters
310
+ ==========
311
+ label: String or Symbol
312
+ The label of the node for which the label has
313
+ to be changed.
314
+
315
+ new_label: String or Symbol
316
+ The new label of the node.
317
+
318
+ Examples
319
+ ========
320
+
321
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
322
+ >>> t = Truss()
323
+ >>> t.add_node('A', 0, 0)
324
+ >>> t.add_node('B', 3, 0)
325
+ >>> t.nodes
326
+ [('A', 0, 0), ('B', 3, 0)]
327
+ >>> t.change_node_label('A', 'C')
328
+ >>> t.nodes
329
+ [('C', 0, 0), ('B', 3, 0)]
330
+ """
331
+ if label not in self._node_labels:
332
+ raise ValueError("No such node exists for the Truss")
333
+ elif new_label in self._node_labels:
334
+ raise ValueError("A node with the given label already exists")
335
+ else:
336
+ for node in self._nodes:
337
+ if node[0] == label:
338
+ self._nodes[self._nodes.index((label, node[1], node[2]))] = (new_label, node[1], node[2])
339
+ self._node_labels[self._node_labels.index(node[0])] = new_label
340
+ self._node_coordinates[new_label] = self._node_coordinates[label]
341
+ self._node_coordinates.pop(label)
342
+ if node[0] in list(self._supports):
343
+ self._supports[new_label] = self._supports[node[0]]
344
+ self._supports.pop(node[0])
345
+ if new_label in list(self._supports):
346
+ if self._supports[new_label] == 'pinned':
347
+ if 'R_'+str(label)+'_x' in list(self._reaction_loads) and 'R_'+str(label)+'_y' in list(self._reaction_loads):
348
+ self._reaction_loads['R_'+str(new_label)+'_x'] = self._reaction_loads['R_'+str(label)+'_x']
349
+ self._reaction_loads['R_'+str(new_label)+'_y'] = self._reaction_loads['R_'+str(label)+'_y']
350
+ self._reaction_loads.pop('R_'+str(label)+'_x')
351
+ self._reaction_loads.pop('R_'+str(label)+'_y')
352
+ self._loads[new_label] = self._loads[label]
353
+ for load in self._loads[new_label]:
354
+ if load[1] == 90:
355
+ load[0] -= Symbol('R_'+str(label)+'_y')
356
+ if load[0] == 0:
357
+ self._loads[label].remove(load)
358
+ break
359
+ for load in self._loads[new_label]:
360
+ if load[1] == 0:
361
+ load[0] -= Symbol('R_'+str(label)+'_x')
362
+ if load[0] == 0:
363
+ self._loads[label].remove(load)
364
+ break
365
+ self.apply_load(new_label, Symbol('R_'+str(new_label)+'_x'), 0)
366
+ self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90)
367
+ self._loads.pop(label)
368
+ elif self._supports[new_label] == 'roller':
369
+ self._loads[new_label] = self._loads[label]
370
+ for load in self._loads[label]:
371
+ if load[1] == 90:
372
+ load[0] -= Symbol('R_'+str(label)+'_y')
373
+ if load[0] == 0:
374
+ self._loads[label].remove(load)
375
+ break
376
+ self.apply_load(new_label, Symbol('R_'+str(new_label)+'_y'), 90)
377
+ self._loads.pop(label)
378
+ else:
379
+ if label in list(self._loads):
380
+ self._loads[new_label] = self._loads[label]
381
+ self._loads.pop(label)
382
+ for member in list(self._members):
383
+ if self._members[member][0] == node[0]:
384
+ self._members[member][0] = new_label
385
+ self._nodes_occupied[(new_label, self._members[member][1])] = True
386
+ self._nodes_occupied[(self._members[member][1], new_label)] = True
387
+ self._nodes_occupied.pop((label, self._members[member][1]))
388
+ self._nodes_occupied.pop((self._members[member][1], label))
389
+ elif self._members[member][1] == node[0]:
390
+ self._members[member][1] = new_label
391
+ self._nodes_occupied[(self._members[member][0], new_label)] = True
392
+ self._nodes_occupied[(new_label, self._members[member][0])] = True
393
+ self._nodes_occupied.pop((self._members[member][0], label))
394
+ self._nodes_occupied.pop((label, self._members[member][0]))
395
+
396
+ def change_member_label(self, label, new_label):
397
+ """
398
+ This method changes the label of a member.
399
+
400
+ Parameters
401
+ ==========
402
+ label: String or Symbol
403
+ The label of the member for which the label has
404
+ to be changed.
405
+
406
+ new_label: String or Symbol
407
+ The new label of the member.
408
+
409
+ Examples
410
+ ========
411
+
412
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
413
+ >>> t = Truss()
414
+ >>> t.add_node('A', 0, 0)
415
+ >>> t.add_node('B', 3, 0)
416
+ >>> t.nodes
417
+ [('A', 0, 0), ('B', 3, 0)]
418
+ >>> t.change_node_label('A', 'C')
419
+ >>> t.nodes
420
+ [('C', 0, 0), ('B', 3, 0)]
421
+ >>> t.add_member('BC', 'B', 'C')
422
+ >>> t.members
423
+ {'BC': ['B', 'C']}
424
+ >>> t.change_member_label('BC', 'BC_new')
425
+ >>> t.members
426
+ {'BC_new': ['B', 'C']}
427
+ """
428
+ if label not in list(self._members):
429
+ raise ValueError("No such member exists for the Truss")
430
+
431
+ else:
432
+ members_duplicate = list(self._members).copy()
433
+ for member in members_duplicate:
434
+ if member == label:
435
+ self._members[new_label] = [self._members[member][0], self._members[member][1]]
436
+ self._members.pop(label)
437
+ self._internal_forces[new_label] = self._internal_forces[label]
438
+ self._internal_forces.pop(label)
439
+
440
+ def apply_load(self, location, magnitude, direction):
441
+ """
442
+ This method applies an external load at a particular node
443
+
444
+ Parameters
445
+ ==========
446
+ location: String or Symbol
447
+ Label of the Node at which load is applied.
448
+
449
+ magnitude: Sympifyable
450
+ Magnitude of the load applied. It must always be positive and any changes in
451
+ the direction of the load are not reflected here.
452
+
453
+ direction: Sympifyable
454
+ The angle, in degrees, that the load vector makes with the horizontal
455
+ in the counter-clockwise direction. It takes the values 0 to 360,
456
+ inclusive.
457
+
458
+ Examples
459
+ ========
460
+
461
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
462
+ >>> from sympy import symbols
463
+ >>> t = Truss()
464
+ >>> t.add_node('A', 0, 0)
465
+ >>> t.add_node('B', 3, 0)
466
+ >>> P = symbols('P')
467
+ >>> t.apply_load('A', P, 90)
468
+ >>> t.apply_load('A', P/2, 45)
469
+ >>> t.apply_load('A', P/4, 90)
470
+ >>> t.loads
471
+ {'A': [[P, 90], [P/2, 45], [P/4, 90]]}
472
+ """
473
+ magnitude = sympify(magnitude)
474
+ direction = sympify(direction)
475
+
476
+ if location not in self.node_labels:
477
+ raise ValueError("Load must be applied at a known node")
478
+
479
+ else:
480
+ if location in list(self._loads):
481
+ self._loads[location].append([magnitude, direction])
482
+ else:
483
+ self._loads[location] = [[magnitude, direction]]
484
+
485
+ def remove_load(self, location, magnitude, direction):
486
+ """
487
+ This method removes an already
488
+ present external load at a particular node
489
+
490
+ Parameters
491
+ ==========
492
+ location: String or Symbol
493
+ Label of the Node at which load is applied and is to be removed.
494
+
495
+ magnitude: Sympifyable
496
+ Magnitude of the load applied.
497
+
498
+ direction: Sympifyable
499
+ The angle, in degrees, that the load vector makes with the horizontal
500
+ in the counter-clockwise direction. It takes the values 0 to 360,
501
+ inclusive.
502
+
503
+ Examples
504
+ ========
505
+
506
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
507
+ >>> from sympy import symbols
508
+ >>> t = Truss()
509
+ >>> t.add_node('A', 0, 0)
510
+ >>> t.add_node('B', 3, 0)
511
+ >>> P = symbols('P')
512
+ >>> t.apply_load('A', P, 90)
513
+ >>> t.apply_load('A', P/2, 45)
514
+ >>> t.apply_load('A', P/4, 90)
515
+ >>> t.loads
516
+ {'A': [[P, 90], [P/2, 45], [P/4, 90]]}
517
+ >>> t.remove_load('A', P/4, 90)
518
+ >>> t.loads
519
+ {'A': [[P, 90], [P/2, 45]]}
520
+ """
521
+ magnitude = sympify(magnitude)
522
+ direction = sympify(direction)
523
+
524
+ if location not in self.node_labels:
525
+ raise ValueError("Load must be removed from a known node")
526
+
527
+ else:
528
+ if [magnitude, direction] not in self._loads[location]:
529
+ raise ValueError("No load of this magnitude and direction has been applied at this node")
530
+ else:
531
+ self._loads[location].remove([magnitude, direction])
532
+ if self._loads[location] == []:
533
+ self._loads.pop(location)
534
+
535
+ def apply_support(self, location, type):
536
+ """
537
+ This method adds a pinned or roller support at a particular node
538
+
539
+ Parameters
540
+ ==========
541
+
542
+ location: String or Symbol
543
+ Label of the Node at which support is added.
544
+
545
+ type: String
546
+ Type of the support being provided at the node.
547
+
548
+ Examples
549
+ ========
550
+
551
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
552
+ >>> t = Truss()
553
+ >>> t.add_node('A', 0, 0)
554
+ >>> t.add_node('B', 3, 0)
555
+ >>> t.apply_support('A', 'pinned')
556
+ >>> t.supports
557
+ {'A': 'pinned'}
558
+ """
559
+ if location not in self._node_labels:
560
+ raise ValueError("Support must be added on a known node")
561
+
562
+ else:
563
+ if location not in list(self._supports):
564
+ if type == 'pinned':
565
+ self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0)
566
+ self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90)
567
+ elif type == 'roller':
568
+ self.apply_load(location, Symbol('R_'+str(location)+'_y'), 90)
569
+ elif self._supports[location] == 'pinned':
570
+ if type == 'roller':
571
+ self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0)
572
+ elif self._supports[location] == 'roller':
573
+ if type == 'pinned':
574
+ self.apply_load(location, Symbol('R_'+str(location)+'_x'), 0)
575
+ self._supports[location] = type
576
+
577
+ def remove_support(self, location):
578
+ """
579
+ This method removes support from a particular node
580
+
581
+ Parameters
582
+ ==========
583
+
584
+ location: String or Symbol
585
+ Label of the Node at which support is to be removed.
586
+
587
+ Examples
588
+ ========
589
+
590
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
591
+ >>> t = Truss()
592
+ >>> t.add_node('A', 0, 0)
593
+ >>> t.add_node('B', 3, 0)
594
+ >>> t.apply_support('A', 'pinned')
595
+ >>> t.supports
596
+ {'A': 'pinned'}
597
+ >>> t.remove_support('A')
598
+ >>> t.supports
599
+ {}
600
+ """
601
+ if location not in self._node_labels:
602
+ raise ValueError("No such node exists in the Truss")
603
+
604
+ elif location not in list(self._supports):
605
+ raise ValueError("No support has been added to the given node")
606
+
607
+ else:
608
+ if self._supports[location] == 'pinned':
609
+ self.remove_load(location, Symbol('R_'+str(location)+'_x'), 0)
610
+ self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90)
611
+ elif self._supports[location] == 'roller':
612
+ self.remove_load(location, Symbol('R_'+str(location)+'_y'), 90)
613
+ self._supports.pop(location)
614
+
615
+ def solve(self):
616
+ """
617
+ This method solves for all reaction forces of all supports and all internal forces
618
+ of all the members in the truss, provided the Truss is solvable.
619
+
620
+ A Truss is solvable if the following condition is met,
621
+
622
+ 2n >= r + m
623
+
624
+ Where n is the number of nodes, r is the number of reaction forces, where each pinned
625
+ support has 2 reaction forces and each roller has 1, and m is the number of members.
626
+
627
+ The given condition is derived from the fact that a system of equations is solvable
628
+ only when the number of variables is lesser than or equal to the number of equations.
629
+ Equilibrium Equations in x and y directions give two equations per node giving 2n number
630
+ equations. However, the truss needs to be stable as well and may be unstable if 2n > r + m.
631
+ The number of variables is simply the sum of the number of reaction forces and member
632
+ forces.
633
+
634
+ .. note::
635
+ The sign convention for the internal forces present in a member revolves around whether each
636
+ force is compressive or tensile. While forming equations for each node, internal force due
637
+ to a member on the node is assumed to be away from the node i.e. each force is assumed to
638
+ be compressive by default. Hence, a positive value for an internal force implies the
639
+ presence of compressive force in the member and a negative value implies a tensile force.
640
+
641
+ Examples
642
+ ========
643
+
644
+ >>> from sympy.physics.continuum_mechanics.truss import Truss
645
+ >>> t = Truss()
646
+ >>> t.add_node("node_1", 0, 0)
647
+ >>> t.add_node("node_2", 6, 0)
648
+ >>> t.add_node("node_3", 2, 2)
649
+ >>> t.add_node("node_4", 2, 0)
650
+ >>> t.add_member("member_1", "node_1", "node_4")
651
+ >>> t.add_member("member_2", "node_2", "node_4")
652
+ >>> t.add_member("member_3", "node_1", "node_3")
653
+ >>> t.add_member("member_4", "node_2", "node_3")
654
+ >>> t.add_member("member_5", "node_3", "node_4")
655
+ >>> t.apply_load("node_4", magnitude=10, direction=270)
656
+ >>> t.apply_support("node_1", type="pinned")
657
+ >>> t.apply_support("node_2", type="roller")
658
+ >>> t.solve()
659
+ >>> t.reaction_loads
660
+ {'R_node_1_x': 0, 'R_node_1_y': 20/3, 'R_node_2_y': 10/3}
661
+ >>> t.internal_forces
662
+ {'member_1': 20/3, 'member_2': 20/3, 'member_3': -20*sqrt(2)/3, 'member_4': -10*sqrt(5)/3, 'member_5': 10}
663
+ """
664
+ count_reaction_loads = 0
665
+ for node in self._nodes:
666
+ if node[0] in list(self._supports):
667
+ if self._supports[node[0]]=='pinned':
668
+ count_reaction_loads += 2
669
+ elif self._supports[node[0]]=='roller':
670
+ count_reaction_loads += 1
671
+ if 2*len(self._nodes) != len(self._members) + count_reaction_loads:
672
+ raise ValueError("The given truss cannot be solved")
673
+ coefficients_matrix = [[0 for i in range(2*len(self._nodes))] for j in range(2*len(self._nodes))]
674
+ load_matrix = zeros(2*len(self.nodes), 1)
675
+ load_matrix_row = 0
676
+ for node in self._nodes:
677
+ if node[0] in list(self._loads):
678
+ for load in self._loads[node[0]]:
679
+ if load[0]!=Symbol('R_'+str(node[0])+'_x') and load[0]!=Symbol('R_'+str(node[0])+'_y'):
680
+ load_matrix[load_matrix_row] -= load[0]*cos(pi*load[1]/180)
681
+ load_matrix[load_matrix_row + 1] -= load[0]*sin(pi*load[1]/180)
682
+ load_matrix_row += 2
683
+ cols = 0
684
+ row = 0
685
+ for node in self._nodes:
686
+ if node[0] in list(self._supports):
687
+ if self._supports[node[0]]=='pinned':
688
+ coefficients_matrix[row][cols] += 1
689
+ coefficients_matrix[row+1][cols+1] += 1
690
+ cols += 2
691
+ elif self._supports[node[0]]=='roller':
692
+ coefficients_matrix[row+1][cols] += 1
693
+ cols += 1
694
+ row += 2
695
+ for member in list(self._members):
696
+ start = self._members[member][0]
697
+ end = self._members[member][1]
698
+ length = sqrt((self._node_coordinates[start][0]-self._node_coordinates[end][0])**2 + (self._node_coordinates[start][1]-self._node_coordinates[end][1])**2)
699
+ start_index = self._node_labels.index(start)
700
+ end_index = self._node_labels.index(end)
701
+ horizontal_component_start = (self._node_coordinates[end][0]-self._node_coordinates[start][0])/length
702
+ vertical_component_start = (self._node_coordinates[end][1]-self._node_coordinates[start][1])/length
703
+ horizontal_component_end = (self._node_coordinates[start][0]-self._node_coordinates[end][0])/length
704
+ vertical_component_end = (self._node_coordinates[start][1]-self._node_coordinates[end][1])/length
705
+ coefficients_matrix[start_index*2][cols] += horizontal_component_start
706
+ coefficients_matrix[start_index*2+1][cols] += vertical_component_start
707
+ coefficients_matrix[end_index*2][cols] += horizontal_component_end
708
+ coefficients_matrix[end_index*2+1][cols] += vertical_component_end
709
+ cols += 1
710
+ forces_matrix = (Matrix(coefficients_matrix)**-1)*load_matrix
711
+ self._reaction_loads = {}
712
+ i = 0
713
+ min_load = inf
714
+ for node in self._nodes:
715
+ if node[0] in list(self._loads):
716
+ for load in self._loads[node[0]]:
717
+ if type(load[0]) not in [Symbol, Mul, Add]:
718
+ min_load = min(min_load, load[0])
719
+ for j in range(len(forces_matrix)):
720
+ if type(forces_matrix[j]) not in [Symbol, Mul, Add]:
721
+ if abs(forces_matrix[j]/min_load) <1E-10:
722
+ forces_matrix[j] = 0
723
+ for node in self._nodes:
724
+ if node[0] in list(self._supports):
725
+ if self._supports[node[0]]=='pinned':
726
+ self._reaction_loads['R_'+str(node[0])+'_x'] = forces_matrix[i]
727
+ self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i+1]
728
+ i += 2
729
+ elif self._supports[node[0]]=='roller':
730
+ self._reaction_loads['R_'+str(node[0])+'_y'] = forces_matrix[i]
731
+ i += 1
732
+ for member in list(self._members):
733
+ self._internal_forces[member] = forces_matrix[i]
734
+ i += 1
735
+ return
venv/lib/python3.10/site-packages/sympy/physics/control/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .lti import (TransferFunction, Series, MIMOSeries, Parallel, MIMOParallel,
2
+ Feedback, MIMOFeedback, TransferFunctionMatrix, bilinear, backward_diff)
3
+ from .control_plots import (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
4
+ step_response_plot, impulse_response_numerical_data, impulse_response_plot, ramp_response_numerical_data,
5
+ ramp_response_plot, bode_magnitude_numerical_data, bode_phase_numerical_data, bode_magnitude_plot,
6
+ bode_phase_plot, bode_plot)
7
+
8
+ __all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel',
9
+ 'MIMOParallel', 'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix','bilinear',
10
+ 'backward_diff', 'pole_zero_numerical_data',
11
+ 'pole_zero_plot', 'step_response_numerical_data', 'step_response_plot',
12
+ 'impulse_response_numerical_data', 'impulse_response_plot',
13
+ 'ramp_response_numerical_data', 'ramp_response_plot',
14
+ 'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
15
+ 'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
venv/lib/python3.10/site-packages/sympy/physics/control/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.02 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/control/__pycache__/control_plots.cpython-310.pyc ADDED
Binary file (30 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/control/__pycache__/lti.cpython-310.pyc ADDED
Binary file (118 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/control/control_plots.py ADDED
@@ -0,0 +1,961 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.numbers import I, pi
2
+ from sympy.functions.elementary.exponential import (exp, log)
3
+ from sympy.polys.partfrac import apart
4
+ from sympy.core.symbol import Dummy
5
+ from sympy.external import import_module
6
+ from sympy.functions import arg, Abs
7
+ from sympy.integrals.laplace import _fast_inverse_laplace
8
+ from sympy.physics.control.lti import SISOLinearTimeInvariant
9
+ from sympy.plotting.plot import LineOver1DRangeSeries
10
+ from sympy.polys.polytools import Poly
11
+ from sympy.printing.latex import latex
12
+
13
+ __all__ = ['pole_zero_numerical_data', 'pole_zero_plot',
14
+ 'step_response_numerical_data', 'step_response_plot',
15
+ 'impulse_response_numerical_data', 'impulse_response_plot',
16
+ 'ramp_response_numerical_data', 'ramp_response_plot',
17
+ 'bode_magnitude_numerical_data', 'bode_phase_numerical_data',
18
+ 'bode_magnitude_plot', 'bode_phase_plot', 'bode_plot']
19
+
20
+ matplotlib = import_module(
21
+ 'matplotlib', import_kwargs={'fromlist': ['pyplot']},
22
+ catch=(RuntimeError,))
23
+
24
+ numpy = import_module('numpy')
25
+
26
+ if matplotlib:
27
+ plt = matplotlib.pyplot
28
+
29
+ if numpy:
30
+ np = numpy # Matplotlib already has numpy as a compulsory dependency. No need to install it separately.
31
+
32
+
33
+ def _check_system(system):
34
+ """Function to check whether the dynamical system passed for plots is
35
+ compatible or not."""
36
+ if not isinstance(system, SISOLinearTimeInvariant):
37
+ raise NotImplementedError("Only SISO LTI systems are currently supported.")
38
+ sys = system.to_expr()
39
+ len_free_symbols = len(sys.free_symbols)
40
+ if len_free_symbols > 1:
41
+ raise ValueError("Extra degree of freedom found. Make sure"
42
+ " that there are no free symbols in the dynamical system other"
43
+ " than the variable of Laplace transform.")
44
+ if sys.has(exp):
45
+ # Should test that exp is not part of a constant, in which case
46
+ # no exception is required, compare exp(s) with s*exp(1)
47
+ raise NotImplementedError("Time delay terms are not supported.")
48
+
49
+
50
+ def pole_zero_numerical_data(system):
51
+ """
52
+ Returns the numerical data of poles and zeros of the system.
53
+ It is internally used by ``pole_zero_plot`` to get the data
54
+ for plotting poles and zeros. Users can use this data to further
55
+ analyse the dynamics of the system or plot using a different
56
+ backend/plotting-module.
57
+
58
+ Parameters
59
+ ==========
60
+
61
+ system : SISOLinearTimeInvariant
62
+ The system for which the pole-zero data is to be computed.
63
+
64
+ Returns
65
+ =======
66
+
67
+ tuple : (zeros, poles)
68
+ zeros = Zeros of the system. NumPy array of complex numbers.
69
+ poles = Poles of the system. NumPy array of complex numbers.
70
+
71
+ Raises
72
+ ======
73
+
74
+ NotImplementedError
75
+ When a SISO LTI system is not passed.
76
+
77
+ When time delay terms are present in the system.
78
+
79
+ ValueError
80
+ When more than one free symbol is present in the system.
81
+ The only variable in the transfer function should be
82
+ the variable of the Laplace transform.
83
+
84
+ Examples
85
+ ========
86
+
87
+ >>> from sympy.abc import s
88
+ >>> from sympy.physics.control.lti import TransferFunction
89
+ >>> from sympy.physics.control.control_plots import pole_zero_numerical_data
90
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
91
+ >>> pole_zero_numerical_data(tf1) # doctest: +SKIP
92
+ ([-0.+1.j 0.-1.j], [-2. +0.j -0.5+0.8660254j -0.5-0.8660254j -1. +0.j ])
93
+
94
+ See Also
95
+ ========
96
+
97
+ pole_zero_plot
98
+
99
+ """
100
+ _check_system(system)
101
+ system = system.doit() # Get the equivalent TransferFunction object.
102
+
103
+ num_poly = Poly(system.num, system.var).all_coeffs()
104
+ den_poly = Poly(system.den, system.var).all_coeffs()
105
+
106
+ num_poly = np.array(num_poly, dtype=np.complex128)
107
+ den_poly = np.array(den_poly, dtype=np.complex128)
108
+
109
+ zeros = np.roots(num_poly)
110
+ poles = np.roots(den_poly)
111
+
112
+ return zeros, poles
113
+
114
+
115
+ def pole_zero_plot(system, pole_color='blue', pole_markersize=10,
116
+ zero_color='orange', zero_markersize=7, grid=True, show_axes=True,
117
+ show=True, **kwargs):
118
+ r"""
119
+ Returns the Pole-Zero plot (also known as PZ Plot or PZ Map) of a system.
120
+
121
+ A Pole-Zero plot is a graphical representation of a system's poles and
122
+ zeros. It is plotted on a complex plane, with circular markers representing
123
+ the system's zeros and 'x' shaped markers representing the system's poles.
124
+
125
+ Parameters
126
+ ==========
127
+
128
+ system : SISOLinearTimeInvariant type systems
129
+ The system for which the pole-zero plot is to be computed.
130
+ pole_color : str, tuple, optional
131
+ The color of the pole points on the plot. Default color
132
+ is blue. The color can be provided as a matplotlib color string,
133
+ or a 3-tuple of floats each in the 0-1 range.
134
+ pole_markersize : Number, optional
135
+ The size of the markers used to mark the poles in the plot.
136
+ Default pole markersize is 10.
137
+ zero_color : str, tuple, optional
138
+ The color of the zero points on the plot. Default color
139
+ is orange. The color can be provided as a matplotlib color string,
140
+ or a 3-tuple of floats each in the 0-1 range.
141
+ zero_markersize : Number, optional
142
+ The size of the markers used to mark the zeros in the plot.
143
+ Default zero markersize is 7.
144
+ grid : boolean, optional
145
+ If ``True``, the plot will have a grid. Defaults to True.
146
+ show_axes : boolean, optional
147
+ If ``True``, the coordinate axes will be shown. Defaults to False.
148
+ show : boolean, optional
149
+ If ``True``, the plot will be displayed otherwise
150
+ the equivalent matplotlib ``plot`` object will be returned.
151
+ Defaults to True.
152
+
153
+ Examples
154
+ ========
155
+
156
+ .. plot::
157
+ :context: close-figs
158
+ :format: doctest
159
+ :include-source: True
160
+
161
+ >>> from sympy.abc import s
162
+ >>> from sympy.physics.control.lti import TransferFunction
163
+ >>> from sympy.physics.control.control_plots import pole_zero_plot
164
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
165
+ >>> pole_zero_plot(tf1) # doctest: +SKIP
166
+
167
+ See Also
168
+ ========
169
+
170
+ pole_zero_numerical_data
171
+
172
+ References
173
+ ==========
174
+
175
+ .. [1] https://en.wikipedia.org/wiki/Pole%E2%80%93zero_plot
176
+
177
+ """
178
+ zeros, poles = pole_zero_numerical_data(system)
179
+
180
+ zero_real = np.real(zeros)
181
+ zero_imag = np.imag(zeros)
182
+
183
+ pole_real = np.real(poles)
184
+ pole_imag = np.imag(poles)
185
+
186
+ plt.plot(pole_real, pole_imag, 'x', mfc='none',
187
+ markersize=pole_markersize, color=pole_color)
188
+ plt.plot(zero_real, zero_imag, 'o', markersize=zero_markersize,
189
+ color=zero_color)
190
+ plt.xlabel('Real Axis')
191
+ plt.ylabel('Imaginary Axis')
192
+ plt.title(f'Poles and Zeros of ${latex(system)}$', pad=20)
193
+
194
+ if grid:
195
+ plt.grid()
196
+ if show_axes:
197
+ plt.axhline(0, color='black')
198
+ plt.axvline(0, color='black')
199
+ if show:
200
+ plt.show()
201
+ return
202
+
203
+ return plt
204
+
205
+
206
+ def step_response_numerical_data(system, prec=8, lower_limit=0,
207
+ upper_limit=10, **kwargs):
208
+ """
209
+ Returns the numerical values of the points in the step response plot
210
+ of a SISO continuous-time system. By default, adaptive sampling
211
+ is used. If the user wants to instead get an uniformly
212
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
213
+ and ``nb_of_points`` must be passed as additional kwargs.
214
+ Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
215
+ for more details.
216
+
217
+ Parameters
218
+ ==========
219
+
220
+ system : SISOLinearTimeInvariant
221
+ The system for which the unit step response data is to be computed.
222
+ prec : int, optional
223
+ The decimal point precision for the point coordinate values.
224
+ Defaults to 8.
225
+ lower_limit : Number, optional
226
+ The lower limit of the plot range. Defaults to 0.
227
+ upper_limit : Number, optional
228
+ The upper limit of the plot range. Defaults to 10.
229
+ kwargs :
230
+ Additional keyword arguments are passed to the underlying
231
+ :class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
232
+
233
+ Returns
234
+ =======
235
+
236
+ tuple : (x, y)
237
+ x = Time-axis values of the points in the step response. NumPy array.
238
+ y = Amplitude-axis values of the points in the step response. NumPy array.
239
+
240
+ Raises
241
+ ======
242
+
243
+ NotImplementedError
244
+ When a SISO LTI system is not passed.
245
+
246
+ When time delay terms are present in the system.
247
+
248
+ ValueError
249
+ When more than one free symbol is present in the system.
250
+ The only variable in the transfer function should be
251
+ the variable of the Laplace transform.
252
+
253
+ When ``lower_limit`` parameter is less than 0.
254
+
255
+ Examples
256
+ ========
257
+
258
+ >>> from sympy.abc import s
259
+ >>> from sympy.physics.control.lti import TransferFunction
260
+ >>> from sympy.physics.control.control_plots import step_response_numerical_data
261
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
262
+ >>> step_response_numerical_data(tf1) # doctest: +SKIP
263
+ ([0.0, 0.025413462339411542, 0.0484508722725343, ... , 9.670250533855183, 9.844291913708725, 10.0],
264
+ [0.0, 0.023844582399907256, 0.042894276802320226, ..., 6.828770759094287e-12, 6.456457160755703e-12])
265
+
266
+ See Also
267
+ ========
268
+
269
+ step_response_plot
270
+
271
+ """
272
+ if lower_limit < 0:
273
+ raise ValueError("Lower limit of time must be greater "
274
+ "than or equal to zero.")
275
+ _check_system(system)
276
+ _x = Dummy("x")
277
+ expr = system.to_expr()/(system.var)
278
+ expr = apart(expr, system.var, full=True)
279
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
280
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
281
+ **kwargs).get_points()
282
+
283
+
284
+ def step_response_plot(system, color='b', prec=8, lower_limit=0,
285
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
286
+ r"""
287
+ Returns the unit step response of a continuous-time system. It is
288
+ the response of the system when the input signal is a step function.
289
+
290
+ Parameters
291
+ ==========
292
+
293
+ system : SISOLinearTimeInvariant type
294
+ The LTI SISO system for which the Step Response is to be computed.
295
+ color : str, tuple, optional
296
+ The color of the line. Default is Blue.
297
+ show : boolean, optional
298
+ If ``True``, the plot will be displayed otherwise
299
+ the equivalent matplotlib ``plot`` object will be returned.
300
+ Defaults to True.
301
+ lower_limit : Number, optional
302
+ The lower limit of the plot range. Defaults to 0.
303
+ upper_limit : Number, optional
304
+ The upper limit of the plot range. Defaults to 10.
305
+ prec : int, optional
306
+ The decimal point precision for the point coordinate values.
307
+ Defaults to 8.
308
+ show_axes : boolean, optional
309
+ If ``True``, the coordinate axes will be shown. Defaults to False.
310
+ grid : boolean, optional
311
+ If ``True``, the plot will have a grid. Defaults to True.
312
+
313
+ Examples
314
+ ========
315
+
316
+ .. plot::
317
+ :context: close-figs
318
+ :format: doctest
319
+ :include-source: True
320
+
321
+ >>> from sympy.abc import s
322
+ >>> from sympy.physics.control.lti import TransferFunction
323
+ >>> from sympy.physics.control.control_plots import step_response_plot
324
+ >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
325
+ >>> step_response_plot(tf1) # doctest: +SKIP
326
+
327
+ See Also
328
+ ========
329
+
330
+ impulse_response_plot, ramp_response_plot
331
+
332
+ References
333
+ ==========
334
+
335
+ .. [1] https://www.mathworks.com/help/control/ref/lti.step.html
336
+
337
+ """
338
+ x, y = step_response_numerical_data(system, prec=prec,
339
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
340
+ plt.plot(x, y, color=color)
341
+ plt.xlabel('Time (s)')
342
+ plt.ylabel('Amplitude')
343
+ plt.title(f'Unit Step Response of ${latex(system)}$', pad=20)
344
+
345
+ if grid:
346
+ plt.grid()
347
+ if show_axes:
348
+ plt.axhline(0, color='black')
349
+ plt.axvline(0, color='black')
350
+ if show:
351
+ plt.show()
352
+ return
353
+
354
+ return plt
355
+
356
+
357
+ def impulse_response_numerical_data(system, prec=8, lower_limit=0,
358
+ upper_limit=10, **kwargs):
359
+ """
360
+ Returns the numerical values of the points in the impulse response plot
361
+ of a SISO continuous-time system. By default, adaptive sampling
362
+ is used. If the user wants to instead get an uniformly
363
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
364
+ and ``nb_of_points`` must be passed as additional kwargs.
365
+ Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
366
+ for more details.
367
+
368
+ Parameters
369
+ ==========
370
+
371
+ system : SISOLinearTimeInvariant
372
+ The system for which the impulse response data is to be computed.
373
+ prec : int, optional
374
+ The decimal point precision for the point coordinate values.
375
+ Defaults to 8.
376
+ lower_limit : Number, optional
377
+ The lower limit of the plot range. Defaults to 0.
378
+ upper_limit : Number, optional
379
+ The upper limit of the plot range. Defaults to 10.
380
+ kwargs :
381
+ Additional keyword arguments are passed to the underlying
382
+ :class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
383
+
384
+ Returns
385
+ =======
386
+
387
+ tuple : (x, y)
388
+ x = Time-axis values of the points in the impulse response. NumPy array.
389
+ y = Amplitude-axis values of the points in the impulse response. NumPy array.
390
+
391
+ Raises
392
+ ======
393
+
394
+ NotImplementedError
395
+ When a SISO LTI system is not passed.
396
+
397
+ When time delay terms are present in the system.
398
+
399
+ ValueError
400
+ When more than one free symbol is present in the system.
401
+ The only variable in the transfer function should be
402
+ the variable of the Laplace transform.
403
+
404
+ When ``lower_limit`` parameter is less than 0.
405
+
406
+ Examples
407
+ ========
408
+
409
+ >>> from sympy.abc import s
410
+ >>> from sympy.physics.control.lti import TransferFunction
411
+ >>> from sympy.physics.control.control_plots import impulse_response_numerical_data
412
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
413
+ >>> impulse_response_numerical_data(tf1) # doctest: +SKIP
414
+ ([0.0, 0.06616480200395854,... , 9.854500743565858, 10.0],
415
+ [0.9999999799999999, 0.7042848373025861,...,7.170748906965121e-13, -5.1901263495547205e-12])
416
+
417
+ See Also
418
+ ========
419
+
420
+ impulse_response_plot
421
+
422
+ """
423
+ if lower_limit < 0:
424
+ raise ValueError("Lower limit of time must be greater "
425
+ "than or equal to zero.")
426
+ _check_system(system)
427
+ _x = Dummy("x")
428
+ expr = system.to_expr()
429
+ expr = apart(expr, system.var, full=True)
430
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
431
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
432
+ **kwargs).get_points()
433
+
434
+
435
+ def impulse_response_plot(system, color='b', prec=8, lower_limit=0,
436
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
437
+ r"""
438
+ Returns the unit impulse response (Input is the Dirac-Delta Function) of a
439
+ continuous-time system.
440
+
441
+ Parameters
442
+ ==========
443
+
444
+ system : SISOLinearTimeInvariant type
445
+ The LTI SISO system for which the Impulse Response is to be computed.
446
+ color : str, tuple, optional
447
+ The color of the line. Default is Blue.
448
+ show : boolean, optional
449
+ If ``True``, the plot will be displayed otherwise
450
+ the equivalent matplotlib ``plot`` object will be returned.
451
+ Defaults to True.
452
+ lower_limit : Number, optional
453
+ The lower limit of the plot range. Defaults to 0.
454
+ upper_limit : Number, optional
455
+ The upper limit of the plot range. Defaults to 10.
456
+ prec : int, optional
457
+ The decimal point precision for the point coordinate values.
458
+ Defaults to 8.
459
+ show_axes : boolean, optional
460
+ If ``True``, the coordinate axes will be shown. Defaults to False.
461
+ grid : boolean, optional
462
+ If ``True``, the plot will have a grid. Defaults to True.
463
+
464
+ Examples
465
+ ========
466
+
467
+ .. plot::
468
+ :context: close-figs
469
+ :format: doctest
470
+ :include-source: True
471
+
472
+ >>> from sympy.abc import s
473
+ >>> from sympy.physics.control.lti import TransferFunction
474
+ >>> from sympy.physics.control.control_plots import impulse_response_plot
475
+ >>> tf1 = TransferFunction(8*s**2 + 18*s + 32, s**3 + 6*s**2 + 14*s + 24, s)
476
+ >>> impulse_response_plot(tf1) # doctest: +SKIP
477
+
478
+ See Also
479
+ ========
480
+
481
+ step_response_plot, ramp_response_plot
482
+
483
+ References
484
+ ==========
485
+
486
+ .. [1] https://www.mathworks.com/help/control/ref/lti.impulse.html
487
+
488
+ """
489
+ x, y = impulse_response_numerical_data(system, prec=prec,
490
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
491
+ plt.plot(x, y, color=color)
492
+ plt.xlabel('Time (s)')
493
+ plt.ylabel('Amplitude')
494
+ plt.title(f'Impulse Response of ${latex(system)}$', pad=20)
495
+
496
+ if grid:
497
+ plt.grid()
498
+ if show_axes:
499
+ plt.axhline(0, color='black')
500
+ plt.axvline(0, color='black')
501
+ if show:
502
+ plt.show()
503
+ return
504
+
505
+ return plt
506
+
507
+
508
+ def ramp_response_numerical_data(system, slope=1, prec=8,
509
+ lower_limit=0, upper_limit=10, **kwargs):
510
+ """
511
+ Returns the numerical values of the points in the ramp response plot
512
+ of a SISO continuous-time system. By default, adaptive sampling
513
+ is used. If the user wants to instead get an uniformly
514
+ sampled response, then ``adaptive`` kwarg should be passed ``False``
515
+ and ``nb_of_points`` must be passed as additional kwargs.
516
+ Refer to the parameters of class :class:`sympy.plotting.plot.LineOver1DRangeSeries`
517
+ for more details.
518
+
519
+ Parameters
520
+ ==========
521
+
522
+ system : SISOLinearTimeInvariant
523
+ The system for which the ramp response data is to be computed.
524
+ slope : Number, optional
525
+ The slope of the input ramp function. Defaults to 1.
526
+ prec : int, optional
527
+ The decimal point precision for the point coordinate values.
528
+ Defaults to 8.
529
+ lower_limit : Number, optional
530
+ The lower limit of the plot range. Defaults to 0.
531
+ upper_limit : Number, optional
532
+ The upper limit of the plot range. Defaults to 10.
533
+ kwargs :
534
+ Additional keyword arguments are passed to the underlying
535
+ :class:`sympy.plotting.plot.LineOver1DRangeSeries` class.
536
+
537
+ Returns
538
+ =======
539
+
540
+ tuple : (x, y)
541
+ x = Time-axis values of the points in the ramp response plot. NumPy array.
542
+ y = Amplitude-axis values of the points in the ramp response plot. NumPy array.
543
+
544
+ Raises
545
+ ======
546
+
547
+ NotImplementedError
548
+ When a SISO LTI system is not passed.
549
+
550
+ When time delay terms are present in the system.
551
+
552
+ ValueError
553
+ When more than one free symbol is present in the system.
554
+ The only variable in the transfer function should be
555
+ the variable of the Laplace transform.
556
+
557
+ When ``lower_limit`` parameter is less than 0.
558
+
559
+ When ``slope`` is negative.
560
+
561
+ Examples
562
+ ========
563
+
564
+ >>> from sympy.abc import s
565
+ >>> from sympy.physics.control.lti import TransferFunction
566
+ >>> from sympy.physics.control.control_plots import ramp_response_numerical_data
567
+ >>> tf1 = TransferFunction(s, s**2 + 5*s + 8, s)
568
+ >>> ramp_response_numerical_data(tf1) # doctest: +SKIP
569
+ (([0.0, 0.12166980856813935,..., 9.861246379582118, 10.0],
570
+ [1.4504508011325967e-09, 0.006046440489058766,..., 0.12499999999568202, 0.12499999999661349]))
571
+
572
+ See Also
573
+ ========
574
+
575
+ ramp_response_plot
576
+
577
+ """
578
+ if slope < 0:
579
+ raise ValueError("Slope must be greater than or equal"
580
+ " to zero.")
581
+ if lower_limit < 0:
582
+ raise ValueError("Lower limit of time must be greater "
583
+ "than or equal to zero.")
584
+ _check_system(system)
585
+ _x = Dummy("x")
586
+ expr = (slope*system.to_expr())/((system.var)**2)
587
+ expr = apart(expr, system.var, full=True)
588
+ _y = _fast_inverse_laplace(expr, system.var, _x).evalf(prec)
589
+ return LineOver1DRangeSeries(_y, (_x, lower_limit, upper_limit),
590
+ **kwargs).get_points()
591
+
592
+
593
+ def ramp_response_plot(system, slope=1, color='b', prec=8, lower_limit=0,
594
+ upper_limit=10, show_axes=False, grid=True, show=True, **kwargs):
595
+ r"""
596
+ Returns the ramp response of a continuous-time system.
597
+
598
+ Ramp function is defined as the straight line
599
+ passing through origin ($f(x) = mx$). The slope of
600
+ the ramp function can be varied by the user and
601
+ the default value is 1.
602
+
603
+ Parameters
604
+ ==========
605
+
606
+ system : SISOLinearTimeInvariant type
607
+ The LTI SISO system for which the Ramp Response is to be computed.
608
+ slope : Number, optional
609
+ The slope of the input ramp function. Defaults to 1.
610
+ color : str, tuple, optional
611
+ The color of the line. Default is Blue.
612
+ show : boolean, optional
613
+ If ``True``, the plot will be displayed otherwise
614
+ the equivalent matplotlib ``plot`` object will be returned.
615
+ Defaults to True.
616
+ lower_limit : Number, optional
617
+ The lower limit of the plot range. Defaults to 0.
618
+ upper_limit : Number, optional
619
+ The upper limit of the plot range. Defaults to 10.
620
+ prec : int, optional
621
+ The decimal point precision for the point coordinate values.
622
+ Defaults to 8.
623
+ show_axes : boolean, optional
624
+ If ``True``, the coordinate axes will be shown. Defaults to False.
625
+ grid : boolean, optional
626
+ If ``True``, the plot will have a grid. Defaults to True.
627
+
628
+ Examples
629
+ ========
630
+
631
+ .. plot::
632
+ :context: close-figs
633
+ :format: doctest
634
+ :include-source: True
635
+
636
+ >>> from sympy.abc import s
637
+ >>> from sympy.physics.control.lti import TransferFunction
638
+ >>> from sympy.physics.control.control_plots import ramp_response_plot
639
+ >>> tf1 = TransferFunction(s, (s+4)*(s+8), s)
640
+ >>> ramp_response_plot(tf1, upper_limit=2) # doctest: +SKIP
641
+
642
+ See Also
643
+ ========
644
+
645
+ step_response_plot, ramp_response_plot
646
+
647
+ References
648
+ ==========
649
+
650
+ .. [1] https://en.wikipedia.org/wiki/Ramp_function
651
+
652
+ """
653
+ x, y = ramp_response_numerical_data(system, slope=slope, prec=prec,
654
+ lower_limit=lower_limit, upper_limit=upper_limit, **kwargs)
655
+ plt.plot(x, y, color=color)
656
+ plt.xlabel('Time (s)')
657
+ plt.ylabel('Amplitude')
658
+ plt.title(f'Ramp Response of ${latex(system)}$ [Slope = {slope}]', pad=20)
659
+
660
+ if grid:
661
+ plt.grid()
662
+ if show_axes:
663
+ plt.axhline(0, color='black')
664
+ plt.axvline(0, color='black')
665
+ if show:
666
+ plt.show()
667
+ return
668
+
669
+ return plt
670
+
671
+
672
+ def bode_magnitude_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', **kwargs):
673
+ """
674
+ Returns the numerical data of the Bode magnitude plot of the system.
675
+ It is internally used by ``bode_magnitude_plot`` to get the data
676
+ for plotting Bode magnitude plot. Users can use this data to further
677
+ analyse the dynamics of the system or plot using a different
678
+ backend/plotting-module.
679
+
680
+ Parameters
681
+ ==========
682
+
683
+ system : SISOLinearTimeInvariant
684
+ The system for which the data is to be computed.
685
+ initial_exp : Number, optional
686
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
687
+ final_exp : Number, optional
688
+ The final exponent of 10 of the semilog plot. Defaults to 5.
689
+ freq_unit : string, optional
690
+ User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
691
+
692
+ Returns
693
+ =======
694
+
695
+ tuple : (x, y)
696
+ x = x-axis values of the Bode magnitude plot.
697
+ y = y-axis values of the Bode magnitude plot.
698
+
699
+ Raises
700
+ ======
701
+
702
+ NotImplementedError
703
+ When a SISO LTI system is not passed.
704
+
705
+ When time delay terms are present in the system.
706
+
707
+ ValueError
708
+ When more than one free symbol is present in the system.
709
+ The only variable in the transfer function should be
710
+ the variable of the Laplace transform.
711
+
712
+ When incorrect frequency units are given as input.
713
+
714
+ Examples
715
+ ========
716
+
717
+ >>> from sympy.abc import s
718
+ >>> from sympy.physics.control.lti import TransferFunction
719
+ >>> from sympy.physics.control.control_plots import bode_magnitude_numerical_data
720
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
721
+ >>> bode_magnitude_numerical_data(tf1) # doctest: +SKIP
722
+ ([1e-05, 1.5148378120533502e-05,..., 68437.36188804005, 100000.0],
723
+ [-6.020599914256786, -6.0205999155219505,..., -193.4117304087953, -200.00000000260573])
724
+
725
+ See Also
726
+ ========
727
+
728
+ bode_magnitude_plot, bode_phase_numerical_data
729
+
730
+ """
731
+ _check_system(system)
732
+ expr = system.to_expr()
733
+ freq_units = ('rad/sec', 'Hz')
734
+ if freq_unit not in freq_units:
735
+ raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
736
+
737
+ _w = Dummy("w", real=True)
738
+ if freq_unit == 'Hz':
739
+ repl = I*_w*2*pi
740
+ else:
741
+ repl = I*_w
742
+ w_expr = expr.subs({system.var: repl})
743
+
744
+ mag = 20*log(Abs(w_expr), 10)
745
+
746
+ x, y = LineOver1DRangeSeries(mag,
747
+ (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
748
+
749
+ return x, y
750
+
751
+
752
+ def bode_magnitude_plot(system, initial_exp=-5, final_exp=5,
753
+ color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', **kwargs):
754
+ r"""
755
+ Returns the Bode magnitude plot of a continuous-time system.
756
+
757
+ See ``bode_plot`` for all the parameters.
758
+ """
759
+ x, y = bode_magnitude_numerical_data(system, initial_exp=initial_exp,
760
+ final_exp=final_exp, freq_unit=freq_unit)
761
+ plt.plot(x, y, color=color, **kwargs)
762
+ plt.xscale('log')
763
+
764
+
765
+ plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
766
+ plt.ylabel('Magnitude (dB)')
767
+ plt.title(f'Bode Plot (Magnitude) of ${latex(system)}$', pad=20)
768
+
769
+ if grid:
770
+ plt.grid(True)
771
+ if show_axes:
772
+ plt.axhline(0, color='black')
773
+ plt.axvline(0, color='black')
774
+ if show:
775
+ plt.show()
776
+ return
777
+
778
+ return plt
779
+
780
+
781
+ def bode_phase_numerical_data(system, initial_exp=-5, final_exp=5, freq_unit='rad/sec', phase_unit='rad', **kwargs):
782
+ """
783
+ Returns the numerical data of the Bode phase plot of the system.
784
+ It is internally used by ``bode_phase_plot`` to get the data
785
+ for plotting Bode phase plot. Users can use this data to further
786
+ analyse the dynamics of the system or plot using a different
787
+ backend/plotting-module.
788
+
789
+ Parameters
790
+ ==========
791
+
792
+ system : SISOLinearTimeInvariant
793
+ The system for which the Bode phase plot data is to be computed.
794
+ initial_exp : Number, optional
795
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
796
+ final_exp : Number, optional
797
+ The final exponent of 10 of the semilog plot. Defaults to 5.
798
+ freq_unit : string, optional
799
+ User can choose between ``'rad/sec'`` (radians/second) and '``'Hz'`` (Hertz) as frequency units.
800
+ phase_unit : string, optional
801
+ User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
802
+
803
+ Returns
804
+ =======
805
+
806
+ tuple : (x, y)
807
+ x = x-axis values of the Bode phase plot.
808
+ y = y-axis values of the Bode phase plot.
809
+
810
+ Raises
811
+ ======
812
+
813
+ NotImplementedError
814
+ When a SISO LTI system is not passed.
815
+
816
+ When time delay terms are present in the system.
817
+
818
+ ValueError
819
+ When more than one free symbol is present in the system.
820
+ The only variable in the transfer function should be
821
+ the variable of the Laplace transform.
822
+
823
+ When incorrect frequency or phase units are given as input.
824
+
825
+ Examples
826
+ ========
827
+
828
+ >>> from sympy.abc import s
829
+ >>> from sympy.physics.control.lti import TransferFunction
830
+ >>> from sympy.physics.control.control_plots import bode_phase_numerical_data
831
+ >>> tf1 = TransferFunction(s**2 + 1, s**4 + 4*s**3 + 6*s**2 + 5*s + 2, s)
832
+ >>> bode_phase_numerical_data(tf1) # doctest: +SKIP
833
+ ([1e-05, 1.4472354033813751e-05, 2.035581932165858e-05,..., 47577.3248186011, 67884.09326036123, 100000.0],
834
+ [-2.5000000000291665e-05, -3.6180885085e-05, -5.08895483066e-05,...,-3.1415085799262523, -3.14155265358979])
835
+
836
+ See Also
837
+ ========
838
+
839
+ bode_magnitude_plot, bode_phase_numerical_data
840
+
841
+ """
842
+ _check_system(system)
843
+ expr = system.to_expr()
844
+ freq_units = ('rad/sec', 'Hz')
845
+ phase_units = ('rad', 'deg')
846
+ if freq_unit not in freq_units:
847
+ raise ValueError('Only "rad/sec" and "Hz" are accepted frequency units.')
848
+ if phase_unit not in phase_units:
849
+ raise ValueError('Only "rad" and "deg" are accepted phase units.')
850
+
851
+ _w = Dummy("w", real=True)
852
+ if freq_unit == 'Hz':
853
+ repl = I*_w*2*pi
854
+ else:
855
+ repl = I*_w
856
+ w_expr = expr.subs({system.var: repl})
857
+
858
+ if phase_unit == 'deg':
859
+ phase = arg(w_expr)*180/pi
860
+ else:
861
+ phase = arg(w_expr)
862
+
863
+ x, y = LineOver1DRangeSeries(phase,
864
+ (_w, 10**initial_exp, 10**final_exp), xscale='log', **kwargs).get_points()
865
+
866
+ return x, y
867
+
868
+
869
+ def bode_phase_plot(system, initial_exp=-5, final_exp=5,
870
+ color='b', show_axes=False, grid=True, show=True, freq_unit='rad/sec', phase_unit='rad', **kwargs):
871
+ r"""
872
+ Returns the Bode phase plot of a continuous-time system.
873
+
874
+ See ``bode_plot`` for all the parameters.
875
+ """
876
+ x, y = bode_phase_numerical_data(system, initial_exp=initial_exp,
877
+ final_exp=final_exp, freq_unit=freq_unit, phase_unit=phase_unit)
878
+ plt.plot(x, y, color=color, **kwargs)
879
+ plt.xscale('log')
880
+
881
+ plt.xlabel('Frequency (%s) [Log Scale]' % freq_unit)
882
+ plt.ylabel('Phase (%s)' % phase_unit)
883
+ plt.title(f'Bode Plot (Phase) of ${latex(system)}$', pad=20)
884
+
885
+ if grid:
886
+ plt.grid(True)
887
+ if show_axes:
888
+ plt.axhline(0, color='black')
889
+ plt.axvline(0, color='black')
890
+ if show:
891
+ plt.show()
892
+ return
893
+
894
+ return plt
895
+
896
+
897
+ def bode_plot(system, initial_exp=-5, final_exp=5,
898
+ grid=True, show_axes=False, show=True, freq_unit='rad/sec', phase_unit='rad', **kwargs):
899
+ r"""
900
+ Returns the Bode phase and magnitude plots of a continuous-time system.
901
+
902
+ Parameters
903
+ ==========
904
+
905
+ system : SISOLinearTimeInvariant type
906
+ The LTI SISO system for which the Bode Plot is to be computed.
907
+ initial_exp : Number, optional
908
+ The initial exponent of 10 of the semilog plot. Defaults to -5.
909
+ final_exp : Number, optional
910
+ The final exponent of 10 of the semilog plot. Defaults to 5.
911
+ show : boolean, optional
912
+ If ``True``, the plot will be displayed otherwise
913
+ the equivalent matplotlib ``plot`` object will be returned.
914
+ Defaults to True.
915
+ prec : int, optional
916
+ The decimal point precision for the point coordinate values.
917
+ Defaults to 8.
918
+ grid : boolean, optional
919
+ If ``True``, the plot will have a grid. Defaults to True.
920
+ show_axes : boolean, optional
921
+ If ``True``, the coordinate axes will be shown. Defaults to False.
922
+ freq_unit : string, optional
923
+ User can choose between ``'rad/sec'`` (radians/second) and ``'Hz'`` (Hertz) as frequency units.
924
+ phase_unit : string, optional
925
+ User can choose between ``'rad'`` (radians) and ``'deg'`` (degree) as phase units.
926
+
927
+ Examples
928
+ ========
929
+
930
+ .. plot::
931
+ :context: close-figs
932
+ :format: doctest
933
+ :include-source: True
934
+
935
+ >>> from sympy.abc import s
936
+ >>> from sympy.physics.control.lti import TransferFunction
937
+ >>> from sympy.physics.control.control_plots import bode_plot
938
+ >>> tf1 = TransferFunction(1*s**2 + 0.1*s + 7.5, 1*s**4 + 0.12*s**3 + 9*s**2, s)
939
+ >>> bode_plot(tf1, initial_exp=0.2, final_exp=0.7) # doctest: +SKIP
940
+
941
+ See Also
942
+ ========
943
+
944
+ bode_magnitude_plot, bode_phase_plot
945
+
946
+ """
947
+ plt.subplot(211)
948
+ mag = bode_magnitude_plot(system, initial_exp=initial_exp, final_exp=final_exp,
949
+ show=False, grid=grid, show_axes=show_axes,
950
+ freq_unit=freq_unit, **kwargs)
951
+ mag.title(f'Bode Plot of ${latex(system)}$', pad=20)
952
+ mag.xlabel(None)
953
+ plt.subplot(212)
954
+ bode_phase_plot(system, initial_exp=initial_exp, final_exp=final_exp,
955
+ show=False, grid=grid, show_axes=show_axes, freq_unit=freq_unit, phase_unit=phase_unit, **kwargs).title(None)
956
+
957
+ if show:
958
+ plt.show()
959
+ return
960
+
961
+ return plt
venv/lib/python3.10/site-packages/sympy/physics/control/lti.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.10/site-packages/sympy/physics/control/tests/__init__.py ADDED
File without changes
venv/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (195 Bytes). View file
 
venv/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_control_plots.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/control/tests/__pycache__/test_lti.cpython-310.pyc ADDED
Binary file (53.8 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/control/tests/test_control_plots.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from math import isclose
2
+ from sympy.core.numbers import I
3
+ from sympy.core.symbol import Dummy
4
+ from sympy.functions.elementary.complexes import (Abs, arg)
5
+ from sympy.functions.elementary.exponential import log
6
+ from sympy.abc import s, p, a
7
+ from sympy.external import import_module
8
+ from sympy.physics.control.control_plots import \
9
+ (pole_zero_numerical_data, pole_zero_plot, step_response_numerical_data,
10
+ step_response_plot, impulse_response_numerical_data,
11
+ impulse_response_plot, ramp_response_numerical_data,
12
+ ramp_response_plot, bode_magnitude_numerical_data,
13
+ bode_phase_numerical_data, bode_plot)
14
+ from sympy.physics.control.lti import (TransferFunction,
15
+ Series, Parallel, TransferFunctionMatrix)
16
+ from sympy.testing.pytest import raises, skip
17
+
18
+ matplotlib = import_module(
19
+ 'matplotlib', import_kwargs={'fromlist': ['pyplot']},
20
+ catch=(RuntimeError,))
21
+
22
+ numpy = import_module('numpy')
23
+
24
+ tf1 = TransferFunction(1, p**2 + 0.5*p + 2, p)
25
+ tf2 = TransferFunction(p, 6*p**2 + 3*p + 1, p)
26
+ tf3 = TransferFunction(p, p**3 - 1, p)
27
+ tf4 = TransferFunction(10, p**3, p)
28
+ tf5 = TransferFunction(5, s**2 + 2*s + 10, s)
29
+ tf6 = TransferFunction(1, 1, s)
30
+ tf7 = TransferFunction(4*s*3 + 9*s**2 + 0.1*s + 11, 8*s**6 + 9*s**4 + 11, s)
31
+ tf8 = TransferFunction(5, s**2 + (2+I)*s + 10, s)
32
+
33
+ ser1 = Series(tf4, TransferFunction(1, p - 5, p))
34
+ ser2 = Series(tf3, TransferFunction(p, p + 2, p))
35
+
36
+ par1 = Parallel(tf1, tf2)
37
+ par2 = Parallel(tf1, tf2, tf3)
38
+
39
+
40
+ def _to_tuple(a, b):
41
+ return tuple(a), tuple(b)
42
+
43
+ def _trim_tuple(a, b):
44
+ a, b = _to_tuple(a, b)
45
+ return tuple(a[0: 2] + a[len(a)//2 : len(a)//2 + 1] + a[-2:]), \
46
+ tuple(b[0: 2] + b[len(b)//2 : len(b)//2 + 1] + b[-2:])
47
+
48
+ def y_coordinate_equality(plot_data_func, evalf_func, system):
49
+ """Checks whether the y-coordinate value of the plotted
50
+ data point is equal to the value of the function at a
51
+ particular x."""
52
+ x, y = plot_data_func(system)
53
+ x, y = _trim_tuple(x, y)
54
+ y_exp = tuple(evalf_func(system, x_i) for x_i in x)
55
+ return all(Abs(y_exp_i - y_i) < 1e-8 for y_exp_i, y_i in zip(y_exp, y))
56
+
57
+
58
+ def test_errors():
59
+ if not matplotlib:
60
+ skip("Matplotlib not the default backend")
61
+
62
+ # Invalid `system` check
63
+ tfm = TransferFunctionMatrix([[tf6, tf5], [tf5, tf6]])
64
+ expr = 1/(s**2 - 1)
65
+ raises(NotImplementedError, lambda: pole_zero_plot(tfm))
66
+ raises(NotImplementedError, lambda: pole_zero_numerical_data(expr))
67
+ raises(NotImplementedError, lambda: impulse_response_plot(expr))
68
+ raises(NotImplementedError, lambda: impulse_response_numerical_data(tfm))
69
+ raises(NotImplementedError, lambda: step_response_plot(tfm))
70
+ raises(NotImplementedError, lambda: step_response_numerical_data(expr))
71
+ raises(NotImplementedError, lambda: ramp_response_plot(expr))
72
+ raises(NotImplementedError, lambda: ramp_response_numerical_data(tfm))
73
+ raises(NotImplementedError, lambda: bode_plot(tfm))
74
+
75
+ # More than 1 variables
76
+ tf_a = TransferFunction(a, s + 1, s)
77
+ raises(ValueError, lambda: pole_zero_plot(tf_a))
78
+ raises(ValueError, lambda: pole_zero_numerical_data(tf_a))
79
+ raises(ValueError, lambda: impulse_response_plot(tf_a))
80
+ raises(ValueError, lambda: impulse_response_numerical_data(tf_a))
81
+ raises(ValueError, lambda: step_response_plot(tf_a))
82
+ raises(ValueError, lambda: step_response_numerical_data(tf_a))
83
+ raises(ValueError, lambda: ramp_response_plot(tf_a))
84
+ raises(ValueError, lambda: ramp_response_numerical_data(tf_a))
85
+ raises(ValueError, lambda: bode_plot(tf_a))
86
+
87
+ # lower_limit > 0 for response plots
88
+ raises(ValueError, lambda: impulse_response_plot(tf1, lower_limit=-1))
89
+ raises(ValueError, lambda: step_response_plot(tf1, lower_limit=-0.1))
90
+ raises(ValueError, lambda: ramp_response_plot(tf1, lower_limit=-4/3))
91
+
92
+ # slope in ramp_response_plot() is negative
93
+ raises(ValueError, lambda: ramp_response_plot(tf1, slope=-0.1))
94
+
95
+ # incorrect frequency or phase unit
96
+ raises(ValueError, lambda: bode_plot(tf1,freq_unit = 'hz'))
97
+ raises(ValueError, lambda: bode_plot(tf1,phase_unit = 'degree'))
98
+
99
+
100
+ def test_pole_zero():
101
+ if not numpy:
102
+ skip("NumPy is required for this test")
103
+
104
+ def pz_tester(sys, expected_value):
105
+ z, p = pole_zero_numerical_data(sys)
106
+ z_check = numpy.allclose(z, expected_value[0])
107
+ p_check = numpy.allclose(p, expected_value[1])
108
+ return p_check and z_check
109
+
110
+ exp1 = [[], [-0.24999999999999994+1.3919410907075054j, -0.24999999999999994-1.3919410907075054j]]
111
+ exp2 = [[0.0], [-0.25+0.3227486121839514j, -0.25-0.3227486121839514j]]
112
+ exp3 = [[0.0], [-0.5000000000000004+0.8660254037844395j,
113
+ -0.5000000000000004-0.8660254037844395j, 0.9999999999999998+0j]]
114
+ exp4 = [[], [5.0, 0.0, 0.0, 0.0]]
115
+ exp5 = [[-5.645751311064592, -0.5000000000000008, -0.3542486889354093],
116
+ [-0.24999999999999986+1.3919410907075052j,
117
+ -0.24999999999999986-1.3919410907075052j, -0.2499999999999998+0.32274861218395134j,
118
+ -0.2499999999999998-0.32274861218395134j]]
119
+ exp6 = [[], [-1.1641600331447917-3.545808351896439j,
120
+ -0.8358399668552097+2.5458083518964383j]]
121
+
122
+ assert pz_tester(tf1, exp1)
123
+ assert pz_tester(tf2, exp2)
124
+ assert pz_tester(tf3, exp3)
125
+ assert pz_tester(ser1, exp4)
126
+ assert pz_tester(par1, exp5)
127
+ assert pz_tester(tf8, exp6)
128
+
129
+
130
+ def test_bode():
131
+ if not numpy:
132
+ skip("NumPy is required for this test")
133
+
134
+ def bode_phase_evalf(system, point):
135
+ expr = system.to_expr()
136
+ _w = Dummy("w", real=True)
137
+ w_expr = expr.subs({system.var: I*_w})
138
+ return arg(w_expr).subs({_w: point}).evalf()
139
+
140
+ def bode_mag_evalf(system, point):
141
+ expr = system.to_expr()
142
+ _w = Dummy("w", real=True)
143
+ w_expr = expr.subs({system.var: I*_w})
144
+ return 20*log(Abs(w_expr), 10).subs({_w: point}).evalf()
145
+
146
+ def test_bode_data(sys):
147
+ return y_coordinate_equality(bode_magnitude_numerical_data, bode_mag_evalf, sys) \
148
+ and y_coordinate_equality(bode_phase_numerical_data, bode_phase_evalf, sys)
149
+
150
+ assert test_bode_data(tf1)
151
+ assert test_bode_data(tf2)
152
+ assert test_bode_data(tf3)
153
+ assert test_bode_data(tf4)
154
+ assert test_bode_data(tf5)
155
+
156
+
157
+ def check_point_accuracy(a, b):
158
+ return all(isclose(a_i, b_i, rel_tol=10e-12) for \
159
+ a_i, b_i in zip(a, b))
160
+
161
+
162
+ def test_impulse_response():
163
+ if not numpy:
164
+ skip("NumPy is required for this test")
165
+
166
+ def impulse_res_tester(sys, expected_value):
167
+ x, y = _to_tuple(*impulse_response_numerical_data(sys,
168
+ adaptive=False, nb_of_points=10))
169
+ x_check = check_point_accuracy(x, expected_value[0])
170
+ y_check = check_point_accuracy(y, expected_value[1])
171
+ return x_check and y_check
172
+
173
+ exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
174
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
175
+ (0.0, 0.544019738507865, 0.01993849743234938, -0.31140243360893216, -0.022852779906491996, 0.1778306498155759,
176
+ 0.01962941084328499, -0.1013115194573652, -0.014975541213105696, 0.0575789724730714))
177
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
178
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.1666666675, 0.08389223412935855,
179
+ 0.02338051973475047, -0.014966807776379383, -0.034645954223054234, -0.040560075735512804,
180
+ -0.037658628907103885, -0.030149507719590022, -0.021162090730736834, -0.012721292737437523))
181
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
182
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (4.369893391586999e-09, 1.1750333000630964,
183
+ 3.2922404058312473, 9.432290008148343, 28.37098083007151, 86.18577464367974, 261.90356653762115,
184
+ 795.6538758627842, 2416.9920942096983, 7342.159505206647))
185
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
186
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 6.17283950617284, 24.69135802469136,
187
+ 55.555555555555564, 98.76543209876544, 154.320987654321, 222.22222222222226, 302.46913580246917,
188
+ 395.0617283950618, 500.0))
189
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
190
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, -0.10455606138085417,
191
+ 0.06757671513476461, -0.03234567568833768, 0.013582514927757873, -0.005273419510705473,
192
+ 0.0019364083003354075, -0.000680070134067832, 0.00022969845960406913, -7.476094359583917e-05))
193
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
194
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
195
+ (-6.016699583000218e-09, 0.35039802056107394, 3.3728423827689884, 12.119846079276684,
196
+ 25.86101014293389, 29.352480635282088, -30.49475907497664, -273.8717189554019, -863.2381702029659,
197
+ -1747.0262164682233))
198
+ exp7 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335,
199
+ 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779,
200
+ 8.88888888888889, 10.0), (0.0, 18.934638095560974, 5346.93244680907, 1384609.8718249386,
201
+ 358161126.65801865, 92645770015.70108, 23964739753087.42, 6198974342083139.0, 1.603492601616059e+18,
202
+ 4.147764422869658e+20))
203
+
204
+ assert impulse_res_tester(tf1, exp1)
205
+ assert impulse_res_tester(tf2, exp2)
206
+ assert impulse_res_tester(tf3, exp3)
207
+ assert impulse_res_tester(tf4, exp4)
208
+ assert impulse_res_tester(tf5, exp5)
209
+ assert impulse_res_tester(tf7, exp6)
210
+ assert impulse_res_tester(ser1, exp7)
211
+
212
+
213
+ def test_step_response():
214
+ if not numpy:
215
+ skip("NumPy is required for this test")
216
+
217
+ def step_res_tester(sys, expected_value):
218
+ x, y = _to_tuple(*step_response_numerical_data(sys,
219
+ adaptive=False, nb_of_points=10))
220
+ x_check = check_point_accuracy(x, expected_value[0])
221
+ y_check = check_point_accuracy(y, expected_value[1])
222
+ return x_check and y_check
223
+
224
+ exp1 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
225
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
226
+ (-1.9193285738516863e-08, 0.42283495488246126, 0.7840485977945262, 0.5546841805655717,
227
+ 0.33903033806932087, 0.4627251747410237, 0.5909907598988051, 0.5247213989553071,
228
+ 0.4486997874319281, 0.4839358435839171))
229
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
230
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
231
+ (0.0, 0.13728409095645816, 0.19474559355325086, 0.1974909129243011, 0.16841657696573073,
232
+ 0.12559777736159378, 0.08153828016664713, 0.04360471317348958, 0.015072994568868221,
233
+ -0.003636420058445484))
234
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
235
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
236
+ (0.0, 0.6314542141914303, 2.9356520038101035, 9.37731009663807, 28.452300356688376,
237
+ 86.25721933273988, 261.9236645044672, 795.6435410577224, 2416.9786984578764, 7342.154119725917))
238
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
239
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
240
+ (0.0, 2.286236899862826, 18.28989519890261, 61.72839629629631, 146.31916159122088, 285.7796124828532,
241
+ 493.8271703703705, 784.1792566529494, 1170.553292729767, 1666.6667))
242
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
243
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
244
+ (-3.999999997894577e-09, 0.6720357068882895, 0.4429938256137113, 0.5182010838004518,
245
+ 0.4944139147159695, 0.5016379853883338, 0.4995466896527733, 0.5001154784851325,
246
+ 0.49997448824584123, 0.5000039745919259))
247
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
248
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
249
+ (-1.5433688493882158e-09, 0.3428705539937336, 1.1253619102202777, 3.1849962651016517,
250
+ 9.47532757182671, 28.727231099148135, 87.29426924860557, 265.2138681048606, 805.6636260007757,
251
+ 2447.387582370878))
252
+
253
+ assert step_res_tester(tf1, exp1)
254
+ assert step_res_tester(tf2, exp2)
255
+ assert step_res_tester(tf3, exp3)
256
+ assert step_res_tester(tf4, exp4)
257
+ assert step_res_tester(tf5, exp5)
258
+ assert step_res_tester(ser2, exp6)
259
+
260
+
261
+ def test_ramp_response():
262
+ if not numpy:
263
+ skip("NumPy is required for this test")
264
+
265
+ def ramp_res_tester(sys, num_points, expected_value, slope=1):
266
+ x, y = _to_tuple(*ramp_response_numerical_data(sys,
267
+ slope=slope, adaptive=False, nb_of_points=num_points))
268
+ x_check = check_point_accuracy(x, expected_value[0])
269
+ y_check = check_point_accuracy(y, expected_value[1])
270
+ return x_check and y_check
271
+
272
+ exp1 = ((0.0, 2.0, 4.0, 6.0, 8.0, 10.0), (0.0, 0.7324667795033895, 1.9909720978650398,
273
+ 2.7956587704217783, 3.9224897567931514, 4.85022655284895))
274
+ exp2 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445,
275
+ 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0),
276
+ (2.4360213402019326e-08, 0.10175320182493253, 0.33057612497658406, 0.5967937263298935,
277
+ 0.8431511866718248, 1.0398805391471613, 1.1776043125035738, 1.2600994825747305, 1.2981042689274653,
278
+ 1.304684417610106))
279
+ exp3 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
280
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (-3.9329040468771836e-08,
281
+ 0.34686634635794555, 2.9998828170537903, 12.33303690737476, 40.993913948137795, 127.84145222317912,
282
+ 391.41713691996, 1192.0006858708389, 3623.9808672503405, 11011.728034546572))
283
+ exp4 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
284
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.9051973784484078, 30.483158055174524,
285
+ 154.32098765432104, 487.7305288827924, 1190.7483615302544, 2469.1358024691367, 4574.3789056546275,
286
+ 7803.688462124678, 12500.0))
287
+ exp5 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
288
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 3.8844361856975635, 9.141792069209865,
289
+ 14.096349157657231, 19.09783068994694, 24.10179770390321, 29.09907319114121, 34.10040420185154,
290
+ 39.09983919254265, 44.10006013058409))
291
+ exp6 = ((0.0, 1.1111111111111112, 2.2222222222222223, 3.3333333333333335, 4.444444444444445, 5.555555555555555,
292
+ 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0), (0.0, 1.1111111111111112, 2.2222222222222223,
293
+ 3.3333333333333335, 4.444444444444445, 5.555555555555555, 6.666666666666667, 7.777777777777779, 8.88888888888889, 10.0))
294
+
295
+ assert ramp_res_tester(tf1, 6, exp1)
296
+ assert ramp_res_tester(tf2, 10, exp2, 1.2)
297
+ assert ramp_res_tester(tf3, 10, exp3, 1.5)
298
+ assert ramp_res_tester(tf4, 10, exp4, 3)
299
+ assert ramp_res_tester(tf5, 10, exp5, 9)
300
+ assert ramp_res_tester(tf6, 10, exp6)
venv/lib/python3.10/site-packages/sympy/physics/control/tests/test_lti.py ADDED
@@ -0,0 +1,1245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.function import Function
3
+ from sympy.core.mul import Mul
4
+ from sympy.core.numbers import (I, Rational, oo)
5
+ from sympy.core.power import Pow
6
+ from sympy.core.singleton import S
7
+ from sympy.core.symbol import symbols
8
+ from sympy.functions.elementary.exponential import exp
9
+ from sympy.functions.elementary.miscellaneous import sqrt
10
+ from sympy.matrices.dense import eye
11
+ from sympy.polys.polytools import factor
12
+ from sympy.polys.rootoftools import CRootOf
13
+ from sympy.simplify.simplify import simplify
14
+ from sympy.core.containers import Tuple
15
+ from sympy.matrices import ImmutableMatrix, Matrix
16
+ from sympy.physics.control import (TransferFunction, Series, Parallel,
17
+ Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback,
18
+ bilinear, backward_diff)
19
+ from sympy.testing.pytest import raises
20
+
21
+ a, x, b, s, g, d, p, k, a0, a1, a2, b0, b1, b2, tau, zeta, wn, T = symbols('a, x, b, s, g, d, p, k,\
22
+ a0:3, b0:3, tau, zeta, wn, T')
23
+ TF1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
24
+ TF2 = TransferFunction(k, 1, s)
25
+ TF3 = TransferFunction(a2*p - s, a2*s + p, s)
26
+
27
+
28
+ def test_TransferFunction_construction():
29
+ tf = TransferFunction(s + 1, s**2 + s + 1, s)
30
+ assert tf.num == (s + 1)
31
+ assert tf.den == (s**2 + s + 1)
32
+ assert tf.args == (s + 1, s**2 + s + 1, s)
33
+
34
+ tf1 = TransferFunction(s + 4, s - 5, s)
35
+ assert tf1.num == (s + 4)
36
+ assert tf1.den == (s - 5)
37
+ assert tf1.args == (s + 4, s - 5, s)
38
+
39
+ # using different polynomial variables.
40
+ tf2 = TransferFunction(p + 3, p**2 - 9, p)
41
+ assert tf2.num == (p + 3)
42
+ assert tf2.den == (p**2 - 9)
43
+ assert tf2.args == (p + 3, p**2 - 9, p)
44
+
45
+ tf3 = TransferFunction(p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
46
+ assert tf3.args == (p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
47
+
48
+ # no pole-zero cancellation on its own.
49
+ tf4 = TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)
50
+ assert tf4.den == (s - 1)*(s + 5)
51
+ assert tf4.args == ((s + 3)*(s - 1), (s - 1)*(s + 5), s)
52
+
53
+ tf4_ = TransferFunction(p + 2, p + 2, p)
54
+ assert tf4_.args == (p + 2, p + 2, p)
55
+
56
+ tf5 = TransferFunction(s - 1, 4 - p, s)
57
+ assert tf5.args == (s - 1, 4 - p, s)
58
+
59
+ tf5_ = TransferFunction(s - 1, s - 1, s)
60
+ assert tf5_.args == (s - 1, s - 1, s)
61
+
62
+ tf6 = TransferFunction(5, 6, s)
63
+ assert tf6.num == 5
64
+ assert tf6.den == 6
65
+ assert tf6.args == (5, 6, s)
66
+
67
+ tf6_ = TransferFunction(1/2, 4, s)
68
+ assert tf6_.num == 0.5
69
+ assert tf6_.den == 4
70
+ assert tf6_.args == (0.500000000000000, 4, s)
71
+
72
+ tf7 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, s)
73
+ tf8 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, p)
74
+ assert not tf7 == tf8
75
+
76
+ tf7_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
77
+ tf8_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
78
+ assert tf7_ == tf8_
79
+ assert -(-tf7_) == tf7_ == -(-(-(-tf7_)))
80
+
81
+ tf9 = TransferFunction(a*s**3 + b*s**2 + g*s + d, d*p + g*p**2 + g*s, s)
82
+ assert tf9.args == (a*s**3 + b*s**2 + d + g*s, d*p + g*p**2 + g*s, s)
83
+
84
+ tf10 = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
85
+ tf10_ = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
86
+ assert tf10.args == (d + p**3, a + d*s + g*s**2, p)
87
+ assert tf10_ == tf10
88
+
89
+ tf11 = TransferFunction(a1*s + a0, b2*s**2 + b1*s + b0, s)
90
+ assert tf11.num == (a0 + a1*s)
91
+ assert tf11.den == (b0 + b1*s + b2*s**2)
92
+ assert tf11.args == (a0 + a1*s, b0 + b1*s + b2*s**2, s)
93
+
94
+ # when just the numerator is 0, leave the denominator alone.
95
+ tf12 = TransferFunction(0, p**2 - p + 1, p)
96
+ assert tf12.args == (0, p**2 - p + 1, p)
97
+
98
+ tf13 = TransferFunction(0, 1, s)
99
+ assert tf13.args == (0, 1, s)
100
+
101
+ # float exponents
102
+ tf14 = TransferFunction(a0*s**0.5 + a2*s**0.6 - a1, a1*p**(-8.7), s)
103
+ assert tf14.args == (a0*s**0.5 - a1 + a2*s**0.6, a1*p**(-8.7), s)
104
+
105
+ tf15 = TransferFunction(a2**2*p**(1/4) + a1*s**(-4/5), a0*s - p, p)
106
+ assert tf15.args == (a1*s**(-0.8) + a2**2*p**0.25, a0*s - p, p)
107
+
108
+ omega_o, k_p, k_o, k_i = symbols('omega_o, k_p, k_o, k_i')
109
+ tf18 = TransferFunction((k_p + k_o*s + k_i/s), s**2 + 2*omega_o*s + omega_o**2, s)
110
+ assert tf18.num == k_i/s + k_o*s + k_p
111
+ assert tf18.args == (k_i/s + k_o*s + k_p, omega_o**2 + 2*omega_o*s + s**2, s)
112
+
113
+ # ValueError when denominator is zero.
114
+ raises(ValueError, lambda: TransferFunction(4, 0, s))
115
+ raises(ValueError, lambda: TransferFunction(s, 0, s))
116
+ raises(ValueError, lambda: TransferFunction(0, 0, s))
117
+
118
+ raises(TypeError, lambda: TransferFunction(Matrix([1, 2, 3]), s, s))
119
+
120
+ raises(TypeError, lambda: TransferFunction(s**2 + 2*s - 1, s + 3, 3))
121
+ raises(TypeError, lambda: TransferFunction(p + 1, 5 - p, 4))
122
+ raises(TypeError, lambda: TransferFunction(3, 4, 8))
123
+
124
+
125
+ def test_TransferFunction_functions():
126
+ # classmethod from_rational_expression
127
+ expr_1 = Mul(0, Pow(s, -1, evaluate=False), evaluate=False)
128
+ expr_2 = s/0
129
+ expr_3 = (p*s**2 + 5*s)/(s + 1)**3
130
+ expr_4 = 6
131
+ expr_5 = ((2 + 3*s)*(5 + 2*s))/((9 + 3*s)*(5 + 2*s**2))
132
+ expr_6 = (9*s**4 + 4*s**2 + 8)/((s + 1)*(s + 9))
133
+ tf = TransferFunction(s + 1, s**2 + 2, s)
134
+ delay = exp(-s/tau)
135
+ expr_7 = delay*tf.to_expr()
136
+ H1 = TransferFunction.from_rational_expression(expr_7, s)
137
+ H2 = TransferFunction(s + 1, (s**2 + 2)*exp(s/tau), s)
138
+ expr_8 = Add(2, 3*s/(s**2 + 1), evaluate=False)
139
+
140
+ assert TransferFunction.from_rational_expression(expr_1) == TransferFunction(0, s, s)
141
+ raises(ZeroDivisionError, lambda: TransferFunction.from_rational_expression(expr_2))
142
+ raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_3))
143
+ assert TransferFunction.from_rational_expression(expr_3, s) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, s)
144
+ assert TransferFunction.from_rational_expression(expr_3, p) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, p)
145
+ raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_4))
146
+ assert TransferFunction.from_rational_expression(expr_4, s) == TransferFunction(6, 1, s)
147
+ assert TransferFunction.from_rational_expression(expr_5, s) == \
148
+ TransferFunction((2 + 3*s)*(5 + 2*s), (9 + 3*s)*(5 + 2*s**2), s)
149
+ assert TransferFunction.from_rational_expression(expr_6, s) == \
150
+ TransferFunction((9*s**4 + 4*s**2 + 8), (s + 1)*(s + 9), s)
151
+ assert H1 == H2
152
+ assert TransferFunction.from_rational_expression(expr_8, s) == \
153
+ TransferFunction(2*s**2 + 3*s + 2, s**2 + 1, s)
154
+
155
+ # explicitly cancel poles and zeros.
156
+ tf0 = TransferFunction(s**5 + s**3 + s, s - s**2, s)
157
+ a = TransferFunction(-(s**4 + s**2 + 1), s - 1, s)
158
+ assert tf0.simplify() == simplify(tf0) == a
159
+
160
+ tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
161
+ b = TransferFunction(p + 3, p + 5, p)
162
+ assert tf1.simplify() == simplify(tf1) == b
163
+
164
+ # expand the numerator and the denominator.
165
+ G1 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
166
+ G2 = TransferFunction(1, -3, p)
167
+ c = (a2*s**p + a1*s**s + a0*p**p)*(p**s + s**p)
168
+ d = (b0*s**s + b1*p**s)*(b2*s*p + p**p)
169
+ e = a0*p**p*p**s + a0*p**p*s**p + a1*p**s*s**s + a1*s**p*s**s + a2*p**s*s**p + a2*s**(2*p)
170
+ f = b0*b2*p*s*s**s + b0*p**p*s**s + b1*b2*p*p**s*s + b1*p**p*p**s
171
+ g = a1*a2*s*s**p + a1*p*s + a2*b1*p*s*s**p + b1*p**2*s
172
+ G3 = TransferFunction(c, d, s)
173
+ G4 = TransferFunction(a0*s**s - b0*p**p, (a1*s + b1*s*p)*(a2*s**p + p), p)
174
+
175
+ assert G1.expand() == TransferFunction(s**2 - 2*s + 1, s**4 + 2*s**2 + 1, s)
176
+ assert tf1.expand() == TransferFunction(p**2 + 2*p - 3, p**2 + 4*p - 5, p)
177
+ assert G2.expand() == G2
178
+ assert G3.expand() == TransferFunction(e, f, s)
179
+ assert G4.expand() == TransferFunction(a0*s**s - b0*p**p, g, p)
180
+
181
+ # purely symbolic polynomials.
182
+ p1 = a1*s + a0
183
+ p2 = b2*s**2 + b1*s + b0
184
+ SP1 = TransferFunction(p1, p2, s)
185
+ expect1 = TransferFunction(2.0*s + 1.0, 5.0*s**2 + 4.0*s + 3.0, s)
186
+ expect1_ = TransferFunction(2*s + 1, 5*s**2 + 4*s + 3, s)
187
+ assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}) == expect1_
188
+ assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}).evalf() == expect1
189
+ assert expect1_.evalf() == expect1
190
+
191
+ c1, d0, d1, d2 = symbols('c1, d0:3')
192
+ p3, p4 = c1*p, d2*p**3 + d1*p**2 - d0
193
+ SP2 = TransferFunction(p3, p4, p)
194
+ expect2 = TransferFunction(2.0*p, 5.0*p**3 + 2.0*p**2 - 3.0, p)
195
+ expect2_ = TransferFunction(2*p, 5*p**3 + 2*p**2 - 3, p)
196
+ assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}) == expect2_
197
+ assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}).evalf() == expect2
198
+ assert expect2_.evalf() == expect2
199
+
200
+ SP3 = TransferFunction(a0*p**3 + a1*s**2 - b0*s + b1, a1*s + p, s)
201
+ expect3 = TransferFunction(2.0*p**3 + 4.0*s**2 - s + 5.0, p + 4.0*s, s)
202
+ expect3_ = TransferFunction(2*p**3 + 4*s**2 - s + 5, p + 4*s, s)
203
+ assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}) == expect3_
204
+ assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}).evalf() == expect3
205
+ assert expect3_.evalf() == expect3
206
+
207
+ SP4 = TransferFunction(s - a1*p**3, a0*s + p, p)
208
+ expect4 = TransferFunction(7.0*p**3 + s, p - s, p)
209
+ expect4_ = TransferFunction(7*p**3 + s, p - s, p)
210
+ assert SP4.subs({a0: -1, a1: -7}) == expect4_
211
+ assert SP4.subs({a0: -1, a1: -7}).evalf() == expect4
212
+ assert expect4_.evalf() == expect4
213
+
214
+ # Low-frequency (or DC) gain.
215
+ assert tf0.dc_gain() == 1
216
+ assert tf1.dc_gain() == Rational(3, 5)
217
+ assert SP2.dc_gain() == 0
218
+ assert expect4.dc_gain() == -1
219
+ assert expect2_.dc_gain() == 0
220
+ assert TransferFunction(1, s, s).dc_gain() == oo
221
+
222
+ # Poles of a transfer function.
223
+ tf_ = TransferFunction(x**3 - k, k, x)
224
+ _tf = TransferFunction(k, x**4 - k, x)
225
+ TF_ = TransferFunction(x**2, x**10 + x + x**2, x)
226
+ _TF = TransferFunction(x**10 + x + x**2, x**2, x)
227
+ assert G1.poles() == [I, I, -I, -I]
228
+ assert G2.poles() == []
229
+ assert tf1.poles() == [-5, 1]
230
+ assert expect4_.poles() == [s]
231
+ assert SP4.poles() == [-a0*s]
232
+ assert expect3.poles() == [-0.25*p]
233
+ assert str(expect2.poles()) == str([0.729001428685125, -0.564500714342563 - 0.710198984796332*I, -0.564500714342563 + 0.710198984796332*I])
234
+ assert str(expect1.poles()) == str([-0.4 - 0.66332495807108*I, -0.4 + 0.66332495807108*I])
235
+ assert _tf.poles() == [k**(Rational(1, 4)), -k**(Rational(1, 4)), I*k**(Rational(1, 4)), -I*k**(Rational(1, 4))]
236
+ assert TF_.poles() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
237
+ CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
238
+ CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
239
+ raises(NotImplementedError, lambda: TransferFunction(x**2, a0*x**10 + x + x**2, x).poles())
240
+
241
+ # Stability of a transfer function.
242
+ q, r = symbols('q, r', negative=True)
243
+ t = symbols('t', positive=True)
244
+ TF_ = TransferFunction(s**2 + a0 - a1*p, q*s - r, s)
245
+ stable_tf = TransferFunction(s**2 + a0 - a1*p, q*s - 1, s)
246
+ stable_tf_ = TransferFunction(s**2 + a0 - a1*p, q*s - t, s)
247
+
248
+ assert G1.is_stable() is False
249
+ assert G2.is_stable() is True
250
+ assert tf1.is_stable() is False # as one pole is +ve, and the other is -ve.
251
+ assert expect2.is_stable() is False
252
+ assert expect1.is_stable() is True
253
+ assert stable_tf.is_stable() is True
254
+ assert stable_tf_.is_stable() is True
255
+ assert TF_.is_stable() is False
256
+ assert expect4_.is_stable() is None # no assumption provided for the only pole 's'.
257
+ assert SP4.is_stable() is None
258
+
259
+ # Zeros of a transfer function.
260
+ assert G1.zeros() == [1, 1]
261
+ assert G2.zeros() == []
262
+ assert tf1.zeros() == [-3, 1]
263
+ assert expect4_.zeros() == [7**(Rational(2, 3))*(-s)**(Rational(1, 3))/7, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 -
264
+ sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 + sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14]
265
+ assert SP4.zeros() == [(s/a1)**(Rational(1, 3)), -(s/a1)**(Rational(1, 3))/2 - sqrt(3)*I*(s/a1)**(Rational(1, 3))/2,
266
+ -(s/a1)**(Rational(1, 3))/2 + sqrt(3)*I*(s/a1)**(Rational(1, 3))/2]
267
+ assert str(expect3.zeros()) == str([0.125 - 1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0),
268
+ 1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0) + 0.125])
269
+ assert tf_.zeros() == [k**(Rational(1, 3)), -k**(Rational(1, 3))/2 - sqrt(3)*I*k**(Rational(1, 3))/2,
270
+ -k**(Rational(1, 3))/2 + sqrt(3)*I*k**(Rational(1, 3))/2]
271
+ assert _TF.zeros() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
272
+ CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
273
+ CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
274
+ raises(NotImplementedError, lambda: TransferFunction(a0*x**10 + x + x**2, x**2, x).zeros())
275
+
276
+ # negation of TF.
277
+ tf2 = TransferFunction(s + 3, s**2 - s**3 + 9, s)
278
+ tf3 = TransferFunction(-3*p + 3, 1 - p, p)
279
+ assert -tf2 == TransferFunction(-s - 3, s**2 - s**3 + 9, s)
280
+ assert -tf3 == TransferFunction(3*p - 3, 1 - p, p)
281
+
282
+ # taking power of a TF.
283
+ tf4 = TransferFunction(p + 4, p - 3, p)
284
+ tf5 = TransferFunction(s**2 + 1, 1 - s, s)
285
+ expect2 = TransferFunction((s**2 + 1)**3, (1 - s)**3, s)
286
+ expect1 = TransferFunction((p + 4)**2, (p - 3)**2, p)
287
+ assert (tf4*tf4).doit() == tf4**2 == pow(tf4, 2) == expect1
288
+ assert (tf5*tf5*tf5).doit() == tf5**3 == pow(tf5, 3) == expect2
289
+ assert tf5**0 == pow(tf5, 0) == TransferFunction(1, 1, s)
290
+ assert Series(tf4).doit()**-1 == tf4**-1 == pow(tf4, -1) == TransferFunction(p - 3, p + 4, p)
291
+ assert (tf5*tf5).doit()**-1 == tf5**-2 == pow(tf5, -2) == TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
292
+
293
+ raises(ValueError, lambda: tf4**(s**2 + s - 1))
294
+ raises(ValueError, lambda: tf5**s)
295
+ raises(ValueError, lambda: tf4**tf5)
296
+
297
+ # SymPy's own functions.
298
+ tf = TransferFunction(s - 1, s**2 - 2*s + 1, s)
299
+ tf6 = TransferFunction(s + p, p**2 - 5, s)
300
+ assert factor(tf) == TransferFunction(s - 1, (s - 1)**2, s)
301
+ assert tf.num.subs(s, 2) == tf.den.subs(s, 2) == 1
302
+ # subs & xreplace
303
+ assert tf.subs(s, 2) == TransferFunction(s - 1, s**2 - 2*s + 1, s)
304
+ assert tf6.subs(p, 3) == TransferFunction(s + 3, 4, s)
305
+ assert tf3.xreplace({p: s}) == TransferFunction(-3*s + 3, 1 - s, s)
306
+ raises(TypeError, lambda: tf3.xreplace({p: exp(2)}))
307
+ assert tf3.subs(p, exp(2)) == tf3
308
+
309
+ tf7 = TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
310
+ assert tf7.xreplace({s: k}) == TransferFunction(a0*k**p + a1*p**k, a2*p - k, k)
311
+ assert tf7.subs(s, k) == TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
312
+
313
+ # Conversion to Expr with to_expr()
314
+ tf8 = TransferFunction(a0*s**5 + 5*s**2 + 3, s**6 - 3, s)
315
+ tf9 = TransferFunction((5 + s), (5 + s)*(6 + s), s)
316
+ tf10 = TransferFunction(0, 1, s)
317
+ tf11 = TransferFunction(1, 1, s)
318
+ assert tf8.to_expr() == Mul((a0*s**5 + 5*s**2 + 3), Pow((s**6 - 3), -1, evaluate=False), evaluate=False)
319
+ assert tf9.to_expr() == Mul((s + 5), Pow((5 + s)*(6 + s), -1, evaluate=False), evaluate=False)
320
+ assert tf10.to_expr() == Mul(S(0), Pow(1, -1, evaluate=False), evaluate=False)
321
+ assert tf11.to_expr() == Pow(1, -1, evaluate=False)
322
+
323
+ def test_TransferFunction_addition_and_subtraction():
324
+ tf1 = TransferFunction(s + 6, s - 5, s)
325
+ tf2 = TransferFunction(s + 3, s + 1, s)
326
+ tf3 = TransferFunction(s + 1, s**2 + s + 1, s)
327
+ tf4 = TransferFunction(p, 2 - p, p)
328
+
329
+ # addition
330
+ assert tf1 + tf2 == Parallel(tf1, tf2)
331
+ assert tf3 + tf1 == Parallel(tf3, tf1)
332
+ assert -tf1 + tf2 + tf3 == Parallel(-tf1, tf2, tf3)
333
+ assert tf1 + (tf2 + tf3) == Parallel(tf1, tf2, tf3)
334
+
335
+ c = symbols("c", commutative=False)
336
+ raises(ValueError, lambda: tf1 + Matrix([1, 2, 3]))
337
+ raises(ValueError, lambda: tf2 + c)
338
+ raises(ValueError, lambda: tf3 + tf4)
339
+ raises(ValueError, lambda: tf1 + (s - 1))
340
+ raises(ValueError, lambda: tf1 + 8)
341
+ raises(ValueError, lambda: (1 - p**3) + tf1)
342
+
343
+ # subtraction
344
+ assert tf1 - tf2 == Parallel(tf1, -tf2)
345
+ assert tf3 - tf2 == Parallel(tf3, -tf2)
346
+ assert -tf1 - tf3 == Parallel(-tf1, -tf3)
347
+ assert tf1 - tf2 + tf3 == Parallel(tf1, -tf2, tf3)
348
+
349
+ raises(ValueError, lambda: tf1 - Matrix([1, 2, 3]))
350
+ raises(ValueError, lambda: tf3 - tf4)
351
+ raises(ValueError, lambda: tf1 - (s - 1))
352
+ raises(ValueError, lambda: tf1 - 8)
353
+ raises(ValueError, lambda: (s + 5) - tf2)
354
+ raises(ValueError, lambda: (1 + p**4) - tf1)
355
+
356
+
357
+ def test_TransferFunction_multiplication_and_division():
358
+ G1 = TransferFunction(s + 3, -s**3 + 9, s)
359
+ G2 = TransferFunction(s + 1, s - 5, s)
360
+ G3 = TransferFunction(p, p**4 - 6, p)
361
+ G4 = TransferFunction(p + 4, p - 5, p)
362
+ G5 = TransferFunction(s + 6, s - 5, s)
363
+ G6 = TransferFunction(s + 3, s + 1, s)
364
+ G7 = TransferFunction(1, 1, s)
365
+
366
+ # multiplication
367
+ assert G1*G2 == Series(G1, G2)
368
+ assert -G1*G5 == Series(-G1, G5)
369
+ assert -G2*G5*-G6 == Series(-G2, G5, -G6)
370
+ assert -G1*-G2*-G5*-G6 == Series(-G1, -G2, -G5, -G6)
371
+ assert G3*G4 == Series(G3, G4)
372
+ assert (G1*G2)*-(G5*G6) == \
373
+ Series(G1, G2, TransferFunction(-1, 1, s), Series(G5, G6))
374
+ assert G1*G2*(G5 + G6) == Series(G1, G2, Parallel(G5, G6))
375
+
376
+ c = symbols("c", commutative=False)
377
+ raises(ValueError, lambda: G3 * Matrix([1, 2, 3]))
378
+ raises(ValueError, lambda: G1 * c)
379
+ raises(ValueError, lambda: G3 * G5)
380
+ raises(ValueError, lambda: G5 * (s - 1))
381
+ raises(ValueError, lambda: 9 * G5)
382
+
383
+ raises(ValueError, lambda: G3 / Matrix([1, 2, 3]))
384
+ raises(ValueError, lambda: G6 / 0)
385
+ raises(ValueError, lambda: G3 / G5)
386
+ raises(ValueError, lambda: G5 / 2)
387
+ raises(ValueError, lambda: G5 / s**2)
388
+ raises(ValueError, lambda: (s - 4*s**2) / G2)
389
+ raises(ValueError, lambda: 0 / G4)
390
+ raises(ValueError, lambda: G5 / G6)
391
+ raises(ValueError, lambda: -G3 /G4)
392
+ raises(ValueError, lambda: G7 / (1 + G6))
393
+ raises(ValueError, lambda: G7 / (G5 * G6))
394
+ raises(ValueError, lambda: G7 / (G7 + (G5 + G6)))
395
+
396
+
397
+ def test_TransferFunction_is_proper():
398
+ omega_o, zeta, tau = symbols('omega_o, zeta, tau')
399
+ G1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
400
+ G2 = TransferFunction(tau - s**3, tau + p**4, tau)
401
+ G3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
402
+ G4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
403
+ assert G1.is_proper
404
+ assert G2.is_proper
405
+ assert G3.is_proper
406
+ assert not G4.is_proper
407
+
408
+
409
+ def test_TransferFunction_is_strictly_proper():
410
+ omega_o, zeta, tau = symbols('omega_o, zeta, tau')
411
+ tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
412
+ tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
413
+ tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
414
+ tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
415
+ assert not tf1.is_strictly_proper
416
+ assert not tf2.is_strictly_proper
417
+ assert tf3.is_strictly_proper
418
+ assert not tf4.is_strictly_proper
419
+
420
+
421
+ def test_TransferFunction_is_biproper():
422
+ tau, omega_o, zeta = symbols('tau, omega_o, zeta')
423
+ tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
424
+ tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
425
+ tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
426
+ tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
427
+ assert tf1.is_biproper
428
+ assert tf2.is_biproper
429
+ assert not tf3.is_biproper
430
+ assert not tf4.is_biproper
431
+
432
+
433
+ def test_Series_construction():
434
+ tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
435
+ tf2 = TransferFunction(a2*p - s, a2*s + p, s)
436
+ tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
437
+ tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
438
+ inp = Function('X_d')(s)
439
+ out = Function('X')(s)
440
+
441
+ s0 = Series(tf, tf2)
442
+ assert s0.args == (tf, tf2)
443
+ assert s0.var == s
444
+
445
+ s1 = Series(Parallel(tf, -tf2), tf2)
446
+ assert s1.args == (Parallel(tf, -tf2), tf2)
447
+ assert s1.var == s
448
+
449
+ tf3_ = TransferFunction(inp, 1, s)
450
+ tf4_ = TransferFunction(-out, 1, s)
451
+ s2 = Series(tf, Parallel(tf3_, tf4_), tf2)
452
+ assert s2.args == (tf, Parallel(tf3_, tf4_), tf2)
453
+
454
+ s3 = Series(tf, tf2, tf4)
455
+ assert s3.args == (tf, tf2, tf4)
456
+
457
+ s4 = Series(tf3_, tf4_)
458
+ assert s4.args == (tf3_, tf4_)
459
+ assert s4.var == s
460
+
461
+ s6 = Series(tf2, tf4, Parallel(tf2, -tf), tf4)
462
+ assert s6.args == (tf2, tf4, Parallel(tf2, -tf), tf4)
463
+
464
+ s7 = Series(tf, tf2)
465
+ assert s0 == s7
466
+ assert not s0 == s2
467
+
468
+ raises(ValueError, lambda: Series(tf, tf3))
469
+ raises(ValueError, lambda: Series(tf, tf2, tf3, tf4))
470
+ raises(ValueError, lambda: Series(-tf3, tf2))
471
+ raises(TypeError, lambda: Series(2, tf, tf4))
472
+ raises(TypeError, lambda: Series(s**2 + p*s, tf3, tf2))
473
+ raises(TypeError, lambda: Series(tf3, Matrix([1, 2, 3, 4])))
474
+
475
+
476
+ def test_MIMOSeries_construction():
477
+ tf_1 = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
478
+ tf_2 = TransferFunction(a2*p - s, a2*s + p, s)
479
+ tf_3 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
480
+
481
+ tfm_1 = TransferFunctionMatrix([[tf_1, tf_2, tf_3], [-tf_3, -tf_2, tf_1]])
482
+ tfm_2 = TransferFunctionMatrix([[-tf_2], [-tf_2], [-tf_3]])
483
+ tfm_3 = TransferFunctionMatrix([[-tf_3]])
484
+ tfm_4 = TransferFunctionMatrix([[TF3], [TF2], [-TF1]])
485
+ tfm_5 = TransferFunctionMatrix.from_Matrix(Matrix([1/p]), p)
486
+
487
+ s8 = MIMOSeries(tfm_2, tfm_1)
488
+ assert s8.args == (tfm_2, tfm_1)
489
+ assert s8.var == s
490
+ assert s8.shape == (s8.num_outputs, s8.num_inputs) == (2, 1)
491
+
492
+ s9 = MIMOSeries(tfm_3, tfm_2, tfm_1)
493
+ assert s9.args == (tfm_3, tfm_2, tfm_1)
494
+ assert s9.var == s
495
+ assert s9.shape == (s9.num_outputs, s9.num_inputs) == (2, 1)
496
+
497
+ s11 = MIMOSeries(tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
498
+ assert s11.args == (tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
499
+ assert s11.shape == (s11.num_outputs, s11.num_inputs) == (2, 1)
500
+
501
+ # arg cannot be empty tuple.
502
+ raises(ValueError, lambda: MIMOSeries())
503
+
504
+ # arg cannot contain SISO as well as MIMO systems.
505
+ raises(TypeError, lambda: MIMOSeries(tfm_1, tf_1))
506
+
507
+ # for all the adjacent transfer function matrices:
508
+ # no. of inputs of first TFM must be equal to the no. of outputs of the second TFM.
509
+ raises(ValueError, lambda: MIMOSeries(tfm_1, tfm_2, -tfm_1))
510
+
511
+ # all the TFMs must use the same complex variable.
512
+ raises(ValueError, lambda: MIMOSeries(tfm_3, tfm_5))
513
+
514
+ # Number or expression not allowed in the arguments.
515
+ raises(TypeError, lambda: MIMOSeries(2, tfm_2, tfm_3))
516
+ raises(TypeError, lambda: MIMOSeries(s**2 + p*s, -tfm_2, tfm_3))
517
+ raises(TypeError, lambda: MIMOSeries(Matrix([1/p]), tfm_3))
518
+
519
+
520
+ def test_Series_functions():
521
+ tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
522
+ tf2 = TransferFunction(k, 1, s)
523
+ tf3 = TransferFunction(a2*p - s, a2*s + p, s)
524
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
525
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
526
+
527
+ assert tf1*tf2*tf3 == Series(tf1, tf2, tf3) == Series(Series(tf1, tf2), tf3) \
528
+ == Series(tf1, Series(tf2, tf3))
529
+ assert tf1*(tf2 + tf3) == Series(tf1, Parallel(tf2, tf3))
530
+ assert tf1*tf2 + tf5 == Parallel(Series(tf1, tf2), tf5)
531
+ assert tf1*tf2 - tf5 == Parallel(Series(tf1, tf2), -tf5)
532
+ assert tf1*tf2 + tf3 + tf5 == Parallel(Series(tf1, tf2), tf3, tf5)
533
+ assert tf1*tf2 - tf3 - tf5 == Parallel(Series(tf1, tf2), -tf3, -tf5)
534
+ assert tf1*tf2 - tf3 + tf5 == Parallel(Series(tf1, tf2), -tf3, tf5)
535
+ assert tf1*tf2 + tf3*tf5 == Parallel(Series(tf1, tf2), Series(tf3, tf5))
536
+ assert tf1*tf2 - tf3*tf5 == Parallel(Series(tf1, tf2), Series(TransferFunction(-1, 1, s), Series(tf3, tf5)))
537
+ assert tf2*tf3*(tf2 - tf1)*tf3 == Series(tf2, tf3, Parallel(tf2, -tf1), tf3)
538
+ assert -tf1*tf2 == Series(-tf1, tf2)
539
+ assert -(tf1*tf2) == Series(TransferFunction(-1, 1, s), Series(tf1, tf2))
540
+ raises(ValueError, lambda: tf1*tf2*tf4)
541
+ raises(ValueError, lambda: tf1*(tf2 - tf4))
542
+ raises(ValueError, lambda: tf3*Matrix([1, 2, 3]))
543
+
544
+ # evaluate=True -> doit()
545
+ assert Series(tf1, tf2, evaluate=True) == Series(tf1, tf2).doit() == \
546
+ TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
547
+ assert Series(tf1, tf2, Parallel(tf1, -tf3), evaluate=True) == Series(tf1, tf2, Parallel(tf1, -tf3)).doit() == \
548
+ TransferFunction(k*(a2*s + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2, s)
549
+ assert Series(tf2, tf1, -tf3, evaluate=True) == Series(tf2, tf1, -tf3).doit() == \
550
+ TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
551
+ assert not Series(tf1, -tf2, evaluate=False) == Series(tf1, -tf2).doit()
552
+
553
+ assert Series(Parallel(tf1, tf2), Parallel(tf2, -tf3)).doit() == \
554
+ TransferFunction((k*(s**2 + 2*s*wn*zeta + wn**2) + 1)*(-a2*p + k*(a2*s + p) + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
555
+ assert Series(-tf1, -tf2, -tf3).doit() == \
556
+ TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
557
+ assert -Series(tf1, tf2, tf3).doit() == \
558
+ TransferFunction(-k*(a2*p - s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
559
+ assert Series(tf2, tf3, Parallel(tf2, -tf1), tf3).doit() == \
560
+ TransferFunction(k*(a2*p - s)**2*(k*(s**2 + 2*s*wn*zeta + wn**2) - 1), (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2), s)
561
+
562
+ assert Series(tf1, tf2).rewrite(TransferFunction) == TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
563
+ assert Series(tf2, tf1, -tf3).rewrite(TransferFunction) == \
564
+ TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
565
+
566
+ S1 = Series(Parallel(tf1, tf2), Parallel(tf2, -tf3))
567
+ assert S1.is_proper
568
+ assert not S1.is_strictly_proper
569
+ assert S1.is_biproper
570
+
571
+ S2 = Series(tf1, tf2, tf3)
572
+ assert S2.is_proper
573
+ assert S2.is_strictly_proper
574
+ assert not S2.is_biproper
575
+
576
+ S3 = Series(tf1, -tf2, Parallel(tf1, -tf3))
577
+ assert S3.is_proper
578
+ assert S3.is_strictly_proper
579
+ assert not S3.is_biproper
580
+
581
+
582
+ def test_MIMOSeries_functions():
583
+ tfm1 = TransferFunctionMatrix([[TF1, TF2, TF3], [-TF3, -TF2, TF1]])
584
+ tfm2 = TransferFunctionMatrix([[-TF1], [-TF2], [-TF3]])
585
+ tfm3 = TransferFunctionMatrix([[-TF1]])
586
+ tfm4 = TransferFunctionMatrix([[-TF2, -TF3], [-TF1, TF2]])
587
+ tfm5 = TransferFunctionMatrix([[TF2, -TF2], [-TF3, -TF2]])
588
+ tfm6 = TransferFunctionMatrix([[-TF3], [TF1]])
589
+ tfm7 = TransferFunctionMatrix([[TF1], [-TF2]])
590
+
591
+ assert tfm1*tfm2 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm6)
592
+ assert tfm1*tfm2 + tfm7 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm7, tfm6)
593
+ assert tfm1*tfm2 - tfm6 - tfm7 == MIMOParallel(MIMOSeries(tfm2, tfm1), -tfm6, -tfm7)
594
+ assert tfm4*tfm5 + (tfm4 - tfm5) == MIMOParallel(MIMOSeries(tfm5, tfm4), tfm4, -tfm5)
595
+ assert tfm4*-tfm6 + (-tfm4*tfm6) == MIMOParallel(MIMOSeries(-tfm6, tfm4), MIMOSeries(tfm6, -tfm4))
596
+
597
+ raises(ValueError, lambda: tfm1*tfm2 + TF1)
598
+ raises(TypeError, lambda: tfm1*tfm2 + a0)
599
+ raises(TypeError, lambda: tfm4*tfm6 - (s - 1))
600
+ raises(TypeError, lambda: tfm4*-tfm6 - 8)
601
+ raises(TypeError, lambda: (-1 + p**5) + tfm1*tfm2)
602
+
603
+ # Shape criteria.
604
+
605
+ raises(TypeError, lambda: -tfm1*tfm2 + tfm4)
606
+ raises(TypeError, lambda: tfm1*tfm2 - tfm4 + tfm5)
607
+ raises(TypeError, lambda: tfm1*tfm2 - tfm4*tfm5)
608
+
609
+ assert tfm1*tfm2*-tfm3 == MIMOSeries(-tfm3, tfm2, tfm1)
610
+ assert (tfm1*-tfm2)*tfm3 == MIMOSeries(tfm3, -tfm2, tfm1)
611
+
612
+ # Multiplication of a Series object with a SISO TF not allowed.
613
+
614
+ raises(ValueError, lambda: tfm4*tfm5*TF1)
615
+ raises(TypeError, lambda: tfm4*tfm5*a1)
616
+ raises(TypeError, lambda: tfm4*-tfm5*(s - 2))
617
+ raises(TypeError, lambda: tfm5*tfm4*9)
618
+ raises(TypeError, lambda: (-p**3 + 1)*tfm5*tfm4)
619
+
620
+ # Transfer function matrix in the arguments.
621
+ assert (MIMOSeries(tfm2, tfm1, evaluate=True) == MIMOSeries(tfm2, tfm1).doit()
622
+ == TransferFunctionMatrix(((TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2)**2 - (a2*s + p)**2,
623
+ (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),),
624
+ (TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
625
+ (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),))))
626
+
627
+ # doit() should not cancel poles and zeros.
628
+ mat_1 = Matrix([[1/(1+s), (1+s)/(1+s**2+2*s)**3]])
629
+ mat_2 = Matrix([[(1+s)], [(1+s**2+2*s)**3/(1+s)]])
630
+ tm_1, tm_2 = TransferFunctionMatrix.from_Matrix(mat_1, s), TransferFunctionMatrix.from_Matrix(mat_2, s)
631
+ assert (MIMOSeries(tm_2, tm_1).doit()
632
+ == TransferFunctionMatrix(((TransferFunction(2*(s + 1)**2*(s**2 + 2*s + 1)**3, (s + 1)**2*(s**2 + 2*s + 1)**3, s),),)))
633
+ assert MIMOSeries(tm_2, tm_1).doit().simplify() == TransferFunctionMatrix(((TransferFunction(2, 1, s),),))
634
+
635
+ # calling doit() will expand the internal Series and Parallel objects.
636
+ assert (MIMOSeries(-tfm3, -tfm2, tfm1, evaluate=True)
637
+ == MIMOSeries(-tfm3, -tfm2, tfm1).doit()
638
+ == TransferFunctionMatrix(((TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*p - s)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*s + p)**2,
639
+ (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),),
640
+ (TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
641
+ (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),))))
642
+ assert (MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5, evaluate=True)
643
+ == MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).doit()
644
+ == TransferFunctionMatrix(((TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), TransferFunction(k*(-a2*p - \
645
+ k*(a2*s + p) + s), a2*s + p, s)), (TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), \
646
+ TransferFunction((-a2*p + s)*(-a2*p - k*(a2*s + p) + s), (a2*s + p)**2, s)))) == MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).rewrite(TransferFunctionMatrix))
647
+
648
+
649
+ def test_Parallel_construction():
650
+ tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
651
+ tf2 = TransferFunction(a2*p - s, a2*s + p, s)
652
+ tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
653
+ tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
654
+ inp = Function('X_d')(s)
655
+ out = Function('X')(s)
656
+
657
+ p0 = Parallel(tf, tf2)
658
+ assert p0.args == (tf, tf2)
659
+ assert p0.var == s
660
+
661
+ p1 = Parallel(Series(tf, -tf2), tf2)
662
+ assert p1.args == (Series(tf, -tf2), tf2)
663
+ assert p1.var == s
664
+
665
+ tf3_ = TransferFunction(inp, 1, s)
666
+ tf4_ = TransferFunction(-out, 1, s)
667
+ p2 = Parallel(tf, Series(tf3_, -tf4_), tf2)
668
+ assert p2.args == (tf, Series(tf3_, -tf4_), tf2)
669
+
670
+ p3 = Parallel(tf, tf2, tf4)
671
+ assert p3.args == (tf, tf2, tf4)
672
+
673
+ p4 = Parallel(tf3_, tf4_)
674
+ assert p4.args == (tf3_, tf4_)
675
+ assert p4.var == s
676
+
677
+ p5 = Parallel(tf, tf2)
678
+ assert p0 == p5
679
+ assert not p0 == p1
680
+
681
+ p6 = Parallel(tf2, tf4, Series(tf2, -tf4))
682
+ assert p6.args == (tf2, tf4, Series(tf2, -tf4))
683
+
684
+ p7 = Parallel(tf2, tf4, Series(tf2, -tf), tf4)
685
+ assert p7.args == (tf2, tf4, Series(tf2, -tf), tf4)
686
+
687
+ raises(ValueError, lambda: Parallel(tf, tf3))
688
+ raises(ValueError, lambda: Parallel(tf, tf2, tf3, tf4))
689
+ raises(ValueError, lambda: Parallel(-tf3, tf4))
690
+ raises(TypeError, lambda: Parallel(2, tf, tf4))
691
+ raises(TypeError, lambda: Parallel(s**2 + p*s, tf3, tf2))
692
+ raises(TypeError, lambda: Parallel(tf3, Matrix([1, 2, 3, 4])))
693
+
694
+
695
+ def test_MIMOParallel_construction():
696
+ tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
697
+ tfm2 = TransferFunctionMatrix([[-TF3], [TF2], [TF1]])
698
+ tfm3 = TransferFunctionMatrix([[TF1]])
699
+ tfm4 = TransferFunctionMatrix([[TF2], [TF1], [TF3]])
700
+ tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF2, TF1]])
701
+ tfm6 = TransferFunctionMatrix([[TF2, TF1], [TF1, TF2]])
702
+ tfm7 = TransferFunctionMatrix.from_Matrix(Matrix([[1/p]]), p)
703
+
704
+ p8 = MIMOParallel(tfm1, tfm2)
705
+ assert p8.args == (tfm1, tfm2)
706
+ assert p8.var == s
707
+ assert p8.shape == (p8.num_outputs, p8.num_inputs) == (3, 1)
708
+
709
+ p9 = MIMOParallel(MIMOSeries(tfm3, tfm1), tfm2)
710
+ assert p9.args == (MIMOSeries(tfm3, tfm1), tfm2)
711
+ assert p9.var == s
712
+ assert p9.shape == (p9.num_outputs, p9.num_inputs) == (3, 1)
713
+
714
+ p10 = MIMOParallel(tfm1, MIMOSeries(tfm3, tfm4), tfm2)
715
+ assert p10.args == (tfm1, MIMOSeries(tfm3, tfm4), tfm2)
716
+ assert p10.var == s
717
+ assert p10.shape == (p10.num_outputs, p10.num_inputs) == (3, 1)
718
+
719
+ p11 = MIMOParallel(tfm2, tfm1, tfm4)
720
+ assert p11.args == (tfm2, tfm1, tfm4)
721
+ assert p11.shape == (p11.num_outputs, p11.num_inputs) == (3, 1)
722
+
723
+ p12 = MIMOParallel(tfm6, tfm5)
724
+ assert p12.args == (tfm6, tfm5)
725
+ assert p12.shape == (p12.num_outputs, p12.num_inputs) == (2, 2)
726
+
727
+ p13 = MIMOParallel(tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
728
+ assert p13.args == (tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
729
+ assert p13.shape == (p13.num_outputs, p13.num_inputs) == (3, 1)
730
+
731
+ # arg cannot be empty tuple.
732
+ raises(TypeError, lambda: MIMOParallel(()))
733
+
734
+ # arg cannot contain SISO as well as MIMO systems.
735
+ raises(TypeError, lambda: MIMOParallel(tfm1, tfm2, TF1))
736
+
737
+ # all TFMs must have same shapes.
738
+ raises(TypeError, lambda: MIMOParallel(tfm1, tfm3, tfm4))
739
+
740
+ # all TFMs must be using the same complex variable.
741
+ raises(ValueError, lambda: MIMOParallel(tfm3, tfm7))
742
+
743
+ # Number or expression not allowed in the arguments.
744
+ raises(TypeError, lambda: MIMOParallel(2, tfm1, tfm4))
745
+ raises(TypeError, lambda: MIMOParallel(s**2 + p*s, -tfm4, tfm2))
746
+
747
+
748
+ def test_Parallel_functions():
749
+ tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
750
+ tf2 = TransferFunction(k, 1, s)
751
+ tf3 = TransferFunction(a2*p - s, a2*s + p, s)
752
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
753
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
754
+
755
+ assert tf1 + tf2 + tf3 == Parallel(tf1, tf2, tf3)
756
+ assert tf1 + tf2 + tf3 + tf5 == Parallel(tf1, tf2, tf3, tf5)
757
+ assert tf1 + tf2 - tf3 - tf5 == Parallel(tf1, tf2, -tf3, -tf5)
758
+ assert tf1 + tf2*tf3 == Parallel(tf1, Series(tf2, tf3))
759
+ assert tf1 - tf2*tf3 == Parallel(tf1, -Series(tf2,tf3))
760
+ assert -tf1 - tf2 == Parallel(-tf1, -tf2)
761
+ assert -(tf1 + tf2) == Series(TransferFunction(-1, 1, s), Parallel(tf1, tf2))
762
+ assert (tf2 + tf3)*tf1 == Series(Parallel(tf2, tf3), tf1)
763
+ assert (tf1 + tf2)*(tf3*tf5) == Series(Parallel(tf1, tf2), tf3, tf5)
764
+ assert -(tf2 + tf3)*-tf5 == Series(TransferFunction(-1, 1, s), Parallel(tf2, tf3), -tf5)
765
+ assert tf2 + tf3 + tf2*tf1 + tf5 == Parallel(tf2, tf3, Series(tf2, tf1), tf5)
766
+ assert tf2 + tf3 + tf2*tf1 - tf3 == Parallel(tf2, tf3, Series(tf2, tf1), -tf3)
767
+ assert (tf1 + tf2 + tf5)*(tf3 + tf5) == Series(Parallel(tf1, tf2, tf5), Parallel(tf3, tf5))
768
+ raises(ValueError, lambda: tf1 + tf2 + tf4)
769
+ raises(ValueError, lambda: tf1 - tf2*tf4)
770
+ raises(ValueError, lambda: tf3 + Matrix([1, 2, 3]))
771
+
772
+ # evaluate=True -> doit()
773
+ assert Parallel(tf1, tf2, evaluate=True) == Parallel(tf1, tf2).doit() == \
774
+ TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
775
+ assert Parallel(tf1, tf2, Series(-tf1, tf3), evaluate=True) == \
776
+ Parallel(tf1, tf2, Series(-tf1, tf3)).doit() == TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2 + \
777
+ (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + \
778
+ 2*s*wn*zeta + wn**2)**2, s)
779
+ assert Parallel(tf2, tf1, -tf3, evaluate=True) == Parallel(tf2, tf1, -tf3).doit() == \
780
+ TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) \
781
+ , (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
782
+ assert not Parallel(tf1, -tf2, evaluate=False) == Parallel(tf1, -tf2).doit()
783
+
784
+ assert Parallel(Series(tf1, tf2), Series(tf2, tf3)).doit() == \
785
+ TransferFunction(k*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + k*(a2*s + p), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
786
+ assert Parallel(-tf1, -tf2, -tf3).doit() == \
787
+ TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2), \
788
+ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
789
+ assert -Parallel(tf1, tf2, tf3).doit() == \
790
+ TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p - (a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2), \
791
+ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
792
+ assert Parallel(tf2, tf3, Series(tf2, -tf1), tf3).doit() == \
793
+ TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - k*(a2*s + p) + (2*a2*p - 2*s)*(s**2 + 2*s*wn*zeta \
794
+ + wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
795
+
796
+ assert Parallel(tf1, tf2).rewrite(TransferFunction) == \
797
+ TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
798
+ assert Parallel(tf2, tf1, -tf3).rewrite(TransferFunction) == \
799
+ TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + \
800
+ wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
801
+
802
+ assert Parallel(tf1, Parallel(tf2, tf3)) == Parallel(tf1, tf2, tf3) == Parallel(Parallel(tf1, tf2), tf3)
803
+
804
+ P1 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
805
+ assert P1.is_proper
806
+ assert not P1.is_strictly_proper
807
+ assert P1.is_biproper
808
+
809
+ P2 = Parallel(tf1, -tf2, -tf3)
810
+ assert P2.is_proper
811
+ assert not P2.is_strictly_proper
812
+ assert P2.is_biproper
813
+
814
+ P3 = Parallel(tf1, -tf2, Series(tf1, tf3))
815
+ assert P3.is_proper
816
+ assert not P3.is_strictly_proper
817
+ assert P3.is_biproper
818
+
819
+
820
+ def test_MIMOParallel_functions():
821
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
822
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
823
+
824
+ tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
825
+ tfm2 = TransferFunctionMatrix([[-TF2], [tf5], [-TF1]])
826
+ tfm3 = TransferFunctionMatrix([[tf5], [-tf5], [TF2]])
827
+ tfm4 = TransferFunctionMatrix([[TF2, -tf5], [TF1, tf5]])
828
+ tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5]])
829
+ tfm6 = TransferFunctionMatrix([[-TF2]])
830
+ tfm7 = TransferFunctionMatrix([[tf4], [-tf4], [tf4]])
831
+
832
+ assert tfm1 + tfm2 + tfm3 == MIMOParallel(tfm1, tfm2, tfm3) == MIMOParallel(MIMOParallel(tfm1, tfm2), tfm3)
833
+ assert tfm2 - tfm1 - tfm3 == MIMOParallel(tfm2, -tfm1, -tfm3)
834
+ assert tfm2 - tfm3 + (-tfm1*tfm6*-tfm6) == MIMOParallel(tfm2, -tfm3, MIMOSeries(-tfm6, tfm6, -tfm1))
835
+ assert tfm1 + tfm1 - (-tfm1*tfm6) == MIMOParallel(tfm1, tfm1, -MIMOSeries(tfm6, -tfm1))
836
+ assert tfm2 - tfm3 - tfm1 + tfm2 == MIMOParallel(tfm2, -tfm3, -tfm1, tfm2)
837
+ assert tfm1 + tfm2 - tfm3 - tfm1 == MIMOParallel(tfm1, tfm2, -tfm3, -tfm1)
838
+ raises(ValueError, lambda: tfm1 + tfm2 + TF2)
839
+ raises(TypeError, lambda: tfm1 - tfm2 - a1)
840
+ raises(TypeError, lambda: tfm2 - tfm3 - (s - 1))
841
+ raises(TypeError, lambda: -tfm3 - tfm2 - 9)
842
+ raises(TypeError, lambda: (1 - p**3) - tfm3 - tfm2)
843
+ # All TFMs must use the same complex var. tfm7 uses 'p'.
844
+ raises(ValueError, lambda: tfm3 - tfm2 - tfm7)
845
+ raises(ValueError, lambda: tfm2 - tfm1 + tfm7)
846
+ # (tfm1 +/- tfm2) has (3, 1) shape while tfm4 has (2, 2) shape.
847
+ raises(TypeError, lambda: tfm1 + tfm2 + tfm4)
848
+ raises(TypeError, lambda: (tfm1 - tfm2) - tfm4)
849
+
850
+ assert (tfm1 + tfm2)*tfm6 == MIMOSeries(tfm6, MIMOParallel(tfm1, tfm2))
851
+ assert (tfm2 - tfm3)*tfm6*-tfm6 == MIMOSeries(-tfm6, tfm6, MIMOParallel(tfm2, -tfm3))
852
+ assert (tfm2 - tfm1 - tfm3)*(tfm6 + tfm6) == MIMOSeries(MIMOParallel(tfm6, tfm6), MIMOParallel(tfm2, -tfm1, -tfm3))
853
+ raises(ValueError, lambda: (tfm4 + tfm5)*TF1)
854
+ raises(TypeError, lambda: (tfm2 - tfm3)*a2)
855
+ raises(TypeError, lambda: (tfm3 + tfm2)*(s - 6))
856
+ raises(TypeError, lambda: (tfm1 + tfm2 + tfm3)*0)
857
+ raises(TypeError, lambda: (1 - p**3)*(tfm1 + tfm3))
858
+
859
+ # (tfm3 - tfm2) has (3, 1) shape while tfm4*tfm5 has (2, 2) shape.
860
+ raises(ValueError, lambda: (tfm3 - tfm2)*tfm4*tfm5)
861
+ # (tfm1 - tfm2) has (3, 1) shape while tfm5 has (2, 2) shape.
862
+ raises(ValueError, lambda: (tfm1 - tfm2)*tfm5)
863
+
864
+ # TFM in the arguments.
865
+ assert (MIMOParallel(tfm1, tfm2, evaluate=True) == MIMOParallel(tfm1, tfm2).doit()
866
+ == MIMOParallel(tfm1, tfm2).rewrite(TransferFunctionMatrix)
867
+ == TransferFunctionMatrix(((TransferFunction(-k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s),), \
868
+ (TransferFunction(-a0 + a1*s**2 + a2*s + k*(a0 + s), a0 + s, s),), (TransferFunction(-a2*s - p + (a2*p - s)* \
869
+ (s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s),))))
870
+
871
+
872
+ def test_Feedback_construction():
873
+ tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
874
+ tf2 = TransferFunction(k, 1, s)
875
+ tf3 = TransferFunction(a2*p - s, a2*s + p, s)
876
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
877
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
878
+ tf6 = TransferFunction(s - p, p + s, p)
879
+
880
+ f1 = Feedback(TransferFunction(1, 1, s), tf1*tf2*tf3)
881
+ assert f1.args == (TransferFunction(1, 1, s), Series(tf1, tf2, tf3), -1)
882
+ assert f1.sys1 == TransferFunction(1, 1, s)
883
+ assert f1.sys2 == Series(tf1, tf2, tf3)
884
+ assert f1.var == s
885
+
886
+ f2 = Feedback(tf1, tf2*tf3)
887
+ assert f2.args == (tf1, Series(tf2, tf3), -1)
888
+ assert f2.sys1 == tf1
889
+ assert f2.sys2 == Series(tf2, tf3)
890
+ assert f2.var == s
891
+
892
+ f3 = Feedback(tf1*tf2, tf5)
893
+ assert f3.args == (Series(tf1, tf2), tf5, -1)
894
+ assert f3.sys1 == Series(tf1, tf2)
895
+
896
+ f4 = Feedback(tf4, tf6)
897
+ assert f4.args == (tf4, tf6, -1)
898
+ assert f4.sys1 == tf4
899
+ assert f4.var == p
900
+
901
+ f5 = Feedback(tf5, TransferFunction(1, 1, s))
902
+ assert f5.args == (tf5, TransferFunction(1, 1, s), -1)
903
+ assert f5.var == s
904
+ assert f5 == Feedback(tf5) # When sys2 is not passed explicitly, it is assumed to be unit tf.
905
+
906
+ f6 = Feedback(TransferFunction(1, 1, p), tf4)
907
+ assert f6.args == (TransferFunction(1, 1, p), tf4, -1)
908
+ assert f6.var == p
909
+
910
+ f7 = -Feedback(tf4*tf6, TransferFunction(1, 1, p))
911
+ assert f7.args == (Series(TransferFunction(-1, 1, p), Series(tf4, tf6)), -TransferFunction(1, 1, p), -1)
912
+ assert f7.sys1 == Series(TransferFunction(-1, 1, p), Series(tf4, tf6))
913
+
914
+ # denominator can't be a Parallel instance
915
+ raises(TypeError, lambda: Feedback(tf1, tf2 + tf3))
916
+ raises(TypeError, lambda: Feedback(tf1, Matrix([1, 2, 3])))
917
+ raises(TypeError, lambda: Feedback(TransferFunction(1, 1, s), s - 1))
918
+ raises(TypeError, lambda: Feedback(1, 1))
919
+ # raises(ValueError, lambda: Feedback(TransferFunction(1, 1, s), TransferFunction(1, 1, s)))
920
+ raises(ValueError, lambda: Feedback(tf2, tf4*tf5))
921
+ raises(ValueError, lambda: Feedback(tf2, tf1, 1.5)) # `sign` can only be -1 or 1
922
+ raises(ValueError, lambda: Feedback(tf1, -tf1**-1)) # denominator can't be zero
923
+ raises(ValueError, lambda: Feedback(tf4, tf5)) # Both systems should use the same `var`
924
+
925
+
926
+ def test_Feedback_functions():
927
+ tf = TransferFunction(1, 1, s)
928
+ tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
929
+ tf2 = TransferFunction(k, 1, s)
930
+ tf3 = TransferFunction(a2*p - s, a2*s + p, s)
931
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
932
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
933
+ tf6 = TransferFunction(s - p, p + s, p)
934
+
935
+ assert tf / (tf + tf1) == Feedback(tf, tf1)
936
+ assert tf / (tf + tf1*tf2*tf3) == Feedback(tf, tf1*tf2*tf3)
937
+ assert tf1 / (tf + tf1*tf2*tf3) == Feedback(tf1, tf2*tf3)
938
+ assert (tf1*tf2) / (tf + tf1*tf2) == Feedback(tf1*tf2, tf)
939
+ assert (tf1*tf2) / (tf + tf1*tf2*tf5) == Feedback(tf1*tf2, tf5)
940
+ assert (tf1*tf2) / (tf + tf1*tf2*tf5*tf3) in (Feedback(tf1*tf2, tf5*tf3), Feedback(tf1*tf2, tf3*tf5))
941
+ assert tf4 / (TransferFunction(1, 1, p) + tf4*tf6) == Feedback(tf4, tf6)
942
+ assert tf5 / (tf + tf5) == Feedback(tf5, tf)
943
+
944
+ raises(TypeError, lambda: tf1*tf2*tf3 / (1 + tf1*tf2*tf3))
945
+ raises(ValueError, lambda: tf1*tf2*tf3 / tf3*tf5)
946
+ raises(ValueError, lambda: tf2*tf3 / (tf + tf2*tf3*tf4))
947
+
948
+ assert Feedback(tf, tf1*tf2*tf3).doit() == \
949
+ TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), k*(a2*p - s) + \
950
+ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
951
+ assert Feedback(tf, tf1*tf2*tf3).sensitivity == \
952
+ 1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
953
+ assert Feedback(tf1, tf2*tf3).doit() == \
954
+ TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (k*(a2*p - s) + \
955
+ (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
956
+ assert Feedback(tf1, tf2*tf3).sensitivity == \
957
+ 1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
958
+ assert Feedback(tf1*tf2, tf5).doit() == \
959
+ TransferFunction(k*(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
960
+ (a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
961
+ assert Feedback(tf1*tf2, tf5, 1).sensitivity == \
962
+ 1/(-k*(-a0 + a1*s**2 + a2*s)/((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
963
+ assert Feedback(tf4, tf6).doit() == \
964
+ TransferFunction(p*(p + s)*(a0*p + p**a1 - s), p*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
965
+ assert -Feedback(tf4*tf6, TransferFunction(1, 1, p)).doit() == \
966
+ TransferFunction(-p*(-p + s)*(p + s)*(a0*p + p**a1 - s), p*(p + s)*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
967
+ assert Feedback(tf, tf).doit() == TransferFunction(1, 2, s)
968
+
969
+ assert Feedback(tf1, tf2*tf5).rewrite(TransferFunction) == \
970
+ TransferFunction((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
971
+ (a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
972
+ assert Feedback(TransferFunction(1, 1, p), tf4).rewrite(TransferFunction) == \
973
+ TransferFunction(p, a0*p + p + p**a1 - s, p)
974
+
975
+
976
+ def test_MIMOFeedback_construction():
977
+ tf1 = TransferFunction(1, s, s)
978
+ tf2 = TransferFunction(s, s**3 - 1, s)
979
+ tf3 = TransferFunction(s, s + 1, s)
980
+ tf4 = TransferFunction(s, s**2 + 1, s)
981
+
982
+ tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
983
+ tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
984
+ tfm_3 = TransferFunctionMatrix([[tf3, tf4], [tf1, tf2]])
985
+
986
+ f1 = MIMOFeedback(tfm_1, tfm_2)
987
+ assert f1.args == (tfm_1, tfm_2, -1)
988
+ assert f1.sys1 == tfm_1
989
+ assert f1.sys2 == tfm_2
990
+ assert f1.var == s
991
+ assert f1.sign == -1
992
+ assert -(-f1) == f1
993
+
994
+ f2 = MIMOFeedback(tfm_2, tfm_1, 1)
995
+ assert f2.args == (tfm_2, tfm_1, 1)
996
+ assert f2.sys1 == tfm_2
997
+ assert f2.sys2 == tfm_1
998
+ assert f2.var == s
999
+ assert f2.sign == 1
1000
+
1001
+ f3 = MIMOFeedback(tfm_1, MIMOSeries(tfm_3, tfm_2))
1002
+ assert f3.args == (tfm_1, MIMOSeries(tfm_3, tfm_2), -1)
1003
+ assert f3.sys1 == tfm_1
1004
+ assert f3.sys2 == MIMOSeries(tfm_3, tfm_2)
1005
+ assert f3.var == s
1006
+ assert f3.sign == -1
1007
+
1008
+ mat = Matrix([[1, 1/s], [0, 1]])
1009
+ sys1 = controller = TransferFunctionMatrix.from_Matrix(mat, s)
1010
+ f4 = MIMOFeedback(sys1, controller)
1011
+ assert f4.args == (sys1, controller, -1)
1012
+ assert f4.sys1 == f4.sys2 == sys1
1013
+
1014
+
1015
+ def test_MIMOFeedback_errors():
1016
+ tf1 = TransferFunction(1, s, s)
1017
+ tf2 = TransferFunction(s, s**3 - 1, s)
1018
+ tf3 = TransferFunction(s, s - 1, s)
1019
+ tf4 = TransferFunction(s, s**2 + 1, s)
1020
+ tf5 = TransferFunction(1, 1, s)
1021
+ tf6 = TransferFunction(-1, s - 1, s)
1022
+
1023
+ tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
1024
+ tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
1025
+ tfm_3 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
1026
+ tfm_4 = TransferFunctionMatrix([[tf1, tf5], [tf5, tf5]])
1027
+ tfm_5 = TransferFunctionMatrix([[-tf3, tf3], [tf3, tf6]])
1028
+ # tfm_4 is inverse of tfm_5. Therefore tfm_5*tfm_4 = I
1029
+ tfm_6 = TransferFunctionMatrix([[-tf3]])
1030
+ tfm_7 = TransferFunctionMatrix([[tf3, tf4]])
1031
+
1032
+ # Unsupported Types
1033
+ raises(TypeError, lambda: MIMOFeedback(tf1, tf2))
1034
+ raises(TypeError, lambda: MIMOFeedback(MIMOParallel(tfm_1, tfm_2), tfm_3))
1035
+ # Shape Errors
1036
+ raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_6, 1))
1037
+ raises(ValueError, lambda: MIMOFeedback(tfm_7, tfm_7))
1038
+ # sign not 1/-1
1039
+ raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_2, -2))
1040
+ # Non-Invertible Systems
1041
+ raises(ValueError, lambda: MIMOFeedback(tfm_5, tfm_4, 1))
1042
+ raises(ValueError, lambda: MIMOFeedback(tfm_4, -tfm_5))
1043
+ raises(ValueError, lambda: MIMOFeedback(tfm_3, tfm_3, 1))
1044
+ # Variable not same in both the systems
1045
+ tfm_8 = TransferFunctionMatrix.from_Matrix(eye(2), var=p)
1046
+ raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_8, 1))
1047
+
1048
+
1049
+ def test_MIMOFeedback_functions():
1050
+ tf1 = TransferFunction(1, s, s)
1051
+ tf2 = TransferFunction(s, s - 1, s)
1052
+ tf3 = TransferFunction(1, 1, s)
1053
+ tf4 = TransferFunction(-1, s - 1, s)
1054
+
1055
+ tfm_1 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
1056
+ tfm_2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf3]])
1057
+ tfm_3 = TransferFunctionMatrix([[-tf2, tf2], [tf2, tf4]])
1058
+ tfm_4 = TransferFunctionMatrix([[tf1, tf2], [-tf2, tf1]])
1059
+
1060
+ # sensitivity, doit(), rewrite()
1061
+ F_1 = MIMOFeedback(tfm_2, tfm_3)
1062
+ F_2 = MIMOFeedback(tfm_2, MIMOSeries(tfm_4, -tfm_1), 1)
1063
+
1064
+ assert F_1.sensitivity == Matrix([[S.Half, 0], [0, S.Half]])
1065
+ assert F_2.sensitivity == Matrix([[(-2*s**4 + s**2)/(s**2 - s + 1),
1066
+ (2*s**3 - s**2)/(s**2 - s + 1)], [-s**2, s]])
1067
+
1068
+ assert F_1.doit() == \
1069
+ TransferFunctionMatrix(((TransferFunction(1, 2*s, s),
1070
+ TransferFunction(1, 2, s)), (TransferFunction(1, 2, s),
1071
+ TransferFunction(1, 2, s)))) == F_1.rewrite(TransferFunctionMatrix)
1072
+ assert F_2.doit(cancel=False, expand=True) == \
1073
+ TransferFunctionMatrix(((TransferFunction(-s**5 + 2*s**4 - 2*s**3 + s**2, s**5 - 2*s**4 + 3*s**3 - 2*s**2 + s, s),
1074
+ TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
1075
+ assert F_2.doit(cancel=False) == \
1076
+ TransferFunctionMatrix(((TransferFunction(s*(2*s**3 - s**2)*(s**2 - s + 1) + \
1077
+ (-2*s**4 + s**2)*(s**2 - s + 1), s*(s**2 - s + 1)**2, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
1078
+ (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
1079
+ assert F_2.doit() == \
1080
+ TransferFunctionMatrix(((TransferFunction(s*(-2*s**2 + s*(2*s - 1) + 1), s**2 - s + 1, s),
1081
+ TransferFunction(-2*s**3*(s - 1), s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(s*(1 - s), 1, s))))
1082
+ assert F_2.doit(expand=True) == \
1083
+ TransferFunctionMatrix(((TransferFunction(-s**2 + s, s**2 - s + 1, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
1084
+ (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
1085
+
1086
+ assert -(F_1.doit()) == (-F_1).doit() # First negating then calculating vs calculating then negating.
1087
+
1088
+
1089
+ def test_TransferFunctionMatrix_construction():
1090
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
1091
+ tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
1092
+
1093
+ tfm3_ = TransferFunctionMatrix([[-TF3]])
1094
+ assert tfm3_.shape == (tfm3_.num_outputs, tfm3_.num_inputs) == (1, 1)
1095
+ assert tfm3_.args == Tuple(Tuple(Tuple(-TF3)))
1096
+ assert tfm3_.var == s
1097
+
1098
+ tfm5 = TransferFunctionMatrix([[TF1, -TF2], [TF3, tf5]])
1099
+ assert tfm5.shape == (tfm5.num_outputs, tfm5.num_inputs) == (2, 2)
1100
+ assert tfm5.args == Tuple(Tuple(Tuple(TF1, -TF2), Tuple(TF3, tf5)))
1101
+ assert tfm5.var == s
1102
+
1103
+ tfm7 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5], [-tf5, TF2]])
1104
+ assert tfm7.shape == (tfm7.num_outputs, tfm7.num_inputs) == (3, 2)
1105
+ assert tfm7.args == Tuple(Tuple(Tuple(TF1, TF2), Tuple(TF3, -tf5), Tuple(-tf5, TF2)))
1106
+ assert tfm7.var == s
1107
+
1108
+ # all transfer functions will use the same complex variable. tf4 uses 'p'.
1109
+ raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF2], [tf4]]))
1110
+ raises(ValueError, lambda: TransferFunctionMatrix([[TF1, tf4], [TF3, tf5]]))
1111
+
1112
+ # length of all the lists in the TFM should be equal.
1113
+ raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF3, tf5]]))
1114
+ raises(ValueError, lambda: TransferFunctionMatrix([[TF1, TF3], [tf5]]))
1115
+
1116
+ # lists should only support transfer functions in them.
1117
+ raises(TypeError, lambda: TransferFunctionMatrix([[TF1, TF2], [TF3, Matrix([1, 2])]]))
1118
+ raises(TypeError, lambda: TransferFunctionMatrix([[TF1, Matrix([1, 2])], [TF3, TF2]]))
1119
+
1120
+ # `arg` should strictly be nested list of TransferFunction
1121
+ raises(ValueError, lambda: TransferFunctionMatrix([TF1, TF2, tf5]))
1122
+ raises(ValueError, lambda: TransferFunctionMatrix([TF1]))
1123
+
1124
+ def test_TransferFunctionMatrix_functions():
1125
+ tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
1126
+
1127
+ # Classmethod (from_matrix)
1128
+
1129
+ mat_1 = ImmutableMatrix([
1130
+ [s*(s + 1)*(s - 3)/(s**4 + 1), 2],
1131
+ [p, p*(s + 1)/(s*(s**1 + 1))]
1132
+ ])
1133
+ mat_2 = ImmutableMatrix([[(2*s + 1)/(s**2 - 9)]])
1134
+ mat_3 = ImmutableMatrix([[1, 2], [3, 4]])
1135
+ assert TransferFunctionMatrix.from_Matrix(mat_1, s) == \
1136
+ TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)],
1137
+ [TransferFunction(p, 1, s), TransferFunction(p, s, s)]])
1138
+ assert TransferFunctionMatrix.from_Matrix(mat_2, s) == \
1139
+ TransferFunctionMatrix([[TransferFunction(2*s + 1, s**2 - 9, s)]])
1140
+ assert TransferFunctionMatrix.from_Matrix(mat_3, p) == \
1141
+ TransferFunctionMatrix([[TransferFunction(1, 1, p), TransferFunction(2, 1, p)],
1142
+ [TransferFunction(3, 1, p), TransferFunction(4, 1, p)]])
1143
+
1144
+ # Negating a TFM
1145
+
1146
+ tfm1 = TransferFunctionMatrix([[TF1], [TF2]])
1147
+ assert -tfm1 == TransferFunctionMatrix([[-TF1], [-TF2]])
1148
+
1149
+ tfm2 = TransferFunctionMatrix([[TF1, TF2, TF3], [tf5, -TF1, -TF3]])
1150
+ assert -tfm2 == TransferFunctionMatrix([[-TF1, -TF2, -TF3], [-tf5, TF1, TF3]])
1151
+
1152
+ # subs()
1153
+
1154
+ H_1 = TransferFunctionMatrix.from_Matrix(mat_1, s)
1155
+ H_2 = TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(s**2 - a), s)]])
1156
+ assert H_1.subs(p, 1) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
1157
+ assert H_1.subs({p: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
1158
+ assert H_1.subs({p: 1, s: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]]) # This should ignore `s` as it is `var`
1159
+ assert H_2.subs(p, 2) == TransferFunctionMatrix([[TransferFunction(2*a*s, k*s**2, s), TransferFunction(2*s, k*(-a + s**2), s)]])
1160
+ assert H_2.subs(k, 1) == TransferFunctionMatrix([[TransferFunction(a*p*s, s**2, s), TransferFunction(p*s, -a + s**2, s)]])
1161
+ assert H_2.subs(a, 0) == TransferFunctionMatrix([[TransferFunction(0, k*s**2, s), TransferFunction(p*s, k*s**2, s)]])
1162
+ assert H_2.subs({p: 1, k: 1, a: a0}) == TransferFunctionMatrix([[TransferFunction(a0*s, s**2, s), TransferFunction(s, -a0 + s**2, s)]])
1163
+
1164
+ # transpose()
1165
+
1166
+ assert H_1.transpose() == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(p, 1, s)], [TransferFunction(2, 1, s), TransferFunction(p, s, s)]])
1167
+ assert H_2.transpose() == TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s)], [TransferFunction(p*s, k*(-a + s**2), s)]])
1168
+ assert H_1.transpose().transpose() == H_1
1169
+ assert H_2.transpose().transpose() == H_2
1170
+
1171
+ # elem_poles()
1172
+
1173
+ assert H_1.elem_poles() == [[[-sqrt(2)/2 - sqrt(2)*I/2, -sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2, sqrt(2)/2 + sqrt(2)*I/2], []],
1174
+ [[], [0]]]
1175
+ assert H_2.elem_poles() == [[[0, 0], [sqrt(a), -sqrt(a)]]]
1176
+ assert tfm2.elem_poles() == [[[wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [], [-p/a2]],
1177
+ [[-a0], [wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [-p/a2]]]
1178
+
1179
+ # elem_zeros()
1180
+
1181
+ assert H_1.elem_zeros() == [[[-1, 0, 3], []], [[], []]]
1182
+ assert H_2.elem_zeros() == [[[0], [0]]]
1183
+ assert tfm2.elem_zeros() == [[[], [], [a2*p]],
1184
+ [[-a2/(2*a1) - sqrt(4*a0*a1 + a2**2)/(2*a1), -a2/(2*a1) + sqrt(4*a0*a1 + a2**2)/(2*a1)], [], [a2*p]]]
1185
+
1186
+ # doit()
1187
+
1188
+ H_3 = TransferFunctionMatrix([[Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]])
1189
+ H_4 = TransferFunctionMatrix([[Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]])
1190
+
1191
+ assert H_3.doit() == TransferFunctionMatrix([[TransferFunction(s**2 - 2*s + 5, s*(s**3 - 3), s)]])
1192
+ assert H_4.doit() == TransferFunctionMatrix([[TransferFunction(1, 4*s**4 - s**2 - 2*s + 5, s)]])
1193
+
1194
+ # _flat()
1195
+
1196
+ assert H_1._flat() == [TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s), TransferFunction(p, 1, s), TransferFunction(p, s, s)]
1197
+ assert H_2._flat() == [TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(-a + s**2), s)]
1198
+ assert H_3._flat() == [Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]
1199
+ assert H_4._flat() == [Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]
1200
+
1201
+ # evalf()
1202
+
1203
+ assert H_1.evalf() == \
1204
+ TransferFunctionMatrix(((TransferFunction(s*(s - 3.0)*(s + 1.0), s**4 + 1.0, s), TransferFunction(2.0, 1, s)), (TransferFunction(1.0*p, 1, s), TransferFunction(p, s, s))))
1205
+ assert H_2.subs({a:3.141, p:2.88, k:2}).evalf() == \
1206
+ TransferFunctionMatrix(((TransferFunction(4.5230399999999999494093572138808667659759521484375, s, s),
1207
+ TransferFunction(2.87999999999999989341858963598497211933135986328125*s, 2.0*s**2 - 6.282000000000000028421709430404007434844970703125, s)),))
1208
+
1209
+ # simplify()
1210
+
1211
+ H_5 = TransferFunctionMatrix([[TransferFunction(s**5 + s**3 + s, s - s**2, s),
1212
+ TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)]])
1213
+
1214
+ assert H_5.simplify() == simplify(H_5) == \
1215
+ TransferFunctionMatrix(((TransferFunction(-s**4 - s**2 - 1, s - 1, s), TransferFunction(s + 3, s + 5, s)),))
1216
+
1217
+ # expand()
1218
+
1219
+ assert (H_1.expand()
1220
+ == TransferFunctionMatrix(((TransferFunction(s**3 - 2*s**2 - 3*s, s**4 + 1, s), TransferFunction(2, 1, s)),
1221
+ (TransferFunction(p, 1, s), TransferFunction(p, s, s)))))
1222
+ assert H_5.expand() == \
1223
+ TransferFunctionMatrix(((TransferFunction(s**5 + s**3 + s, -s**2 + s, s), TransferFunction(s**2 + 2*s - 3, s**2 + 4*s - 5, s)),))
1224
+
1225
+ def test_TransferFunction_bilinear():
1226
+ # simple transfer function, e.g. ohms law
1227
+ tf = TransferFunction(1, a*s+b, s)
1228
+ numZ, denZ = bilinear(tf, T)
1229
+ # discretized transfer function with coefs from tf.bilinear()
1230
+ tf_test_bilinear = TransferFunction(s*numZ[0]+numZ[1], s*denZ[0]+denZ[1], s)
1231
+ # corresponding tf with manually calculated coefs
1232
+ tf_test_manual = TransferFunction(s*T+T, s*(T*b+2*a)+T*b-2*a, s)
1233
+
1234
+ assert S.Zero == (tf_test_bilinear-tf_test_manual).simplify().num
1235
+
1236
+ def test_TransferFunction_backward_diff():
1237
+ # simple transfer function, e.g. ohms law
1238
+ tf = TransferFunction(1, a*s+b, s)
1239
+ numZ, denZ = backward_diff(tf, T)
1240
+ # discretized transfer function with coefs from tf.bilinear()
1241
+ tf_test_bilinear = TransferFunction(s*numZ[0]+numZ[1], s*denZ[0]+denZ[1], s)
1242
+ # corresponding tf with manually calculated coefs
1243
+ tf_test_manual = TransferFunction(s*T, s*(T*b+a)-a, s)
1244
+
1245
+ assert S.Zero == (tf_test_bilinear-tf_test_manual).simplify().num
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/body.cpython-310.pyc ADDED
Binary file (18.2 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/functions.cpython-310.pyc ADDED
Binary file (23.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/joint.cpython-310.pyc ADDED
Binary file (79.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/jointsmethod.cpython-310.pyc ADDED
Binary file (8.77 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/kane.cpython-310.pyc ADDED
Binary file (25.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/lagrange.cpython-310.pyc ADDED
Binary file (16.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/linearize.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/method.cpython-310.pyc ADDED
Binary file (1.59 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/models.cpython-310.pyc ADDED
Binary file (5.58 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/particle.cpython-310.pyc ADDED
Binary file (8.46 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/rigidbody.cpython-310.pyc ADDED
Binary file (11.6 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/__pycache__/system.cpython-310.pyc ADDED
Binary file (16.1 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_lagrange2.cpython-310.pyc ADDED
Binary file (1.2 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_linearize.cpython-310.pyc ADDED
Binary file (9.15 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/mechanics/tests/__pycache__/test_models.cpython-310.pyc ADDED
Binary file (4.25 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/circuitutils.cpython-310.pyc ADDED
Binary file (11 kB). View file
 
venv/lib/python3.10/site-packages/sympy/physics/quantum/__pycache__/matrixutils.cpython-310.pyc ADDED
Binary file (7.39 kB). View file