-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathMRPy.py
1495 lines (1054 loc) · 48.1 KB
/
MRPy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import sys
import gzip as gz
import pickle as pk
import numpy as np
import pandas as pd
from warnings import warn
from scipy.interpolate import interp1d
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
#=============================================================================
#=============================================================================
class MRPy(np.ndarray):
#=============================================================================
#=============================================================================
# 1. Class initialization
#=============================================================================
def __new__(cls, np_array, fs=None, Td=None):
X = np.asarray(np_array).view(cls)
if (X.size == 0):
sys.exit('Empty array not allowed for new objects!')
sh = X.shape
if (len(sh) == 1):
X = np.reshape(X,(1,sh[0]))
elif (sh[0] > sh[1]):
X = X.T
sh = X.shape
X.NX = sh[0]
X.N = sh[1]
if (X.N < 2):
sys.exit('Come on!!! Start with at least 2 elements!')
err = 1.0
if (np.mod(X.N, 2) != 0): # enforce N to be even...
X = X[:,:-1] # ... odd element is discarded!!!
err = (X.N - 1)/X.N # correction over Td
X.N = X.N - 1
if (fs != None): # if fs is prescribed...
X.fs = float(fs)
X.Td = X.N/X.fs # ... Td is calculated
elif (Td != None): # but if Td is prescribed...
X.Td = err*float(Td)
X.fs = X.N/X.Td # ... fs is calculated
else: sys.exit('Either fs or Td must be provided!')
X.M = X.N//2 + 1
return X
#-----------------------------------------------------------------------------
def __array_finalize__(self, X):
if X is None: return
self.fs = getattr(X, 'fs', None)
self.Td = getattr(X, 'Td', None)
self.NX = getattr(X, 'NX', None)
self.N = getattr(X, 'N', None)
self.M = getattr(X, 'M', None)
#=============================================================================
# 2. Class constructors from other sources
#=============================================================================
def from_file(filename, form='mrpy'):
"""
Load time series from file. Please contact the author for
including other types of datafile.
Parameters: filename: file to be loaded, including path,
whithout file extension
form: data formatting. Options are
'mrpy' - default gzip pickle loading
'excel' - excel generated with pandas
'columns' - t, X1, [X2, X3 ...]
'invh ' - csv file by iNVH app
'mpu6050' - gzip excel 6 axis data
"""
try:
#-------------
if (form.lower() == 'mrpy'):
with gz.GzipFile(filename+'.csv.gz', 'rb') as target:
return MRPy(*pk.load(target))
#---------------
elif (form.lower() == 'excel'):
with open(filename+'.xlsx', 'rb') as target:
data = pd.read_excel(target,
index_col=0,
sheet_name='MRPy')
ti = np.array(data.index, dtype=float)
return MRPy.resampling(ti, data.values)
#---------------
elif (form.lower() == 'columns'):
with open(filename+'.txt', 'rb') as target:
data = np.genfromtxt(target,
delimiter='\t')
ti = data[:,0]
return MRPy.resampling(ti, data[:,1:])
#---------------
elif (form.lower() == 'invh'):
with open(filename+'.csv', 'rb') as target:
data = np.genfromtxt(target,
delimiter=',',
skip_header=1)
ti = data[:,0]
return MRPy.resampling(ti, data[:,1:-1])
#---------------
elif (form.lower() == 'mpu6050'):
with gz.open(filename+'.csv.gz', 'rb') as target:
data = np.genfromtxt(target,
delimiter=',')
ti = data[:,0] - data[0,0]
return MRPy.resampling(ti, data[:,1:]/16384)
#---------------
else:
sys.exit('Data formatting not available!')
return None
except:
sys.exit('Could not read file "{0}"!'.format(filename))
return None
#-----------------------------------------------------------------------------
def from_periodogram(Sx, fs):
"""
Simulate RPs from given spectral densities.
Parameters: Sx: spectral densities as ndarray (must have odd
length, otherwise it will be truncated by 1 and
the length of simulation will not be as expected!)
The largest dimension of Sx is assumed to be the
frequency axis.
fs: sampling frequency in Hz
"""
sh = Sx.shape
if (len(sh) == 1):
Sx = np.reshape(Sx,(1,sh[0]))
elif (sh[0] > sh[1]):
Sx = Sx.T
sh = Sx.shape
NX = sh[0]
M0 = sh[1]
M = M0 - (np.mod(M0,2) == 0) # ensure M is odd
N = 2*(M - 1)
Sx = N*fs*np.abs(Sx[:,0:M])/2
X = np.empty((NX, N))
for k in range(NX):
phi = 2*np.pi*np.random.rand(M);
phi[0] = 0.
Pw = np.sqrt(Sx[k,:]) * (np.cos(phi) + 1j*np.sin(phi))
Pw = np.hstack((Pw, np.conj(Pw[-2:0:-1])))
X[k,:] = np.real(np.fft.ifft(Pw))
return MRPy(X, fs)
#-----------------------------------------------------------------------------
def from_autocov(Cx, Tmax):
"""
Simulate RPs from given autocovariance functions.
Parameters: Cx: autocovariances as ndarray (must have odd
length, otherwise it will be truncated by 1 and
the length of simulation will not be as expected!)
The largest dimension of Cx is assumed to be the
time gap axis.
Tmax: largest time gap, associated to the last element
in array Cx. Defines process duration, which
will be approximately 2Tmax.
"""
Sx, fs = MRPy.Cx2Sx(Cx, Tmax)
return MRPy.from_periodogram(Sx, fs)
#-----------------------------------------------------------------------------
def from_pseudo(Sa, Tmax, T, zeta=0.05): # NOT READY!!!
"""
Simulate ground acceleration records from a given pseudo acceleration
spectra.
Parameters: Sa: acceleration pseudo spectra as ndarray (must have
odd length, otherwise it will be truncated by 1 and
the length of simulation will not be as expected!)
The largest dimension of Sa is assumed to be the
period axis.
Tmax: largest period, associated to the last element
in array Sa. Defines process duration, which
will be approximately 2Tmax.
T: tuple (T1, T2, T0) defining envelope timing, where
T1 is the end of attack time, T2 is the end of
sustain time, and T0 is the time constant of the
exponential amplitude decay.
zeta: system damping (ratio of critical) can be
provided or default value of 5% is assumed.
"""
sh = Sa.shape
if (len(sh) == 1):
Sa = np.reshape(Sa,(1,sh[0]))
else:
if (sh[0] > sh[1]):
Sa = Sa.T
sh = Sa.shape
NX = sh[0]
M0 = sh[1]
M = M0 - (np.mod(M0,2) == 0) # ensure M is odd
N = 2*(M - 1)
err = M/M0
fs = (M - 1)/(err*Tmax) # eventually corrects for Tmax
f = np.linspace(0, fs/2, M)
tau = np.linspace(0, Tmax, M)
fi = np.zeros(M)
fi[1:] = 1/tau[:0:-1]
X = np.empty((NX,N))
for k in range(NX):
Sxi = np.zeros(M)
Sxi[1:] = Sa[k,1:]
fSx = interp1d(fi, Sxi, kind='quadratic')
X[k] = MRPy.from_periodogram(fSx(f), fs)
X[k] *= Sa.max()/X[k].max()
return MRPy(X, fs).Kanai().envelope(T)
#=============================================================================
# 3. Class constructors by modification
#=============================================================================
def zero_mean(self):
"""
Clean mean values.
"""
X = MRPy.copy(self)
Xm = X.mean(axis=1)
for k in range(self.NX):
X[k,:] -= Xm[k]
return X
#-----------------------------------------------------------------------------
def superpose(self, weight=1.):
"""
Add up all series in MRPy weighted by 'weight', which is a
scalar or list with weights for summation. This method can be
used, for instance, for combining modal responses according to
modal shape coordinate at a given structural node.
"""
if ~hasattr(weight, "__len__"):
weight = weight*np.ones(self.NX)
elif (len(weight) != self.NX):
sys.exit('Weight length must equal number of processes!')
X = np.zeros((1, self.N))
for kX, row in enumerate(self):
X[0,:] += weight[kX]*row
return MRPy(X, self.fs)
#-----------------------------------------------------------------------------
def double(self):
"""
Double MRPy duration by filling with mean values.
"""
Xm = self.mean(axis=1)
X = np.hstack((self, np.tile(Xm,(self.N, 1)).T))
return MRPy(X, self.fs)
#-----------------------------------------------------------------------------
def extract(self, segm=(1/4, 3/4), by='fraction'):
"""
Extract a central segment of time range. The lower and upper
cutting point as defined as a tuple or list, which meaning is
defined by a code 'by':
Parameters: segm: tuple or list with the lower and upper
cutting points.
by: code indicating the meaning of cutting points:
'fraction': default meaning
'time' : time axis related
'index' : directly through indexing
"""
if (segm[0] >= segm[1]):
sys.exit('Upper limit must be larger than lower limit!')
if (by.lower() == 'fraction'):
i0 = int(segm[0]*self.N)
i1 = int(segm[1]*self.N)
elif (by.lower() == 'time'):
i0 = int(segm[0]*self.fs)
i1 = int(segm[1]*self.fs)
elif (by.lower() == 'index'):
i0 = int(segm[0])
i1 = int(segm[1])
else:
sys.exit('Segment definition code is unknown!')
return None
i1 = i1 - np.mod(i1-i0, 2) # ensure even length
if (i0 < 0 ): i0 = 0 # do not go over boundaries
if (i1 > self.N): i1 = self.N
return MRPy(self[:,i0:i1], self.fs)
#-----------------------------------------------------------------------------
def envelope(self, T):
"""
Apply an amplitude envelope with exponential attack e decay.
This type of envelope is used for simulation of seismic acceleration.
Parameters: T: tuple (T1, T2, T0) defining envelope timing, where
T1 is the end of attack time, T2 is the end of
sustain time, and T0 is the time constant of the
exponential amplitude attack and decay.
"""
t = self.t_axis()
X = MRPy.copy(self)
env = np.ones(self.N)
env[t < T[0]] = (1 - np.exp(-t[t < T[0]]/T[0]))/(1 - np.exp(-1))
env[t > T[1]] = np.exp((T[1] - t[t > T[1]])/T[2])
for k in range(self.NX):
X[k,:] *= env
return X
#-----------------------------------------------------------------------------
def mov_average(self, n=3, win='tri'):
"""
Apply moving average with specified window.
Parameters: n: window width (truncated to be odd integer)
win: window type. Available windows are:
'rec': rectangular
'tri': triangular (default)
"""
n = int(n) # truncate to integer
n = n - (1 - np.mod(n,2)) # n is odd or will be decreased by 1
m = (n - 1)//2 + 1 # window center
W = np.ones(n) # default rectangular window
if (win.lower() == 'rec'):
pass
elif (win.lower() == 'tri'):
W[ :m] = np.linspace(1/m, 1., m)
W[m-1: ] = np.linspace(1., 1/m, m)
else:
sys.error('Averaging window type not available!')
m = m - 1
W = W/W.sum()
X = MRPy.copy(self)
for kX in range(self.NX):
for k in range(0, m):
k0 = m - k
W0 = W[k0:]/np.sum(W[k0:])
X[kX,k] = np.sum(W0*self[kX,:k+m+1])
for k in range(m, self.N-m-1):
X[kX,k] = np.sum(W*self[kX,k-m:k+m+1])
for k in range(self.N-m-1, self.N):
k0 = m - k + self.N
W0 = W[:k0]/np.sum(W[:k0])
X[kX,k] = np.sum(W0*self[kX,k-m:])
return X
#-----------------------------------------------------------------------------
def filtered(self, band, mode='pass'):
"""
Apply filtering in frequency domain. Series size is doubled by
trailing zeros before filtering, in order to minimize aliasing.
Parameters: band: frequency band as tuple or list: [f_low, f_high]
mode: filter type. Available:
'pass': band pass (default)
'stop': band stop
"""
X = self.double()
f = X.f_axis()
b0, b1 = MRPy.check_band(self.f, band)
for kX in range(X.NX):
Xw = np.fft.fft(X[kX,:])[0:X.M]
if mode.lower() == 'pass':
Xw[(f < b0) | (f >= b1)] = 0.
elif mode.lower() == 'stop':
Xw[(f >= b0) & (f < b1)] = 0.
else:
warn('Filter type not available!')
X[kX,:] = np.real(np.fft.ifft(
np.hstack((Xw, np.conj(Xw[-2:0:-1])))))
return MRPy(X[:,0:self.N], self.fs)
#-----------------------------------------------------------------------------
def Kanai(self, H1=(4.84, 0.60), H2=(0.97, 0.60)):
"""
Apply Kanai/Tajimi filtering, with low frequency range attenuation
to avoid integration drifting. This filter is used for simulation
of seismic acceleration.
Parameters: H1: tuple (f1, zeta1) for first filter part,
where default values represent firm soil condition.
H2: tuple (f2, zeta2) for second filter part, which
must properly attenuate low frequency range.
"""
X = np.empty((self.NX, self.N))
for kX, row in enumerate(self):
Xw = np.fft.fft(row)[0:self.M]
w1 = self.f_axis()/H1[0]
w2 = self.f_axis()/H2[0]
Hw1 = (1 + 2j*H1[1]*w1)/(1 - w1*w1 + 2j*H1[1]*w1)
Hw2 = (w2*w2)/(1 - w2*w2 + 2j*H2[1]*w2)
Xw = Xw*Hw1*Hw2
Xk = np.real(np.fft.ifft(np.hstack((Xw, np.conj(Xw[-2:0:-1])))))
X[kX,:] = Xk[0:self.N]
return MRPy(X, self.fs)
#-----------------------------------------------------------------------------
def integrate(self, band=None):
"""
Frequency domain integration with passing band.
Parameters: band: frequency band to keep, tuple: (f_low, f_high)
"""
b0, b1 = MRPy.check_band(self.fs, band)
X = np.empty((self.NX, self.N))
f = self.f_axis(); f[0] = f[1] # avoid division by zero
for kX, row in enumerate(self):
Xw = np.fft.fft(row)[0:self.M]
Xw = Xw / (2j*np.pi*f) # division means integration
Xw[0] = 0. # disregard integration constant
Xw[(f <= b0) | (f > b1)] = 0.
X[kX,:] = np.real(np.fft.ifft(
np.hstack((Xw, np.conj(Xw[-2:0:-1])))))
return MRPy(X, self.fs)
#-----------------------------------------------------------------------------
def differentiate(self, band=None):
"""
Frequency domain differentiation with passing band.
Parameters: band: frequency band to keep, tuple: (f_low, f_high)
"""
b0, b1 = MRPy.check_band(self.fs, band)
X = np.empty((self.NX, self.N))
f = self.f_axis(); f[0] = f[1] # avoid division by zero
for kX, row in enumerate(self):
Xw = np.fft.fft(row)[0:self.M]
Xw = Xw * (2j*np.pi*f) # multiplication means derivation
Xw[(f <= b0) | (f > b1)] = 0.
X[kX,:] = np.real(np.fft.ifft(
np.hstack((Xw, np.conj(Xw[-2:0:-1])))))
return MRPy(X, self.fs)
#-----------------------------------------------------------------------------
def sdof_fdiff(self, fn, zeta, U0=0., V0=0.):
"""
Integrates the dynamic equilibrium differential equation by
the central finite differences method.
The input is assumed to be an acceleration (force over mass),
otherwise the result must be divided by system mass to have
displacement unit.
System properties (frequency and damping) may be provided as
scalars or lists. If they are scalars, same properties are used
for all series in the MRP. The same applies for initial conditions
U0 (displacement) and V0 (velocity)
Parameters: fn: sdof natural frequency (Hz)
zeta: sdof damping as ratio of critial (nondim)
U0: initial position (default is all zero)
V0: initial velocity (default is all zero)
"""
if ~hasattr(fn, "__len__"):
fn = fn*np.ones(self.NX)
if ~hasattr(zeta, "__len__"):
zeta = zeta*np.ones(self.NX)
if ~hasattr(U0, "__len__"):
U0 = U0*np.ones(self.NX)
if ~hasattr(V0, "__len__"):
V0 = V0*np.ones(self.NX)
dt = 1/self.fs
X = MRPy(np.empty((self.NX, self.N)), self.fs)
for kX, row in enumerate(self):
zt = zeta[kX]
wn = 2*np.pi*fn[kX]
b1 = ( zt*wn + 1/dt)/dt
b2 = ( zt*wn - 1/dt)/dt
b3 = (dt*wn*wn - 2/dt)/dt
X[kX,0] = U0
X[kX,1] = U0 + V0*dt + row[0]*dt*dt/2
for k in range(2,self.N):
X[kX,k] = (row[k-1] + b2*X[kX,k-2] - b3*X[kX,k-1])/b1
return X
#-----------------------------------------------------------------------------
def sdof_Duhamel(self, fn, zeta, U0=0., V0=0.):
"""
Integrates the dynamic equilibrium differential equation by Duhamel.
The input is assumed to be an acceleration (force over mass),
otherwise the result must be divided by system mass to have
displacement unit.
System properties (frequency and damping) may be provided as
scalars or lists. If they are scalars, same properties are used
for all series in the MRP. The same applies for initial conditions
U0 (displacement) and V0 (velocity)
Parameters: fn: sdof natural frequency (Hz)
zeta: sdof damping as ratio of critial (nondim)
U0: initial position (default is all zero)
V0: initial velocity (default is all zero)
"""
if ~hasattr(fn, "__len__"):
fn = fn*np.ones(self.NX)
if ~hasattr(zeta, "__len__"):
zeta = zeta*np.ones(self.NX)
if ~hasattr(U0, "__len__"):
U0 = U0*np.ones(self.NX)
if ~hasattr(V0, "__len__"):
V0 = V0*np.ones(self.NX)
t = self.t_axis()
dt = 1/self.fs
X = MRPy(np.zeros((self.NX, self.N)), self.fs)
for kX, row in enumerate(self):
zt = zeta[kX]
wn = 2*np.pi*fn[kX]
wd = wn*np.sqrt(1 - zt*zt)
et = np.exp(zt*wn*t)
st = np.sin(wd*t)
ct = np.cos(wd*t)
X[kX,:] = (U0[kX]*ct + (V0[kX] + U0[kX]*zt*wn)*st/wd)/et
A = dt*np.cumsum(row*et*ct)
B = dt*np.cumsum(row*et*st)
X[kX,:] += (A*st - B*ct)/et/wd
return X
#-----------------------------------------------------------------------------
def sdof_Fourier(self, fn, zeta):
"""
Integrates the dynamic equilibrium differential equation by Fourier.
The input MRPy is assumed to be an acceleration (force over mass),
otherwise the result must be divided by system mass to have
displacement unit.
System properties (frequency and damping) may be provided as
scalars or lists. If they are scalars, same properties are used
for all series in the MRP.
Parameters: fn: sdof natural frequency (Hz)
zeta: sdof damping (nondim)
"""
if ~hasattr(fn, "__len__"):
fn = fn*np.ones(self.NX)
if ~hasattr(zeta, "__len__"):
zeta = zeta*np.ones(self.NX)
X = MRPy(np.empty((self.NX, self.N)), self.fs)
for kX, row in enumerate(self):
zt = zeta[kX]
wn = 2*np.pi*fn[kX]
K = wn*wn
b = 2*np.pi*self.f_axis()/wn
Hw = (K*((1.0 - b**2) + 1j*(2*zt*b)))**(-1)
Hw = np.hstack((Hw,np.conj(Hw[-2:0:-1])))
X[kX,:] = np.real(np.fft.ifft(Hw*np.fft.fft(row)))
return X
#-----------------------------------------------------------------------------
def random_decrement(self, div=4, thr=1.0, ref=0):
"""
MATHEUS CARINI HAS FOUND A PROBLEM HERE! MUST BE REVISED!!!
Estimate the free decay response of a dynamic system from the
response to a wide band excitation by the random decrement (RD)
method.
Parameters: div: number of divisions of total length, N//n,
to define the length of decrement series.
The divided length will be eventually truncated
to be even.
thr: threshold level that defines the reference
upcrossing level, given as a multiple of the
standard deviation of the reference MRP.
ref: row of MRPy to be used as reference series.
The other series will be splitted at the same
crossing points, what implies phase consistency.
"""
n = self.N//div # convert to length
n = n - (np.mod(n,2) == 1) # force length to be even
Xm = self.mean(axis=1) # mean values are zero
Xref = self[ref,:] # reference series
X0 = thr*(Xref.std()) # crossing reference level
kref = ( ((Xref[0:(self.N-1)] < X0) & (Xref[1:self.N] >= X0)) |
((Xref[0:(self.N-1)] > X0) & (Xref[1:self.N] <= X0)) )
nk = sum(kref)
Y = MRPy(np.zeros((self.NX, n)), self.fs)
for kX, row in enumerate(self):
row -= Xm[kX] # remove mean value
for k in range(self.N - n):
if kref[k]:
Y[kX,:] += row[k:(k+n)]
return Y/nk
#-----------------------------------------------------------------------------
def fit_decay(self):
"""
Fit the theoretical free decay function of a sdof dynamic system
to the provided MRP. The MRPy mean value is discarded. The fitted
parameters are output as a tuple P = (Xp, fn, zt, ph), where
Xp is the amplitude, fn is the fundamental (undamped) frequency,
zt is the damping as the ratio of critical, and ph is the phase
angle with respect with the cosinus function. This method is
typically used to fit the output of the random decrement method.
"""
#-------------------------------------------------------
def decay(t, Xp, fn, zt, ph):
wn = 2*np.pi*fn
wd = wn*np.sqrt(1. - zt*zt)
return Xp*np.exp(-zt*wn*t)*np.cos(wd*t - ph)
#-------------------------------------------------------
t = self.t_axis()
f = self.f_axis()
P = np.zeros((self.NX, 4))
X = self.zero_mean()
Sx, fs = X.periodogram()
for kX, row in enumerate(X):
Xp = np.max(row) # initial amplitude value
fn = f[np.argmax(Sx[kX,:])] # initial natural frequency
zt = 0.03 # initial damping
ph = 0.00 # initial phase
Pmin = (0.5*Xp, 1/t[-1], 0.0, -np.pi) # lower bounds
P0 = ( Xp, fn, zt, ph ) # initial guesses
Pmax = (1.5*Xp, 1*f[-1], 0.5, np.pi) # upper bounds
try:
P[kX,:], cv = curve_fit(decay, t, row,
p0=P0, bounds=(Pmin, Pmax))
except:
P[kX,:] = np.zeros(5)
print('Not able to fit decay function!!!')
pass
X[kX,:] = decay(t, *P[kX,:])
return MRPy(X, fs), P
#=============================================================================
# 4. Class constructors from conceptual properties
#=============================================================================
def zeros(NX=1, N=1024, fs=None, Td=None):
"""
Add up all series in MRPy weighted by 'weight'.
Parameters: NX: number of processes in the MRPy object.
N: length of each process.
fs: sampling frequency (in Hz), or alternatively
Td: processes duration (second)
"""
fs, Td = MRPy.check_fs(N, fs, Td)
return MRPy(np.zeros((NX,N)), fs)
#-----------------------------------------------------------------------------
def Dirac(NX=1, N=1024, t0=0.0, fs=None, Td=None):
"""
Add up all series in MRPy weighted by 'weight'.
Parameters: NX: number of processes in the MRPy object.
N: length of each process.
t0: time at which impulse must be given
fs: sampling frequency (in Hz), or alternatively
Td: processes duration (second)
"""
fs, Td = MRPy.check_fs(N, fs, Td)
i0 = int(t0*fs)
X = np.zeros((NX,N))
X[:,i0] = 1.0
return MRPy(X, fs)
#-----------------------------------------------------------------------------
def Heaviside(NX=1, N=1024, t0=0.0, fs=None, Td=None):
"""
Add up all series in MRPy weighted by 'weight'.
Parameters: NX: number of processes in the MRPy object.
N: length of each process.
t0: time at which step must be given
fs: sampling frequency (in Hz), or alternatively
Td: processes duration (second)
"""
fs, Td = MRPy.check_fs(N, fs, Td)
i0 = int(t0*fs)
X = np.zeros((NX,N))
X[:,i0:] = 1.0
return MRPy(X, fs)
#-----------------------------------------------------------------------------
def harmonic(NX=1, N=1024, fs=None, Td=None, X0=1.0, f0=1.0, phi=0.0):
"""
Creates an instance with harmonic functions with unity amplitude.
Parameters: NX: number of processes in the MRPy object.
N: length of each process.
fs: sampling frequency (in Hz), or alternatively
Td: processes duration (second)
X0: process amplitude
f0: signal frequency (in Hz)
phi: signal phase (rad).
"""
fs, Td = MRPy.check_fs(N, fs, Td)
X = np.zeros((NX,N))
if ~hasattr(X0, "__len__"):
X0 = X0*np.ones(NX)
if ~hasattr(f0, "__len__"):
f0 = f0*np.ones(NX)
if ~hasattr(phi, "__len__"):
phi = phi*np.ones(NX)
t = np.linspace(0, Td, N)
for kX in range(NX):
X[kX,:] = X0[kX]*np.sin(2*np.pi*f0[kX]*t + phi[kX])
return MRPy(X, fs)
#-----------------------------------------------------------------------------
def white_noise(NX=1, N=1024, fs=None, Td=None, band=None):
"""
Simulates a band-limited Gaussian white noise'.
Parameters: NX: number of processes in the MRPy object.
N: length of each process.
fs: sampling frequency (in Hz), or alternatively
Td: processes duration (second)
band: band with nonzero power (in Hz)
"""
fs, Td = MRPy.check_fs(N, fs, Td)
b0, b1 = MRPy.check_band(fs, band)
M = N//2 + 1
Sx = np.ones((NX, M))
k0 = int(2*M*b0/fs)
k1 = int(2*M*b1/fs)
Sx[:,:k0] = 0.
Sx[:,k1:] = 0.
for kX in range(NX):
Sx[kX] = Sx[kX]/np.trapz(Sx[kX], dx=1./Td)
return MRPy.from_periodogram(Sx, fs)
#-----------------------------------------------------------------------------
def pink_noise(NX=1, N=1024, fs=None, band=None):
"""
Add up all series in MRPy weighted by 'weight'.
Parameters: NX: number of processes in the MRPy object.
N: length of each process.
fs: sampling frequency (in Hz), or alternatively
Td: processes duration (second)
band: band with nonzero power (in Hz)
"""
fs, Td = MRPy.check_fs(N, fs, Td)
b0, b1 = MRPy.check_band(fs, band)
M = N//2 + 1
Sx = np.ones((NX, M))
k0 = int(2*M*b0/fs)
k1 = int(2*M*b1/fs)
Sx[:,:k0] = 0.
Sx[:,k1:] = 0.
for kX in range(NX):
Sx[kX] = Sx[kX]/np.trapz(Sx[kX], dx=1./Td)
return MRPy.from_periodogram(Sx, fs)
#=============================================================================
# 5. MRPy properties (as non-MRPy outputs)
#=============================================================================
def periodogram(self):
"""
Estimates the one-side power spectrum of a MRP.
"""
Sx = np.empty((self.NX, self.M))
for kX in range(self.NX):
Fx = np.fft.fft(self[kX,:] - self[kX,:].mean())
Sxk = np.real(Fx*Fx.conj())*2/self.N/self.fs
Sx[kX,:] = Sxk[:self.M]
return Sx, self.fs
#-----------------------------------------------------------------------------
def autocov(self):
"""
Estimates the autocovariance functions of a MRP.
"""
Tmax = (self.M - 1)/self.fs
Cx = np.empty((self.NX, self.M))
Sx, fs = self.periodogram()
for kX in range(self.NX):
Sxk = np.hstack((Sx[kX,:], Sx[kX,-2:0:-1]))
Cxk = np.fft.ifft(Sxk)*fs/2
Cx[kX,:] = np.real(Cxk[:self.M])
return Cx, Tmax
#-----------------------------------------------------------------------------
def autocorr(self):
"""
Estimates the autocorrelation function of a MRP.
"""
Xs = self.std(axis=1)
Rx = np.empty((self.NX,self.M))