-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patherror_correlation.py
More file actions
1652 lines (1459 loc) · 64.5 KB
/
Copy patherror_correlation.py
File metadata and controls
1652 lines (1459 loc) · 64.5 KB
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
## to analyse the correlation between errors, both in time and space
import csv
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
#from pyemd import emd
import math
from pylab import rcParams
import numpy as np
import scipy as sc
import dateutil.parser as dt
from dateutil.relativedelta import relativedelta
import spline
home_dir = 'C:\\users\\sabrina\\documents\\research\\code for real user\\'
# ------------------------------ introductory analysis -----------------------------------------------------------------
# arguments:
# () type: either Solar or Wind
# () date_range: optional date range to be considered (list of two dates)
# Calls to:
# () get_error (returns prediction errors)
# () restrain_to_date_range (to treat a specified date range)
# Returns:
# () correlation between north and south error forecast
def space_correlation(type, date_range=[]):
# getting the data
date1, errors1 = get_data(type, 'NP')
print('date len=%d,errors len=%d' % (len(date1), len(errors1)))
date2, errors2 = get_data(type, 'SP')
print('date len=%d,errors len=%d' % (len(date2), len(errors2)))
if len(date_range) == 2:
restrain_to_date_range(date1, errors1, date_range)
restrain_to_date_range(date1, errors1, date_range)
# estimate correlation, checking that dates correspond
correlation = 0
count = 0
len1 = len(date1)
len2 = len(date2)
diff = 0
for i in range(len1):
i = len1 - i - 1
d1 = date1.pop()
date_match = d1 == date2[i + diff]
if not date_match:
for j in range(max(0, i + diff - 50), min(len2, i + diff + 50)):
if d1 == date2[j]:
diff = j - i
date_match = True
break
if date_match:
correlation = correlation + errors1[i] * errors2[i + diff]
count = count + 1
# final result
correlation = correlation / (count * np.sqrt(sc.var(errors1) * sc.var(errors2)))
print('space correlation between North and South for %s is %.3f \n' % (type, correlation))
return correlation
### This functions draws the time correlation of prediction errors
# arguments:
# () type, location: specify the errors wanted
# () date_and_errors: if you prefer to put in directly the dates and errors, a tuple containing these 2 lists
# () range_max : it will analyse the time correlated errors for time intervals ranging from 0 hour to range_max hour
# () date_range: 2-elements-list to specify a datetime range for the data. by default, all data is considered
# () fig_nb: figure number for plotting
# Calls to:
# () get_error (returns prediction errors)
# () restrain_to_date_range (to treat a specified date range)
# Returns nothing
def time_correlation(type, location, date_and_errors=(), range_max=120, date_range=[], fig_nb=1):
# getting the date and errors
try:
if len(date_and_errors) == 2 & len(date_and_errors[0]) > 0:
date, errors = date_and_errors
else:
raise IndexError("no good arguments")
except IndexError:
date, errors = get_data(type, location)
print('date len=%d,errors len=%d' % (len(date), len(errors)))
if len(date) < 1 | len(errors) < 1:
print('Problem with the provided date & error. Taking a default file instead')
file_name_wind = '/home/ambroiseidoine/UCD/code/prescient/release/Prescient_1.0/exec/confcomp_data/Wind/Wind_actual_forecast_SP15_070114_063015.csv'
date, errors = get_data(file_name_wind)
# restraining data to 'date_range' if provided
if (len(date_range) == 2):
date, errors = restrain_to_date_range(date, errors, date_range)
# basic statistical analysis
mean_error = sc.mean(errors);
var_error = sc.var(errors);
correl = []
nb_days = int(np.ceil(range_max / 24))
for i in range(range_max):
correl.append((sc.mean([errors[j] * errors[i + j] for j in range(len(errors) - range_max)]) - np.power(
mean_error, 2)) / var_error)
# when is the correlation under 0.5, 0.2, 0.1?
temp = correl.copy()
temp.reverse()
incr = 0
levels = [0.1, 0.2, 0.5]
temp_levels = levels.copy()
temp_levels.sort(reverse=True)
crossing_times = []
for lev in temp_levels:
while temp.pop() > lev:
incr = incr + 1
crossing_times.append(incr)
print('correlation under %.2f after %d hours' % (lev, incr))
del (temp, incr)
# additional information
location_names = {'total': 'California', 'NP': 'North California', 'SP': 'South California'}
print("mean error : %d \n" % mean_error)
# plotting
plt.figure(fig_nb)
ax = plt.subplot()
for i in range(3):
i = 2 - i
ax.fill_between([0, range_max], [-levels[i], -levels[i]], [levels[i], levels[i]],
color=(0.7 + i * 0.1, 0.7 + i * 0.1, 0.7 + i * 0.1))
plt.plot([0, range_max], [0, 0], color='black')
plt.plot(correl);
plt.xticks(range(0, 24 * nb_days, 24))
plt.title("time correlation in %s forecast errors (%s)" % (type, location_names[location]))
plt.xlabel("time interval")
plt.ylabel("correlation")
# plt.show()
# ------------------------------ adjacent functions for introductory analysis ------------------------------------------
### This functions reads data as specified by the type (Solar,Wind) and location (total,NP,SP0
# It returns 2 lists:
# () the date & time (formated string)
# () the difference between forecast and actual (at this time)
def get_data(type='Solar', location='total', kind='errors'):
if (type in {'Solar', 'Wind'}) & (location in {'NP', 'SP', 'total'}):
if location != 'total':
location = location + '15' # file names compatibility
#
data_dir = home_dir + 'prescient/release/Prescient_1.0/exec/confcomp_data/'
data_files = ['_actual_forecast_', '_070114_063015.csv']
date = []
values = {'for': [], 'act': []}
#
if (type == 'Wind') & (location == 'total'):
# we add NP15 and SP15 (beware of the missing data: we check that the dates are the same)
values_temp = {'for': [], 'act': []}
date_temp = []
count = 0
for loc in ['SP15', 'NP15']:
file_name = data_dir + type + '/' + type + data_files[0] + loc + data_files[1]
csv_read = csv.reader(open(file_name, 'r'))
if loc == 'SP15':
for line in csv_read:
if (len(line) < 1) or (line[1] == '#'):
continue
date_temp.append(str(dt.parse(line[0])))
values_temp['for'].append(float(line[1]))
values_temp['act'].append(float(line[2]))
else:
len_value_temp = len(values_temp['act'])
for line in csv_read:
if (len(line) < 1) or (line[1] == '#'):
continue
if count >= len_value_temp:
break
if dt.parse(date_temp[count]) != dt.parse(line[0]): # check that the dates correspond
print('missing data at date %s for %s' % (dt.parse(line[0]), type))
go_on = True
for i in range(max(-10, -count),
min(10, len_value_temp - 1 - count)): # Searching neighbouring dates
if dt.parse(date_temp[count + i]) == dt.parse(line[0]):
count = count + i
go_on = False
continue
if go_on:
continue
else:
date.append(str(dt.parse(line[0])))
else:
date.append(str(dt.parse(line[0])))
#
values['for'].append(float(line[1]) + values_temp['for'][count])
values['act'].append(float(line[2]) + values_temp['act'][count])
count = count + 1
#
elif (type == 'Solar') & (location == 'NP15'):
# we subtract total and SP15 (beware of the missing data: we check that dates correspond)
values_temp = {'for': [], 'act': []}
date_temp = []
count = 0
for loc in ['SP15', 'total']:
file_name = data_dir + type + '/' + type + data_files[0] + loc + data_files[1]
csv_read = csv.reader(open(file_name, 'r'))
if loc == 'SP15':
for line in csv_read:
if (len(line) < 1) or (line[1] == '#'):
continue
date_temp.append(str(dt.parse(line[0])))
values_temp['for'].append(float(line[1]))
values_temp['act'].append(float(line[2]))
else:
len_value_temp = len(values_temp['act'])
for line in csv_read:
if (len(line) < 1) or (line[1] == '#'):
continue
if count >= len_value_temp:
break
if dt.parse(date_temp[count]) != dt.parse(line[0]): # check that the dates correspond
print('missing data at date %s for %s' % (dt.parse(line[0]), type))
go_on = True
for i in range(max(-10, -count),
min(10, len_value_temp - 1 - count)): # Searching neighbouring dates
if dt.parse(date_temp[count + i]) == dt.parse(line[0]):
count = count + i
go_on = False
continue
if go_on:
continue
else:
date.append(str(dt.parse(line[0])))
else:
date.append(str(dt.parse(line[0])))
#
values['for'].append(float(line[1]) - values_temp['for'][count])
values['act'].append(float(line[2]) - values_temp['act'][count])
count = count + 1
#
else:
file_name = data_dir + type + '/' + type + data_files[0] + location + data_files[1]
csv_read = csv.reader(open(file_name, 'r'))
for line in csv_read:
if (len(line) < 1) or (line[1] == '#'):
continue
date.append(str(dt.parse(line[0])))
values['for'].append(float(line[1]))
values['act'].append(float(line[2]))
print(file_name)
#
print('kind ; %s' % kind)
if kind == 'errors':
print('successfully retrieved data for %s in region: %s \n' % (type, location))
return date, map_list(values['act'], values['for'])
elif kind == 'forecasts':
print('successfully retrieved data for %s in region: %s \n' % (type, location))
return date, values['for']
elif kind == 'actuals':
print('successfully retrieved data for %s in region: %s \n' % (type, location))
return date, values['act']
else:
print('kind is not correct, here is the retrieved data for %s in region: %s \n' % (type, location))
return date, values
else:
print('foo')
return ()
### This function maps a function 'f' on two lists, returning a list
# Returns a list:
# () res : [f(vect1[0],vect2[0]), ... ]
# Arguments:
# () vect1,vect2, 2 lists to map f on
# () f: a function
def map_list(vect1, vect2, f=None, action='subtract'):
if (action == 'subtract') & (f is None):
def f(x, y):
return x - y;
elif f is None:
print('no valid action specified')
return -1
diff = len(vect1) - len(vect2)
if (diff):
print('possible error: vectors do not have same length')
#
v1, v2 = vect1.copy(), vect2.copy()
if (diff > 0):
v1 = v1[0:-diff]
elif (diff < 0):
v2 = v2[0:diff]
#
v1.reverse(), v2.reverse()
#
if type(f(0, 0)) == list:
length = len(f(0, 0))
res = [[] for i in f(0, 0)]
while (v1 != []) & (v2 != 0):
temp = (f(v1.pop(), v2.pop()))
for i in range(length):
res[i].append(temp[i])
else:
res = []
while (v1 != []) & (v2 != []):
res.append(f(v1.pop(), v2.pop()))
return res
# arguments:
# () date: list of ordered dates
# () errors: list of corresponding values
# () date_range: 2-elements-list to specify a datetime range for the data.
# returns:
# () a tuple: (date,errors) shortened to fit the date range
def restrain_to_date_range(date, errors, date_range):
date = date.copy()
errors = errors.copy()
if len(date) != len(errors):
return ([], [])
else:
date_min, date_max = (
max(dt.parse(date[0]), dt.parse(date_range[0])), min(dt.parse(date[len(date) - 1]), dt.parse(date_range[1])))
date_temp = []
error_temp = []
while (dt.parse(date.pop()) > date_max):
errors.pop()
last_date = dt.parse(date.pop())
while (last_date > date_min):
date_temp.append(str(last_date))
error_temp.append(errors.pop())
last_date = dt.parse(date.pop())
if (last_date == date_min):
date_temp.append(str(last_date))
error_temp.append(errors.pop())
error_temp.reverse()
date_temp.reverse()
print('restrained to specified date range')
return (date_temp, error_temp)
# ------------------------------ copula analysis -----------------------------------------------------------------------
### This function plots and return the empirical copula of 2 error forecasts with possible hour offsets
# arguments:
# () type1,location1,type2,location2: specifies the 2 data range to be compared with
# () hour_offset: it will compare errors1 at date1 with errors2 at date2+offset (in hours)
# () redistribute: if different from Identity, it will call a function to redistribute the data according to a certain law (gaussian for example)
# () parameter: a dictionary specifying the parameters: {'main': ... ,'loc': ... ,'kin': ... } with main in {'date','Wind','Solar'}, loc in {'total','NP','SP'} and kin in {'errors','forecasts','actuals'}
# () which_data
# Calls to:
# () prepare_data (returns two lists of errors)
# () draw_copula (to create and plot the empirical copula points and density)
# Returns a dict as {'unif':[[unif1,unif2],...], 'characteristics': [(mean, 10th percentile , 90th percentile) , ...] ] with:
# () (unif1,unif2): the error distribution, with uniform marginals
def plot_copula_2d(type1, location1, type2, location2, options, hour_offset=0, date_range=[], fig_nb=1,
redistribute='Identity', parameter={}, kind='errors', first_hour=None):
result = {'unif': [], 'characteristics': [[], []]}
returned = prepare_data(type1, location1, type2, location2, options, hour_offset=hour_offset, date_range=date_range,
kind=kind, first_hour=first_hour)
for ret in returned:
errors1, errors2, date, count, offset = ret
title = 'Copula of forecast error \n between (%s in %s) and (%s in %s), \n \n hour offset: %d' % (
type1, location1, type2, location2, offset)
xlabels = '%s in %s' % (type1, location1)
ylabels = '%s in %s' % (type2, location2)
if (type(redistribute) == str) & (redistribute != 'Identity'):
if redistribute == 'Gaussian':
print('this is what a gaussian fitted to the data would give')
errors1, errors2, count = redistribute_gaussian(errors1, errors2)
title += ('\n redistributed: gaussian')
elif redistribute == 'Diagonal':
print('we look at the correlation between the sum and subtraction of the two vectors')
errors1, errors2, count = redistribute_diagonal(errors1, errors2)
title += ('\n redistributed: diagonals')
elif redistribute == 'Spline':
print('this is what a spline copula would give')
errors1, errors2, count = redistribute_spline(errors1, errors2, options)
title += ('\n redistributed: spline copula')
else:
print('redistribute error: no function for %s; plotting default copula' % redistribute)
title += ('\n redistributed: NO')
else:
title += ('\n redistributed: NO')
# calls draw_copula to plot the copula and get the results to return
if parameter == {}:
res = draw_copula(errors1, errors2, title=title, xlabels=xlabels, ylabels=ylabels, fig_nb=fig_nb)
result['unif'].append(res)
else:
res = draw_copula_parameter(errors1, errors2, date, type1, location1, type2, location2,
hour_offset=hour_offset, date_range=date_range, title=title, xlabels=xlabels,
ylabels=ylabels, fig_nb=fig_nb, visualize=True, parameter=parameter)
result['unif'].append(res)
# what is the upper and lower quantile of the error distribution?
l = np.array(errors1)
temp = (np.mean(l), np.percentile(l, 10), np.percentile(l, 90))
print('%s mean: %d quantiles 1: (10,%d) (90,%d)' % (kind, temp[0], temp[1], temp[2]))
result['characteristics'][0].append(temp)
l = np.array(errors2)
temp = (np.mean(l), np.percentile(l, 10), np.percentile(l, 90))
print('%s mean: %d quantiles 2: (10,%d) (90,%d)' % (kind, temp[0], temp[1], temp[2]))
result['characteristics'][1].append(temp)
fig_nb += 1
print(result['unif'])
return result
### This function plots and return the empirical copula of 2 error forecasts, but also
### the distribution along the diagonal and anti-diagonal axis
# Returns a list as [ [diag,anti_diag],... ] with:
# () diag,anti_diag: the distribution along the diagonal and anti_diagonal axis
# arguments:
# () type1,location1,type2,location2: specifies the 2 data range to compare
# () hour_offset: it will compare errors1 at date1 with errors2 at date2+offset (in hours)
# Calls to:
# () plot_copula_2d (returns the empirical copula)
# () compute_diag (computes the distribution of 2D points along the diagonal and anti-diagonal axis)
def copula_analysis(type1, location1, type2, location2, options, hour_offset=0, date_range=[], fig_nb=1):
if type(hour_offset) != list:
hour_offset = [hour_offset]
returned = \
plot_copula_2d(type1, location1, type2, location2, options, hour_offset=hour_offset, date_range=date_range,
fig_nb=fig_nb)['unif']
len_offset = len(hour_offset)
step = 300
incr = 0
result = []
for ret in returned:
unif1, unif2 = ret
diag, anti_diag = compute_diag(unif1, unif2, step)
index = [i for i in range(step)]
f_anti_diag = spline.create_spline(spline.find_spline(index, anti_diag, options, visualize=False))
temp = options.seg_N
options.seg_N //= 2
f_diag = spline.create_spline(
spline.find_spline(index[0:(step // 2)], diag[0:(step // 2)], options, visualize=False))
options.seg_N = temp
del (temp)
print(len(hour_offset) - incr - 1)
plt.figure(fig_nb + 2 * incr + len_offset - 1 + 1)
plt.title('diagonal distribution, offset: %d' % (hour_offset[incr]))
val = [f_diag(step // 2 - abs(step // 2 - i)) for i in index]
plt.plot(index, val, color='red')
plt.plot(diag, '.')
plt.figure(fig_nb + 2 * incr + len_offset - 1 + 2)
plt.title('anti-diagonal distribution, offset: %d' % (hour_offset[incr]))
val = [f_anti_diag(i) for i in index]
plt.plot(index, val, color='red')
plt.plot(anti_diag, '.')
incr = incr + 1
result.append([diag, anti_diag])
# this function works with copula points:
# it computes quadrants with an equal number of points, and the barycenter of the extreme points in each quadrant
# returns as a list [[x0,x1,..],[y0,y1,..]]:
# () coordinates of the barycenters
# arguments:
# () type1,location1,type2,location2: specifies the 2 data range to compare
# () quantile= specifies the extreme points to be taken into account
# () nbPoints= number of quadrants
# () distance function= a norm used to determine extreme points ('l1','l2',linf')
def representative_points(type1, location1, type2, location2, options, quantile=0.1, nbPoints=4, distance_func='l1',
hour_offset=0, date_range=[], fig_nb=1):
# retrieving copula data
returned = (
plot_copula_2d(type1, location1, type2, location2, options, hour_offset=hour_offset, date_range=date_range,
fig_nb=fig_nb))['unif']
if returned != []:
ret = returned.pop()
[unif1, unif2] = ret
length = len(unif1)
if (len(unif2) != length):
print('coordinate vectors must be same length')
return -1
# computing coor (coordinate along the edge of a 1 length square)
# and quant (distance to the center of the square)
temp1, temp2 = unif1.copy(), unif2.copy()
coor = []
quant = []
def comp_angle(x, y):
valAbs = abs(x) + abs(y)
if valAbs == 0:
return -1
if y - x < 0:
if y + x < 0:
res = (0 + (1 - x / y) / 2)
else:
res = (1 + (y / x + 1) / 2)
else:
if y + x > 0:
res = (2 + (1 - x / y) / 2)
else:
res = (3 + (y / x + 1) / 2)
return res
def comp_angle_inv(ang):
num = ang // 1
if num == 0:
return (ang, 0)
elif num == 1:
return (1, ang - num)
elif num == 2:
return (1 - ang + num, 1)
else:
return (0, max(0, 1 - ang + num))
while temp1 != []:
x, y = 2 * temp1.pop() - 1, 2 * temp2.pop() - 1
if (distance_func == 'l1'):
valAbs = l1(x, y)
elif (distance_func == 'l2'):
valAbs = l2(x, y)
elif (distance_func == 'linf'):
valAbs = linf(x, y)
else:
print('distance function %s is not defined, using l1 norm as default' % distance_func)
valAbs = l1(x, y)
quant.append(valAbs)
coor.append(comp_angle(x, y))
# sorting the copula points according to coor
coor.reverse()
quant.reverse()
unif1_temp = unif1.copy()
unif2_temp = unif2.copy()
all = []
for i in range(length):
all.append([unif1_temp.pop(), unif2_temp.pop(), quant.pop(), coor.pop()])
def temp_sort(a):
return a[3]
all.sort(key=temp_sort)
# defining the separators of the quadrants
separators = []
for i in range(nbPoints):
index = int(np.floor((i + 1 / 2) * length / nbPoints))
separators.append((all[index][3], index))
def findSep(i):
res = 0
if i >= separators[nbPoints - 1][1]:
res = 0
else:
for j in range(nbPoints):
if i < separators[j][1]:
res = j
break
return res
points = [[0 for i in range(nbPoints)], [0 for i in range(nbPoints)]]
quadrants_pts = [[] for i in range(nbPoints)]
for i in range(length):
x, y, radius, angle = all.pop()
index = findSep(length - i - 1)
quadrants_pts[index].append((x, y, radius))
def temp_sort(a):
return a[2]
# computing the barycenters and plotting
for i in range(nbPoints):
quadrants_pts[i].sort(key=temp_sort)
length_temp = int(np.floor(len(quadrants_pts[i]) * quantile))
list_temp = [[], []]
for j in range(length_temp):
x, y, radius = quadrants_pts[i].pop()
points[0][i] += x
points[1][i] += y
list_temp[0].append(x)
list_temp[1].append(y)
points[0][i] /= length_temp
points[1][i] /= length_temp
plt.figure(fig_nb)
# plt.subplot(211)
plt.plot(list_temp[0], list_temp[1], '.', color='green')
plt.plot(points[0], points[1], '+', color='red', markersize=10, markeredgewidth=2)
for i in range(nbPoints):
line = comp_angle_inv(separators[i][0])
plt.plot([line[0], 0.5], [line[1], 0.5], color='red', linewidth=2)
print('\n %d quadrants, quantile= %0.3f' % (nbPoints, quantile))
for i in range(nbPoints):
print('point of the %d th quadrant: %0.3f , %0.3f' % (i, points[0][i], points[1][i]))
print('\n');
return points
return []
"""
def best_copula(type1, location1, type2, location2, options, nb_parts=4, nb_points_parts=0, hour_offset=0,
date_range=[], fig_nb=1, precision=20):
# retrieving and preparing the data
result = prepare_data(type1, location1, type2, location2, options, hour_offset=hour_offset, date_range=date_range)
if (result == []):
print('No data to deal with')
return -1;
errors1, errors2, date, count, offset = result.pop()
copula = ['Identity', 'Gaussian', 'Gaussian no fit', 'Spline']
unif1, unif2 = (draw_copula(errors1, errors2, visualize=False))
length = len(unif1)
parts = [int(length * i // nb_parts) for i in range(nb_parts)]
parts.append(length)
values = [[[], []] for i in range(len(copula))]
for i in range(nb_parts - 1):
i += 1
print(i)
err1 = errors1[parts[i - 1]:parts[i]]
err2 = errors2[parts[i - 1]:parts[i]]
if (nb_points_parts < 10) | (nb_points_parts > 50000):
l = min(parts[i + 1], 2 * parts[i] - parts[i - 1])
else:
l = parts[i] + nb_points_parts
# generating the copula to compare to
for j in range(len(copula)):
redistribute = copula[j]
if (type(redistribute) == str) & (redistribute != 'Identity'):
if redistribute == 'Gaussian':
e1, e2, count = redistribute_gaussian(err1, err2, length=nb_points_parts)
if redistribute == 'Gaussian no fit':
e1, e2, count = redistribute_gaussian(err1, err2, length=nb_points_parts, fit=False)
elif redistribute == 'Diagonal':
e1, e2, count = redistribute_diagonal(err1, err2, length=nb_points_parts)
elif redistribute == 'Spline':
e1, e2, count = redistribute_spline(err1, err2, options, length=nb_points_parts)
else:
lbis = min(parts[i + 1], 2 * parts[i] - parts[i - 1])
e1, e2 = errors1[parts[i]:lbis], errors2[parts[i]:lbis]
unif1, unif2 = (draw_copula(e1, e2, visualize=False))
print('\n \n \n %d: length: %d %d' % (i, sum(unif1), sum(unif2)))
(values[j][0]).extend(unif1)
(values[j][1]).extend(unif2)
# title='Copula of forecast error \n between (%s in %s) and (%s in %s), \n \n hour offset: %d'% (type1,location1,type2,location2,offset)
# xlabels='%s in %s'% (type1,location1)
# ylabels='%s in %s'% (type2,location2)
#
# if (type(redistribute)==str)&(redistribute!='Identity'):
# if redistribute=='Gaussian':
# print('this is what a gaussian fitted to the data would give')
# title+=('\n redistributed: gaussian')
# elif redistribute=='Gaussian no fit':
# print('this is what a random gaussian would give')
# title+=('\n redistributed: gaussian no fit')
# elif redistribute=='Diagonal':
# print('we look at the correlation between the sum and subtraction of the two vectors')
# title+=('\n redistributed: diagonals')
# elif redistribute=='Spline':
# print('this is what a spline copula would give')
# title+=('\n redistributed: spline copula')
# else:
# print('redistribute error: no function for %s; plotting default copula'% redistribute)
# title+=('\n redistributed: NO')
# else:
# if fig_nb<=9:
# plt.figure(fig_nb)
# plt.plot(unif1,unif2,'.')
# plt.xlabel(xlabels)
# plt.title(title)
# plt.ylabel(ylabels)
# fig_nb+=1
for j in range(len(copula)):
redistribute = copula[j]
title = 'Copula of forecast error \n between (%s in %s) and (%s in %s), \n \n hour offset: %d' % (
type1, location1, type2, location2, offset)
xlabels = '%s in %s' % (type1, location1)
ylabels = '%s in %s' % (type2, location2)
if (type(redistribute) == str) & (redistribute != 'Identity'):
if redistribute == 'Gaussian':
print('this is what a gaussian fitted to the data would give')
title += ('\n redistributed: gaussian')
elif redistribute == 'Gaussian no fit':
print('this is what a random gaussian would give')
title += ('\n redistributed: gaussian no fit')
elif redistribute == 'Diagonal':
print('we look at the correlation between the sum and subtraction of the two vectors')
title += ('\n redistributed: diagonals')
elif redistribute == 'Spline':
print('this is what a spline copula would give')
title += ('\n redistributed: spline copula')
else:
print('redistribute error: no function for %s; plotting default copula' % redistribute)
title += ('\n redistributed: NO')
else:
title += ('\n redistributed: NO')
plt.figure(fig_nb)
plt.plot(values[j][0][0:(min(parts[2], 2 * parts[1]) - parts[1])],
values[j][1][0:(min(parts[2], 2 * parts[1]) - parts[1])], '.')
plt.xlabel(xlabels)
plt.title(title)
plt.ylabel(ylabels)
fig_nb += 1
print('\n########')
for j in range(len(copula) - 1):
j += 1
redistribute = copula[j]
distance = 0
for i in range(nb_parts - 1):
i += 1
begin = parts[i] - parts[1]
if (nb_points_parts < 10) | (nb_points_parts > 50000):
end = min(parts[i + 1], 2 * parts[i] - parts[i - 1]) - parts[1]
else:
end = begin + nb_points_parts
distance += compute_distance_emd(values[0][0][begin:end], values[0][1][begin:end], values[j][0][begin:end],
values[j][1][begin:end], precision=precision)
print('distance between empirical and %s copula: %f' % (redistribute, distance))
print('########\n')
"""
# ------------------------------ adjacent functions for copula analysis ------------------------------------------------
### This function prepares the data for a later copula analysis
# returns:
# () errors1,errors2 : the errors between forecasts for the two data files
# () date: the corresponding date (for the first data range, if there is an offset)
# () count: the length of these 4 vectors
# () offset: the hour offset between the two data ranges
# calls to:
# () restrain_to_date_range (to treat a specified date range)
def prepare_data(type1, location1, type2, location2, options, hour_offset=0, date_range=[], kind='errors',
first_hour=None):
date_original1, errors_original1 = get_data(type1, location1, kind=kind)
if (type1 == type2) & (location1 == location2):
date_original2, errors_original2 = (date_original1.copy(), errors_original1.copy())
else:
date_original2, errors_original2 = get_data(type2, location2, kind=kind)
# Iterating on hour_offset
if type(hour_offset) != list:
hour_offset = [hour_offset]
result = []
for offset in hour_offset:
date_temp1, errors_temp1 = (date_original1.copy(), errors_original1.copy())
date_temp2, errors_temp2 = (date_original2.copy(), errors_original2.copy())
# setting an hour offset to data
if (offset != 0) & (type(offset) == int):
date_temp2 = [str(dt.parse(date_temp2[i]) + relativedelta(hours=offset)) for i in range(len(date_temp2))]
if len(date_range) == 2:
date_temp1, errors_temp1 = restrain_to_date_range(date_temp1, errors_temp1, date_range)
date_temp2, errors_temp2 = restrain_to_date_range(date_temp2, errors_temp2, date_range)
# checking for corresponding dates
len1 = len(date_temp1)
len2 = len(date_temp2)
errors1 = []
errors2 = []
date = []
diff = (dt.parse(date_temp1[0]) - dt.parse(date_temp2[0])).seconds // 3600 + (
dt.parse(date_temp1[0]) - dt.parse(
date_temp2[0])).days * 24
print('diff %d' % diff)
count = 0
for i in range(len1):
if (i + diff > len2 - 1) | (i + diff < 0):
continue
d1 = date_temp1[i]
date_match = (d1 == date_temp2[i + diff])
if not date_match:
for j in range(max(0, i + diff - 50), min(len2, i + diff + 50)):
if d1 == date_temp2[j]:
diff = j - i
date_match = True
break
if date_match:
date.append(d1)
errors1.append(errors_temp1[i])
errors2.append(errors_temp2[i + diff])
count = count + 1
isfh, first_hour = is_list_of(first_hour, child=int)
if isfh:
b = []
for i in date:
b.append(dt.parse(i).hour in first_hour)
[errors1, errors2, date] = remove_in_list([errors1, errors2, date], b, when=[False])
count = len(errors1)
result.append((errors1, errors2, date, count, offset))
return result
### This function plots and return the empirical copula of 2 error forecasts
# arguments:
# () vect1,vect2: specifies the 2 data range to be compared with
# Returns a list whose elements are:
# () (unif1,unif2): the error distribution, with uniform marginals
def draw_copula(vect1, vect2, title='', xlabels='', ylabels='', fig_nb=1, visualize=True, parameter={}):
count = len(vect1)
print('count : %d ' % count)
if (len(vect2) != count):
print("vect1 and vect2 must have the same length")
return []
else:
index1 = sorted(range(count), key=vect1.__getitem__, reverse=False)
index2 = sorted(range(count), key=vect2.__getitem__, reverse=False)
unif1 = [0 for i in range(count)]
unif2 = [0 for i in range(count)]
print('len pour 1: %d len pour 2: %d count: %d' % (len(index1), len(index2), count))
for i in range(count):
unif1[index1[i]] = i / count
unif2[index2[i]] = i / count
# estimating correlation
correlation = (sum([unif1[i] * unif2[i] for i in range(count)]) - 0.25 * count) / (
((count + 1) * (2 * count + 1) / (count * 6)) - 0.25 * count) # divided by the sum of squares formula
title = title + ('\n estimated correlation: %.4f' % correlation)
# estimating copula density
#
# dim=int(np.floor(np.sqrt(count/10)))
# density=[[0 for i in range(dim)] for j in range(dim)]
# temp1=unif1.copy()
# temp2=unif2.copy()
# for i in range(count):
# x=int(np.floor(temp1.pop()*dim))
# y=int(np.floor(temp2.pop()*dim))
# density[x][y]=density[x][y]+1
# del(temp1,temp2)
# plotting copula points
if visualize:
rcParams['figure.figsize'] = 7, 7
plt.figure(fig_nb)
# plt.subplot(211)
plt.title(title)
plt.plot(unif1, unif2, '.')
plt.xlabel(xlabels)
plt.ylabel(ylabels)
axes = plt.gca()
axes.set_xlim([0, 1])
axes.set_ylim([0, 1])
# plotting copula density
# plt.subplot(212)
# ax=plt.subplot(212)
# patches=[]
# inv=1.0/dim
# inv_max_density=1/np.max(density)
# i=0
# for den in density:
# j=0
# for val in den:
# col=1-val*inv_max_density*0.8
# rect = mpatches.Rectangle([i,j],inv,inv, color=(col,col,col))
# ax.add_patch(rect)
# patches.append(rect)
# j=j+inv
#
# i=i+inv
#
# plt.xlabel(xlabels)
# plt.ylabel(ylabels)
# axes = plt.gca()
# axes.set_xlim([0,1])
# axes.set_ylim([0,1])
rcParams['figure.figsize'] = 7, 6
return (unif1, unif2)
### This function plots and return the empirical copula of 2 error forecasts, coloured according to some parameter (date,forecasts,...)
# arguments:
# () vect1,vect2: specifies the 2 data range to be compared with
# () parameter: a dictionary specifying the parameters: {'main': ... ,'loc': ... ,'kin': ... } with main in {'date','Wind','Solar'}, loc in {'total','NP','SP'} and kin in {'errors','forecasts','actuals'}
# Returns:
# () (unif1,unif2): the error distribution, with uniform marginals
def draw_copula_parameter(vect1, vect2, date, type1, location1, type2, location2, hour_offset=0, date_range=[],
title='', xlabels='', ylabels='', fig_nb=1, visualize=True, parameter={}):
vect1, vect2 = vect1.copy(), vect2.copy()
count = len(vect1)
print('count : %d ' % count)
if (len(vect2) != count):
print("vect1 and vect2 must have the same length")
return []
else:
index1 = sorted(range(count), key=vect1.__getitem__, reverse=False)
index2 = sorted(range(count), key=vect2.__getitem__, reverse=False)
unif1 = [0 for i in range(count)]
unif2 = [0 for i in range(count)]
print('len pour 1: %d len pour 2: %d count: %d' % (len(index1), len(index2), count))
for i in range(count):
unif1[index1[i]] = i / count
unif2[index2[i]] = i / count
# estimating correlation
correlation = (sum([unif1[i] * unif2[i] for i in range(count)]) - 0.25 * count) / (
((count + 1) * (2 * count + 1) / (count * 6)) - 0.25 * count) # divided by the sum of squares formula
title = title + ('\n estimated correlation: %.4f' % correlation)
# initializing param
param = []
dic_main = {'date', 'Wind', 'Solar'}
dic_loc = {'total', 'NP', 'SP'}
dic_kin = {'errors', 'forecasts', 'actuals'}
keys = parameter.keys()
# getting parameters from 'parameter'
if (parameter != {}) & ('main' in keys):
if parameter['main'] == 'date':
temp = date
temp.reverse()
t0 = dt.parse('01/01/2010 00:00')
while temp != []:
t = temp.pop()
param.append((dt.parse(t) - t0).days % 365)
del (t)
title = title + ('\n parameter: date')
else:
typ = type1
loc = location1
kin = 'forecasts'
if 'loc' in keys:
if parameter['loc'] in dic_loc:
typ = parameter['loc']
else:
print('Wrong \'loc\' parameter, using %s' % loc)
else:
print('No \'loc\' parameter, using %s' % loc)
if parameter['main'] in dic_main:
if parameter['main'] == 'Solar':
loc = 'Solar'
else:
loc = 'Wind'
if 'kind' in keys:
if parameter['kind'] == 'errors':
kin = 'errors'
elif parameter['kind'] == 'actuals':
kin = 'actuals'
elif parameter['kind'] == 'forecasts':
kin = 'forecasts'
else:
print('wrong \'kind\' parameter, using %s' % kin)
else:
print('No \'kind\' parameter, using %s' % kin)
title = title + ('\n parameter: %s %s in %s' % (typ, kin, loc))
# retrieving the data for param, and checking that the dates correspond to those in 'date'
if (typ == type1) & (loc == location1) & (kin == 'errors'):
param = vect1
elif (typ == type2) & (loc == location2) & (kin == 'errors'):
param = vect2
else:
date_temp, param_temp = get_data(type=typ, location=loc, kind=kin)
# date checking
len_temp = len(date_temp)
print(date_temp)
difference = dt.parse(date[0]) - dt.parse(date_temp[0])
diff = difference.seconds // 3600 + difference.days * 24
param_temp_bis = []