/
linear_systems.py
2238 lines (1739 loc) · 79.7 KB
/
linear_systems.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import math
from inspect import getfullargspec
import warnings
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle, Wedge
import numpy as np
from .system import System as _System
from .system import _SingleDoFCoordinatesDict
from .nonlinear_systems import MultiDoFNonLinearSystem as _MDNLS
from .functions import benchmark_par_to_canonical, spring, centered_rectangle
class _LinearSystem(_System):
"""This is the abstract base class for any linear system."""
def __init__(self):
super(_LinearSystem, self).__init__()
self._canonical_coeffs_func = None
def __str__(self):
text = super().__str__()
divider = 'Configuration plot function'
parts = text.split(divider)
new_line_tmpl = 'Canonical coefficients function defined: {}\n'
new_line = new_line_tmpl.format('True' if self.canonical_coeffs_func is not None else 'False')
return parts[0] + new_line + divider + parts[1]
@property
def canonical_coeffs_func(self):
"""A function that returns the three linear coefficients of the left
hand side of a canonical second order ordinary differential equation.
This equation looks like the following for linear motion:
mv' + cv + kx = F(t)
and like the following for angular motion:
Iω' + cω + kθ = T(t)
where:
- m: mass of the moving particle
- I: moment of inertia of a rigid body
- c: viscous damping coefficient (linear or angular)
- k: spring stiffness (linear or angular)
- x: the positional coordinate of the mass
- v: the positional speed of the mass
- θ: the angular coordinate of the body
- ω: the angular speed of the body
The coefficients (m, c, k, I) must be defined in terms of the system's
constants.
Example
=======
>>> from resonance.linear_systems import SingleDoFLinearSystem
>>> sys = SingleDoFLinearSystem()
>>> sys.constants['gravity'] = 9.8 # m/s**2
>>> sys.constants['length'] = 1.0 # m
>>> sys.constants['mass'] = 0.5 # kg
>>> sys.coordinates['theta'] = 0.3 # rad
>>> sys.speeds['omega'] = 0.0 # rad/s
>>> def coeffs(gravity, length, mass):
... # Represents a linear model of a simple pendulum:
... # m * l**2 ω' + m * g * l * θ = 0
... I = mass * length**2
... c = 0.0
... k = mass * gravity * length
... return I, c, k
...
>>> sys.canonical_coeffs_func = coeffs
"""
return self._canonical_coeffs_func
@canonical_coeffs_func.setter
def canonical_coeffs_func(self, func):
self._measurements._check_for_duplicate_keys()
for k in getfullargspec(func).args:
# NOTE : Measurements do not have to be time varying.
if k not in (list(self.constants.keys()) +
list(self.measurements.keys())):
msg = ('The function argument {} is not in constants or '
'measurements. Redefine your function in terms of '
'non-time varying parameters.')
raise ValueError(msg.format(k))
self._canonical_coeffs_func = func
def canonical_coefficients(self):
"""Returns the mass, damping, and stiffness coefficients of the
canonical second order differential equation.
Returns
=======
m : float
System mass coefficient.
c : float
System damping coefficient.
k : float
System stiffness coefficient.
Example
=======
>>> from resonance.linear_systems import SingleDoFLinearSystem
>>> sys = SingleDoFLinearSystem()
>>> sys.constants['gravity'] = 9.8 # m/s**2
>>> sys.constants['length'] = 1.0 # m
>>> sys.constants['mass'] = 0.5 # kg
>>> sys.coordinates['theta'] = 0.3 # rad
>>> sys.speeds['omega'] = 0.0 # rad/s
>>> def coeffs(gravity, length, mass):
... # Represents a linear model of a simple pendulum:
... # m * l**2 ω' + m * g * l * θ = 0
... I = mass * length**2
... c = 0.0
... k = mass * gravity * length
... return I, c, k
...
>>> sys.canonical_coeffs_func = coeffs
>>> sys.canonical_coefficients()
(0.5, 0.0, 4.9)
"""
self._check_system()
if self.canonical_coeffs_func is None:
msg = ('There is no function available to calculate the canonical'
' coefficients.')
raise ValueError(msg)
else:
f = self.canonical_coeffs_func
args = [self._get_par_vals(k) for k in getfullargspec(f).args]
return f(*args)
class SingleDoFLinearSystem(_LinearSystem):
"""This is the abstract base class for any single degree of freedom linear
system. It can be sub-classed to make a custom system or the necessary
methods can be added dynamically."""
def __init__(self):
super(_LinearSystem, self).__init__()
self._coordinates = _SingleDoFCoordinatesDict({})
self._speeds = _SingleDoFCoordinatesDict({})
self._measurements._coordinates = self._coordinates
self._measurements._speeds = self._speeds
self._canonical_coeffs_func = None
def _initial_conditions(self):
x0 = list(self.coordinates.values())[0]
v0 = list(self.speeds.values())[0]
return x0, v0
@staticmethod
def _natural_frequency(mass, stiffness):
"""Returns the real or complex valued natural frequency of the
system."""
wn = np.lib.scimath.sqrt(stiffness / mass)
if isinstance(wn, complex):
msg = ('The combination of system constants produces a complex '
'natural frequency, which results in an unstable system.')
warnings.warn(msg)
return wn
@staticmethod
def _damping_ratio(mass, damping, natural_frequency):
zeta = damping / 2.0 / mass / natural_frequency
if zeta * natural_frequency < 0.0:
msg = ('The combination of system constants produces a negative '
'damping ratio, which results in an unstable system.')
warnings.warn(msg)
return zeta
def _damped_natural_frequency(self, natural_frequency, damping_ratio):
typ = self._solution_type()
if typ == 'underdamped':
return natural_frequency * np.sqrt(1.0 - damping_ratio**2)
elif typ == 'no_damping_unstable' or typ == 'no_damping':
return natural_frequency
else:
return 0.0
def _normalized_form(self, m, c, k):
wn = self._natural_frequency(m, k)
z = self._damping_ratio(m, c, wn)
wd = self._damped_natural_frequency(wn, z)
return wn, z, wd
def _solution_type(self):
"""Returns a string giving the solution type based on the canonical
coefficients.
Returns
=======
str
- no_damping_unstable : k/m is negative
- no_damping : k/m is positive, stable
- underdamped
- overdamped
- critically_damped
"""
m, c, k = self.canonical_coefficients()
omega_n = self._natural_frequency(m, k)
if math.isclose(c, 0.0):
if isinstance(omega_n, complex):
return 'no_damping_unstable'
else:
return 'no_damping'
else: # damping, so check zeta
zeta = self._damping_ratio(m, c, omega_n)
if zeta < 1.0:
return 'underdamped'
elif math.isclose(zeta, 1.0):
return 'critically_damped'
elif zeta > 1.0:
return 'overdamped'
else:
msg = 'No valid simulation solution with these constants.'
raise ValueError(msg)
def _solution_func(self):
m, c, k = self.canonical_coefficients()
omega_n = self._natural_frequency(m, k)
if math.isclose(c, 0.0):
if isinstance(omega_n, complex):
sol_func = self._no_damping_unstable_solution
else:
sol_func = self._no_damping_solution
else: # damping, so check zeta
zeta = self._damping_ratio(m, c, omega_n)
if zeta < 1.0:
sol_func = self._underdamped_solution
elif math.isclose(zeta, 1.0):
sol_func = self._critically_damped_solution
elif zeta > 1.0:
sol_func = self._overdamped_solution
else:
msg = 'No valid simulation solution with these parameters.'
raise ValueError(msg)
return sol_func
def _no_damping_solution(self, time):
t = time
m, c, k = self.canonical_coefficients()
wn = self._natural_frequency(m, k)
x0 = list(self.coordinates.values())[0]
v0 = list(self.speeds.values())[0]
c1 = v0 / wn
c2 = x0
pos = c1 * np.sin(wn * t) + c2 * np.cos(wn * t)
vel = c1 * wn * np.cos(wn * t) - c2 * wn * np.sin(wn * t)
acc = -c1 * wn**2 * np.sin(wn * t) - c2 * wn**2 * np.cos(wn * t)
return pos, vel, acc
def _no_damping_unstable_solution(self, time):
t = time
m, c, k = self.canonical_coefficients()
wn = self._natural_frequency(m, k).imag
x0 = list(self.coordinates.values())[0]
v0 = list(self.speeds.values())[0]
# TODO : Verify these are correct.
c1 = v0 / wn
c2 = x0
pos = c1 * np.sinh(wn * t) + c2 * np.cosh(wn * t)
vel = wn * (c1 * np.cosh(wn * t) + c2 * np.sinh(wn * t))
acc = wn**2 * (c1 * np.sinh(wn * t) + c2 * np.cosh(wn * t))
return pos, vel, acc
def _damped_sinusoid(self, A, phi, t):
"""pos = A * exp(-z*wn*t) * sin(wd*t + phi)
A and phi are different and depend on the particular solution.
"""
m, c, k = self.canonical_coefficients()
wn, z, wd = self._normalized_form(m, c, k)
pos = A * np.exp(-z*wn*t) * np.sin(wd*t + phi)
vel = (A * -z * wn * np.exp(-z*wn*t) * np.sin(wd*t + phi) +
A * np.exp(-z*wn*t) * wd * np.cos(wd*t + phi))
acc = (A * (-z * wn)**2 * np.exp(-z*wn*t) * np.sin(wd*t + phi) +
A * -z * wn * np.exp(-z*wn*t) * wd * np.cos(wd*t + phi) +
A * -z * wn * np.exp(-z*wn*t) * wd * np.cos(wd*t + phi) -
A * np.exp(-z*wn*t) * wd**2 * np.sin(wd*t + phi))
return pos, vel, acc
def _underdamped_solution(self, time):
t = time
m, c, k = self.canonical_coefficients()
wn, z, wd = self._normalized_form(m, c, k)
x0, v0 = self._initial_conditions()
A = np.sqrt(((v0 + z * wn * x0)**2 + (x0 * wd)**2) / wd**2)
phi = np.arctan2(x0 * wd, v0 + z * wn * x0)
pos, vel, acc = self._damped_sinusoid(A, phi, t)
return pos, vel, acc
def _overdamped_solution(self, time):
t = time
m, c, k = self.canonical_coefficients()
wn = self._natural_frequency(m, k)
z = self._damping_ratio(m, c, wn)
x0 = list(self.coordinates.values())[0]
v0 = list(self.speeds.values())[0]
a1 = ((-v0 + (-z + np.sqrt(z**2 - 1)) * wn * x0) / 2 / wn /
np.sqrt(z**2 - 1))
a2 = ((v0 + (z + np.sqrt(z**2 - 1)) * wn * x0) / 2 / wn /
np.sqrt(z**2 - 1))
time_const = wn * np.sqrt(z**2 - 1)
pos = np.exp(-z*wn*t)*(a1*np.exp(-time_const*t) +
a2*np.exp(time_const*t))
vel = (-z*wn*np.exp(-z*wn*t)*(a1*np.exp(-time_const*t) +
a2*np.exp(time_const*t)) +
np.exp(-z*wn*t)*(-a1*time_const*np.exp(-time_const*t) +
a2*time_const*np.exp(time_const*t)))
acc = ((-z*wn)**2*np.exp(-z*wn*t)*(a1*np.exp(-time_const*t) +
a2*np.exp(time_const*t)) -
z*wn*np.exp(-z*wn*t)*(-a1*time_const*np.exp(-time_const*t) +
a2*time_const*np.exp(time_const*t)) -
z*wn*np.exp(-z*wn*t)*(-a1*time_const*np.exp(-time_const*t) +
a2*time_const*np.exp(time_const*t)) +
np.exp(-z*wn*t)*(a1*time_const**2*np.exp(-time_const*t) +
a2*time_const**2*np.exp(time_const*t)))
return pos, vel, acc
def _critically_damped_solution(self, time):
t = time
m, c, k = self.canonical_coefficients()
wn = self._natural_frequency(m, k)
x0 = list(self.coordinates.values())[0]
v0 = list(self.speeds.values())[0]
a1 = x0
a2 = v0 + wn * x0
pos = (a1 + a2 * t) * np.exp(-wn * t)
vel = a2 * np.exp(-wn * t) + (a1 + a2 * t) * -wn * np.exp(-wn * t)
acc = (a2 * -wn * np.exp(-wn * t) + a2 * -wn * np.exp(-wn * t) +
(a1 + a2 * t) * wn**2 * np.exp(-wn * t))
return pos, vel, acc
def _generate_state_trajectories(self, times, **kwargs):
sol_func = self._solution_func()
return sol_func(times)
def period(self):
"""Returns the (damped) period of oscillation of the coordinate in
seconds."""
m, c, k = self.canonical_coefficients()
wn = self._natural_frequency(m, k)
z = self._damping_ratio(m, c, wn)
if z < 1.0: # underdamped, no damping, or unstable
return 2.0 * np.pi / self._damped_natural_frequency(wn, z)
else:
return np.inf
def _periodic_forcing_steady_state(self, a0, an, bn, wT, t):
M = t.shape[0]
# scalars
m, c, k = self.canonical_coefficients()
wn, z, wd = self._normalized_form(m, c, k)
N = an.shape[0]
# column array of n values, shape(N, 1)
n = np.arange(1, N+1)[:, np.newaxis]
assert n.shape == (N, 1)
# phase shift of each term in the series, shape(N, 1)
theta_n = np.arctan2(2*z*wn*n*wT, wn**2-(n*wT)**2)
assert theta_n.shape == (N, 1)
# an is a col and t is 1D, so each row of xcn is a term
# in the series at all times in t
# shape(N, 1)
denom = m * np.sqrt((wn**2 - (n*wT)**2)**2 + (2*z*wn*n*wT)**2)
assert denom.shape == (N, 1)
# shape(N, M)
cwT = np.cos(n*wT*t - theta_n)
swT = np.sin(n*wT*t - theta_n)
assert cwT.shape == (N, M)
assert swT.shape == (N, M)
# shape(N, M)
xcn = an / denom * cwT
vcn = -an * n * wT / denom * swT
acn = -an * (n * wT)**2 / denom * cwT
assert xcn.shape == (N, M)
# shape(N, M)
xsn = bn / denom * swT
vsn = bn * n * wT / denom * cwT
asn = -bn * (n * wT)**2 / denom * swT
assert xsn.shape == (N, M)
# steady state solution (particular solution)
# x is the sum of each xcn term (the rows)
xss = a0 / 2 / k + np.sum(xcn + xsn, axis=0)
vss = np.sum(vcn + vsn, axis=0)
ass = np.sum(acn + asn, axis=0)
assert xss.shape == (M, )
return xss, vss, ass, n, theta_n, denom
def _periodic_forcing_transient_A_phi(self, wT, n, a0, an, bn, theta_n,
denom, t):
# scalars
m, c, k = self.canonical_coefficients()
wn, z, wd = self._normalized_form(m, c, k)
# the transient solution (homogeneous)
x0, v0 = self._initial_conditions()
c1 = np.sum((-np.sin(theta_n)*bn + np.cos(theta_n)*an) / denom)
c2 = wT * np.sum((np.sin(theta_n)*an + np.cos(theta_n)*bn) * n / denom)
phi = np.arctan2(wd*(2*c1*k+a0-2*k*x0),
2*c1*k*wn*z + 2*c2*k + a0*wn*z - 2*k*wn*x0*z -
2*k*v0)
A = (-a0 / 2 + k * (-c1 + x0)) / k / np.sin(phi)
return A, phi
def periodic_forcing_response(self, twice_avg, cos_coeffs, sin_coeffs,
frequency, final_time, initial_time=0.0,
sample_rate=100,
col_name='forcing_function'):
"""Returns the trajectory of the system's coordinates, speeds,
accelerations, and measurements if a periodic forcing function defined
by a Fourier series is applied as a force or torque in the same
direction as the system's coordinate. The forcing function is defined
as::
N
F(t) or T(t) = a0 / 2 + ∑ (an * cos(n*ω*t) + bn * sin(n*ω*t))
n=1
Where a0, a1...an, and b1...bn are the Fourier coefficients. If N=∞
then the Fourier series can describe any periodic function with a
period (2*π)/ω.
Parameters
==========
twice_avg : float
Twice the average value over one cycle, a0.
cos_coeffs : float or sequence of floats
The N cosine Fourier coefficients: a1, ..., aN.
sin_coeffs : float or sequence of floats
The N sine Fourier coefficients: b1, ..., bN.
frequency : float
The frequency, ω, in radians per second corresponding to one full
cycle of the function.
final_time : float
A value of time in seconds corresponding to the end of the
simulation.
initial_time : float, optional
A value of time in seconds corresponding to the start of the
simulation.
sample_rate : integer, optional
The sample rate of the simulation in Hertz (samples per second).
The time values will be reported at the initial time and final
time, i.e. inclusive, along with times space equally based on the
sample rate.
col_name : string, optional
A valid Python identifier that will be used as the column name for
the forcing function trajectory in the returned data frame.
Returns
=======
pandas.DataFrame
A data frame indexed by time with all of the coordinates and
measurements as columns.
"""
if self._solution_type() != 'underdamped':
msg = 'Currently, only supported for underdamped systems.'
raise ValueError(msg)
# shape(N, 1)
an = np.atleast_2d(cos_coeffs).T
bn = np.atleast_2d(sin_coeffs).T
if an.shape[1] != 1 or bn.shape[1] != 1:
msg = 'an and bn must be 1D sequences or a single float.'
raise ValueError(msg)
if an.shape != bn.shape:
raise ValueError('an and bn must be the same length')
# shape (M,), M: number of time samples
t = self._calc_times(final_time, initial_time, sample_rate)
# scalars
m, c, k = self.canonical_coefficients()
wn, z, wd = self._normalized_form(m, c, k)
wT = frequency
xss, vss, ass, n, theta_n, denom = \
self._periodic_forcing_steady_state(twice_avg, an, bn, wT, t)
# the transient solution (homogeneous)
A, phi = self._periodic_forcing_transient_A_phi(wT, n, twice_avg, an,
bn, theta_n, denom, t)
xh, vh, ah = self._damped_sinusoid(A, phi, t)
self.result = self._state_traj_to_dataframe(t, xh + xss, vh + vss,
ah + ass)
if not col_name.isidentifier():
msg = "'{}' is not a valid Python identifier."
raise ValueError(msg.format(col_name))
elif col_name in self.result.columns:
raise ValueError('{} already taken.'.format(col_name))
else:
self.result[col_name] = twice_avg / 2 + \
np.sum(an * np.cos(frequency * n * t) +
bn * np.sin(frequency * n * t), axis=0)
return self.result
def sinusoidal_forcing_response(self, amplitude, frequency, final_time,
initial_time=0.0, sample_rate=100,
col_name='forcing_function'):
"""Returns the trajectory of the system's coordinates, speeds,
accelerations, and measurements if a sinusoidal forcing (or torquing)
function defined by:
F(t) = Fo * cos(ω * t)
or
T(t) = To * cos(ω * t)
is applied to the moving body in the direction of the system's
coordinate.
Parameters
==========
amplitude : float
The amplitude of the forcing/torquing function, Fo or To, in
Newtons or Newton-Meters.
frequency : float
The frequency, ω, in radians per second of the sinusoidal forcing.
final_time : float
A value of time in seconds corresponding to the end of the
simulation.
initial_time : float, optional
A value of time in seconds corresponding to the start of the
simulation.
sample_rate : integer, optional
The sample rate of the simulation in Hertz (samples per second).
The time values will be reported at the initial time and final
time, i.e. inclusive, along with times space equally based on the
sample rate.
col_name : string, optional
A valid Python identifier that will be used as the column name for
the forcing function trajectory in the returned data frame.
Returns
=======
pandas.DataFrame
A data frame indexed by time with all of the coordinates and
measurements as columns.
"""
t = self._calc_times(final_time, initial_time, sample_rate)
typ = self._solution_type()
x0, v0 = self._initial_conditions()
m, c, k = self.canonical_coefficients()
Fo = amplitude
w = frequency
fo = Fo / m
if typ == 'no_damping':
wn = self._natural_frequency(m, k)
if math.isclose(w, wn): # resonant frequency
X = fo / 2 / w
xss = X * t * np.sin(w*t)
vss = X * w * t * np.cos(w*t) + X * np.sin(w*t)
ass = (-X * w**2 * t * np.sin(w*t) + X * w * np.cos(w*t) + X *
w * np.cos(w*t))
x = v0 / w * np.sin(w*t) + x0 * np.cos(w*t)
v = v0 / w * w * np.cos(w*t) - x0 * w * np.sin(w*t)
a = -v0 / w * w**2 * np.sin(w*t) - x0 * w**2 * np.cos(w*t)
else:
# steady state solution (particular solution)
X = fo / (wn**2 - w**2)
xss = X * np.cos(w * t)
vss = -X * w * np.sin(w * t)
ass = -X * w**2 * np.cos(w * t)
# transient solution (homogenous solution)
A1 = v0 / wn # sin
A2 = x0 - fo / (wn**2 - w**2) # cos
A = np.sqrt(A1**2 + A2**2)
phi = np.arctan2(A2, A1)
x = A * np.sin(wn * t + phi)
v = A * wn * np.cos(wn * t + phi)
a = -A * wn**2 * np.sin(wn * t + phi)
elif typ == 'underdamped':
wn, z, wd = self._normalized_form(m, c, k)
theta = np.arctan2(2*z*wn*w, wn**2 - w**2)
X = fo / np.sqrt((wn**2 - w**2)**2 + (2*z*wn*w)**2)
xss = X * np.cos(w*t - theta)
vss = -X * w * np.sin(w*t - theta)
ass = -X * w**2 * np.cos(w*t - theta)
phi = np.arctan2(wd * (x0 - X * np.cos(theta)),
v0 + (x0 - X * np.cos(theta)) *
z * wn - w * X * np.sin(theta))
A = (x0 - X * np.cos(theta)) / np.sin(phi)
x, v, a = self._damped_sinusoid(A, phi, t)
else:
raise ValueError('{} not yet supported.'.format(typ))
self.result = self._state_traj_to_dataframe(t, x + xss, v + vss,
a + ass)
if not col_name.isidentifier():
msg = "'{}' is not a valid Python identifier."
raise ValueError(msg.format(col_name))
elif col_name in self.result.columns:
raise ValueError('{} already taken.'.format(col_name))
else:
self.result[col_name] = amplitude * np.cos(frequency * t)
return self.result
def frequency_response(self, frequencies, amplitude):
"""Returns the amplitude and phase shift for simple sinusoidal forcing
of the system. The first holds the plot of the coordinate's amplitude
as a function of forcing frequency and the second holds a plot of the
coordinate's phase shift with respect to the forcing function.
Parameters
==========
frequencies : array_like, shape(n,)
amplitude : float
The value of the forcing amplitude.
Returns
=======
amp_curve : ndarray, shape(n,)
The amplitude values of the coordinate at different frequencies.
phase_curve : ndarray, shape(n,)
The phase shift values in radians of the coordinate relative to the
forcing.
"""
m, c, k = self.canonical_coefficients()
wn, z, wd = self._normalized_form(m, c, k)
fo = amplitude / m
w = np.asarray(frequencies)
amp_curve = fo / np.sqrt((wn**2 - w**2)**2 + (2*z*wn*w)**2)
phase_curve = np.arctan2(2*z*wn*w, wn**2 - w**2)
return amp_curve, phase_curve
def frequency_response_plot(self, amplitude, log=False, axes=None):
"""Returns an array of two matplotlib axes. The first holds the plot of
the coordinate's amplitude as a function of forcing frequency and the
second holds a plot of the coordinate's phase shift with respect to the
forcing function.
Parameters
==========
amplitude : float
The value of the forcing amplitude.
log : boolean, optional
If True, the amplitude will be plotted on a semi-log Y plot.
"""
m, c, k = self.canonical_coefficients()
wn, z, wd = self._normalized_form(m, c, k)
w = np.linspace(0.0, 5 * wn, num=200)
amp_curve, phase_curve = self.frequency_response(w, amplitude)
if axes is None:
fig, axes = plt.subplots(2, 1, sharex=True)
axes[0].axvline(wn, color='black')
if log:
axes[0].semilogy(w, amp_curve)
else:
axes[0].plot(w, amp_curve)
axes[0].set_ylabel('Coordinate Amplitude')
axes[1].axvline(wn, color='black')
axes[1].plot(w, np.rad2deg(phase_curve))
axes[1].set_ylabel('Phase Shift [deg]')
axes[1].set_xlabel(r'Forcing Frequency, $\omega$, [rad/s]')
return axes
class MultiDoFLinearSystem(_MDNLS):
"""This is the abstract base class for any multi degree of freedom linear
system. It can be sub-classed to make a custom system or the necessary
methods can be added dynamically."""
def __init__(self):
super(MultiDoFLinearSystem, self).__init__()
self._canonical_coeffs_func = None
self._forcing_func = None
self._compute_forcing = False
def __str__(self):
text = super().__str__()
pattern = 'Differential equations function defined.*\n'
text = re.sub(pattern, '', text)
divider = 'Configuration plot function'
parts = text.split(divider)
new_line_tmpl = 'Canonical coefficients function defined: {}\n'
new_line = new_line_tmpl.format('True' if self.canonical_coeffs_func is not None else 'False')
return parts[0] + new_line + divider + parts[1]
@property
def canonical_coeffs_func(self):
"""A function that returns the three linear coefficient matrices of the
left hand side of a set of canonical second order ordinary differential
equations. This equation looks like the following:
Mv' + Cv + Kx = F(t)
where:
- M: mass matrix
- C: damping matrix
- K: stiffness matrix
- x: the generalized coordinate vector
- v: the generalized speed vector
The coefficients M, C, and K must be defined in terms of the system's
constants.
Example
=======
This is an example of a simple double pendulum linearized about its
equilibrium.
>>> from resonance.linear_systems import MultiDoFLinearSystem
>>> sys = MultiDoFLinearSystem()
>>> sys.constants['g'] = 9.8 # m/s**2
>>> sys.constants['l1'] = 1.0 # m
>>> sys.constants['l2'] = 1.0 # m
>>> sys.constants['m1'] = 0.5 # kg
>>> sys.constants['m2'] = 0.5 # kg
>>> sys.coordinates['theta1'] = 0.3 # rad
>>> sys.coordinates['theta2'] = 0.0 # rad
>>> sys.speeds['omega1'] = 0.0 # rad/s
>>> sys.speeds['omega2'] = 0.0 # rad/s
>>> def coeffs(m1, m2, l1, l2, g):
... # Represents a linear model of a simple double pendulum
... M = np.array([[l1 * (m1 + m2), m2 * l2],
... [m2 * l2, m2 * l1]])
... C = np.zeros((2, 2))
... K = np.array([[-g * (m1 + m2), 0],
... [0, -m2 * g]])
... return M, C, K
>>> sys.canonical_coeffs_func = coeffs
"""
return self._canonical_coeffs_func
@canonical_coeffs_func.setter
def canonical_coeffs_func(self, func):
self._measurements._check_for_duplicate_keys()
func_args = getfullargspec(func).args
for k in func_args:
# NOTE : Measurements do not have to be time varying.
if k not in (list(self.constants.keys()) +
list(self.measurements.keys())):
msg = ('The function argument {} is not in constants or '
'measurements. Redefine your function in terms of '
'non-time varying parameters.')
raise ValueError(msg.format(k))
M, C, K = func(*np.random.random(len(func_args)))
self._check_system()
# TODO : Maybe this should belong in a overridden _check_system()?
num_states = len(self.states)
num_coords = len(self.coordinates)
num_speeds = len(self.speeds)
msg = ('The {} matrix should have a row and column for each '
'coordinate.')
if M.shape != (num_speeds, num_speeds):
raise ValueError(msg.format('mass'))
if C.shape != (num_speeds, num_speeds):
raise ValueError(msg.format('damping'))
if K.shape != (num_coords, num_coords):
raise ValueError(msg.format('stiffness'))
self._canonical_coeffs_func = func
self._ode_eval_func = self._generate_array_rhs_eval_func()
@property
def forcing_func(self):
"""A function that returns the right hand side forcing vector, F(t), of
the canonical second order linear ordinary differential equations. This
equation looks like the following:
Mv' + Cv + Kx = F(t)
where:
- M: mass matrix
- C: damping matrix
- K: stiffness matrix
- x: the generalized coordinate vector
- v: the generalized speed vector
The coefficients M, C, and K must be defined in terms of the system's
constants.
Example
=======
This is an example of a simple double pendulum linearized about its
equilibrium. The angles, theta1 and theta2, are defined relative to the
vertical and when both are zero the pendulum is in its hanging
equilibrium. The forcing function applies sinusoidal torquing to each
pendulum arm with respect to the inertial reference frame.
>>> from resonance.linear_systems import MultiDoFLinearSystem
>>> sys = MultiDoFLinearSystem()
>>> sys.constants['g'] = 9.8 # m/s**2
>>> sys.constants['l1'] = 1.0 # m
>>> sys.constants['l2'] = 1.0 # m
>>> sys.constants['m1'] = 0.5 # kg
>>> sys.constants['m2'] = 0.5 # kg
>>> sys.coordinates['theta1'] = 0.3 # rad
>>> sys.coordinates['theta2'] = 0.0 # rad
>>> sys.speeds['omega1'] = 0.0 # rad/s
>>> sys.speeds['omega2'] = 0.0 # rad/s
>>> def coeffs(m1, m2, l1, l2, g):
... # Represents a linear model of a simple double pendulum
... M = np.array([[l1 * (m1 + m2), m2 * l2],
... [m2 * l2, m2 * l1]])
... C = np.zeros_like(M)
... K = np.array([[-g * (m1 + m2), 0],
... [0, -m2 * g]])
... return M, C, K
>>> sys.canonical_coeffs_func = coeffs
>>> sys.constants['To'] = 1.0 # Nm
>>> sys.constants['beta'] = 0.01 # rad/s
>>> def forcing(To, beta, time):
... T1 = To * np.cos(beta * time)
... T2 = To * np.sin(beta * time)
... return T1, T2
...
>>> sys.forcing_func = forcing
"""
return self._forcing_func
@forcing_func.setter
def forcing_func(self, func):
args = [self._get_par_vals(k) for k in getfullargspec(func).args]
res = func(*args)
msg = ("Forcing function must return the same number of values as "
"the number of coordinates.")
try:
len(res)
except TypeError: # returns a single value
if len(self.coordinates) != 1:
raise ValueError(msg)
else:
if len(res) != len(self.coordinates):
raise ValueError(msg)
self._forcing_func = func
self._forcing_func_arg_names = getfullargspec(func).args
def canonical_coefficients(self):
"""Returns the mass, damping, and stiffness matrices in that order."""
if self.canonical_coeffs_func is None:
msg = ('There is no function available to calculate the canonical'
' coefficients.')
raise ValueError(msg)
else:
f = self.canonical_coeffs_func
args = [self._get_par_vals(k) for k in getfullargspec(f).args]
return f(*args)
def _form_A_B(self):
M, C, K = self.canonical_coefficients()
num_states = len(self.states)
num_coords = len(self.coordinates)
num_speeds = len(self.speeds)
# Mv' + Cv + Kx = F(t)
# A = [0 I ] x = [coords]
# [-M^-1 K -M^-1 C] [speeds]
# B = [0] u = [0]
# [M^-1] [generalized forces, F(t)]
A = np.zeros((num_states, num_states))
A[:num_coords, num_coords:] = np.eye(num_coords)
A[num_coords:, :num_coords] = -np.linalg.solve(M, K)
A[num_coords:, num_coords:] = -np.linalg.solve(M, C)
B = np.zeros((num_states, num_states))
# wouldn't this be better to do np.linalg.solve(M, self.forcing())
B[num_coords:, num_coords:] = np.linalg.inv(M)
return A, B
def _eval_forcing(self, t):
# t is either:
# shape(2n, 1)
# shape(m, 2n, 1)
size_t = np.size(t)
len_states = len(self.coordinates) + len(self.speeds)
if size_t > 1:
u = np.zeros((len(t), len_states, 1))
else:
u = np.zeros((len_states, 1))
if self._compute_forcing:
self._time['t'] = t