-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathlsa.py
More file actions
1845 lines (1635 loc) · 84.9 KB
/
lsa.py
File metadata and controls
1845 lines (1635 loc) · 84.9 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 numpy as np
from collections import defaultdict
from scipy.stats import linregress, iqr
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLineCollection
from matplotlib.collections import LineCollection
from matplotlib.patches import Rectangle
from matplotlib.backends.backend_pdf import PdfPages
from os import path
import warnings
import time
import io
class SensitivityAnalysis(object):
def __init__(self, population=None, X=None, y=None, save=True, save_format='png', save_txt=True, verbose=True,
jupyter=False):
"""
provide either:
1) a PopulationStorage object (_population_)
2) the independent and dependent variables as two separate arrays (_X_ and _y_)
example usage:
storage = PopulationStorage(file_path="path.hdf5")
sa = SensitivityAnalysis(population=storage)
plot, perturb = sa.run_analysis()
:param population: PopulationStorage object.
:param X: 2d np array or None (default). columns = variables, rows = examples
:param y: 2d np array or None (default). columns = variables, rows = examples
:param verbose: Bool; if true, prints out which variables were confounds in the set of points. Once can also
see the confounds in first_pass_colormaps.pdf if save is True.
:param save: Bool; if true, all neighbor search plots are saved.
:param save_format: string: 'png,' 'pdf,' or 'svg.' 'png' is the default. this specifies how the scatter plots
will be saved (if they are saved)
:param save_txt: bool; if True, will save the printed output in a text file
:param jupyter: bool. set as True if running in jupyter notebook
"""
self.feat_strings = ['f', 'feature', 'features']
self.obj_strings = ['o', 'objective', 'objectives']
self.param_strings = ['parameter', 'p', 'parameters']
self.lsa_heatmap_values = {'confound': .35, 'no_neighbors': .1}
self.rel_start, self.beta, self.repeat = None, None, None
self.confound_baseline, self.p_baseline = None, None
self.r_ceiling_val, self.uniform = None, None
self.n_neighbors, self.max_neighbors = None, None
self.population = population
self.X, self.y = X, y
self.x0_idx = None
self.input_names, self.y_names = None, None
self.save = save
self.save_txt = save_txt
self.txt_file = None
self.save_format = save_format
self.jupyter = jupyter
self.verbose = verbose
self.global_log_indep, self.global_log_dep = None, None
self.x0_str, self.input_str, self.output_str = None, None, None
self.inp_out_same = None
self.indep_norm, self.dep_norm = None, None
self.X_norm_obj, self.y_normed_obj = None, None
self.X_normed,self.y_normed = None, None
self.lsa_completed = False
self.plot_obj = None
self.perturb = None
if jupyter and save:
raise RuntimeError(
"Automatically saving the figures while running sensitivity analysis in a "
"Jupyter Notebook is not supported.")
check_save_format_correct(save_format)
check_data_format_correct(population, X, y)
def _prompt(self, x0_str, input_str, output_str, indep_norm, dep_norm, global_log_indep, global_log_dep):
if x0_str is None and self.population is not None:
self.x0_str = prompt(self.population.objective_names + ['best'],
'Specify x0',
give_hint=True)
if input_str is None and self.population is not None:
self.input_str = prompt(self.feat_strings + self.param_strings + self.obj_strings,
'What is the independent variable (features/objectives/parameters)?')
if output_str is None and self.population is not None:
self.output_str = prompt(self.feat_strings + self.obj_strings,
'What is the dependent variable (features/objectives)?')
if indep_norm is None:
self.indep_norm = prompt(['lin', 'loglin', 'none'],
"How should independent variables be normalized? Accepted "
"answers: lin/loglin/none")
if dep_norm is None:
self.dep_norm = prompt(['lin', 'loglin', 'none'],
"How should dependent variables be normalized? Accepted "
"answers: lin/loglin/none")
if self.indep_norm == 'loglin' and global_log_indep is None:
self.global_log_indep = prompt(['g', 'global', 'l', 'local'],
"For determining whether an independent variable is log "
"normalized, should its value across all generations be examined "
"or only the last third? Accepted answers: local/global")
if self.dep_norm == 'loglin' and global_log_dep is None:
self.global_log_dep = prompt(['g', 'global', 'l', 'local'],
"For determining whether a dependent variable is log "
"normalized, should its value across all generations be examined "
"or only the last third? Accepted answers: local/global")
def _configure(self, config_file_path, x0_str, input_str, output_str, indep_norm, dep_norm, beta,
rel_start, p_baseline, r_ceiling_val, confound_baseline, global_log_indep, global_log_dep, repeat,
n_neighbors, max_neighbors, uniform, no_lsa):
"""set variables and prompt user if needed"""
if config_file_path is not None and not path.isfile(config_file_path):
raise RuntimeError("Please specify a valid config file path.")
self.x0_str, self.input_str, self.output_str = x0_str, input_str, output_str
self.indep_norm, self.dep_norm, self.global_log_indep, self.global_log_dep = \
indep_norm, dep_norm, global_log_indep, global_log_indep
self.confound_baseline, self.p_baseline, self.r_ceiling_val = \
confound_baseline, p_baseline, r_ceiling_val
self.rel_start, self.beta, self.repeat, self.uniform = \
rel_start, beta, repeat, uniform
self.n_neighbors, self.max_neighbors = n_neighbors, max_neighbors
# for missing values
self._prompt(
x0_str, input_str, output_str, indep_norm, dep_norm, global_log_indep, global_log_dep)
# set variables based on user input
if self.population is None:
self.input_names = np.array(["input " + str(i) for i in range(self.X.shape[1])])
self.y_names = np.array(["output " + str(i) for i in range(self.y.shape[1])])
else:
self.input_names, self.y_names = get_variable_names(
self.population, self.input_str, self.output_str, self.obj_strings,
self.feat_strings, self.param_strings)
if self.save_txt and not no_lsa:
if not path.isdir('data') or not path.isdir('data/lsa'):
raise RuntimeError("Sensitivity analysis: data/lsa is not a directory in "
"your cwd. Plots will not be automatically saved.")
else:
self.txt_file = io.open("data/lsa/{}{}{}{}{}{}_output_txt.txt".format(*time.localtime()),
"w", encoding='utf-8')
write_settings_to_file(
input_str, output_str, x0_str, indep_norm, dep_norm, global_log_indep,
global_log_dep, beta, rel_start, confound_baseline, p_baseline, repeat,
self.txt_file)
both_f = self.input_str in self.feat_strings and self.output_str in self.feat_strings
both_o = self.input_str in self.obj_strings and self.output_str in self.obj_strings
self.inp_out_same = both_f or both_o
def _normalize_data(self, x0_idx):
if self.population is not None:
self.X, self.y = pop_to_matrix(
self.population, self.input_str, self.output_str, self.param_strings,
self.obj_strings)
if x0_idx is None:
if self.population is not None:
self.x0_idx = x0_to_index(
self.population, self.x0_str, self.X, self.input_str, self.param_strings,
self.obj_strings)
else:
self.x0_idx = np.random.randint(0, self.X.shape[1])
self.X_norm_obj = NormalizePopulation(
self.X, self.input_names, self.x0_idx, self.indep_norm, global_log=self.global_log_indep)
self.y_norm_obj = NormalizePopulation(
self.y, self.y_names, self.x0_idx, self.dep_norm, global_log=self.global_log_dep)
self.X_normed = self.X_norm_obj.data_normed
self.y_normed = self.y_norm_obj.data_normed
if self.dep_norm != 'none' or self.indep_norm != 'none':
print("Data normalized.")
def _create_objects_without_search(self, config_file_path):
"""
if no_lsa is True, user can selectively conduct sensitivity analysis
by clicking on cells in the colormap (InteractivePlot). also still create
plot and perturbation object for unfiltered plotting and targeted
perturbations of indep variables respectively
"""
# shape is (num input, num output, num points)
all_points = np.full(
(self.X_normed.shape[1], self.y_normed.shape[1], self.X_normed.shape[0]),
range(self.X_normed.shape[0]))
coef_matrix, pval_matrix = get_coef_and_plot(
all_points, self.X_normed, self.y_normed, self.input_names, self.y_names,
save=False, plot=False)
plot_obj = SensitivityPlots(
pop=self.population, sa_obj=self, input_id2name=self.input_names,
y_id2name=self.y_names, X=self.X_normed, y=self.y_normed, x0_idx=self.x0_idx,
y_norm_obj=self.y_norm_obj, lsa_heatmap_values=self.lsa_heatmap_values,
coef_matrix=coef_matrix, pval_matrix=pval_matrix)
perturb = Perturbations(
config_file_path, self.n_neighbors, self.population.param_names,
self.population.feature_names, self.population.objective_names, self.X,
self.x0_idx, None)
InteractivePlot(
plot_obj, searched=False, sa_obj=self, p_baseline=self.p_baseline,
r_ceiling_val=self.r_ceiling_val)
return plot_obj, perturb
def _neighbor_search(self, X_x0_normed):
"""
includes first pass (sets of neighbors for each independent variable based
on absolute perturbation) and 'clean-up' step (sets of neighbors for
each indep-dep variable pair based on absolute R values)
"""
neighbors_per_query = first_pass(
self.X_normed, self.input_names, self.max_neighbors, self.beta,
self.x0_idx, self.txt_file)
neighbor_matrix, confound_matrix = clean_up(
neighbors_per_query, self.X_normed, self.y_normed, X_x0_normed,
self.input_names, self.y_names, self.n_neighbors, self.r_ceiling_val,
self.p_baseline, self.confound_baseline, self.rel_start, self.repeat,
self.save, self.txt_file, self.verbose, self.uniform, not self.jupyter)
return neighbors_per_query, neighbor_matrix, confound_matrix
def _plot_neighbor_sets(self, neighbors_per_query, neighbor_matrix, confound_matrix):
# jupyter gets clogged with all the plots
if not self.jupyter:
idxs_dict = {}
for i in range(self.X.shape[1]):
idxs_dict[i] = np.arange(self.y.shape[1])
plot_neighbor_sets(
self.X_normed, self.y_normed, idxs_dict, neighbors_per_query, neighbor_matrix,
confound_matrix, self.input_names, self.y_names, self.save, self.save_format)
def _compute_values_for_final_plot(self, neighbor_matrix):
coef_matrix, pval_matrix = get_coef_and_plot(
neighbor_matrix, self.X_normed, self.y_normed, self.input_names,
self.y_names, self.save, self.save_format, not self.jupyter)
failed_matrix = create_failed_search_matrix(
neighbor_matrix, self.n_neighbors, self.lsa_heatmap_values)
return coef_matrix, pval_matrix, failed_matrix
def run_analysis(self, config_file_path=None, x0_idx=None, x0_str=None, input_str=None,
output_str=None, no_lsa=False, indep_norm=None, dep_norm=None, n_neighbors=60, max_neighbors=np.inf,
beta=2., rel_start=.5, p_baseline=.05, confound_baseline=.5, r_ceiling_val=None,
global_log_indep=None, global_log_dep=None, repeat=False, uniform=False):
"""
:param config_file_path: str or None. path to yaml file, used to check parameter bounds on the perturbation vector
(if the IV is the parameters). if config_file_path is not supplied, it is assumed that potentially generating
parameter values outside their optimization bounds is acceptable.
:param x0_idx: int or None (default). index of the center in the X array/PopulationStorage object
:param x0_str: string or None. specify either x0_idx or x0_string, but not both. if both are None, a random
center is selected. x0_string represents the center point of the neighbor search. accepted strings are 'best' or
any of the objective names
:param input_str: string representing the independent variable. accepted strings are 'parameter', 'p,' objective,'
'o,' 'feature,' 'f.'
:param output_str: string representing the independent variable. accepted strings are 'objective,'
'o,' 'feature,' 'f.'
:param no_lsa: bool; if true, sensitivity analysis is not done, but the LSA object is returned. this allows for
convenient unfiltered plotting of the optimization.
:param indep_norm: string specifying how the dependent variable is normalized. 'loglin,' 'lin', or 'none' are
accepted strings.
:param dep_norm: string specifying how the independent variable is normalized. 'loglin,' 'lin', or 'none' are
accepted strings.
:param n_neighbors: int. The minimum amount of neighbors desired to be selected during the first pass.
:param max_neighbors: int or None. The maximum amount of neighbors desired to be selected during the first pass.
If None, no maximum.
:param beta: float. represents the maximum distance a nonquery parameter can vary relative to the query parameter
during the first pass, i.e., a scalar factor.
:param rel_start: float. represents the maximum distance a nonquery confound parameter can vary relative to the query
parameter during clean-up. if repeat is True, the relative allowed distance is gradually decremented until there
are no more confounds.
:param p_baseline: float between 0 and 1. Threshold for statistical significance.
:param confound_baseline: float between 0 and 1. Threshold for the absolute R coefficient a variable needs in
order to be considered a confound.
:param r_ceiling_val: float between 0 and 1, or None. If specified, all the colormaps in first_pass_colormaps.pdf
will have a maximum of r_ceiling_val. This is to standardize the plots.
:param global_log_indep: string or None. if indep_norm is 'loglin,' user can specify if normalization should be
global or local. accepted strings are 'local' or 'global.'
:param global_log_dep: string or None. if dep_norm is 'loglin,' user can specify if normalization should be
global or local. accepted strings are 'local' or 'global.'
:param repeat: Bool; if true, repeatedly checks the set of points to see if there are still confounds.
:param uniform: bool; if True, will select a set of n_neighbor points after the clean up process that are as uniformly
spaced as possible (wrt the query parameter)
:return: a SensitivityPlot object and a perturbation object. if perturbations are needed, the user must call the
create() function from the perturbation object
"""
if self.lsa_completed:
# gini is completely redone but it's quick
plot_gini(self.X_normed, self.y_normed, self.input_names, self.y_names,
self.inp_out_same, uniform, n_neighbors)
InteractivePlot(self.plot_obj, searched=True, sa_obj=self,
p_baseline=self.p_baseline, r_ceiling_val=self.r_ceiling_val)
return self.plot_obj, self.perturb
self._configure(
config_file_path, x0_str, input_str, output_str, indep_norm, dep_norm, beta,
rel_start, p_baseline, r_ceiling_val, confound_baseline, global_log_indep,
global_log_dep, repeat, n_neighbors, max_neighbors, uniform, no_lsa)
self._normalize_data(x0_idx)
X_x0_normed = self.X_normed[self.x0_idx]
if no_lsa:
return self._create_objects_without_search(config_file_path)
plot_gini(self.X_normed, self.y_normed, self.input_names, self.y_names,
self.inp_out_same, uniform, n_neighbors)
neighbors_per_query, neighbor_matrix, confound_matrix = self._neighbor_search(
X_x0_normed)
self._plot_neighbor_sets(neighbors_per_query, neighbor_matrix, confound_matrix)
coef_matrix, pval_matrix, failed_matrix = self._compute_values_for_final_plot(
neighbor_matrix)
self.plot_obj = SensitivityPlots(
pop=self.population, sa_obj=self, neighbor_matrix=neighbor_matrix,
query_neighbors=neighbors_per_query, input_id2name=self.input_names,
y_id2name=self.y_names, X=self.X_normed, y=self.y_normed, x0_idx=self.x0_idx,
y_norm_obj=self.y_norm_obj, n_neighbors=n_neighbors,
confound_matrix=confound_matrix, lsa_heatmap_values=self.lsa_heatmap_values,
coef_matrix=coef_matrix, pval_matrix=pval_matrix,
failed_matrix=failed_matrix)
if self.txt_file is not None:
self.txt_file.close()
if self.input_str not in self.param_strings and self.population is not None:
print("The parameter perturbation object was not generated because the "
"independent variables were features or objectives, not parameters.")
else:
self.perturb = Perturbations(
config_file_path, n_neighbors, self.population.param_names,
self.population.feature_names, self.population.objective_names, self.X,
self.x0_idx, neighbor_matrix)
InteractivePlot(self.plot_obj, searched=True, sa_obj=self,
p_baseline=p_baseline, r_ceiling_val=r_ceiling_val)
self.lsa_completed = True
return self.plot_obj, self.perturb
def single_pair_analysis(self, input_idx, output_idx, first_pass_neighbors):
"""
for the situation when no_lsa is true. user can select which indep/dep
variable pair to run the analysis on
"""
if not first_pass_neighbors:
first_pass_neighbors = first_pass_single_input(
self.X_normed, self.x0_idx, input_idx, self.beta, self.max_neighbors,
self.txt_file, self.input_names)
neighbors, confounds = clean_up_single_pair(
first_pass_neighbors, input_idx, output_idx, self.X_normed, self.y_normed,
self.X_normed[self.x0_idx], self.input_names, self.y_names, self.n_neighbors,
self.p_baseline, self.confound_baseline, self.rel_start, self.repeat, None,
self.verbose, self.uniform)
coef, pval = None, None
if len(neighbors) >= self.n_neighbors:
coef = abs(linregress(self.X_normed[neighbors, input_idx],
self.y_normed[neighbors, output_idx])[2])
pval = linregress(self.X_normed[neighbors, input_idx],
self.y_normed[neighbors, output_idx])[3]
return first_pass_neighbors, neighbors, confounds, coef, pval
def save_analysis(self, save_path=None):
if save_path is None:
save_path = "data/{}{}{}{}{}{}_analysis_object.pkl".format(*time.localtime())
save(save_path, self)
print("Analysis object saved to %s." % save_path)
def load(load_path):
import dill
with open(load_path, "rb") as f:
obj = dill.load(f)
return obj
def save(save_path, obj):
import dill
with open(save_path, "wb") as f:
dill.dump(obj, f)
class Perturbations(object):
def __init__(self, config_file_path, n_neighbors, param_names, feature_names, objective_names, X, x0_idx,
neighbor_matrix):
"""
user needs to call create() function separately to generate perturbations
object can handle generating perturbations for all IVs or for IVs that were
problematic during neighbor search (ie too few neighbors).
also, if the perturbation range includes values that are outside of the
parameter range specified in the config .yaml file, then the center
of the perturbations can be moved
:param config_file_path: str to .yaml file
:param n_neighbors: int - will generate n_neighbors of IV vectors for each IV
that needs to be perturbed
:param param_names: list of str
:param feature_names: list of str
:param objective_names: list of str
:param X: 2d array. not normalized
:param x0_idx: int
:param neighbor_matrix: 3d np array
"""
self.config_file_path = config_file_path
self.num_input = len(param_names)
self.n_neighbors = n_neighbors
self.param_names = param_names
self.feature_names = feature_names
self.objective_names = objective_names
self.X_x0 = X[x0_idx]
self.x0_idx = x0_idx
self.X = X # should do something else other than lugging this around
self.X_norm_obj = None
self.missing_indep_vars = self._get_missing_query_variables(neighbor_matrix)
def _get_missing_query_variables(self, neighbor_matrix):
"""
relevant for 'as-needed' perturbations, where we need to figure out
IVs that were paired with some DV such that neighbor search for IV-DV
did not select at least n_neighbor points
:return: list of IV indices
"""
if neighbor_matrix is None: return # no lsa done
missing = []
for inp in range(neighbor_matrix.shape[0]):
for output in range(neighbor_matrix.shape[1]):
if neighbor_matrix[inp][output] is None \
or len(neighbor_matrix[inp][output]) < self.n_neighbors:
missing.append(inp)
break
return missing
@staticmethod
def _prompt_perturb_hyperparams(perturb_range, X_x0, X_x0_normed, bounds):
"""can change perturbation size and/or move x0 to the center of the bounds"""
user_input = ''
while not isinstance(user_input, float):
user_input = input("What should the perturbation range be? Currently it "
"is %.2f. " % perturb_range)
try:
user_input = float(user_input)
except ValueError:
raise ValueError("Input should be a float.")
user_input = prompt(['y', 'yes', 'n', 'no'],
"Should x0 be moved to the center of the bounds in the config file? "
"Currently the center is %s. (y/n)")
if user_input in ['y', 'yes']:
X_x0_normed = np.array([.5] * len(X_x0_normed))
for i, endpoints in enumerate(bounds):
X_x0[i] = (endpoints[1] - endpoints[0]) / 2
return perturb_range, X_x0, X_x0_normed
@staticmethod
def _create_perturb_matrix(X_x0, n_neighbors, inp, perturbations):
"""
:param X_x0: 1d array
:param n_neighbors: int, how many perturbations were made
:param inp: int, idx for independent variable to manipulate
:param perturbations: array
:return:
"""
perturb_matrix = np.tile(np.array(X_x0), (n_neighbors, 1))
perturb_matrix[:, inp] = perturbations
return perturb_matrix
def _normalize_vector(self, norm, global_log_norm):
if norm == 'none':
return self.X_x0
self.X_norm_obj = NormalizePopulation(
self.X, self.param_names, self.x0_idx, norm, global_log=global_log_norm)
return self.X_norm_obj.data_normed[self.x0_idx]
def _generate_explore_vector(self, norm, global_log_norm, perturb_str, perturb_range):
"""
figure out which X/y pairs need to be explored: not enough neighbors
generate n_neighbor points around best point. perturb just POI... 5% each direction
:return: dict, key=param number (int), value=list of arrays
"""
if self.n_neighbors % 2 == 1: self.n_neighbors += 1
perturb_dist = perturb_range / 2
bounds = None
if self.config_file_path is not None:
bounds = get_param_bounds(self.config_file_path)
full_perturb_matrix = None
out_bounds = True
X_x0_normed = self._normalize_vector(norm, global_log_norm)
X_x0 = self.X_x0 # may get overwritten if perturbation vector is out-of-bounds
while out_bounds:
out_bounds = False
for inp in range(self.num_input):
if perturb_str == 'all' \
or (perturb_str == 'as_needed' and inp in self.missing_indep_vars):
if bounds is not None:
curr_out_bounds = check_parameter_bounds(
bounds[inp], X_x0[inp], perturb_dist, self.param_names[inp])
if curr_out_bounds:
out_bounds = True
upper = perturb_dist * np.random.random_sample((int(self.n_neighbors / 2),)) \
+ X_x0_normed[inp]
lower = perturb_dist * np.random.random_sample((int(self.n_neighbors / 2),)) \
+ X_x0_normed[inp] - perturb_dist
perturbations = np.concatenate((upper, lower), axis=0)
this_perturb_matrix = self._create_perturb_matrix(
X_x0, self.n_neighbors, inp, perturbations)
full_perturb_matrix = this_perturb_matrix if full_perturb_matrix is None \
else np.vstack((full_perturb_matrix, this_perturb_matrix))
if out_bounds:
perturb_range, X_x0, X_x0_normed = self._prompt_perturb_hyperparams(
perturb_range, X_x0, X_x0_normed, bounds)
return full_perturb_matrix
def create(self, norm, perturb_str='all', global_log_norm=None, perturb_range=.1, save_path=None):
"""
creates .hdf5 file with targeted perturbations
:param norm: independent variable normalization; 'lin,' 'loglin,' or 'none'
:param global_log_norm: None, 'local,' or 'global'
:param perturb_str: 'all' or 'as_needed'
:param perturb_range: float in (0., 1.)
:return:
"""
from nested.optimize_utils import save_pregen
import datetime
if norm not in ['loglin', 'lin', 'none']:
raise RuntimeError("Accepted normalization arguments are the strings loglin, "
"lin, and none.")
if perturb_str == 'as_needed' and self.missing_indep_vars is None:
raise RuntimeError("\'as_needed\' is not an accepted argument because "
"sensitivity analysis was not run. Use \'all\' instead.")
if norm == 'loglin' and global_log_norm is None:
raise RuntimeError("For log-lin normalization, please specify whether the "
"normalization should use a local or global threshold.")
explore_matrix = self._generate_explore_vector(norm, global_log_norm,
perturb_str, perturb_range)
if save_path is None:
save_path = "data/%s_perturbations.hdf5" % (
datetime.datetime.today().strftime('%Y%m%d_%H%M%S'))
save_pregen(explore_matrix, save_path)
print("Perturbations saved to %s." % save_path)
#------------------processing populationstorage and normalizing data
def pop_to_matrix(population, input_str, output_str, param_strings, obj_strings):
"""converts collection of individuals in PopulationStorage into a matrix for data manipulation
:param population: PopulationStorage object
:return: data: 2d array. rows = each data point or individual, col = parameters, then features
"""
total_models = np.sum([len(x) for x in population.history])
if total_models == 0:
return np.array([]), np.array([])
if input_str in param_strings:
X_data = np.zeros((total_models, len(population.param_names)))
elif input_str in obj_strings:
X_data = np.zeros((total_models, len(population.objective_names)))
else:
X_data = np.zeros((total_models, len(population.feature_names)))
y_data = np.zeros((total_models, len(population.objective_names))) if output_str in obj_strings else \
np.zeros((total_models, len(population.feature_names)))
counter = 0
for generation in population.history:
for datum in generation:
y_data[counter] = datum.objectives if output_str in obj_strings else datum.features
if input_str in param_strings:
X_data[counter] = datum.x
elif input_str in obj_strings:
X_data[counter] = datum.objectives
else:
X_data[counter] = datum.features
counter += 1
return X_data, y_data
def x0_to_index(population, x0_string, X_data, input_str, param_strings, obj_strings):
"""
from x0 string (e.g. 'best'), returns the respective array/data which contains
both the parameter and output values
"""
from nested.optimize_utils import OptimizationReport
report = OptimizationReport(population)
if x0_string == 'best':
if input_str in param_strings:
x0_x_array = report.survivors[0].x
elif input_str in obj_strings:
x0_x_array = report.survivors[0].objectives
else:
x0_x_array = report.survivors[0].features
else:
if input_str in param_strings:
x0_x_array = report.specialists[x0_string].x
elif input_str in obj_strings:
x0_x_array = report.specialists[x0_string].objectives
else:
x0_x_array = report.specialists[x0_string].features
index = np.where(X_data == x0_x_array)[0][0]
return index
class NormalizePopulation(object):
def __init__(self, arr, names, x0_idx, norm, global_log=None, magnitude_threshold=2.):
"""normalizer for one category (e.g. objectives)"""
self.arr = arr
self.x0_idx = x0_idx
self.norm = norm
self.global_log = global_log
self.magnitude_threshold = magnitude_threshold
self.names = names
self.processed_data, self._crossing, self._z, self._pure_neg = [None] * 4
self.data_normed, self.scaling = None, None
self._logdiff_array, self._logmin_array = None, None
self._diff_array, self._min_array = None, None
self.process_data()
self.normalize_data()
def renorm(self):
self.process_data()
self.normalize_data()
def process_data(self):
"""
need to log normalize parts of the data, so processing columns
that are negative and/or have zeros is needed
"""
processed_data = np.copy(self.arr)
neg = list(set(np.where(self.arr < 0)[1]))
pos = list(set(np.where(self.arr > 0)[1]))
z = list(set(np.where(self.arr == 0)[1]))
crossing = [num for num in pos if num in neg]
pure_neg = [num for num in neg if num not in pos]
# transform data
processed_data[:, pure_neg] *= -1
# diff = np.max(data, axis=0) - np.min(data, axis=0)
# diff[np.where(diff == 0)[0]] = 1.
# magnitude = np.log10(diff)
# offset = 10 ** (magnitude - 2)
# processed_data[:, z] += offset[z]
self.processed_data = processed_data
self._crossing, self._z, self._pure_neg = crossing, z, pure_neg
def normalize_data(self):
# process_data DOES NOT process the columns (ie, parameters and features) that cross 0, because
# that col will just be lin normed.
warnings.simplefilter("ignore")
data_normed = np.copy(self.processed_data)
num_rows, num_cols = self.processed_data.shape
min_array, diff_array = self._get_linear_arrays()
diff_array[np.where(diff_array == 0)[0]] = 1
data_log_10 = np.log10(self.processed_data)
logmin_array, logdiff_array, logmax_array = self._get_log_arrays(data_log_10)
scaling = [] # holds a list of whether the column was log or lin normalized (string)
if self.norm == 'loglin':
scaling = np.array(['log'] * num_cols)
scaling[np.where(logdiff_array < self.magnitude_threshold)[0]] = 'lin'
scaling[self._crossing] = 'lin'
scaling[self._z] = 'lin'
lin_loc = np.where(scaling == 'lin')[0]
log_loc = np.where(scaling == 'log')[0]
print("Normalization: %s." % list(zip(self.names, scaling)))
elif self.norm == 'lin':
scaling = np.array(['lin'] * num_cols)
lin_loc = np.arange(num_cols)
log_loc = []
else:
lin_loc = []
log_loc = []
data_normed[:, lin_loc] = np.true_divide(
(self.processed_data[:, lin_loc] - min_array[lin_loc]), diff_array[lin_loc])
data_normed[:, log_loc] = np.true_divide(
(data_log_10[:, log_loc] - logmin_array[log_loc]), logdiff_array[log_loc])
data_normed = np.nan_to_num(data_normed)
data_normed[:, self._pure_neg] *= -1
self.data_normed, self.scaling = data_normed, scaling
self._logdiff_array, self._logmin_array = logdiff_array, logmin_array
self._diff_array, self._min_array = diff_array, min_array
def _get_linear_arrays(self):
min_array = np.min(self.processed_data, axis=0)
max_array = np.max(self.processed_data, axis=0)
diff_array = abs(max_array - min_array)
return min_array, diff_array
def _get_log_arrays(self, data_log_10):
logmin_array = np.min(data_log_10, axis=0)
logmin_array[np.isnan(logmin_array)] = 0
logmax_array = np.max(data_log_10, axis=0)
logmax_array[np.isnan(logmax_array)] = 0
if self.global_log:
logdiff_array = abs(logmax_array - logmin_array)
else:
n = data_log_10.shape[0]
data_log_10_sorted = self._sort_matrix_by_dist(data_log_10)
logmax_array_local = np.max(data_log_10_sorted[:max(1, n // 3)], axis=0)
logmin_array_local = np.min(data_log_10_sorted[:max(1, n // 3)], axis=0)
logdiff_array = abs(logmax_array_local - logmin_array_local)
return logmin_array, logdiff_array, logmax_array
def _sort_matrix_by_dist(self, X):
dist = abs(X[self.x0_idx] - X)
sorted_idx = np.argsort(dist.sum(axis=1))
return X[sorted_idx]
#------------------independent variable importance
def accept_outliers(coef):
IQR = iqr(coef)
q3 = np.percentile(coef, 75)
upper_baseline = q3 + 1.5 * IQR
return set(np.where(coef > upper_baseline)[0])
#------------------consider all variables unimportant at first
def first_pass(X, input_names, max_neighbors, beta, x0_idx, txt_file):
neighbor_arr = [[] for _ in range(X.shape[1])]
x0_normed = X[x0_idx]
X_dists = np.abs(X - x0_normed)
output_text(
"First pass: ",
txt_file,
True,
)
for i in range(X.shape[1]):
neighbor_arr[i] = first_pass_single_input(
X, x0_idx, i, beta, max_neighbors, txt_file, input_names, X_dists)
return neighbor_arr
def first_pass_single_input(X, x0_idx, input_idx, beta, max_neighbors, txt_file, input_names, X_dists=None):
x0_normed = X[x0_idx]
# None only if no_lsa is true and user is doing sensitivity analysis
# on demand. otherwise computed once in outer function
if X_dists is None:
X_dists = np.abs(X - x0_normed)
neighbors = []
unimp = [x for x in range(X.shape[1]) if x != input_idx]
sorted_idx = X_dists[:, input_idx].argsort()
for j in range(X.shape[0]):
curr = X_dists[sorted_idx[j]]
rad = curr[input_idx]
if np.all(np.abs(curr[unimp]) <= beta * rad):
neighbors.append(sorted_idx[j])
if len(neighbors) >= max_neighbors: break
max_dist = np.max(X_dists[neighbors][:, input_idx])
output_text(
" %s - %d neighbors found. Max query distance of %.8f." %
(input_names[input_idx], len(neighbors), max_dist),
txt_file,
True,
)
return neighbors
def clean_up(neighbor_arr, X, y, X_x0, input_names, y_names, n_neighbors, r_ceiling_val, p_baseline,
confound_baseline, rel_start, repeat, save, txt_file, verbose, uniform, plot):
num_input = X.shape[1]
neighbor_matrix = np.empty((num_input, y.shape[1]), dtype=object)
confound_matrix = np.empty((num_input, y.shape[1]), dtype=object)
pdf = PdfPages("data/lsa/{}{}{}{}{}{}_first_pass_colormaps.pdf".format(*time.localtime())) if save else None
for i in range(num_input):
neighbor_orig = neighbor_arr[i].copy()
confound_list = [[] for _ in range(y.shape[1])] # for plotting
for o in range(y.shape[1]):
final_neighbors, confounds = clean_up_single_pair(
neighbor_arr[i], i, o, X, y, X_x0, input_names, y_names, n_neighbors,
p_baseline, confound_baseline, rel_start, repeat, txt_file, verbose, uniform)
confound_matrix[i][o] = confounds
confound_list[o] = confounds
neighbor_matrix[i][o] = final_neighbors
if plot:
plot_first_pass_colormap(
neighbor_orig, X, y, input_names, y_names, input_names[i], confound_list,
p_baseline, r_ceiling_val, pdf, save)
if save: pdf.close()
return neighbor_matrix, confound_matrix
def clean_up_single_pair(first_pass_neighbors, input_idx, output_idx, X, y, X_x0, input_names, y_names, n_neighbors,
p_baseline, confound_baseline, rel_start, repeat, txt_file, verbose, uniform):
from diversipy import psa_select
nq = [x for x in range(X.shape[1]) if x != input_idx]
neighbors = first_pass_neighbors.copy()
counter = 0
current_confounds = None
rel = rel_start
while current_confounds is None \
or (rel > 0 and len(current_confounds) != 0 and len(neighbors) > n_neighbors):
current_confounds = []
rmv_list = []
for i2 in nq:
r = abs(linregress(X[neighbors][:, i2], y[neighbors][:, output_idx])[2])
pval = linregress(X[neighbors][:, i2], y[neighbors][:, output_idx])[3]
if r >= confound_baseline and pval < p_baseline:
output_text(
"Iteration %d: For the set of neighbors associated with %s vs %s, %s was "
"significantly correlated with %s." %
(counter, input_names[input_idx], y_names[output_idx], input_names[i2],
y_names[output_idx]),
txt_file,
verbose,
)
current_confounds.append(i2)
for n in neighbors:
if abs(X[n, i2] - X_x0[i2]) > rel * abs(X[n, input_idx] - X_x0[input_idx]):
if n not in rmv_list: rmv_list.append(n)
for n in rmv_list: neighbors.remove(n)
output_text(
"During iteration %d, for the pair %s vs %s, %d points were removed. %d remain." %
(counter, input_names[input_idx], y_names[output_idx], len(rmv_list), len(neighbors)),
txt_file,
verbose,
)
if not repeat: break
rel -= (rel_start / 10.)
counter += 1
if repeat and len(current_confounds) != 0:
final_neighbors = []
else:
cleaned_selection = X[neighbors][:, input_idx].reshape(-1, 1)
if uniform and len(neighbors) >= n_neighbors \
and np.min(cleaned_selection) != np.max(cleaned_selection):
renormed = (cleaned_selection - np.min(cleaned_selection)) \
/ (np.max(cleaned_selection) - np.min(cleaned_selection))
subset = psa_select(renormed, n_neighbors)
_, idx_nested, _ = np.intersect1d(renormed, subset, return_indices=True)
final_neighbors = np.array(neighbors)[idx_nested]
else:
final_neighbors = neighbors
if len(neighbors) < n_neighbors:
output_text(
"----Clean up: %s vs %s - %d neighbor(s) remaining!" %
(input_names[input_idx], y_names[output_idx], len(neighbors)),
txt_file,
True,
)
return final_neighbors, current_confounds
def plot_neighbors(X_col, y_col, neighbors, input_name, y_name, title, save, save_format, close=True):
a = np.array(X_col)[neighbors]
b = np.array(y_col)[neighbors]
plt.figure()
plt.scatter(a, b, c=neighbors, cmap='viridis')
plt.ylabel(y_name)
plt.xlabel(input_name)
# if all the points are in a hyper-local cluster, mpl's auto xlim and ylim are too large
plt.xlim(np.min(a), np.max(a))
plt.ylim(np.min(b), np.max(b))
plt.title(title)
if len(a) > 1:
r = abs(linregress(a, b)[2])
pval = linregress(a, b)[3]
fit_fn = np.poly1d(np.polyfit(a, b, 1))
plt.plot(a, fit_fn(a), color='red')
plt.title("{} - Abs R = {:.2e}, p-val = {:.2e}".format(title, r, pval))
cbar = plt.colorbar()
cbar.ax.set_ylabel("Model number", rotation=90)
if save:
fig_name = 'data/lsa/%s_%s_vs_%s.%s' % (
title, check_name_valid(input_name), check_name_valid(y_name), save_format)
plt.savefig(fig_name, format=save_format)
if close: plt.close()
def plot_neighbor_sets(X, y, idxs_dict, query_set, neighbor_matrix, confound_matrix, input_names, y_names, save,
save_format, close=True, plot_confounds=True):
for i, output_list in idxs_dict.items():
before = query_set[i]
input_name = input_names[i]
X_col = X[:, i]
for o in output_list:
after = neighbor_matrix[i][o]
y_name = y_names[o]
y_col = y[:, o]
plt.figure()
a = X_col[after]
b = y_col[after]
removed = list(set(before) - set(after))
if removed:
alp = max(1. - .001 * len(removed), .1)
plt.scatter(X_col[removed], y_col[removed], color='orange',
label="Removed points", alpha=alp)
plt.legend()
plt.scatter(a, b, color='purple', label="Selected points")
plt.ylabel(y_name)
plt.xlabel(input_name)
plt.xlim(np.min(X_col[before]), np.max(X_col[before]))
plt.ylim(np.min(y_col[before]), np.max(y_col[before]))
plt.title("{} vs {}".format(input_name, y_name))
if len(a) > 1:
r = abs(linregress(a, b)[2])
pval = linregress(a, b)[3]
fit_fn = np.poly1d(np.polyfit(a, b, 1))
plt.plot(a, fit_fn(a), color='red')
plt.title("{} vs {} - Abs R = {:.2e}, p-val = {:.2e}".format(input_name, y_name, r, pval))
if save:
fig_name = 'data/lsa/selected_points_%s_vs_%s.%s' % (
check_name_valid(input_name), check_name_valid(y_name), save_format)
plt.savefig(fig_name, format=save_format)
if close: plt.close()
if plot_confounds:
for i2 in confound_matrix[i][o]:
plot_neighbors(X[:, i2], y[:, o], before, input_names[i2], y_name,
"Clean up (query parameter = %s)" %
check_name_valid(input_names[i]), save, save_format, close=close)
def plot_first_pass_colormap(neighbors, X, y, input_names, y_names, input_name, confound_list, p_baseline=.05,
r_ceiling_val=None, pdf=None, save=True, close=True):
epsilon = .01
coef_matrix = np.zeros((X.shape[1], y.shape[1]))
pval_matrix = np.zeros((X.shape[1], y.shape[1]))
for i in range(X.shape[1]):
for o in range(y.shape[1]):
coef_matrix[i][o] = abs(linregress(X[neighbors, i], y[neighbors, o])[2])
pval_matrix[i][o] = linregress(X[neighbors, i], y[neighbors, o])[3]
fig, ax = plt.subplots(figsize=(16, 5))
plt.title("Absolute R Coefficients - First pass of %s" % input_name)
vmax = np.max(coef_matrix) if r_ceiling_val is None else r_ceiling_val
cmap = plt.cm.GnBu
cmap.set_under((0, 0, 0, 0))
coef_matrix_masked = np.where(pval_matrix > p_baseline, 0, coef_matrix)
ax.pcolor(coef_matrix_masked, cmap=cmap, vmin=epsilon, vmax=max(vmax, epsilon))
annotate(coef_matrix_masked, vmax)
set_centered_axes_labels(ax, input_names, y_names)
outline_colormap(ax, confound_list)
plt.xticks(rotation=-90)
plt.yticks(rotation=0)
plt.tight_layout()
if save: pdf.savefig(fig)
if close: plt.close()
def outline_colormap(ax, outline_list, fill=False):
"""
:param ax: pyplot axis
:param outline_list: 2d list. nested lists have the idxs of the input variables that were confounds
:return:
"""
patch_list = []
for o, inp_list in enumerate(outline_list):
for inp in inp_list:
new_patch = Rectangle((o, inp), 1, 1, fill=fill, edgecolor='blue', lw=1.5) #idx from bottom left
ax.add_patch(new_patch)
patch_list.append(new_patch)
return patch_list
def output_text(text, txt_file, verbose):
if verbose: print(text)
if txt_file is not None:
txt_file.write(text)
txt_file.write("\n")
def write_settings_to_file(input_str, output_str, x0_str, indep_norm, dep_norm, global_log_indep, global_log_dep, beta,
rel_start, confound_baseline, p_baseline, repeat, txt_file):
txt_file.write("***************************************************\n")
txt_file.write("Independent variable: %s\n" %input_str)
txt_file.write("Dependent variable: %s\n" % output_str)
txt_file.write("x0: %s\n" % x0_str)
txt_file.write("Beta: %.2f\n" % beta)
txt_file.write("Alpha: %.2f\n" % rel_start)
txt_file.write("Repeats?: %s\n" % repeat)
txt_file.write("Confound baseline: %.2f\n" % confound_baseline)
txt_file.write("P-value threshold: %.2f\n" % p_baseline)
txt_file.write("Independent variable normalization: %s\n" % indep_norm)
if indep_norm == 'loglin':
txt = 'global' if global_log_indep else 'local'
txt_file.write("Independent variable log normalization: %s\n" % txt)
txt_file.write("Dependent variable normalization: %s\n" % dep_norm)
if dep_norm == 'loglin':
txt = 'global' if global_log_dep else 'local'
txt_file.write("Dependent variable log normalization: %s\n" % txt)
txt_file.write("***************************************************\n")
def check_name_valid(name):
for invalid_ch in "\/:*?\"<>|":
name = name.replace(invalid_ch, "-'")
return name
#------------------lsa plot