/
resolucaoexercicios.py
665 lines (592 loc) · 25.4 KB
/
resolucaoexercicios.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
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 10:10:23 2020
@author: gio-x
"""
'''
###############################################################################
IMPORTAÇÃO DE MÓDULOS
##############################################################################
'''
# import matplotlib.mlab as mlab
from scipy.stats import norm, genextreme
# from scipy import optimize
import numpy.random as rnd
from numpy.fft import rfftfreq, irfft
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
# from pylab import savefig
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import Polygon
from yellowbrick.cluster import KElbowVisualizer
import mfdfa
import statsfuncs
'''
###############################################################################
FUNÇÕES QUE GERAM MODELOS
Seção do código de funções enviadas pelo professor, modificadas para caber
em um código que faça tudo de uma vez
###############################################################################
'''
def pmodel(seriestype):
if(seriestype=="Endogenous"):
p=0.32 + 0.1*rnd.uniform()
slope= 0.4
else:
p=0.18 + 0.1*rnd.uniform()
slope=0.7
noValues=8192
noOrders = int(np.ceil(np.log2(noValues)))
y = np.array([1])
for n in range(noOrders):
y = next_step_1d(y, p)
if (slope):
fourierCoeff = fractal_spectrum_1d(noValues, slope/2)
meanVal = np.mean(y)
stdy = np.std(y)
x = np.fft.ifft(y - meanVal)
phase = np.angle(x)
x = fourierCoeff*np.exp(1j*phase)
x = np.fft.fft(x).real
x *= stdy/np.std(x)
x += meanVal
else:
x = y
return x[0:noValues], y[0:noValues]
def next_step_1d(y, p):
y2 = np.zeros(y.size*2)
sign = np.random.rand(1, y.size) - 0.5
sign /= np.abs(sign)
y2[0:2*y.size:2] = y + sign*(1-2*p)*y
y2[1:2*y.size+1:2] = y - sign*(1-2*p)*y
return y2
def fractal_spectrum_1d(noValues, slope):
ori_vector_size = noValues
ori_half_size = ori_vector_size//2
a = np.zeros(ori_vector_size)
for t2 in range(ori_half_size):
index = t2
t4 = 1 + ori_vector_size - t2
if (t4 >= ori_vector_size):
t4 = t2
coeff = (index + 1)**slope
a[t2] = coeff
a[t4] = coeff
a[1] = 0
return a
def powerlaw_psd_gaussian(exponent, size=8192, fmin=0):
"""Gaussian (1/f)**beta noise.
Based on the algorithm in:
Timmer, J. and Koenig, M.:
On generating power law noise.
Astron. Astrophys. 300, 707-710 (1995)
Normalised to unit variance
Parameters:
-----------
exponent : float
The power-spectrum of the generated noise is proportional to
S(f) = (1 / f)**beta
flicker / pink noise: exponent beta = 1
brown noise: exponent beta = 2
Furthermore, the autocorrelation decays proportional to lag**-gamma
with gamma = 1 - beta for 0 < beta < 1.
There may be finite-size issues for beta close to one.
shape : int or iterable
The output has the given shape, and the desired power spectrum in
the last coordinate. That is, the last dimension is taken as time,
and all other components are independent.
fmin : float, optional
Low-frequency cutoff.
Default: 0 corresponds to original paper. It is not actually
zero, but 1/samples.
Returns
-------
out : array
The samples.
Examples:
---------
# generate 1/f noise == pink noise == flicker noise
>>> import colorednoise as cn
>>> y = cn.powerlaw_psd_gaussian(1, 5)
"""
# Make sure size is a list so we can iterate it and assign to it.
try:
size = list(size)
except TypeError:
size = [size]
# The number of samples in each time series
samples = size[-1]
# Calculate Frequencies (we asume a sample rate of one)
# Use fft functions for real output (-> hermitian spectrum)
f = rfftfreq(samples)
# Build scaling factors for all frequencies
s_scale = f
fmin = max(fmin, 1./samples) # Low frequency cutoff
ix = np.sum(s_scale < fmin) # Index of the cutoff
if ix and ix < len(s_scale):
s_scale[:ix] = s_scale[ix]
s_scale = s_scale**(-exponent/2.)
# Calculate theoretical output standard deviation from scaling
w = s_scale[1:].copy()
w[-1] *= (1 + (samples % 2)) / 2. # correct f = +-0.5
sigma = 2 * np.sqrt(np.sum(w**2)) / samples
# Adjust size to generate one Fourier component per frequency
size[-1] = len(f)
# Add empty dimension(s) to broadcast s_scale along last
# dimension of generated random power + phase (below)
dims_to_add = len(size) - 1
s_scale = s_scale[(np.newaxis,) * dims_to_add + (Ellipsis,)]
# Generate scaled random power + phase
sr = rnd.normal(scale=s_scale, size=size)
si = rnd.normal(scale=s_scale, size=size)
# If the signal length is even, frequencies +/- 0.5 are equal
# so the coefficient must be real.
if not (samples % 2): si[...,-1] = 0
# Regardless of signal length, the DC component must be real
si[...,0] = 0
# Combine power + corrected phase to Fourier components
s = sr + 1J * si
# Transform to real time series & scale to unit variance
y = irfft(s, n=samples, axis=-1) / sigma
x=range(0,len(y))
return x,y
def randomseries(n):
'''
Gerador de Série Temporal Estocástica - V.1.2 por R.R.Rosa
Trata-se de um gerador randômico não-gaussiano sem classe de universalidade via PDF.
Input: n=número de pontos da série
res: resolução
'''
res = n/12
df = pd.DataFrame(np.random.randn(n) * np.sqrt(res) * np.sqrt(1 / 128.)).cumsum()
a=df[0].tolist()
a=statsfuncs.normalize(a)
x=range(0,n)
return x,a
def Logistic(dummy):
N=8192
rho=3.85 + 0.15*np.random.uniform()
tau = 1.1
x = [0.001]
y = [0.001]
for i in range(1,N):
y.append( tau*x[-1] )
x.append( rho*x[-1]*(1.0-x[-1]))
return y,x
def HenonMap(dummy):
N=8192
a=1.350 + 0.05*np.random.uniform()
b=0.21 + 0.08*np.random.uniform()
x = [0.1]
y = [0.3]
for i in range(1,N):
y.append(b * x[-1])
x.append(y[-2] + 1.0 - a *x[-1]*x[-1])
return x,y
'''
###############################################################################
FUNÇÕES CONSTRUTORAS DE SÉRIES OU ESPAÇOS
Funções que servem para construir as séries temporais ou construir os k-means
geralmente retornam os dados que elas geram.
###############################################################################
'''
def makeseries(func, iterationlist, amount, title="Nada", graphs=False):
values=[]
ilist=[]
rawdata=[]
for i in iterationlist:
for j in range(amount):
x,y=func(i)
alfa,xdfa,ydfa, reta = statsfuncs.dfa1d(y,1)
freqs, power, xdata, ydata, amp, index, powerlaw, INICIO, FIM = statsfuncs.psd(y)
psi,alphal,falpha=mfdfa.makemfdfa(y)
values.append([statsfuncs.variance(y), statsfuncs.skewness(y), statsfuncs.kurtosis(y)+3, alfa, index,psi])
ilist.append(i)
if graphs==True:
plt.plot(alphal, falpha, 'ko-', label=str(j))
if graphs==True:
plt.title("Espectro de Singularidade, para: {} {}".format(title,i))
plt.xlabel(r'$\alpha$')
plt.ylabel(r'$f(\alpha)$')
plt.grid('on', which = 'major')
plt.savefig("{}singularityspectrum{}".format(title,i))
plt.show()
rawdata.append([i,x,y, alfa, xdfa, ydfa, reta, freqs, power, xdata, ydata, amp, index, powerlaw, INICIO, FIM])
return values, ilist, rawdata
def makeK(d,ilist, title):
print(ilist)
d=np.array(d)
kk=pd.DataFrame({'Variance': d[:,0], 'Skewness': d[:,1], 'Kurtosis': d[:,2]})
K=20
model=KMeans()
visualizer = KElbowVisualizer(model, k=(1,K))
kIdx=visualizer.fit(kk) # Fit the data to the visualizer
visualizer.show() # Finalize and render the figure
kIdx=kIdx.elbow_value_
model=KMeans(n_clusters=kIdx).fit(kk)
# scatter plot
fig = plt.figure()
ax = Axes3D(fig) #.add_subplot(111))
cmap = plt.get_cmap('gnuplot')
clr = [cmap(i) for i in np.linspace(0, 1, kIdx)]
for i in range(0,kIdx):
ind = (model.labels_==i)
ax.scatter(d[ind,2],d[ind,1], d[ind,0], s=30, c=clr[i], label='Cluster %d'%i)
ax.set_xlabel("Kurtosis")
ax.set_ylabel("Skew")
ax.set_zlabel("Variance")
plt.title(title+': KMeans clustering with K=%d' % kIdx)
plt.legend()
plt.savefig(title+"clusters.png")
plt.show()
d=pd.DataFrame({'Variance': d[:,0], 'Skewness': d[:,1], 'Kurtosis': d[:,2], 'Alpha': d[:,3], 'Beta': d[:,4], "Psi": d[:,5], "Cluster": model.labels_}, index=ilist)
return d
'''
###############################################################################
FUNÇÕES QUE GERAM GRÁFICOS
Funções que não retornam nada e só fazem gráficos
###############################################################################
'''
def cullenfrey(xd,yd,legend, title):
plt.figure(num=None, figsize=(8, 8), dpi=100, facecolor='w', edgecolor='k')
fig, ax = plt.subplots()
maior=max(xd)
polyX1=maior if maior > 4.4 else 4.4
polyY1=polyX1+1
polyY2=3/2.*polyX1+3
y_lim = polyY2 if polyY2 > 10 else 10
x = [0,polyX1,polyX1,0]
y = [1,polyY1,polyY2,3]
scale = 1
poly = Polygon( np.c_[x,y]*scale, facecolor='#1B9AAA', edgecolor='#1B9AAA', alpha=0.5)
ax.add_patch(poly)
ax.plot(xd,yd, marker="o", c="#e86a92", label=legend, linestyle='')
ax.plot(0, 4.187999875999753, label="logistic", marker='+', c='black')
ax.plot(0, 1.7962675925351856, label ="uniform", marker='^',c='black')
ax.plot(4, 9, label="exponential", marker='s', c='black')
ax.plot(0, 3, label="normal", marker='*',c='black')
ax.plot(np.arange(0,polyX1,0.1), 3/2.*np.arange(0,polyX1,0.1)+3, label="gamma", linestyle='-',c='black')
ax.plot(np.arange(0,polyX1,0.1), 2*np.arange(0,polyX1,0.1)+3, label="lognormal", linestyle='-.',c='black')
ax.legend()
ax.set_ylim(y_lim,0)
ax.set_xlim(-0.2,polyX1)
plt.xlabel("Skewness²")
plt.title(title+": Cullen and Frey map")
plt.ylabel("Kurtosis")
plt.savefig(title+legend+"cullenfrey.png")
plt.show()
def makespaces(s2, k, alpha, beta, legend, title):
kk=pd.DataFrame({'Skew²': s2, 'Kurtosis': k, 'Alpha': alpha, 'Beta': beta})
K=8
model=KMeans()
visualizer = KElbowVisualizer(model, k=(1,K))
kIdx=visualizer.fit(kk.drop(columns="Beta")) # Fit the data to the visualizer
visualizer.show() # Finalize and render the figure
kIdx=kIdx.elbow_value_
model=KMeans(n_clusters=kIdx).fit(kk.drop(columns="Beta"))
fig = plt.figure()
ax = Axes3D(fig)
cmap = plt.get_cmap('gnuplot')
clr = [cmap(i) for i in np.linspace(0, 1, kIdx)]
for i in range(0,kIdx):
ind = (model.labels_==i)
ax.scatter(kk["Skew²"][ind],kk["Kurtosis"][ind], kk["Alpha"][ind], s=30, c=clr[i], label='Cluster %d'%i)
ax.set_xlabel("Skew²")
ax.set_ylabel("Kurtosis")
ax.set_zlabel(r"$\alpha$")
ax.legend()
plt.title(title+": EDF-K-means")
plt.savefig(title+"EDF.png")
plt.show()
model=KMeans()
visualizer = KElbowVisualizer(model, k=(1,K))
kIdx=visualizer.fit(kk.drop(columns="Alpha")) # Fit the data to the visualizer
visualizer.show() # Finalize and render the figure
kIdx=kIdx.elbow_value_
model=KMeans(n_clusters=kIdx).fit(kk.drop(columns="Alpha"))
fig = plt.figure()
ax = Axes3D(fig)
cmap = plt.get_cmap('gnuplot')
clr = [cmap(i) for i in np.linspace(0, 1, kIdx)]
for i in range(0,kIdx):
ind = (model.labels_==i)
ax.scatter(kk["Skew²"][ind],kk["Kurtosis"][ind], kk["Beta"][ind], s=30, c=clr[i], label='Cluster %d'%i)
ax.set_xlabel("Skew²")
ax.set_ylabel("Kurtosis")
ax.set_zlabel(r"$\beta$")
ax.legend()
plt.title(title+": EPSB-K-means")
plt.savefig(title+"EPSB.png")
plt.show()
def makespaces62(s2, k, alpha, beta, legend, title, ilist):
SMALL_SIZE = 10
MEDIUM_SIZE = 15
BIGGER_SIZE = 20
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
kk=pd.DataFrame({'Skew²': s2, 'Kurtosis': k, 'Alpha': alpha, 'Beta': beta, "Entity": ilist})
K=8
model=KMeans()
visualizer = KElbowVisualizer(model, k=(1,K))
kIdx=visualizer.fit(kk.drop(columns=["Beta", "Entity"])) # Fit the data to the visualizer
visualizer.show() # Finalize and render the figure
kIdx=kIdx.elbow_value_
model=KMeans(n_clusters=kIdx).fit(kk.drop(columns=["Beta", "Entity"]))
print(len(model.labels_))
fig = plt.figure(figsize=(20,15))
ax = Axes3D(fig)
cmap = plt.get_cmap('gnuplot')
ilist2=list(set(ilist))
clr = [cmap(i) for i in np.linspace(0, 1, len(ilist2))]
for i in range(0,len(ilist2)):
ind = (kk["Entity"]==ilist2[i])
ax.scatter(kk["Skew²"][ind],kk["Kurtosis"][ind], kk["Alpha"][ind], s=120, c=clr[i], label=ilist2[i])
ax.set_xlabel("Skew²")
ax.set_ylabel("Kurtosis")
ax.set_zlabel(r"$\alpha$")
ax.legend()
plt.title(title+": EDF-K-means")
plt.savefig("datasetandcovidEDF.png")
plt.show()
kk=pd.DataFrame({'Skew²': s2, 'Kurtosis': k, 'Alpha': alpha, 'Beta': beta, "Entity": ilist}, index=model.labels_)
kk.sort_index(inplace=True)
kk.to_csv("clusteringalpha.csv")
model=KMeans()
visualizer = KElbowVisualizer(model, k=(1,K))
kIdx=visualizer.fit(kk.drop(columns=["Alpha", "Entity"])) # Fit the data to the visualizer
visualizer.show() # Finalize and render the figure
kIdx=kIdx.elbow_value_
model=KMeans(n_clusters=kIdx).fit(kk.drop(columns=["Alpha", "Entity"]))
fig = plt.figure(figsize=(20,15))
ax = Axes3D(fig)
cmap = plt.get_cmap('gnuplot')
clr = [cmap(i) for i in np.linspace(0, 1, len(ilist2))]
for i in range(0,len(ilist2)):
ind = (kk["Entity"]==ilist2[i])
ax.scatter(kk["Skew²"][ind],kk["Kurtosis"][ind], kk["Beta"][ind], s=120, c=clr[i], label=ilist2[i])
ax.set_xlabel("Skew²")
ax.set_ylabel("Kurtosis")
ax.set_zlabel(r"$\beta$")
ax.legend()
plt.title(title+": EPSB-K-means")
plt.savefig("datasetandcovidEPSB.png")
plt.show()
kk=pd.DataFrame({'Skew²': s2, 'Kurtosis': k, 'Alpha': alpha, 'Beta': beta, "Entity": ilist}, index=model.labels_)
kk.sort_index(inplace=True)
kk.to_csv("clusteringbeta.csv")
def makeGraphs(rawdata,title, filename, pmodel=False, chaosnoise=False):
for i in range(len(rawdata)):
#Plot e ajuste do histograma da série temporal
(mu, sigma) = norm.fit(rawdata[0][2])
# rv_nrm = norm(loc=mu, scale=sigma)
# Estimate GEV:
n=8192
ypoints=[min(rawdata[0][2]) + (i/n) * (max(rawdata[0][2])-min(rawdata[0][2])) for i in range(0, n+1)]
gev_fit = genextreme.fit(rawdata[0][2])
# GEV parameters from fit:
c, loc, scale = gev_fit
mean, var, skew, kurt = genextreme.stats(c, moments='mvsk')
rv_gev = genextreme(c, loc=loc, scale=scale)
# Create data from estimated GEV to plot:
gev_pdf = rv_gev.pdf(ypoints)
plt.title((title+"\nMu= {1:.3}, Sigma={2:.3}.").format(rawdata[i][0], mu, sigma))
n, bins, patches = plt.hist(rawdata[0][2], 60, density=1, facecolor='powderblue', alpha=0.75, label="Normalized data")
plt.plot(np.arange(min(bins), max(bins), (max(bins) - min(bins))/len(rawdata[0][2])), gev_pdf[:len(rawdata[0][2])],'r-', lw=5, alpha=0.6, label='genextreme pdf')
plt.ylabel("Probability Density")
plt.xlabel("Value")
plt.legend()
plt.savefig("PDF"+filename.format(i))
plt.show()
plt.figure(figsize=(20, 12))
#Plot da série temporal
ax1 = plt.subplot(211)
ax1.set_title(title.format(rawdata[i][0]), fontsize=18)
if pmodel==True:
ax1.plot(rawdata[i][2], color="firebrick", linestyle='-', label="Data")
elif chaosnoise==True:
ax1.plot(rawdata[i][1],rawdata[i][2], color="firebrick", marker= 'o', linestyle='', label="Data")
else:
ax1.plot(rawdata[i][1],rawdata[i][2], color="firebrick", linestyle='-', label="Data")
#Plot e cálculo do DFA
ax2 = plt.subplot(223)
ax2.set_title(r"Detrended Fluctuation Analysis $\alpha$={0:.3}".format(rawdata[i][3]), fontsize=15)
ax2.plot(rawdata[i][4],rawdata[i][5], marker='o', linestyle='', color="#12355B", label="{0:.3}".format(rawdata[i][3]))
ax2.plot(rawdata[i][4], rawdata[i][6], color="#9DACB2")
#Plot e cáculo do PSD
ax3 = plt.subplot(224)
ax3.set_title(r"Power Spectrum Density $\beta$={0:.3}".format(rawdata[i][12]), fontsize=15)
ax3.set_yscale('log')
ax3.set_xscale('log')
ax3.plot(rawdata[i][7], rawdata[i][8], '-', color = 'deepskyblue', alpha = 0.7)
ax3.plot(rawdata[i][9], rawdata[i][10], color = "darkblue", alpha = 0.8)
ax3.axvline(rawdata[i][7][rawdata[i][14]], color = "darkblue", linestyle = '--')
ax3.axvline(rawdata[i][7][rawdata[i][15]], color = "darkblue", linestyle = '--')
ax3.plot(rawdata[i][9], rawdata[i][13](rawdata[i][9], rawdata[i][11], rawdata[i][12]),color="#D65108", linestyle='-', linewidth = 3, label = '{0:.3}$'.format(rawdata[i][12]))
ax2.set_xlabel("log(s)")
ax2.set_ylabel("log F(s)")
ax3.set_xlabel("Frequência (Hz)")
ax3.set_ylabel("Potência")
ax3.legend()
plt.savefig(filename.format(i))
plt.show()
'''
###############################################################################
FUNÇÃO PRINCIPAL (main)
Main é onde eu construo a maioria dos gráficos, é feito separadamente em vez
de fazer em uma só função pois exercícios diferentes pedem gráficos diferentes.
Então ajustei cada tipo de acordo com a necessidade.
A função pede um input, com a ideia de fazer tudo que se pede em um click.
###############################################################################
'''
def main():
choice=input("Qual distribuição escolher:\n1 - GRNG\n2 - Colored Noise\n3 - pmodel\n4 - Chaos Noise \n5 - Ler de um arquivo\n6 - Sair\n\n")
if(choice=="1"):
'''
Começando pela série GRNG, serão gerados 8 famílias de sinais com elementos 2^n
sendo que n varia de 6 até 13, ou, 64 a 8192 e para cada família serão gerados
10 sinais diferentes e guardados todos eles numa lista rawdata, seus momentos
estatísticos serão guardados em d, e ilist é uma lista de iteração para cada N
usada para identificar corretamente os valores no DataFrame que será gerado.
Feito esse conjunto de dados, serão feitas as análises, começando pelo Detrended
Fluctuation Analysis e o Power Spectrum Density, que serão mostrados em um gráfico.
Essas duas análises serão feitas só para um de cada família gerada.
Depois disso será feito o agrupamento dos momentos estatísticos pelo método
K-Means, que fará um gráfico mostrando o agrupamento, e finalizando fazendo
o mapeamento de Cullen e Frey, um para cada família das séries.
'''
title="Série: GRNG. Quantidade de Dados N={0}"
i=[2**i for i in range(6,14)]
d,ilist,rawdata=makeseries(randomseries, i,10, "GRNG", True)
filename="GRNGserietemporalpsddfa{}.png"
makeGraphs(rawdata,title,filename)
title="GRNG"
d=makeK(d,ilist, title)
elif(choice=="2"):
'''
De maneira semelhante ao GRNG, serão feitas as mesmas coisas para as famílias
de ruído colorido White Noise, Pink Noise e Red Noise. Gerando 20 sinais para
cada uma dessas famílias.
Aqui será feito em adição um histograma que será ajustado numa gaussiana com
parâmetros mu e sigma.
'''
title="Série: Colored Noise. Expoente = {0}"
d,ilist,rawdata=makeseries(powerlaw_psd_gaussian, range(0,3), 20, "colorednoise", True)
while(0 in ilist or 1 in ilist or 2 in ilist):
ilist[ilist.index(0)] = 'white noise'
ilist[ilist.index(1)] = 'pink noise'
ilist[ilist.index(2)] = 'red noise'
filename="CNserietemporalpsddfa{}.png"
makeGraphs(rawdata, title, filename)
title="colorednoise"
d=makeK(d,ilist, title)
elif(choice=="3"):
'''
Para o pmodel serão feitas as mesmas análises que o GRNG, com as famílias
Endógeno e Exógeno, que geram valores aleatórios para cada família.
Valores entre 0.32~0.42 e 0.18~0.28, respectivamente, gerando 30 valores
aleatórios onde cada um gera seu sinal totalizando em 60 sinais.
'''
qtd=1
p=[]
for i in range(qtd):
p.append("Endogenous")
for i in range(qtd):
p.append("Exogenous")
title="Série: pmodel. {0}"
d,ilist,rawdata=makeseries(pmodel, p,30, "pmodel", True)
filename="Pmodelserietemporalpsddfa{}.png"
makeGraphs(rawdata, title, filename, pmodel=True)
title="pmodel"
d=makeK(d,ilist, title)
elif(choice=="4"):
'''
Na série Chaos Noise seguirão as mesmas análises, usando as séries Logística
e Henon, ambas vão gerar parâmetros aleatórios dentro de um intervalo de
rho=3.85~4 para a série logística, e a=1.35~1.4, b=0.21~0.29 para a série de
Henon.
Totalizando em 60 sinais no total.
'''
title="Série: Chaos Noise. {0}"
d,ilist,rawdata=makeseries(Logistic, ["Logistic"], 30, "Chaos Noise", True)
aux1,aux2,aux3=makeseries(HenonMap, ["Henon"], 30, "Chaos Noise", True)
rawdata+=aux3
d+=aux1
ilist+=aux2
filename="Chaosserietemporalpsddfa{}.png"
makeGraphs(rawdata, title, filename, chaosnoise=True)
title="chaosnoise"
d=makeK(d,ilist, title)
elif(choice=="5"):
namefile=["sol3ghz.dat","surftemp504.txt", "covidbrasil.dat"]
ilist=namefile
d=[]
for file in namefile:
fileread=open(file)
y=[]
for line in fileread:
y.append(float(line))
alfa,xdfa,ydfa, reta = statsfuncs.dfa1d(y,1)
freqs, power, xdata, ydata, amp, index, powerlaw, INICIO, FIM = statsfuncs.psd(y)
d.append([statsfuncs.variance(y), statsfuncs.skewness(y), statsfuncs.kurtosis(y)+3, alfa, index, 0])
QTD=10
d2,ilist2,rawdata=makeseries(randomseries, [8192],QTD)
for i in d2:
d.append(i)
for j in ilist2:
ilist.append(j)
d2,ilist2,rawdata=makeseries(powerlaw_psd_gaussian, range(0,3), QTD//3)
for i in d2:
d.append(i)
for j in ilist2:
ilist.append(j)
d2,ilist2,rawdata=makeseries(pmodel, ["Exogenous", "Endogenous"] , QTD//2)
for i in d2:
d.append(i)
for j in ilist2:
ilist.append(j)
d2,ilist2,rawdata=makeseries(Logistic, ["Logistic"], QTD//2)
for i in d2:
d.append(i)
for j in ilist2:
ilist.append(j)
d2,ilist2,rawdata=makeseries(HenonMap, ["Henon"], QTD//2)
for i in d2:
d.append(i)
for j in ilist2:
ilist.append(j)
s2=[]
k=[]
alpha=[]
beta=[]
for i in range(len(d)):
s2.append(d[i][1]**2)
k.append(d[i][2])
alpha.append(d[i][3])
beta.append(d[i][4])
makespaces62(s2,k,alpha,beta,"All signals and Brazil Covid data", "Brazil", ilist)
return d
else:
return
#Fazendo o clustering, via kmeans, dos momentos estatísticos obtidos.
ilist=set(ilist) #tirando valores duplicados
for j in ilist:
#Fazendo listas pra plotar em outras funções
s2=[i**2 for i in d.filter(like=str(j), axis=0)['Skewness']] #skew²
k=d.filter(like=str(j),axis=0)["Kurtosis"]
alpha=d.filter(like=str(j),axis=0)["Alpha"]
beta=d.filter(like=str(j),axis=0)["Beta"]
legend=str(j)
cullenfrey(s2,k, legend, title) #Mapa de cullen e frey
makespaces(s2,k, alpha, beta, legend, title)
return d
if __name__ == "__main__":
d=main()
# with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also
# print(d)