-
Notifications
You must be signed in to change notification settings - Fork 0
/
forecasting_test
executable file
·884 lines (786 loc) · 34.6 KB
/
forecasting_test
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import division
import argparse,csv,sys
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.interpolate import InterpolatedUnivariateSpline
font = {'family': 'Times New Roman', 'weight': 'normal', 'size': '14.0'}
plt.rc('font', **font)
def exp_smoothing(x, y, args):
'''Test of three kinds of exponential smoothing models: SES, ES_A and ES_DA.
Smoothing coefficient is adjusted on every step with Nelder-Mead minimization of
squared error of last prediction.
'''
from scipy.optimize import fmin_tnc
# Should we restrict smoothing parameters (True) or not (False)?
use_constraints = True
def SES(alpha, x_current, s_previous):
'''Simple exponential smoothing
'''
s_current = alpha * x_current + (1 - alpha) * s_previous
return s_current, s_current
def ES_A((alpha, gamma), x_current, s_previous, t_previous):
'''Exponential smoothing with additive trend
'''
s_current = alpha * x_current + (1 - alpha) * (s_previous + t_previous)
t_current = gamma * (s_current - s_previous) + (1 - gamma) * t_previous
return s_current + t_current, s_current, t_current
def ES_DA((alpha, gamma, phi), x_current, s_previous, t_previous):
'''Exponential smoothing with damped additive trend
'''
s_current = alpha * x_current + (1 - alpha) * (s_previous + phi * t_previous)
t_current = gamma * (s_current - s_previous) + (1 - gamma) * phi * t_previous
return s_current + phi * t_current, s_current, t_current
# Models with multiplicative trends: ES-M and ES-DM
#def ES_M((alpha, gamma), x_current, s_previous, r_previous):
# '''Exponential smoothing with multiplicative trend
# '''
# s_current = alpha * x_current + (1 - alpha) * (s_previous * r_previous)
# r_current = gamma * (s_current / s_previous) + (1 - gamma) * r_previous
# return s_current * r_current, s_current, r_current
#def ES_DM((alpha, gamma, phi), x_current, s_previous, r_previous):
# '''Exponential smoothing with damped multiplicative trend
# '''
# s_current = alpha * x_current + (1 - alpha) * (s_previous * pow(r_previous, phi))
# r_current = gamma * (s_current / s_previous) + (1 - gamma) * pow(r_previous, phi)
# return s_current * pow(r_current, phi), s_current, r_current
def squared_error(parameters, y_current, y_previous, s, t=0, model='SES'):
'''Summarized squared error of exponential smoothing prediction
'''
sse = 0; data_length = len(y_current)
if model == 'SES':
assert(data_length == len(y_previous) == len(s))
for i in xrange(data_length):
sse += pow((y_current[i] - SES(parameters, y_previous[i], s[i])[0]), 2)
elif model == 'ES_A':
assert(data_length == len(y_previous) == len(s) == len(t))
for i in xrange(data_length):
sse += pow((y_current[i] - ES_A(parameters, y_previous[i], s[i], t[i])[0]), 2)
elif model == 'ES_DA':
assert(data_length == len(y_previous) == len(s) == len(t))
for i in xrange(data_length):
sse += pow((y_current[i] - ES_DA(parameters, y_previous[i], s[i], t[i])[0]), 2)
return sse / data_length
def param_optimization(initial_parameters, y_current, y_previous, s, t=0, model='SES'):
'''Adjusts smoothing, trend and damping coefficients, minimizing the square of last prediction error
'''
# Set constraints for values
if use_constraints:
bounds_SES = [(0,1)]
bounds_ES_A = [(0,1), (None, None)]
bounds_ES_DA = [(0,1), (None, None), (None, None)]
else:
bounds_SES = [(None, None)]
bounds_ES_A = [(None, None), (None, None)]
bounds_ES_DA = [(None, None), (None, None), (None, None)]
if model == 'SES':
# Find optimal alpha value with truncated Newton algorithm. For debug set option: disp=5.
result = fmin_tnc(squared_error, initial_parameters, bounds=bounds_SES, approx_grad=True, args=(y_current, y_previous, s, model), xtol=0.001, disp=0)
elif model == 'ES_A':
# Find optimal alpha and gamma values
result = fmin_tnc(squared_error, initial_parameters, bounds=bounds_ES_A, approx_grad=True, args=(y_current, y_previous, s, t, model), xtol=0.001, disp=0)
elif model == 'ES_DA':
# Find optimal alpha, gamma and phi values
result = fmin_tnc(squared_error, initial_parameters, bounds=bounds_ES_DA, approx_grad=True, args=(y_current, y_previous, s, t, model), xtol=0.001, disp=0)
else:
print "Error! Wrong model type!"
exit(1)
return result[0]
# Prediction data initialization
predict = np.zeros((6, len(y)))
pr_models = [u"Модель N-N. Пошаговая оценка ", u"Модель A-N. Пошаговая оценка ", u"Модель DA-N. Пошаговая оценка ", u"Модель N-N. Интервальная оценка ", u"Модель A-N. Интервальная оценка ", u"Модель DA-N. Интервальная оценка"]
# Parameters initializing
# Parameters estimation interval
pe_interval = int(raw_input("Input analyzed interval length: "))
# Initial values in predicted array
for i in xrange(6):
predict[i,:pe_interval + 2] = y[:pe_interval + 2]
# Models initial parameters
alpha_SES = np.zeros(len(y)); alpha_ES_A = np.zeros(len(y)); alpha_ES_DA = np.zeros(len(y))
alpha_SES[:pe_interval+2] = alpha_ES_A[:pe_interval+2] = alpha_ES_DA[:pe_interval+2] = np.repeat(0.2, pe_interval+2)
gamma_ES_A = np.zeros(len(y)); gamma_ES_DA = np.zeros(len(y))
gamma_ES_A[:pe_interval+2] = gamma_ES_DA[:pe_interval+2] = np.repeat(1.0, pe_interval+2)
phi_ES_DA = np.zeros(len(y));
phi_ES_DA[:pe_interval+2] = np.repeat(0.5, pe_interval+2)
alpha_SES_pe = np.zeros(len(y)); alpha_ES_A_pe = np.zeros(len(y)); alpha_ES_DA_pe = np.zeros(len(y))
alpha_SES_pe[:pe_interval+2] = alpha_ES_A_pe[:pe_interval+2] = alpha_ES_DA_pe[:pe_interval+2] = np.repeat(0.2, pe_interval+2)
gamma_ES_A_pe = np.zeros(len(y)); gamma_ES_DA_pe = np.zeros(len(y))
gamma_ES_A_pe[:pe_interval+2] = gamma_ES_DA_pe[:pe_interval+2] = np.repeat(1.0, pe_interval+2)
phi_ES_DA_pe = np.zeros(len(y));
phi_ES_DA_pe[:pe_interval+2] = np.repeat(0.5, pe_interval+2)
# Smoothed and trend initial values
s_ses = np.zeros(len(y)); s_es_a = np.zeros(len(y)); s_es_da = np.zeros(len(y))
t_es_a = np.zeros(len(y)); t_es_da = np.zeros(len(y))
s_ses[:pe_interval+2] = s_es_a[:pe_interval+2] = s_es_da[:pe_interval+2] = np.mean(y[:pe_interval+2])
t_es_a[:pe_interval+2] = t_es_da[:pe_interval+2] = (y[pe_interval + 2] - y[0]) / (pe_interval + 2)
s_ses_pe = np.zeros(len(y)); s_es_a_pe = np.zeros(len(y)); s_es_da_pe = np.zeros(len(y))
t_es_a_pe = np.zeros(len(y)); t_es_da_pe = np.zeros(len(y))
s_ses_pe[:pe_interval+2] = s_es_a_pe[:pe_interval+2] = s_es_da_pe[:pe_interval+2] = np.mean(y[:pe_interval+2])
t_es_a_pe[:pe_interval+2] = t_es_da_pe[:pe_interval+2] = (y[pe_interval + 2] - y[0]) / (pe_interval + 2)
# Prediction procedure
for i in xrange(pe_interval + 1, len(y) - 1):
# Every-step estimation
# SES prediction
alpha_SES[i] = param_optimization(alpha_SES[i-1], y[i-pe_interval+1:i+1], y[i-pe_interval:i], s_ses[i-pe_interval-1:i-1], model='SES')
predict[0, i+1], s_ses[i] = SES(alpha_SES[i], y[i], s_ses[i-1])
# ES_A prediction
alpha_ES_A[i], gamma_ES_A[i] = param_optimization(np.asarray([alpha_ES_A[i-1], gamma_ES_A[i-1]]), y[i-pe_interval+1:i+1], y[i-pe_interval:i], s_es_a[i-pe_interval-1:i-1], t_es_a[i-pe_interval-1:i-1], model='ES_A')
predict[1, i+1], s_es_a[i], t_es_a[i] = ES_A((alpha_ES_A[i], gamma_ES_A[i]), y[i], s_es_a[i-1], t_es_a[i-1])
# ES_DA prediction
alpha_ES_DA[i], gamma_ES_DA[i], phi_ES_DA[i] = param_optimization(np.asarray([alpha_ES_DA[i-1], gamma_ES_DA[i-1], phi_ES_DA[i-1]]), y[i-pe_interval+1:i+1], y[i-pe_interval:i], s_es_da[i-pe_interval-1:i-1], t_es_da[i-pe_interval-1:i-1], model='ES_DA')
predict[2, i+1], s_es_da[i], t_es_da[i] = ES_DA((alpha_ES_DA[i], gamma_ES_DA[i], phi_ES_DA[i]), y[i], s_es_da[i-1], t_es_da[i-1])
# Per-interval estimation
if (i - 1) % pe_interval == 0:
# Estimate parameters
alpha_SES_pe[i] = param_optimization(alpha_SES_pe[i-1], y[i-pe_interval+1:i+1], y[i-pe_interval:i], s_ses[i-pe_interval-1:i-1], model='SES')
alpha_ES_A_pe[i], gamma_ES_A_pe[i] = param_optimization(np.asarray([alpha_ES_A_pe[i-1], gamma_ES_A_pe[i-1]]), y[i-pe_interval+1:i+1], y[i-pe_interval:i], s_es_a[i-pe_interval-1:i-1], t_es_a[i-pe_interval-1:i-1], model='ES_A')
alpha_ES_DA_pe[i], gamma_ES_DA_pe[i], phi_ES_DA_pe[i] = param_optimization(np.asarray([alpha_ES_DA_pe[i-1], gamma_ES_DA_pe[i-1], phi_ES_DA_pe[i-1]]), y[i-pe_interval+1:i+1], y[i-pe_interval:i], s_es_da[i-pe_interval-1:i-1], t_es_da[i-pe_interval-1:i-1], model='ES_DA')
# Set parameters for the next period
array_tail = len(y) - i
if array_tail > pe_interval:
alpha_SES_pe[i:i+pe_interval] = np.repeat(alpha_SES_pe[i], pe_interval)
alpha_ES_A_pe[i:i+pe_interval] = np.repeat(alpha_ES_A_pe[i], pe_interval)
alpha_ES_DA_pe[i:i+pe_interval] = np.repeat(alpha_ES_DA_pe[i], pe_interval)
gamma_ES_A_pe[i:i+pe_interval] = np.repeat(gamma_ES_A_pe[i], pe_interval)
gamma_ES_DA_pe[i:i+pe_interval] = np.repeat(gamma_ES_DA_pe[i], pe_interval)
phi_ES_DA_pe[i:i+pe_interval] = np.repeat(phi_ES_DA_pe[i], pe_interval)
else:
alpha_SES_pe[i:i+array_tail] = np.repeat(alpha_SES_pe[i], array_tail)
alpha_ES_A_pe[i:i+array_tail] = np.repeat(alpha_ES_A_pe[i], array_tail)
alpha_ES_DA_pe[i:i+array_tail] = np.repeat(alpha_ES_DA_pe[i], array_tail)
gamma_ES_A_pe[i:i+array_tail] = np.repeat(gamma_ES_A_pe[i], array_tail)
gamma_ES_DA_pe[i:i+array_tail] = np.repeat(gamma_ES_DA_pe[i], array_tail)
phi_ES_DA_pe[i:i+array_tail] = np.repeat(phi_ES_DA_pe[i], array_tail)
# Predictions
predict[3, i+1], s_ses_pe[i] = SES(alpha_SES_pe[i], y[i], s_ses_pe[i-1])
predict[4, i+1], s_es_a_pe[i], t_es_a_pe[i] = ES_A((alpha_ES_A_pe[i], gamma_ES_A_pe[i]), y[i], s_es_a_pe[i-1], t_es_a_pe[i-1])
predict[5, i+1], s_es_da_pe[i], t_es_da_pe[i] = ES_DA((alpha_ES_DA_pe[i], gamma_ES_DA_pe[i], phi_ES_DA_pe[i]), y[i], s_es_da_pe[i-1], t_es_da_pe[i-1])
# Error estimation
predict_error_abs = np.zeros((6, len(y))); predict_error_rel = np.zeros((6, len(y)))
for i in xrange(6):
for j in xrange(len(y)):
predict_error_abs[i, j] = abs(y[i] - predict[i, j])
if y[i] != 0:
predict_error_rel[i, j] = 100 * predict_error_abs[i, j] / y[i]
else:
if predict[i, j] == 0:
predict_error_rel[i, j] = 0
else:
predict_error_rel[i, j] = 100
# Mean error and variance calculation
#mean_abs_error = []; std_abs_error = []
mean_rel_error = []; std_rel_error = []
line_separator = "------------------------------------------------------------------------"
print "{}\nPrediction model MAPE,% Std.dev. MAPE,%\n{}".format(line_separator, line_separator)
for i in xrange(6):
mean_rel_error.append(np.mean(predict_error_rel[i]))
std_rel_error.append(np.std(predict_error_rel[i]))
print "%s %15.2f %15.2f" % (pr_models[i], mean_rel_error[i], std_rel_error[i])
print line_separator
# Plot results
if args.plot:
# Plot prediction results
fig1 = plt.figure()
for i in xrange(6):
plt.plot(x, predict[i], marker=markers[i], label=pr_models[i])
plt.plot(x, y, '--', label=u"Исходный")
plt.xlabel(u'Время')
plt.ylabel(u'Интенсивность трафика')
plt.title(u"Экспоненциальное сглаживание")
plt.legend(loc='best')
plt.grid(True)
if args.save:
plt.savefig(args.file + "-forecast.png", dpi=300)
# Plot SES-model parameter evolution
fig2 = plt.figure()
plt.plot(x[:-1], alpha_SES[:-1], label=u"Коэффициент сглаживания")
plt.xlabel(u'Время')
plt.ylabel(u'Значение параметра')
plt.title(u"Модель N-N. Эволюция параметров - пошаговая оценка")
plt.legend(loc='best')
plt.grid(True)
if args.save:
plt.savefig(args.file + "-NN.png", dpi=300)
# Plot ES_A-model parameter evolution
fig3 = plt.figure()
plt.plot(x[:-1], alpha_ES_A[:-1], marker=markers[0], label=u"Коэффициент сглаживания")
plt.plot(x[:-1], gamma_ES_A[:-1], marker=markers[2], label=u"Сглаживание тренда")
plt.xlabel(u'Время')
plt.ylabel(u'Значение параметра')
plt.title(u"Модель A-N. Эволюция параметров - пошаговая оценка")
plt.legend(loc='best')
plt.grid(True)
if args.save:
plt.savefig(args.file + "-AN.png", dpi=300)
# Plot ES_DA-model parameter evolution
fig4 = plt.figure()
plt.plot(x[:-1], alpha_ES_DA[:-1], marker=markers[0], label=u"Коэффициент сглаживания")
plt.plot(x[:-1], gamma_ES_DA[:-1], marker=markers[1], label=u"Сглаживание тренда")
plt.plot(x[:-1], phi_ES_DA[:-1], marker=markers[2], label=u"Параметр демпфирования")
plt.xlabel(u'Время')
plt.ylabel(u'Значение параметра')
plt.title(u"Модель DA-N. Эволюция параметров - пошаговая оценка")
plt.legend(loc='best')
plt.grid(True)
if args.save:
plt.savefig(args.file + "-DAN.png", dpi=300)
# Plot SES-PE-model parameter evolution
fig5 = plt.figure()
plt.plot(x[:-1], alpha_SES_pe[:-1], label=u"Коэффициент сглаживания")
plt.xlabel(u'Время')
plt.ylabel(u'Значение параметра')
plt.title(u"Модель N-N. Эволюция параметров - интервальная оценка")
plt.legend(loc='best')
plt.grid(True)
if args.save:
plt.savefig(args.file + "-NN-PE.png", dpi=300)
# Plot ES_A-PE-model parameter evolution
fig6 = plt.figure()
plt.plot(x[:-1], alpha_ES_A_pe[:-1], marker=markers[0], label=u"Коэффициент сглаживания")
plt.plot(x[:-1], gamma_ES_A_pe[:-1], marker=markers[1], label=u"Сглаживание тренда")
plt.xlabel(u'Время')
plt.ylabel(u'Значение параметра')
plt.title(u"Модель A-N. Эволюция параметров - интервальная оценка")
plt.legend(loc='best')
plt.grid(True)
if args.save:
plt.savefig(args.file + "-AN-PE.png", dpi=300)
# Plot ES_DA-PE-model parameter evolution
fig7 = plt.figure()
plt.plot(x[:-1], alpha_ES_DA_pe[:-1], marker=markers[0], label=u"Коэффициент сглаживания")
plt.plot(x[:-1], gamma_ES_DA_pe[:-1], marker=markers[1], label=u"Сглаживание тренда")
plt.plot(x[:-1], phi_ES_DA_pe[:-1], marker=markers[2], label=u"Параметр демпфирования")
plt.xlabel(u'Время')
plt.ylabel(u'Значение параметра')
plt.title(u"Модель DA-N. Эволюция параметров - интервальная оценка")
plt.legend(loc='best')
plt.grid(True)
if args.save:
plt.savefig(args.file + "-DAN-PE.png", dpi=300)
print "Results are saved in correponding files."
plt.show()
def LP(x, y, args):
import lpc
'''Test of linear prediction with different prediction orders and different correlation matrix size.
Linear prediction procedure used here is similar to the one implemented in LP vocoders.'''
#global markers
def input_list_int(text, splitter=','):
lst_string = raw_input(text).split(splitter)
lst = []
for i in lst_string:
try:
lst.append(int(i))
except ValueError:
print "Inappropriate value..."
continue
num_elements = len(lst)
if num_elements < 1:
print "Parameters list is empty! Game over."
exit(1)
return sorted(lst), num_elements
orders, num_orders = input_list_int("Enter predictor orders separated by comma: ")
signal_lengths, num_signal_lengths = input_list_int("Enter analysed signal lengths separated by comma: ")
# Create array to store LP coefficients
coefficients_array = [[] for i in xrange(num_orders*num_signal_lengths)]
# Check signal lengths
if max(orders) > min(signal_lengths):
print "Wrong parameters! Signal length should be greater than prediction order."
exit(1)
# Prediction data initialization
predict=np.zeros((num_signal_lengths, num_orders, len(y)))
# Initial history points for prediction
for i in xrange(num_signal_lengths):
for j in xrange(num_orders):
predict[i,j,:signal_lengths[i]]=y[:signal_lengths[i]]
# Prediction procedure
for i in xrange(num_signal_lengths):
for j in xrange(num_orders):
for k in xrange(signal_lengths[i],len(y)):
lp_coefficients = lpc.lpc_ref(y[k-signal_lengths[i]:k], orders[j])
# Save coefficients for further spectrum animation
if args.save:
coefficients_array[i*num_orders+j].append(lp_coefficients)
point = lpc.lpc_predict(y[k-orders[j]:k], orders[j], lp_coefficients)
if point > 0:
predict[i,j,k] = point
else:
predict[i,j,k] = 0
# Plot results
if args.plot:
for i in xrange(num_signal_lengths):
for j in xrange(num_orders):
plt.plot(x, predict[i,j], marker=markers[i*num_orders+j], label=u"Порядок предсказания={}, длина сигнала ={}".format(orders[j],signal_lengths[i]))
plt.plot(x, y, '--', label=u"Исходный")
plt.xlabel(u'Время')
plt.ylabel(u'Интенсивность трафика')
plt.title(u"Метод линейного предсказания")
plt.legend(loc='best')
plt.grid(True)
plt.show()
# Prediction error estimation
predict_error_abs = []; predict_error_rel = []
for i in xrange(num_signal_lengths):
for j in xrange(num_orders):
predict_error_abs.append(np.zeros(len(y) - signal_lengths[i]))
predict_error_rel.append(np.zeros(len(y) - signal_lengths[i]))
for k in xrange(len(y) - signal_lengths[i]):
# Pointers for different arrays
data_pointer = k + signal_lengths[i]; err_pointer = k; array_pointer = i * num_orders + j
predict_error_abs[array_pointer][err_pointer] = abs(y[data_pointer] - predict[i,j,data_pointer])
if y[data_pointer] != 0:
predict_error_rel[array_pointer][err_pointer] = 100 * predict_error_abs[array_pointer][err_pointer] / y[data_pointer]
else:
if predict[i,j,data_pointer] == 0:
predict_error_rel[array_pointer][err_pointer] = 0
else:
predict_error_rel[array_pointer][err_pointer] = 100
mean_abs_error = []; mean_rel_error = []; std_abs_error = []; std_rel_error = []
# Full version
#print "\nLag_length Absolute_error Absolute_error Relative_error Relative_error"
#print " (mean) (std.dev) (mean,%) (std.dev)"
# Short output
line_separator = "------------------------------------------------------------------------"
print "{}\nParameters MAPE,% Std.dev. MAPE,%\n{}".format(line_separator, line_separator)
for i in xrange(num_signal_lengths):
for j in xrange(num_orders):
array_pointer = i * num_orders + j
# mean_abs_error.append(np.mean(predict_error_abs[array_pointer]))
# std_abs_error.append(np.std(predict_error_abs[array_pointer]))
mean_rel_error.append(np.mean(predict_error_rel[array_pointer]))
std_rel_error.append(np.std(predict_error_rel[array_pointer]))
# print "Lag=%2i: %15.2f %15.2f %15.1f %15.1f" % (lag[i],mean_abs_error[i],std_abs_error[i],mean_rel_error[i],std_rel_error[i])
print "Signal_length %d, order %d: %15.2f %15.2f" % (signal_lengths[i], orders[j], mean_rel_error[array_pointer], std_rel_error[array_pointer])
print line_separator
# Save LP coefficients in file
if args.save:
# Open file
for i in xrange(num_signal_lengths):
for j in xrange(num_orders):
filename = args.file + "_ord%d_sig%d.dat" % (orders[j], signal_lengths[i])
outfile=open(filename, 'wb')
# title = "LP coefficients change during prediction"
# outfile.write(title + "\n")
for coeff in coefficients_array[i * num_orders + j]:
string = ""
for value in coeff:
string += str(value) + " "
outfile.write(string + "\n")
outfile.close()
print "Results are saved in correponding files."
def polynome_test(x, y, args):
'''Test of polynome prediction with different powers'''
#global markers
pinit = raw_input("Enter polynome powers separated by comma: ").split(',')
plist = []
for i in pinit:
try:
plist.append(int(i))
except ValueError:
print "That`s not a good value for polynome power..."
continue
n = len(plist)
if n < 1:
print "Power list is empty! Game over."
exit(1)
# Extrapolation
# Extrapolation. To use or not to use?
if args.extrapolate:
predict_extrapolate = np.zeros((3,len(y)))
extrapow = ['linear','quadratic','cubic']
# Initial history points for extrapolation
for i in xrange(3):
predict_extrapolate[i,:4] = y[:4]
# Extrapolation procedure
for i in xrange(4, len(y)):
for p in xrange(3):
ext = InterpolatedUnivariateSpline(x[i-4:i], y[i-4:i], k=p+1)
expoint = ext(x[i])
if expoint > 0:
predict_extrapolate[p, i] = expoint
else:
predict_extrapolate[p,i] = 0
# Approximation
# Prediction data initialization
predict = np.zeros((n, len(y)))
lag = int(raw_input("Enter lag (number of \"history\" points): "))
if lag < (max(plist) + 1):
print "Wrong lag value. Lag is set to {}.".format(max(plist) + 1)
lag = max(plist) + 1
plist.sort()
# Initial history points for prediction
for i in xrange(n):
predict[i, :lag] = y[:lag]
# Prediction procedure
for i in xrange(lag, len(y)):
for k in xrange(n):
approxpoint = np.polyval(np.polyfit(x[i-lag:i], y[i-lag:i], deg=plist[k]), x[i])
if approxpoint > 0:
predict[k, i] = approxpoint
else:
predict[k, i] = 0
# Prediction error estimation
predict_error_abs = []; predict_error_rel = []
# Error estimation for approximation procedure
for i in xrange(n):
predict_error_abs.append(np.zeros(len(y) - lag))
predict_error_rel.append(np.zeros(len(y) - lag))
for j in xrange(len(y) - lag):
data_pointer = j + lag;
predict_error_abs[i][j] = y[data_pointer] - predict[i, data_pointer]
if y[data_pointer] != 0:
predict_error_rel[i][j] = 100.0 * abs(predict_error_abs[i][j]) / y[data_pointer]
else:
if predict[i, data_pointer] == 0:
predict_error_rel[i][j] = 0
else:
predict_error_rel[i][j] = 100
if args.extrapolate:
# Error estimation for extrapolation procedure
for i in xrange(n, n+3):
predict_error_abs.append(np.zeros(len(y) - 4))
predict_error_rel.append(np.zeros(len(y) - 4))
for j in xrange(len(y) - 4):
data_pointer = j + 4;
predict_error_abs[i][j] = y[data_pointer] - predict_extrapolate[i-n, data_pointer]
if y[data_pointer] != 0:
predict_error_rel[i][j] = 100.0 * abs(predict_error_abs[i][j]) / y[data_pointer]
else:
if predict_extrapolate[i-n, data_pointer] == 0:
predict_error_rel[i][j] = 0
else:
predict_error_rel[i][j] = 100
#mean_abs_error = []; std_abs_error = []
mean_rel_error = []; std_rel_error = []
line_separator = "---------------------------------------------------------"
print "{}\nApproximation type MAPE,% Std.dev. MAPE,%\n{}".format(line_separator, line_separator)
if args.extrapolate:
for i in xrange(n):
mean_rel_error.append(np.mean(predict_error_rel[i]))
std_rel_error.append(np.std(predict_error_rel[i]))
print "%i-approximation: %14.2f %14.2f" % (plist[i], mean_rel_error[i], std_rel_error[i])
for i in xrange(n, n+3):
mean_rel_error.append(np.mean(predict_error_rel[i]))
std_rel_error.append(np.std(predict_error_rel[i]))
print "%i-extrapolation: %14.2f %14.2f" % (i - n + 1, mean_rel_error[i], std_rel_error[i])
else:
for i in xrange(n):
mean_rel_error.append(np.mean(predict_error_rel[i]))
std_rel_error.append(np.std(predict_error_rel[i]))
print "%i-approximation: %14.2f %14.2f" % (plist[i], mean_rel_error[i], std_rel_error[i])
print line_separator
# Save results in file
if args.save:
# Choose splitter
if args.space:
splitter = " "
else:
splitter = ","
# Open file
outfile = open(args.file + "-testresult.csv", 'wb')
title = "Approximation by different polynomes with lag {}".format(lag)
outfile.write(title + "\n")
# Have we got any extrapolation data? Yes...
if args.extrapolate:
head = "x" + splitter + "y"
for s in xrange(n):
head += splitter + str(plist[s]) + "-approx"
head += splitter + "lin-ex" + splitter + "quad-ex" + splitter + "cubic-ex"
outfile.write(head + "\n")
for r in xrange(len(x)):
string = str(x[r]) + splitter + str(y[r])
for c in xrange(n):
string += splitter + str(predict[c, r])
string += splitter + str(predict_extrapolate[0, r]) + splitter + str(predict_extrapolate[1, r]) + splitter + str(predict_extrapolate[2, r])
outfile.write(string + "\n")
# No, we haven`t :)
else:
head = "x" + splitter + "y"
for s in xrange(n):
head+=splitter+str(plist[s])+"-approx"
outfile.write(head+"\n")
for r in xrange(len(x)):
string=str(x[r])+splitter+str(y[r])
for c in xrange(n):
string+=splitter+str(predict[c,r])
outfile.write(string+"\n")
outfile.close()
# Plot obtained results
if args.plot:
for i in xrange(n):
plt.plot(x, predict[i], marker=markers[i], label=u"{}-аппроксимация".format(plist[i]))
if args.extrapolate:
for i in xrange(3):
plt.plot(x, predict_extrapolate[i], marker=markers[i+n], label=u"{}-экстраполяция".format(extrapow[i]))
plt.plot(x, y, '--', label=u"Исходный")
plt.xlabel(u'Время')
plt.ylabel(u'Интенсивность трафика')
plt.title(u"Предсказание с помощью полиномиальной аппроксимации")
plt.legend(loc='best')
plt.grid(True)
plt.show()
def lag_test(x, y, args):
'''Test prediction with different lag-size (i.e. number of history points)'''
#global markers
p = int(raw_input("Enter approximation polynome power (>=1): "))
llist = raw_input("Enter lag values separated by comma (>=power+1): ").split(',')
lag = []
for i in llist:
try:
lag.append(int(i))
except ValueError:
print "Damn it! That`s not a good value for lag, man..."
continue
n = len(lag)
if n < 1:
print "Lag list is empty! Game over."
exit(1)
# Approximation
# Prediction data initialization
predict = np.zeros((n, len(x)))
lag.sort()
# Initial history points for prediction
for i in xrange(n):
predict[i, :lag[i]] = y[:lag[i]]
# Prediction procedure
for i in xrange(n):
for k in xrange(lag[i], len(x)):
approxpoint = np.polyval(np.polyfit(x[k - lag[i]:k], y[k-lag[i]:k], deg=p), x[k])
if approxpoint > 0:
predict[i, k] = approxpoint
else:
predict[i, k] = 0
# Error estimation procedure. Only predicted values are taken into account, no initial points!
predict_error_abs = []; predict_error_rel = []
for i in xrange(n):
predict_error_abs.append(np.zeros(len(y) - lag[i]))
predict_error_rel.append(np.zeros(len(y) - lag[i]))
for j in xrange(len(y) - lag[i]):
predict_error_abs[i][j]=abs(y[j + lag[i]] - predict[i, j + lag[i]])
if y[j + lag[i]] != 0:
predict_error_rel[i][j] = 100 * predict_error_abs[i][j] / y[j + lag[i]]
else:
if predict[i, j + lag[i]] == 0:
predict_error_rel[i][j] = 0
else:
predict_error_rel[i][j] = 100
#mean_abs_error = []; std_abs_error = []
mean_rel_error = []; std_rel_error = []
line_separator = "-----------------------------------------------"
print "{}\nLag length MAPE,% Std.dev. MAPE,%\n{}".format(line_separator, line_separator)
for i in xrange(n):
mean_rel_error.append(np.mean(predict_error_rel[i]))
std_rel_error.append(np.std(predict_error_rel[i]))
print "Lag %2i: %15.1f %15.1f" % (lag[i], mean_rel_error[i], std_rel_error[i])
print line_separator
# Save results in file
if args.save:
# Choose splitter
if args.space:
splitter = " "
else:
splitter = ","
# Open file
outfile = open(args.file + "-testresult.csv",'wb')
title = "Approximation by {}-power polynome with different lags".format(p)
outfile.write(title + "\n")
head = "x" + splitter + "y"
for s in xrange(n):
head += splitter + str(lag[s]) + "-lag"
outfile.write(head + "\n")
for r in xrange(len(x)):
string=str(x[r]) + splitter + str(y[r])
for c in xrange(n):
string += splitter + str(predict[c, r])
outfile.write(string + "\n")
outfile.close()
# Plot obtained results
if args.plot:
for i in xrange(n):
plt.plot(x, predict[i,], marker=markers[i], label=u"Интервал {}".format(lag[i]))
plt.plot(x, y, '--', label=u"Исходный")
plt.xlabel(u'Время')
plt.ylabel(u'Интенсивность трафика')
plt.title(u"Предсказание с помощью аппроксимации {}-го порядка".format(p))
plt.legend(loc='best')
plt.grid(True)
plt.show()
def sp5point(points):
'''Returns next point of the trend, obtained from given 5 points list (Spencer 5-point)'''
p = [-28, 77, -28, -98, 112]; s = 0
if len(points) != 5:
print "Spencer 5-point procedure: Wrong number of points!"
exit(1)
for i in xrange(len(points)):
s += points[i] * p[i]
return s / 35
def sp7point(points):
'''Returns next point of the trend, obtained from given 7 points list (Spencer 7-point)'''
p = [-12, 18, 12, -9, -24, -12, 48]; s = 0
if len(points) != 7:
print "Spencer 7-point procedure: Wrong number of points!"
exit(1)
for i in xrange(len(points)):
s += points[i] * p[i]
return s / 21
def spencer(x, y, args):
'''Prediction by obtaining trend with Spencer methods (5- and 7-point)'''
#global markers
# Prediction array initialization
predict = np.zeros((2, len(x)))
# Initial history points for prediction
predict[0, :5] = y[:5]
predict[1, :7] = y[:7]
# Prediction, method: 5-point
for k in xrange(5, len(x)):
approxpoint = sp5point(y[k - 5 : k])
if approxpoint > 0:
predict[0, k] = approxpoint
else:
predict[0, k] = 0
# Prediction, method: 7-point
for k in xrange(7, len(x)):
approxpoint = sp7point(y[k - 7 : k])
if approxpoint > 0:
predict[1, k] = approxpoint
else:
predict[1, k] = 0
# Error estimation procedure. Only predicted values are taken into account, no initial points!
# Inintialize error arrays
predict_error_abs_5p = np.zeros(len(y) - 5)
predict_error_rel_5p = np.zeros(len(y) - 5)
predict_error_abs_7p = np.zeros(len(y) - 7)
predict_error_rel_7p = np.zeros(len(y) - 7)
# Error calculation for 5-point method
for i in xrange(len(y) - 5):
predict_error_abs_5p[i] = abs(y[i+5] - predict[0, i+5])
if y[i+5] != 0:
predict_error_rel_5p[i] = 100 * predict_error_abs_5p[i] / y[i+5]
else:
if predict[0, i+5] == 0:
predict_error_rel_5p[i] = 0
else:
predict_error_rel_5p[i] = 100
# Error calculation for 7-point method
for i in xrange(len(y) - 7):
predict_error_abs_7p[i]=abs(y[i+7] - predict[1, i+7])
if y[i+7] != 0:
predict_error_rel_7p[i] = 100 * predict_error_abs_7p[i] / y[i+7]
else:
if predict[1, i+7] == 0:
predict_error_rel_7p[i] = 0
else:
predict_error_rel_7p[i] = 100
# Calculate error statistics:
# - for 5-point method
mean_abs_error_5p = np.mean(predict_error_abs_5p)
mean_rel_error_5p = np.mean(predict_error_rel_5p)
std_abs_error_5p = np.std(predict_error_abs_5p)
std_rel_error_5p = np.std(predict_error_rel_5p)
# - for 7-point method
mean_abs_error_7p = np.mean(predict_error_abs_7p)
mean_rel_error_7p = np.mean(predict_error_rel_7p)
std_abs_error_7p = np.std(predict_error_abs_7p)
std_rel_error_7p = np.std(predict_error_rel_7p)
# Print results
line_separator = "-----------------------------------------------"
print "{}\nMethod MAPE,% Std.dev. MAPE,%\n{}".format(line_separator, line_separator)
print "5-point: %15.2f %15.2f" % (mean_rel_error_5p,std_rel_error_5p)
print "7-point: %15.2f %15.2f" % (mean_rel_error_7p,std_rel_error_7p)
print line_separator
# Plot results
if args.plot:
plt.plot(x, predict[0,], marker=markers[1], label=u"5 точек")
plt.plot(x, predict[1,], marker=markers[2], label=u"7 точек")
plt.plot(x, y, '--', label=u"Исходный")
plt.xlabel(u'Время')
plt.ylabel(u'Интенсивность трафика')
plt.title(u"Предсказание с помощью процедуры Спенсера")
plt.legend(loc='best')
plt.grid(True)
plt.show()
exit(0)
############ Main()
# Utility options
parser = argparse.ArgumentParser(description='Utility is intended to test different traffic prediction functions in LBO.')
parser.add_argument('file', help='File with original traffic trace data')
#parser.add_argument("-a","--animate",action="store_true",help="Save animation of LP coefficients spectrum change")
parser.add_argument("-e","--extrapolate", action="store_true", help="use additional 1,2,3-power extrapolation in polynome-test")
#parser.add_argument("-n",type=int,default=2,help="number of experiments")
parser.add_argument("-p","--plot", action="store_true", help="plot obtained results")
parser.add_argument("-r", default="", help="time range to simulate, sec: start-finish (i.e. 0.2-17.65)")
parser.add_argument("-s","--save", action="store_true", help="save obtained results to file")
parser.add_argument("--space", action="store_true", help="used to separate values in file by whitespaces. By default \
commas are used.")
parser.add_argument("-t","--type", default="polynome", help="type of experiment (default test is polynome)", choices=["ES", "lag", "LP", "polynome", "spencer"])
args = parser.parse_args()
# Color list
#colors = ('b','g','r','c','m','y','k','*','o','--')
# Markers for plots
markers = ('x', 'o', '*', 'v', '^', '.', '+', 's', 'p')
# Load data from file
xl = []; yl = []; i = 0
fd = open(args.file,'rU')
c = csv.reader(fd)
for row in c:
i += 1
if len(row) != 0:
try:
xl.append(float(row[0]))
yl.append(float(row[1]))
except ValueError:
print "Inappropriate data detected in row {}: {}!".format(i,row)
else:
print "String {} is empty!".format(i)
# Check obtained arrays for length equality
if (len(xl) != len(yl)):
print "Wrong input data!"
exit(1)
# Take chosen range from whole trace
if (args.r == ""):
x = np.asarray(xl)
y = np.asarray(yl)
else:
# Time interval to operate
time = args.r.split('-')
if (len(time) != 2):
print "Wrong time range!"
exit(1)
try:
t_start = float(time[0])
t_stop = float(time[1])
except:
print "Wrong time format!"
exit(1)
if (t_start >= max(xl) or t_stop <= min(xl)):
print "Wrong time range defined: out of time range in file!"
exit(1)
for t in xl:
if t >= t_start:
i_start = xl.index(t)
break
for t in xl:
if t >= t_stop:
i_stop = xl.index(t) + 1
break
x = np.array(xl[i_start:i_stop])
y = np.array(yl[i_start:i_stop])
# Run chosen type of test
if (args.type == "polynome"):
print "Experiment with various power polynome and constant lag"
polynome_test(x, y, args)
elif (args.type == "ES"):
print "Experiment with 3 different exponential smoothing models"
exp_smoothing(x, y, args)
elif (args.type == "lag"):
print "Experiment with constant power polynome and different lags"
lag_test(x, y, args)
elif (args.type == "LP"):
print "LP procedure with various orders and correlation matrix sizes"
LP(x, y, args)
elif (args.type == "spencer"):
print "Experiment with 5-point and 7-point Spencer`s smoothing formula"
spencer(x, y, args)
else:
print "Wrong experiment type!"