-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathvines.py
More file actions
1563 lines (1242 loc) · 52.2 KB
/
Copy pathvines.py
File metadata and controls
1563 lines (1242 loc) · 52.2 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
import matplotlib.pyplot as plt
import math
import time
import random
import numpy as np
from scipy import stats
import scipy.special as spe
import scipy.optimize as optimize
from scipy.integrate import quad
import utilities as ut
# -------------------------------------- 2 types of vines ------------------------------------------------------------
epsilon = 0.000001
class conditional(object):
dim = 1
length = 0
name = ''
val = []
cop_mod = None
copulae = [[]]
mode = 'conditional'
def update_parameter(self, par):
pass
def pdf(self, unifs):
return [1]
def log_likelihood(self, par, arg_unifs=[[]]):
return 0
def simulate(self, count):
return []
def print_par(self):
for i in self.copulae:
for j in i:
print(j.par)
def print_names(self):
for i in self.copulae:
for j in i:
print(j.name)
def pprint(self):
pass
def conditionnalPDF(self, obs):
def pdf(x):
if 0 < x < 1:
return 1
else:
return 0
return pdf
class C_vine(conditional):
name = 'canonical vine'
ACR = 'CV'
def __init__(self, uniforms, list_models=None, add_name=''):
# arranging the coordinates for the canonical-vine decomposition: n-1,n-2,..,1,n so that the unknown Xn
# will be estimated using Xn-1 first, then Xn-2 ...etc
unifs = uniforms[:-1]
unifs.reverse()
unifs.append(uniforms[-1])
dim = len(unifs)
if list_models is None:
list_models = [[cop2d_gaussian, cop2d_student, cop2d_clayton, cop2d_frank, cop2d_gumbel] for i in
range(dim - 1)]
elif not type(list_models[0]) in {tuple, list, np.array}:
list_models = [list_models for i in range(dim - 1)]
copulae = []
obs = unifs
# creating the vine copula and selecting the models for each pair
print('creating the vine copula and selecting the models for each pair')
for step in range(dim - 1):
print('step: %d' % step)
copulae_for_step = []
sum_lld = 0
# selecting and fitting the best copula model for each pair of observations
for pair in range(1, dim - step):
best_copula = None
best_lld = 0
for cop in list_models[step]:
try:
copula_tp = cop([obs[0], obs[pair]])
lld_tp = copula_tp.log_likelihood([obs[0], obs[pair]])
if best_copula is None:
best_lld = lld_tp
best_copula = copula_tp
else:
if lld_tp > best_lld:
best_copula = copula_tp
best_lld = lld_tp
except:
print("could not estimate log likelihood of %s" % cop.name)
sum_lld += best_lld
copulae_for_step.append(best_copula)
# print('sum lld: %f' % sum_lld)
copulae.append(copulae_for_step)
# computing the observations for the next step
obs_for_next_step = []
for pair in range(1, dim - step):
obs_for_next_step.append(copulae_for_step[pair - 1].conditionalCDF([obs[0], obs[pair]], 0))
obs = obs_for_next_step
self.dim = dim
self.copulae = copulae
self.uniforms = uniforms
self.name += add_name
# defining the log likelihood function for our problem
par_start = []
for step in range(dim - 1):
for pair in range(1, dim - step):
par_tp = copulae[step][pair - 1].parameter_list()
par_start.extend(par_tp)
self.par_start = par_start
# function to update the parameters of the copula
def update_parameter(self, par):
cur = 0
for step in range(self.dim - 1):
for pair in range(1, self.dim - step):
length_par = len(self.copulae[step][pair - 1].parameter_list())
self.copulae[step][pair - 1].assign_parameter(par[cur:cur + length_par])
cur = cur + length_par
# returns the log-likelihood
def log_likelihood(self, par, arg_unif=None, restricted=False):
if arg_unif is None:
arg_unif = self.uniforms
not_list = np.ndim(arg_unif[0]) == 0
if not_list:
arg_unif = [[i] for i in arg_unif]
unifs = arg_unif[:-1]
unifs.reverse()
unifs.append(arg_unif[-1])
if par is not None:
self.update_parameter(par)
obs = unifs
res = 0
# computing the log-likelihood
for step in range(self.dim - 1):
# print('step: %d, \no1: %r , \no2:%r'%(step,obs[0][:10],obs[-1][:10]))
if restricted:
res = res + self.copulae[step][-1].log_likelihood([obs[0], obs[-1]])
else:
for pair in range(1, self.dim - step):
# print(' we add: %r'%(self.copulae[step][pair-1].log_likelihood([obs[0],obs[pair]])))
res = res + self.copulae[step][pair - 1].log_likelihood([obs[0], obs[pair]])
obs_for_next_step = []
for pair in range(1, self.dim - step):
obs_for_next_step.append(self.copulae[step][pair - 1].conditionalCDF([obs[0], obs[pair]], 0))
obs = obs_for_next_step
return res
# returns the density
def pdf(self, unifs):
not_list = np.ndim(unifs[0]) == 0
if not_list:
unifs = [[i] for i in unifs]
res = list(map(math.exp, [self.log_likelihood(None, arg_unif=[[i] for i in x]) for x in zip(*unifs)]))
return res
# print('maximizing the log-likelihood')
# par=optimize.minimize(lambda x: -log_likelihood(x),par_start.copy())
def conditionalPDF(self, observed):
if (min(observed) <= 0) | (max(observed) >= 1):
raise (RuntimeError('\'observed\' must be in the unit cube'))
arrange_observed = observed
arrange_observed.reverse()
def pdf(x):
not_list = np.ndim(x) == 0
if not_list:
x = [x]
if (max(x) >= 1) | (min(x) <= 0):
raise (RuntimeError('\'observed\' must be in the unit cube'))
arguments = []
for xx in x:
temp = arrange_observed.copy()
temp.append(xx)
arguments.append(temp)
return [math.exp(-self.log_likelihood(None, unifs=arg)) for arg in arguments]
return pdf
def partial(self, unifs, a, b):
if (b >= a) | (not (type(b) == type(a) == int)) | b < -1:
raise (RuntimeError('Wrong argument in partial'))
if b == -1:
return unifs[a]
else:
u1 = self.partial(unifs, a, b - 1)
u2 = self.partial(unifs, b, b - 1)
return self.copulae[b][a - b - 1].conditionalCDF([u1, u2], coor=1)
def simulate(self, nb):
unifs = np.random.uniform(0, 1, (self.dim, nb))
res = [unifs[0]]
for i in range(1, self.dim):
temp = [self.partial(res, j, j - 1) for j in range(i)]
def cdf(x, pt, temp=temp):
res_tp = [x]
for j in range(i):
res_tp = self.copulae[j][i - j - 1].conditionalCDF([res_tp, [temp[j][pt]]], coor=1)
return res_tp[0]
res_tp = [optimize.brentq(lambda x: cdf(x, pt) - unifs[i][pt], epsilon, 1 - epsilon, xtol=epsilon / 2) for
pt in
range(nb)]
res.append(res_tp)
return res
class D_vine(conditional):
name = 'D_vine'
ACR = 'DV'
def __init__(self, uniforms, list_models=None, rearrange=False, add_name=''):
# arranging the coordinates for the canonical-vine decomposition: n-1,n-2,..,1,n so that the unknown Xn
# will be estimated using Xn-1 first, then Xn-2 ...etc
unifs = uniforms
dim = len(unifs)
if list_models is None:
list_models = [[cop2d_gaussian, cop2d_student, cop2d_clayton, cop2d_frank, cop2d_gumbel] for i in
range(dim - 1)]
elif np.ndim(list_models[0]) == 0:
list_models = [list_models for i in range(dim - 1)]
copulae = []
obs1 = unifs[:-1]
obs2 = unifs[1:]
self.dump = []
# creating the vine copula and selecting the models for each pair
print('creating the vine copula and selecting the models for each pair')
for step in range(dim - 1):
print('step: %r' % step)
copulae_for_step = []
# selecting and fitting the best copula model for each pair of observations
for pair in range(dim - step - 1):
pair_obs = [obs1[pair], obs2[pair]]
best_copula = max(list_models[step], key=lambda cop: cop(pair_obs).log_likelihood(pair_obs))
best_lld = 0
# print(list_models)
# for cop in list_models[step]:
# # try:
# copula_tp = cop([obs1[pair], obs2[pair]])
# lld_tp = copula_tp.log_likelihood([obs1[pair], obs2[pair]]) - len(copula_tp.parameter_list())
# # print('\n### step: %d copula: %s, log: %r, par: %r\n'%(step,copula_tp.name,lld_tp,copula_tp.par))
#
# if best_copula is None:
# best_lld = lld_tp
# best_copula = copula_tp
# else:
# if lld_tp > best_lld:
# best_copula = copula_tp
# best_lld = lld_tp
# # except:
# # print([obs1[pair], obs2[pair]])
# # print("could not estimate log likelihood of %dth copula" % pair)
copulae_for_step.append(best_copula)
copulae.append(copulae_for_step)
# computing the observations for the next step
obs_for_next_step_1 = []
obs_for_next_step_2 = []
for pair in range(0, dim - step - 2):
obs_for_next_step_1.append(copulae[step][pair].conditionalCDF([obs1[pair], obs2[pair]], 1))
for pair in range(1, dim - step - 1):
obs_for_next_step_2.append(copulae[step][pair].conditionalCDF([obs1[pair], obs2[pair]], 0))
if rearrange:
obs1 = []
obs2 = []
for obs_for_copula in zip(*[obs_for_next_step_1, obs_for_next_step_2]):
unif_tp = ut.uniforms(obs_for_copula, rand=False)
obs1.append(unif_tp[0])
obs2.append(unif_tp[1])
else:
obs1 = obs_for_next_step_1
obs2 = obs_for_next_step_2
# print('obs: %r %r'%(obs1,obs2))
self.dump.append((obs1, obs2))
name = 'D_vine'
for i in copulae:
for j in i:
name = '%s_%s' % (name, j.ACR)
name += '|'
name += add_name
self.dim = dim
self.copulae = copulae
self.rearrange = rearrange
self.uniforms = uniforms
self.name = name
# defining the log likelihood function for our problem
par_start = []
for step in range(dim - 1):
for pair in range(1, dim - step):
par_tp = copulae[step][pair - 1].parameter_list()
par_start.extend(par_tp)
self.par_start = par_start
# function to update the parameters of the copula
def update_parameter(self, par):
cur = 0
for step in range(self.dim - 1):
for pair in range(1, self.dim - step):
length_par = len(self.copulae[step][pair - 1].parameter_list())
self.copulae[step][pair - 1].assign_parameter(par[cur:cur + length_par])
cur = cur + length_par
# returns the log-likelihood
def log_likelihood(self, par, arg_unif=None):
if arg_unif is None:
arg_unif = self.uniforms
not_list = np.ndim(arg_unif[0]) == 0
if not_list:
arg_unif = [[i] for i in arg_unif]
if par is not None:
self.update_parameter(par)
obs1 = arg_unif[:-1]
obs2 = arg_unif[1:]
res = 0
# computing the log-likelihood
for step in range(self.dim - 1):
for pair in range(self.dim - step - 1):
res = res + self.copulae[step][pair].log_likelihood([obs1[pair], obs2[pair]])
# creating the conditional values of the CDF
obs_for_next_step_1 = []
obs_for_next_step_2 = []
for pair in range(0, self.dim - step - 2):
obs_for_next_step_1.append(self.copulae[step][pair].conditionalCDF([obs1[pair], obs2[pair]], 1))
for pair in range(1, self.dim - step - 1):
obs_for_next_step_2.append(self.copulae[step][pair].conditionalCDF([obs1[pair], obs2[pair]], 0))
if self.rearrange:
obs1 = []
obs2 = []
for obs_for_copula in zip(*[obs_for_next_step_1, obs_for_next_step_2]):
unif_tp = ut.uniforms(obs_for_copula, rand=False)
obs1.append(unif_tp[0])
obs2.append(unif_tp[1])
else:
obs1 = obs_for_next_step_1
obs2 = obs_for_next_step_2
return res
# returns the density
def pdf(self, unifs):
not_list = np.ndim(unifs[0]) == 0
if not_list:
unifs = [[i] for i in unifs]
res = list(map(math.exp, [self.log_likelihood(None, arg_unif=[[i] for i in x]) for x in zip(*unifs)]))
return res
def partial(self, unifs, first, last, which=0):
height = last - first
if not ((type(first) == type(last) == int) & (first <= last)):
raise (RuntimeError('wrong argument in partial'))
if first == last:
return unifs[first]
else:
a = self.partial(unifs, first, last - 1, which=1)
b = self.partial(unifs, first + 1, last, which=0)
return self.copulae[height - 1][first].conditionalCDF([a, b], coor=which)
def simulate(self, nb):
unifs = [list(i) for i in np.random.uniform(0, 1, (self.dim, nb))]
res = [unifs[0]]
for i in range(1, self.dim):
temp = [self.partial(res, j, i - 1, which=1) for j in range(i)]
def cdf(x, temp=temp):
res_tp = x
for j in range(i):
res_tp = self.copulae[j][i - j - 1].conditionalCDF([temp[i - j - 1], res_tp], coor=0)
return res_tp
res_tp = ut.simultaneous_quantile(cdf, unifs[i])
res.append(res_tp)
return res
# ------------------------------------- defining 2d-copulae -----------------------------------------------------------
### upper class for copula models
# () val: Points of this copula
# () simulate: A function (of 'count') returning 'count' points distributed according to the copula
# () par: The parameters of the copula
# () pdf: The pdf of the copula
class cop2d(object):
length = 0
name = ''
ACR = ''
par = {}
lld = 0
nbPar = 0
# simulates points from ths copula
def simulate(self, count):
return [[]]
# pdf of th ecopula
def pdf(self, x):
return 1
### returns the conditional CDF with respect to the 'coor' coordinate:
# arguments:
# () unifs: a list of two coordinate lists
# () coor: 0 or 1: we will compute the CDF knowing unifs[coor] of unif[other]
# P(X[coor] <= c[coor] | X[other] = c[other])
def conditionalCDF(self, unifs, coor):
return [1]
### returns the sum of the log-likelihood of unifs with the parameters theta
def log_likelihood(self, unifs, theta=None):
return 0
## returns a list of the parameters
def parameter_list(self):
return []
## modifies the parameters of the copula
def assign_parameter(self, theta):
pass
## print method for 2d copulae
def pprint(self):
s = '\n### Copula Model: ' + self.name + ' ###\n\n'
s += 'parameters: %r' % self.par
print(s)
def plot_points(self, nb=1800):
v = self.simulate(nb)
plt.figure()
plt.plot(v[0], v[1], '.')
plt.title('%s copula' % self.name)
def plot_pdf(self):
ut.curve3d(lambda x: self.pdf([[x[0]], [x[1]]])[0], title='%s copula' % self.name)
# -------------------------------------- 2d copulae models ------------------------------------------------------------
### returns a 'gaussian copula' fitted to the given points
class cop2d_gaussian(cop2d):
name = 'gaussian'
ACR = 'GA'
def __init__(self, uniforms):
# Inference
if uniforms is None:
uniforms = [[0.5, 0.6], [0.5, 0.4]]
if not (ut.good_format(uniforms)[1]):
print(uniforms)
raise (RuntimeError('uniforms should be a list of same length list'))
a = stats.norm([0], [1])
vects = [[a.ppf(j)[0] for j in coor] for coor in uniforms]
cov = norm_matrix(np.cov(np.matrix(vects)))
self.uniforms = uniforms
self.vects = vects
self.length = len(uniforms[0])
self.name = 'gaussian'
self.nbPar = 1
self.par = {'cov': cov}
self.bounds = bounds = [(epsilon - 1, 1 - epsilon)]
opt_result = optimize.minimize_scalar(self.obs_likelihood, bounds=bounds[0], method='bounded')
if opt_result['success']:
# print('old parameter: %f, new: %f ' % (self.par['cov'][0, 1], opt_result['x']))
self.par['cov'][0, 1] = opt_result['x']
self.par['cov'][1, 0] = opt_result['x']
else:
print('Maximization of log likelihood was unsuccessful in cop2d_gaussian')
# defining the conditional cdf
self.createConditionalCDF()
# Simulation
def simulate(self, x):
redistributed = np.transpose(np.random.multivariate_normal([0 for i in range(2)], self.par['cov'], x))
return ut.uniforms(redistributed.tolist())
# density function
def pdf(self, unifs):
cov = self.par['cov']
not_list = np.ndim(unifs[0]) == 0
if not_list:
unifs = [[i] for i in unifs]
# the corresponding points in the 'real space' (ie. where the are distributed according to a normal law))
vecs = []
marginal_density = []
for i in range(2):
a = stats.norm([0], np.sqrt(cov[i, i]))
temp = [float(a.ppf(j)) for j in unifs[i]]
marginal_density.append([float(a.pdf(j)) for j in temp])
vecs.append(temp)
res = []
vecs = list(zip(*vecs))
marginal_density = list(zip(*marginal_density))
factor = np.sqrt((2 * math.pi) ** 2 * np.linalg.det(cov))
cov_inv = cov ** (-1)
for i in list(zip(*[vecs, marginal_density])):
v = np.matrix(i[0])
m = np.prod(i[1])
if m > 0:
temp = 1 / (m * factor) * math.exp(-0.5 * v * cov_inv * np.transpose(v))
else:
temp = 0
res.append(temp)
return res
# partial CDF: dC/dx
# coor specifies along which coordinate (x0 or x1) it is differentiated
def createConditionalCDF(self):
cov = self.par['cov']
new_var = (1 - cov[0, 1] ** 2)
self.norm_obj0 = stats.norm(0, 1)
self.norm_obj1 = stats.norm(0, np.sqrt(new_var))
self.last_par_1 = cov[0, 1]
def conditionalCDF(unifs, coor):
if not self.last_par_1 == self.par['cov'][0, 1]:
new_var = (1 - cov[0, 1] ** 2)
self.norm_obj1 = ut.fast_stats(stats.norm([0], np.sqrt(new_var)))
self.last_par_1 = cov[0, 1]
not_list = np.ndim(unifs) < 2
if not_list:
unifs = [[i] for i in unifs]
if (coor != 0) & (coor != 1):
raise (RuntimeError('coor specifies the coordinate: it must be either 0 or 1'))
if coor == 1:
other = 0
else:
other = 1
# the corresponding points in the 'real space' (ie. where the are distributed according to a normal law))
vecs = [self.norm_obj0.ppf(unifs[i]) for i in range(2)]
temp = [i[other] - cov[0, 1] * i[coor] for i in zip(*vecs)]
res = self.norm_obj1.cdf(temp)
return res
self.conditionalCDF = conditionalCDF
return conditionalCDF
# log-likelihood
def log_likelihood(self, unifs, theta=None, vects=None):
if unifs is None:
unifs = self.uniforms
not_list = np.ndim(unifs[0]) == 0
if not_list:
unifs = [[i] for i in unifs]
use_theta = False
if theta is not None:
if -1 < theta < 1:
use_theta = True
# else:
# raise(RuntimeError('theta must be in the interval (-1,1)'))
if not use_theta:
theta = self.par['cov'][0, 1]
if not -1 < theta < 1:
return self.log_likelihood(unifs, theta=0.99, vects=vects) * 10 * theta ** 2
else:
a = stats.norm([0], [1])
log0, log1 = 0, 0
if vects is None:
for i in zip(*unifs):
i = [a.ppf(i[0])[0], a.ppf(i[1])[0]]
log0 = log0 + i[0] ** 2 + i[1] ** 2
log1 = log1 + i[0] * i[1]
else:
for i in zip(*vects):
log0 = log0 + i[0] ** 2 + i[1] ** 2
log1 = log1 + i[0] * i[1]
log0 = -log0 * theta ** 2 / (1 - theta ** 2) / 2
log1 = log1 * theta / (1 - theta ** 2)
return log0 + log1 - len(unifs[0]) * math.log(1 - theta ** 2) / 2
def parameter_list(self):
return [self.par['cov'][0, 1]]
def assign_parameter(self, theta):
self.par['cov'] = np.matrix([[1, theta[0]], [theta[0], 1]])
# maximize log-likelihood
def obs_likelihood(self, theta):
if np.ndim(theta) > 0:
theta = theta[0]
if -1 < theta < 1:
return -self.log_likelihood(self.uniforms, theta=theta, vects=self.vects)
else:
return 10 * self.obs_likelihood(0.99) * theta ** 2
### returns a 'student copula' fitted to the given points
class cop2d_student(cop2d):
name = 'student'
ACR = 'ST'
def __init__(self, uniforms, precise=False):
length, format = ut.good_format(uniforms)
if not (format):
print(uniforms)
raise (RuntimeError('uniforms do not have the good format'))
if len(uniforms) != 2:
raise (RuntimeError('uniforms should be of dimension 2'))
# computing correlation
a = stats.norm([0], [1])
vects = [[a.ppf(j)[0] for j in coor] for coor in uniforms]
dim = len(uniforms)
cor = norm_matrix(np.cov(np.matrix(vects)))
cor_inv = np.linalg.inv(cor)
self.cor = cor
self.precise = precise
self.uniforms = uniforms
self.dim = 2
self.name = 'student'
self.length = length
self.bounds = [((-1 + 9 * cor[0, 1]) / 10, (1 + 9 * cor[0, 1]) / 10), (2 + epsilon, 10)]
theta = self.find_parameter()
# print(theta)
v = max(theta[1], 2 + epsilon)
s = np.matrix([[1, theta[0]], [theta[0], 1]]) # no need to multiply by factor (v-2)/v for the uniform
par = {'v': v, 'sigma': s}
self.par = par
self.createConditionalCDF()
# definition of the log_likelihood
def log_likelihood(self, unifs, theta=None):
if unifs is None:
unifs = self.uniforms
not_list = np.ndim(unifs[0]) == 0
if not_list:
unifs = [[i] for i in unifs]
if theta is None:
v = self.par['v']
sigma = norm_matrix(self.par['sigma'])
else:
# print(theta)
v = theta[1]
sigma = np.matrix([[1, theta[0]], [theta[0], 1]])
sigma_inv = sigma ** (-1)
# back in the real distribution space...
vecs = []
marginal_density = []
t_obj = stats.t(v)
for i in range(self.dim):
temp = [float(j) for j in t_obj.ppf(unifs[i])]
marginal_density.append([float(j) for j in t_obj.pdf(temp)])
vecs.append(temp)
vecs = list(zip(*vecs))
marginal_density = list(zip(*marginal_density))
# factor of the density in the real space
factor = math.log(spe.gamma((v + self.dim) / 2)) \
- math.log(spe.gamma(v / 2)) \
- 0.5 * self.dim * math.log((math.pi * v)) \
- 0.5 * math.log(np.linalg.det(sigma))
# computing the log likelihood
res = []
for pt in list(zip(*[vecs, marginal_density])):
x = np.matrix(pt[0])
try:
m = np.sum([math.log(density) for density in pt[1]])
temp = -m + factor + math.log(1 + x * sigma_inv * np.transpose(x) / v) * (-(v + self.dim) / 2)
except:
print(self.par)
print('error computing the density of student copula: pdf value is too low')
temp = 1
res.append(temp)
return sum(res)
# parameters of the student copula
# maximizing log-likelihood to find the parameters
def find_parameter(self):
cor = self.cor
if self.precise:
opt_result = optimize.minimize(lambda x: -(self.log_likelihood(self.uniforms, theta=x)), [cor[0, 1], 2.1],
bounds=self.bounds, method='L-BFGS-B')
else:
opt_result = optimize.minimize(lambda x: -(self.log_likelihood(self.uniforms, theta=[cor[0, 1], x[0]])),
[2.1],
bounds=[(2 + epsilon, 10)], method='L-BFGS-B')
if opt_result['success']:
if self.precise:
theta = opt_result['x']
else:
theta = [cor[0, 1]]
theta.append(float(opt_result['x']))
else:
print('Warning: optimization did not converge')
theta = [cor[0, 1], 5]
return theta
# computing t distribution (see " https://en.wikipedia.org/wiki/Multivariate_t-distribution")
def simulate(self, nb, theta=None):
if theta is None:
theta = [self.par['sigma'][0, 1], self.par['v']]
s = np.matrix([[1, theta[0]], [theta[0], 1]])
Y = np.transpose(np.random.multivariate_normal([0 for i in range(self.dim)], s, nb))
u = np.sqrt(theta[1] / np.random.chisquare(theta[1], nb))
temp = []
for yy in Y:
temp.append(list(np.array(yy) * u))
return (ut.uniforms(temp))
# density function definition
def pdf(self, unifs):
not_list = np.ndim(unifs[0]) == 0
if not_list:
unifs = [[i] for i in unifs]
v = self.par['v']
sigma = norm_matrix(self.par['sigma'])
sigma_inv = sigma ** (-1)
# back in the real distribution space...
vecs = []
marginal_density = []
t_obj = stats.t(v)
for i in range(self.dim):
temp = [float(j) for j in t_obj.ppf(unifs[i])]
marginal_density.append([float(j) for j in t_obj.pdf(temp)])
vecs.append(temp)
res = []
vecs = list(zip(*vecs))
marginal_density = list(zip(*marginal_density))
# factor of the density in the real space
factor = spe.gamma((v + self.dim) / 2) / (
spe.gamma(v / 2) * math.sqrt((math.pi * v) ** self.dim * np.linalg.det(sigma)))
for i in list(zip(*[vecs, marginal_density])):
x = np.matrix(i[0])
m = np.prod(i[1])
if m > 0:
temp = 1 / m * factor * math.exp(
math.log(1 + x * sigma_inv * np.transpose(x) / v) * (-(v + self.dim) / 2))
else:
# print(self.par)
# print('error computing the density of student copula: pdf value is too low')
temp = 0
res.append(temp)
return res
# estimating the conditional distributions
def createConditionalCDF(self):
v = self.par['v']
sigma = self.par['sigma']
self.condCDFpar = [v, sigma[0, 1]]
factor1 = sigma[0, 1] / 1
factor2 = 1 - sigma[0, 1] / 1 * sigma[0, 1]
variance = math.sqrt(v / (v - 2))
t_obj = stats.t(v)
new_t_obj = stats.t(v + 1)
def conditionalCDF(unifs, coor):
if not ((self.par['v'] == self.condCDFpar[0]) & (self.par['sigma'][0, 1] == self.condCDFpar[1])):
return self.createConditionalCDF()(unifs, coor)
not_list = np.ndim(unifs) < 2
if not_list:
unifs = [[i] for i in unifs]
if (coor != 0) & (coor != 1):
raise (RuntimeError('coor specifies the coordinate: it must be either 0 or 1'))
if coor == 0:
other = 1
else:
other = 0
vecs = np.array([t_obj.ppf(unifs[i]) for i in range(2)]) * variance
new_sigmas = (v + vecs[coor] ** 2) / (v + 1) * factor2
new_obs = (vecs[other] - factor1 * vecs[coor]) / np.sqrt(new_sigmas)
probas = new_t_obj.cdf(new_obs)
return probas
self.conditionalCDF = conditionalCDF
return conditionalCDF
def parameter_list(self):
return [self.par['sigma'][0, 1], self.par['v']]
def assign_parameter(self, theta):
self.par['sigma'] = np.matrix([[1, theta[0]], [theta[0], 1]])
self.par['v'] = theta[1]
### return a uniform copula for comparison purpose
class cop2d_uniform(cop2d):
name = 'uniform'
ACR = 'UN'
def __init__(self, unifs):
if unifs is None:
unifs = [[0.5], [0.5]]
self.dim = len(unifs)
self.length = len(unifs[0])
self.bounds = []
def simulate(self, count):
return np.random.uniform(0, 1, (self.dim, count))
def pdf(self, x):
if len(np.shape(x)) == 1:
x = [x]
return [1 for i in range(len(x[0]))]
def conditionalCDF(self, unifs, coor):
if coor == 0:
other = 1
else:
other = 0
return unifs[other]
def log_likelihood(self, unifs, theta=None):
return 0
def parameter_list(self):
return []
def assign_parameter(self, theta):
pass
######################
### From dominique ###
######################
# A class which returns a copula which maximizes the log likelihood of the weighted sums of copulas
# Max(x1 * c1 + x2 * c2 + x3 * c3 + ... + xn * cn)
# where x1 + x2 + x3 + ... + xn = 1,
# x1, x2, ... , xn >= 0
#
# To initialize pass in a list of points, and a list of copula models to test
class WeightedCopula(cop2d):
ACR = 'WE'
def __init__(self, vects, models, precise=True, max_models=10):
dim = len(vects)
if dim < 2:
raise ValueError('Data must be of at least dimension 2')
elif dim > 2:
vects = vects[:2] # Using only first two rows
count = len(models)
copulas = [copula(vects) for copula in models]
name = 'weighted'
if not precise:
name += '_simple'
for copula in copulas:
name += '_' + copula.ACR
self.ACR += '-' + copula.ACR
if count > max_models:
lld = [len(cop.parameter_list()) - cop.log_likelihood(vects) for cop in copulas]
# print(lld)
indexes = sorted(range(count), key=lld.__getitem__)[:max_models]
copulas = list(map(copulas.__getitem__, indexes))
models = list(map(models.__getitem__, indexes))
count = max_models
self.models = models
self.copulas = copulas
self.count = count
self.uniforms = vects
self.name = name
'''
if not precise:
cons = {'type': 'eq', 'fun': lambda x: sum(x) - 1}
bnds = ((0, 1),) * count