-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathElicipy.py
More file actions
2928 lines (1970 loc) · 84 KB
/
Copy pathElicipy.py
File metadata and controls
2928 lines (1970 loc) · 84 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 datetime
import numpy as np
import os
import sys
import pandas as pd
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor
from pptx.enum.shapes import MSO_SHAPE
from pptx.enum.text import MSO_AUTO_SIZE
from pptx import Presentation
from saveFromGithub import saveDataFromGithub
from createSamples import createSamples
from COOKEweights import COOKEweights
from ERFweights import ERFweights
from merge_csv import merge_csv
# from createPlots import create_fig_hist
from createPlots import create_figure_violin
from createPlots import create_figure_pie
from createPlots import create_figure_trend
from createPlots import create_figure_answers
from createPlots import create_barplot
from createPlots import create_figure_index
from tools import printProgressBar
# from krippendorff_alpha import calculate_alpha
from computeIndex import calculate_index
max_len_table = 21
max_len_tableB = 18
max_len_plot = 21
def add_date(slide):
shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, 0, Inches(0.2),
Inches(16), Inches(0.3))
shape.shadow.inherit = False
fill = shape.fill
fill.solid()
fill.fore_color.rgb = RGBColor(60, 90, 180)
line = shape.line
line.color.rgb = RGBColor(60, 90, 180)
shape.text = "Expert elicitation " + \
datetime.datetime.today().strftime("%d-%b-%Y")
shape_para = shape.text_frame.paragraphs[0]
shape_para.font.name = "Helvetica"
shape_para.font.size = Pt(17)
def add_small_logo(slide, left, top, logofile):
slide.shapes.add_picture(logofile,
left + Inches(13.0),
top + Inches(6.8),
width=Inches(0.8))
def add_figure(slide, figname, left, top, width):
img = slide.shapes.add_picture(figname,
left + Inches(3.4),
top,
width=width)
slide.shapes._spTree.insert(2, img._element)
def add_small_figure(slide, figname, left, top, width):
img = slide.shapes.add_picture(figname, left, top, width=width)
slide.shapes._spTree.insert(2, img._element)
def add_title(slide, text_title):
title_shape = slide.shapes.title
title_shape.text = text_title
title_shape.top = Inches(0.2)
title_shape.width = Inches(15)
title_shape.height = Inches(2)
title_para = slide.shapes.title.text_frame.paragraphs[0]
title_para.font.name = "Helvetica"
if len(text_title) < 50:
title_para.font.size = Pt(44)
else:
title_para.font.size = Pt(34)
def add_text_box(slide, left, top, text_box, font_size):
txBox = slide.shapes.add_textbox(left - Inches(1),
top + Inches(0.5),
width=Inches(4),
height=Inches(5))
tf = txBox.text_frame
tf.text = text_box
for par in tf.paragraphs:
par.font.size = Pt(font_size)
# tf.paragraphs[0].font.size = Pt(font_size)
# tf.text = 'prova'
tf.word_wrap = True
def iter_cells(table):
for row in table.rows:
for cell in row.cells:
yield cell
def read_answers(input_dir, csv_file, group, n_pctl, df_indexes_SQ,
df_indexes_TQ, seed, target, output_dir, elicitation_name,
write_flag, label_indexes):
verbose = False
try:
from ElicipyDict import label_flag
except ImportError:
label_flag = False
import difflib
# merge the files of the different experts
# creating one file for seeds and one for tagets
merge_csv(input_dir, seed, target, group, csv_file, label_flag, write_flag)
if seed:
# seeds file name
filename = input_dir + "/seed.csv"
# Read a comma-separated values (csv) file into DataFrame df_SQ
df_SQ = pd.read_csv(filename)
# create a 2D numpy array with the answers to the seed questions
cols_as_np = df_SQ[df_SQ.columns[4:]].to_numpy()
# we want to work with a 3D array, with the following dimension:
# n_expert X n_pctl X n_SQ
n_experts = cols_as_np.shape[0]
n_SQ = int(cols_as_np.shape[1] / n_pctl)
# The second column (index 1) must contain the first name of the expert
firstname = df_SQ[df_SQ.columns[1]].astype(str).tolist()
# The third column (index 2) must contain the first name of the expert
surname = df_SQ[df_SQ.columns[2]].astype(str).tolist()
# create a list with firstname+surname
# this is needed to search for expert matches between
# seed and target questions
NS_SQ = []
for name, surname in zip(firstname, surname):
NS_SQ.append(name + surname)
if verbose:
print("NS_SQ", NS_SQ)
# reshaped numpy array with expert answers
SQ_array = np.reshape(cols_as_np, (n_experts, n_SQ, n_pctl))
# swap the array to have seed for the last index
SQ_array = np.swapaxes(SQ_array, 1, 2)
# sort according to the percentile values
# (sometimes the expert give the percentiles in the wrong order)
SQ_array = np.sort(SQ_array, axis=1)
# chech and correct for equal percentiles
for i in np.arange(n_SQ):
for k in np.arange(n_experts):
# if 5% and 50% percentiles are equal, reduce 5%
if SQ_array[k, 0, i] == SQ_array[k, 1, i]:
SQ_array[k, 0, i] = SQ_array[k, 1, i] * 0.99
# if 50% and 95% percentiles are equal, increase 95%
if SQ_array[k, 2, i] == SQ_array[k, 1, i]:
SQ_array[k, 2, i] = SQ_array[k, 1, i] * 1.01
# if we have a subset of the SQ, then extract from SQ_array
# the correct slice
if len(df_indexes_SQ) > 0:
# print('SQ_array',SQ_array)
SQ_array = SQ_array[:, :, df_indexes_SQ]
n_SQ = len(df_indexes_SQ)
# print('SQ_array',SQ_array)
if verbose:
for i in np.arange(n_SQ):
print("")
print("Seed question ", label_indexes[i])
print(SQ_array[:, :, i])
else:
n_SQ = 0
df_indexes_SQ = []
if target:
filename = input_dir + "/target.csv"
# Read a comma-separated values (csv) file into DataFrame df_TQ
df_TQ = pd.read_csv(filename)
# The second column (index 1) must contain the first name of the expert
firstname = df_TQ[df_TQ.columns[1]].astype(str).tolist()
# The third column (index 2) must contain the first name of the expert
surname = df_TQ[df_TQ.columns[2]].astype(str).tolist()
# create a list with firstname+surname
# this is needed to search for expert matches between seed
# and target questions
NS_TQ = []
for name, surname in zip(firstname, surname):
NS_TQ.append(name + surname)
if seed:
sorted_idx = []
# loop to search for matches between experts in seed and target
for SQ_name in NS_SQ:
index = NS_TQ.index(
difflib.get_close_matches(SQ_name, NS_TQ)[0])
sorted_idx.append(index)
if verbose:
print("Sorted list of experts to match the order of seeds:",
sorted_idx)
print(NS_SQ)
print([NS_TQ[s_idx] for s_idx in sorted_idx])
else:
sorted_idx = range(len(NS_TQ))
NS_SQ = NS_TQ
# create a 2D numpy array with the answers to the target questions
cols_as_np = df_TQ[df_TQ.columns[4:]].to_numpy()
# sort for expert names
cols_as_np = cols_as_np[sorted_idx, :]
# we want to work with a 3D array, with the following dimension:
# n_expert X n_pctl X n_TQ
n_experts = cols_as_np.shape[0]
n_TQ = int(cols_as_np.shape[1] / n_pctl)
# reshaped numpy array with expert answers
TQ_array = np.reshape(cols_as_np, (n_experts, n_TQ, n_pctl))
# swap the array to have pctls for the second index
TQ_array = np.swapaxes(TQ_array, 1, 2)
# sort according to the percentile values
# (sometimes the expert give the percentiles in the wrong order)
TQ_array = np.sort(TQ_array, axis=1)
for i in np.arange(n_TQ):
for k in np.arange(n_experts):
if TQ_array[k, 0, i] == TQ_array[k, 1, i]:
TQ_array[k, 0, i] = TQ_array[k, 1, i] * 0.99
if TQ_array[k, 2, i] == TQ_array[k, 1, i]:
TQ_array[k, 2, i] = TQ_array[k, 1, i] * 1.01
if len(df_indexes_TQ) > 0:
# print('TQ_array',TQ_array)
TQ_array = TQ_array[:, :, df_indexes_TQ]
n_TQ = len(df_indexes_TQ)
# print('TQ_array',TQ_array)
if verbose:
for i in np.arange(n_TQ):
print("Target question ", label_indexes[i + n_SQ])
print(TQ_array[:, :, i])
else:
n_TQ = 0
TQ_array = np.zeros((n_experts, n_pctl, n_TQ))
if not seed:
SQ_array = np.zeros((n_experts, n_pctl, n_SQ))
csv_name = output_dir + "/" + elicitation_name + "_experts.csv"
d = {"index": range(1, n_experts + 1), "Expert": NS_SQ}
df = pd.DataFrame(data=d)
df.to_csv(csv_name, index=False)
return n_experts, n_SQ, n_TQ, SQ_array, TQ_array, NS_SQ
def read_questionnaire(input_dir, csv_file, seed, target):
"""Read .csv questionnaire file
Parameters
----------
input_dir : string
name of input folder
csv_file : string
name of csv_file
target : boolean
True to read targets
Returns
-------
df_indexes_SQ, df_indexes_TQ, SQ_scale, SQ_realization, TQ_scale, \
SQ_minVals, SQ_maxVals, TQ_minVals, TQ_maxVals, SQ_units, TQ_units, \
SQ_LongQuestion, TQ_LongQuestion, SQ_question, TQ_question, \
idx_list, global_scale, global_log, label_indexes, parents, \
global_idxMin, global_idxMax, global_sum50
"""
verbose = False
print("STEP1: Reading questionnaire")
try:
from ElicipyDict import label_flag
except ImportError:
label_flag = False
df_read = pd.read_csv(input_dir + "/" + csv_file, header=0)
# print(df_read)
quest_type = df_read["QUEST_TYPE"].to_list()
n_SQ = quest_type.count("seed")
if verbose:
print(quest_type)
try:
from ElicipyDict import seed_list
if verbose:
print("seed_list read", seed_list)
except ImportError:
seed_list = list(df_read["IDX"])[0:n_SQ]
if verbose:
print("seed_list", seed_list)
# extract the seed questions with index in
# seed_list (from column IDX)
new_indexes = []
for idx in seed_list[:]:
indices = df_read.index[(df_read["IDX"] == idx)
& (df_read.QUEST_TYPE.str.contains("seed"))]
new_indexes.append(indices[0])
df_SQ = df_read.iloc[new_indexes]
df_indexes_SQ = np.array(new_indexes).astype(int)
if verbose:
print("df_indexes_SQ", df_indexes_SQ)
if target:
try:
from ElicipyDict import target_list
if verbose:
print("target_list read", target_list)
except ImportError:
if verbose:
print("ImportError")
target_list = list(df_read["IDX"])[n_SQ:]
if verbose:
print("target_list", target_list)
# extract the target questions with index in
# target_list (from column IDX)
new_indexes = []
for idx in target_list[:]:
indices = df_read.index[
(df_read["IDX"] == idx)
& (df_read.QUEST_TYPE.str.contains("target"))]
new_indexes.append(indices[0])
df_TQ = df_read.iloc[new_indexes]
df_indexes_TQ = np.array(new_indexes).astype(int) - n_SQ
if verbose:
print("df_indexes_TQ", df_indexes_TQ)
if seed:
# df_quest = df_SQ.append(df_TQ)
df_quest = pd.concat([df_SQ, df_TQ])
else:
df_quest = df_TQ
else:
df_indexes_TQ = []
df_quest = df_SQ
if label_flag:
label_indexes = df_quest["LABEL"].astype(str).tolist()
else:
label_indexes = np.asarray(df_quest["IDX"])
label_indexes = label_indexes.astype(str).tolist()
if verbose:
print("label_indexes", label_indexes)
data_top = df_quest.head()
langs = []
# check if there are multiple languages
for head in data_top:
if "LONG Q" in head:
string = head.replace("LONG Q", "")
string2 = string.replace("_", "")
langs.append(string2)
if verbose:
print("Languages:", langs)
try:
from ElicipyDict import language
except ImportError:
language = ""
# select the columns to use according with the language
if len(langs) > 1:
if language in langs:
lang_index = langs.index(language)
# list of column indexes to use
index_list = [1, 2, 3, lang_index + 4] + list(
range(len(langs) + 4,
len(langs) + 15))
else:
raise Exception("Sorry, language is not in questionnaire")
else:
lang_index = 0
language = ""
index_list = list(range(1, 16))
# list with the short title of the target questions
SQ_question = []
# list with the long title of the target questions
SQ_LongQuestion = []
# list with min vals for target questions
SQ_minVals = []
# list with max vals for target questions
SQ_maxVals = []
# list with the units of the target questions
SQ_units = []
# scale for target question:
SQ_scale = []
SQ_realization = []
global_log = []
global_idxMin = []
global_idxMax = []
global_sum50 = []
for i in df_quest.itertuples():
(
idx,
label,
shortQ,
longQ,
unit,
scale,
minVal,
maxVal,
realization,
question,
idxMin,
idxMax,
sum50,
parent,
image,
) = [i[j] for j in index_list]
minVal = float(minVal)
maxVal = float(maxVal)
if scale == "uni":
global_log.append(0)
else:
global_log.append(1)
if question == "seed":
SQ_question.append(shortQ)
SQ_LongQuestion.append(longQ)
SQ_units.append(unit)
SQ_scale.append(scale)
SQ_realization.append(float(realization))
if minVal.is_integer():
minVal = int(minVal)
if maxVal.is_integer():
maxVal = int(maxVal)
SQ_minVals.append(minVal)
SQ_maxVals.append(maxVal)
if idxMin > 0:
df_min = df_quest.loc[(df_quest['IDX'] == idxMin)
& (df_quest['QUEST_TYPE'] == 'seed')]
global_idxMin.append(str(df_min['IDX'].iloc[0]))
else:
global_idxMin.append('')
if idxMax > 0:
df_max = df_quest.loc[(df_quest['IDX'] == idxMax)
& (df_quest['QUEST_TYPE'] == 'seed')]
global_idxMax.append(str(df_max['IDX'].iloc[0]))
else:
global_idxMax.append('')
global_sum50.append(sum50)
# print on screen the units
if verbose:
print("Seed_units = ", SQ_units)
# print on screen the units
if verbose:
print("Seed_scales = ", SQ_scale)
# list with the "title" of the target questions
TQ_question = []
# list with the long title of the target questions
TQ_LongQuestion = []
TQ_minVals = []
TQ_maxVals = []
# list with the units of the target questions
TQ_units = []
# scale for target question:
TQ_scale = []
idx_list = []
parents = []
if target:
for i in df_quest.itertuples():
(
idx,
label,
shortQ,
longQ,
unit,
scale,
minVal,
maxVal,
realization,
question,
idxMin,
idxMax,
sum50,
parent,
image,
) = [i[j] for j in index_list]
minVal = float(minVal)
maxVal = float(maxVal)
if question == "target":
TQ_question.append(shortQ)
TQ_LongQuestion.append(longQ)
TQ_units.append(unit)
TQ_scale.append(scale)
if minVal.is_integer():
minVal = int(minVal)
if maxVal.is_integer():
maxVal = int(maxVal)
TQ_minVals.append(minVal)
TQ_maxVals.append(maxVal)
idx_list.append(int(idx))
parents.append(int(parent))
if (idxMin > 0):
df_min = df_quest.loc[(df_quest['IDX'] == idxMin) &
(df_quest['QUEST_TYPE'] == 'target')]
global_idxMin.append(str(df_min['IDX'].iloc[0]))
else:
global_idxMin.append('')
if (idxMax > 0):
df_max = df_quest.loc[(df_quest['IDX'] == idxMax) &
(df_quest['QUEST_TYPE'] == 'target')]
global_idxMax.append(str(df_max['IDX'].iloc[0]))
else:
global_idxMax.append('')
global_sum50.append(sum50)
# print on screen the units
if verbose:
print("Target units = ", TQ_units)
# print on screen the units
if verbose:
print("Target scales = ", TQ_scale)
global_scale = SQ_scale + TQ_scale
else:
global_scale = SQ_scale
return (df_indexes_SQ, df_indexes_TQ, SQ_scale, SQ_realization, TQ_scale,
SQ_minVals, SQ_maxVals, TQ_minVals, TQ_maxVals, SQ_units, TQ_units,
SQ_LongQuestion, TQ_LongQuestion, SQ_question, TQ_question,
idx_list, global_scale, global_log, label_indexes, parents,
global_idxMin, global_idxMax, global_sum50, df_quest)
def answer_analysis(input_dir, csv_file, n_experts, n_SQ, n_TQ, SQ_array,
TQ_array, realization, global_scale, global_log, alpha,
overshoot, cal_power, ERF_flag, Cooke_flag, seed,
NS_experts, weights_file):
verbose = False
if Cooke_flag < 0:
# when Cooke_flag is negative, the weights are read from
# and external file (weights_file) define in input
from merge_csv import similar
weights = pd.read_csv(weights_file)
print(weights)
fname = weights["First Name"].to_list()
lname = weights["Last Name"].to_list()
W = np.zeros((n_experts, 5))
for i, (f, l) in enumerate(zip(fname, lname)):
flname = str(f) + str(l)
lfname = str(l) + str(f)
for ex, name in enumerate(NS_experts):
sim1 = similar(flname, name)
sim2 = similar(lfname, name)
sim = max(sim1, sim2)
if sim > 0.8:
W[ex, 0] = weights.C[i]
W[ex, 1] = weights.I_tot[i]
W[ex, 2] = weights.I_real[i]
W[ex, 3] = weights.w[i]
W[ex, 4] = weights.normW[i]
W[:, 4] /= np.sum(W[:, 4])
elif Cooke_flag > 0:
W, score, information, M = COOKEweights(SQ_array, TQ_array,
realization, alpha,
global_scale, overshoot,
cal_power, Cooke_flag)
if verbose:
print('score', score)
print('information', information)
else:
W = np.ones((n_experts, 5))
score = np.zeros(n_experts)
information = np.zeros(n_experts)
if ERF_flag:
W_erf, score_erf = ERFweights(realization, SQ_array)
else:
W_erf = np.ones((n_experts, 5))
# score_erf = np.zeros(n_experts)
sensitivity = False
if sensitivity:
for i in range(n_SQ):
SQ_temp = np.delete(SQ_array, i, axis=2)
realization_temp = np.delete(realization, i)
global_scale_temp = np.delete(global_scale, i)
W_temp, score_temp, information_temp, M = COOKEweights(
SQ_temp, TQ_array, realization_temp, alpha, global_scale_temp,
overshoot, cal_power, Cooke_flag)
W_reldiff = W[:, 3] / \
np.sum(W[:, 3]) - W_temp[:, 3] / np.sum(W_temp[:, 3])
W_mean = np.mean(np.abs(W_reldiff))
W_std = np.sqrt(np.sum(np.square(W_reldiff)) / n_experts)
print(i + 1, W_mean, W_std, np.sum(W_temp[:, 4] > 0))
W_erf_temp, score_erf_temp = ERFweights(realization_temp, SQ_temp)
W_reldiff = W_erf[:, 4] - W_erf_temp[:, 4]
W_mean = np.mean(np.abs(W_reldiff))
W_std = np.sqrt(np.sum(np.square(W_reldiff)) / n_experts)
print(i + 1, W_mean, W_std, np.sum(W_erf_temp > alpha))
Weq = np.ones(n_experts)
Weqok = [x / n_experts for x in Weq]
W_gt0_01 = []
Werf_gt0_01 = []
expin = []
k = 1
for x, y in zip(W[:, 4], W_erf[:, 4]):
if (x > 0) or (y > 0):
W_gt0_01.append(x)
Werf_gt0_01.append(y)
expin.append(k)
k += 1
W_gt0 = [round((x * 100.0), 5) for x in W_gt0_01]
Werf_gt0 = [round((x * 100.0), 5) for x in Werf_gt0_01]
if verbose:
if ERF_flag > 0:
print("")
print("W_erf")
print(W_erf[:, -1])
if Cooke_flag != 0:
print("")
print("W_cooke")
print(W[:, -1])
print("score", score)
print("information", information)
print("unNormalized weight", W[:, 3])
print("")
print("Weq")
print(Weqok)
return W, W_erf, Weqok, W_gt0, Werf_gt0, expin
def save_dtt_rll(input_dir, n_experts, n_SQ, n_TQ, df_quest, target,
SQ_realization, SQ_scale, SQ_array, TQ_scale, TQ_array):
# ----------------------------------------- #
# ------------ Save dtt and rls ----------- #
# ----------------------------------------- #
# Save a reference to the original standard output
original_stdout = sys.stdout
filename = input_dir + "/seed_and_target.rls"
with open(filename, "w") as f:
sys.stdout = f # Change the standard output to the file we created.
for i in np.arange(n_SQ):
# print(i+1,str(i+1),SQ_realization[i],SQ_scale[i])
print(f'{i+1:>5d} {"SQ"+str(i+1):>13} {""} ' +
f'{SQ_realization[i]:6e} {SQ_scale[i]:4}')
# Reset the standard output to its original value
sys.stdout = original_stdout
if target:
filename = input_dir + "/seed_and_target.dtt"
else:
filename = input_dir + "/seed.dtt"
with open(filename, "w") as f:
sys.stdout = f # Change the standard output to the file we created.
print("* CLASS ASCII OUTPUT FILE. NQ= 3 QU= 5 50 95")
print("")
print("")
for k in np.arange(n_experts):
for i in np.arange(n_SQ):
print(f'{k+1:5d} {"Exp"+str(k+1):>8} {i+1:4d} ' +
f'{"SQ"+str(i+1):>13} {SQ_scale[i]:4} ' +
f'{SQ_array[k, 0, i]:6e} {""} {SQ_array[k, 1, i]:6e} ' +
f'{" "}{SQ_array[k, 2, i]:6e}')
if target:
for i in np.arange(n_TQ):
print(
f'{k+1:5d} {"Exp"+str(k+1):>8} {i+1:4d} ' +
f'{"TQ"+str(i+1):>13} {TQ_scale[i]:4} ' +
f'{TQ_array[k, 0, i]:6e} {""} {TQ_array[k, 1, i]:6e} '
+ f'{" "}{TQ_array[k, 2, i]:6e}')
# Reset the standard output to its original value
sys.stdout = original_stdout
return
def create_samples(group, n_experts, n_SQ, n_TQ, n_pctl, SQ_array, TQ_array,
n_sample, W, W_erf, Weqok, W_gt0, Werf_gt0, expin,
global_log, global_minVal, global_maxVal, label_indexes,
ERF_flag, Cooke_flag, EW_flag, overshoot, globalSum,
normalizeSum):
verbose = False
DAT = np.zeros((n_experts * (n_SQ + n_TQ), n_pctl + 2))
DAT[:, 0] = np.repeat(np.arange(1, n_experts + 1), n_SQ + n_TQ)
DAT[:, 1] = np.tile(np.arange(1, n_SQ + n_TQ + 1), n_experts)
DAT[:, 2:] = np.append(SQ_array, TQ_array,
axis=2).transpose(0, 2, 1).reshape(-1, 3)
q_Cooke = np.zeros((n_SQ + n_TQ, 4))
q_erf = np.zeros((n_SQ + n_TQ, 4))
q_EW = np.zeros((n_SQ + n_TQ, 4))
samples = np.zeros((n_sample, n_SQ + n_TQ))
samples_erf = np.zeros((n_sample, n_SQ + n_TQ))
samples_EW = np.zeros((n_sample, n_SQ + n_TQ))
print(' Creating samples for questions')
for j in np.arange(n_SQ + n_TQ):
if (n_SQ + n_TQ > 1):
printProgressBar(j, n_SQ + n_TQ - 1, prefix=' ')
C_EW = createSamples(
DAT,
j,
Weqok,
n_sample,
global_log[j],
[global_minVal[j], global_maxVal[j]],
overshoot,
0,
)
samples_EW[:, j] = C_EW
if Cooke_flag != 0:
C = createSamples(
DAT,
j,
W[:, 4].flatten(),
n_sample,
global_log[j],
[global_minVal[j], global_maxVal[j]],
overshoot,
0,
)
else:
C = C_EW
samples[:, j] = C
if ERF_flag > 0:
C_erf = \
createSamples(
DAT,
j,
W_erf[:, 4].flatten(),
n_sample,
global_log[j],
[global_minVal[j], global_maxVal[j]],
overshoot,
ERF_flag,
)
else:
C_erf = C_EW
samples_erf[:, j] = C_erf
if (normalizeSum):
for triplet in globalSum:
# print(triplet[0],triplet[1],triplet[2])
sum_samples = np.sum(samples_EW[:, n_SQ + triplet[0]:n_SQ +
triplet[1] + 1],
axis=1)
sum_samples = np.expand_dims(sum_samples, axis=1)
samples_EW[:,