-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.txt
More file actions
2833 lines (2216 loc) · 83.3 KB
/
code.txt
File metadata and controls
2833 lines (2216 loc) · 83.3 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
function M = chooseNumCentres(w, new_budget)
% Adaptive number of KDE centres
%
% Inputs:
% w : N×1 positive weights, already normalised (sum=1)
% new_budget : batch size we intend to propose
%
% Output:
% M : number of KDE centres
% Coverage: cumulative weight threshold
covT = 0.9;
% Target q/M ratio
alpha = 2;
wSorted = sort(w,'descend');
kCov = find(cumsum(wSorted) >= covT, 1,'first');
if isempty(kCov), kCov = numel(w); end % extremely flat weights
% combine both criteria
M = min( ceil( new_budget / alpha ), kCov );
end
function split = create_subspaces(ndims,manual_splits)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
if (0<ndims) && (ndims<=3)
split = {1:ndims};
elseif ndims > 3 && nargin == 1 % No manual splits
[nsub3,nsub2] = number_subsp(ndims);
split = cell(nsub3+nsub2,1);
for i=1:nsub3
split{i} = [3*i-2 3*i-1 3*i];
end
if nsub2==1
split{nsub3+nsub2} = [3*nsub3+1 3*nsub3+2];
elseif nsub2==2
split{nsub3+nsub2-1} = [3*nsub3+1 3*nsub3+2];
split{nsub3+nsub2} = [3*nsub3+3 3*nsub3+4];
end
elseif ndims > 3 && nargin > 1 % Manual splits
% We check that the manual splits do not share
% dimensions with each other
elems = [];
for i=1:length(manual_splits)
elems = cat(2,elems,manual_splits{i});
end
elems_u = unique(elems);
if length(elems) ~= length(elems_u)
error('Subspaces cannot share dimensions. Check manual dimensions')
end
dims_taken = [];
for i=1:length(manual_splits)
dims_taken = cat(2,dims_taken,manual_splits{i});
end
dims_taken = sort(dims_taken);
ndims_left = ndims - length(dims_taken);
[nsub3,nsub2] = number_subsp(ndims_left);
autom_splits = cell(nsub3+nsub2,1);
candidates = setdiff(1:ndims,dims_taken);
for i=1:nsub3
autom_splits{i} = [candidates(3*i-2) ...
candidates(3*i-1) ...
candidates(3*i)];
end
if nsub2==1
autom_splits{nsub3+nsub2} = [candidates(end-1) candidates(end)];
elseif nsub2==2
autom_splits{nsub3+nsub2-1} = [candidates(end-3) candidates(end-2)];
autom_splits{nsub3+nsub2} = [candidates(end-1) candidates(end)];
end
split = [manual_splits'; autom_splits];
else
error('The function cannot have a negative number of dimensions')
end
end
function [samples_pos_tri, weighted_means_pos] = ...
discretiseCoords(samples_tri, weighted_means, discret_spl, dim_spl)
% Snap each row of samples_tri to an integer grid defined by dim_spl
% and average weighted_means when multiple rows land on the same bin.
%
% Inputs:
% samples_tri N×D continuous coordinates
% weighted_means N×1 values attached to every row of samples_tri
% discret_spl 1×D cell; discret_spl{d}(1) = min_d, end = max_d
% dim_spl 1×D number of discrete indices per dimension
%
% Outputs:
% samples_pos_tri M×D integer indices (1...dim_spl(d))
% weighted_means_pos M×1 averaged values for each unique row
[N, D] = size(samples_tri);
assert(numel(discret_spl) == D, 'discret_spl must have D cells');
assert(numel(dim_spl) == D, 'dim_spl must have length D');
assert(size(weighted_means,1) == N, 'weighted_means must match rows');
%% 1. Map every coordinate to its integer bin index
idxMat = zeros(N, D);
for d = 1:D
lo = discret_spl{d}(1); % lower bound
hi = discret_spl{d}(end); % upper bound
M = dim_spl(d); % number of bins
step = (hi-lo) / (M-1); % uniform spacing
% Nearest index in 1...M
idx = round((samples_tri(:,d) - lo) / step) + 1;
idx = min(max(idx,1), M); % clamp
idxMat(:,d) = idx;
end
%% 2. Collapse duplicates & average values
[samples_pos_tri, ~, ic] = unique(idxMat, 'rows'); % ic: group id (N×1)
weighted_means_pos = accumarray(ic, weighted_means, [], @mean);
end
function elapsed = efficient_sampler(ex,func_name,dims,total_budget)
% continuous_complex_2D, epidemic_3D, rosenbrock_3D
% func_name = "well";
% dims = 24;
% total_budget = 50000;
st = dbstack;
f_name = st.name;
tic
% Fix the seed for reproducibility
rng(42+ex, 'twister'); % 51
%% 1. INPUT PARAMETERS
new_budget = 64; % budget for next iterations - 4
% n_runs = 12; % 200
fixed_strategy = 0; % 0 (no), 1, 2, 3
% input parameter: err_min_value | err_tensor_estimation
err_func_name = 'err_samples_prediction_stdev';
opt_function = str2func(func_name);
name = strcat(func_name,"_",int2str(dims));
%% 2. INTERNAL PARAMETERS
n_strategies = 3;
if fixed_strategy ~= 0
n_strategies = 1;
end
analysis = logical(1-0); % USE false 1-1
epsilon = 0.1; % for epsilon-greedy strategy
%% 3. INITIALIZATION
error_function = str2func(err_func_name);
% paramspace not used
[~,discret,steps,dim,n_dims,splits] = initialize_function(name);
initial_budget = min(2000*numel(splits), floor(0.1*total_budget)); % 20*|50*
% Structural information about subspaces
% n_dims_left_run, dims_before_run & dims_after_run not used
[ndims_run,dims_run,steps_run,discrets_run,~,~,~,dims_left_run] = ...
initialize_splits(splits,dim,steps,discret,n_dims);
clear steps
% We will execute each strategy at least once.
% After that we concatenate the new results
err_means = cellfun(@(x) zeros(n_strategies,n_strategies), splits, ...
'UniformOutput', false);
errs_sts = cell(n_strategies,length(splits));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Checkings
samples_pos_sts = cell(n_strategies,length(splits));
strategy1 = cell(numel(splits),1);
strategy1_vals = cell(numel(splits),1);
strategy2 = cell(numel(splits),1);
strategy2_vals = cell(numel(splits),1);
strategy3 = cell(numel(splits),1);
strategy3_vals = cell(numel(splits),1);
samples_tri_wm = cell(numel(splits),1);
samples_pos_err_wm = cell(numel(splits),1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% RUN variables are used to share information of the different subspaces
% across the different runs
samples_pos_tri_run = cell(size(splits));
samples_tri_run = cell(size(splits));
% triangs_run = cell(size(splits));
% Variable that stores the samples proposed by each strategy in each subspace
samples_tri_sts = cell(n_strategies,length(splits));
% Variable that stores the samples proposed by each strategy
samples_comp_sts = cell(n_strategies,length(splits));
% To share information
% samples_pos_err_subesp_prev = cell(size(splits));
store = cell(1, numel(splits));
for s = 1:numel(splits)
d = numel(splits{s}); % 2 or 3 for this subspace
empty = zeros(0, d+1); % 0 rows, (d coords + val) cols
% One cell per strategy, every cell starts with an empty matrix
store{s}.samples = repmat({empty}, 1, n_strategies);
% (optional) Keep meta-data
% store{s}.dims = d; % dimensionality
% store{s}.idx = splits{s}; % columns of the global point
end
% To add extra close samples
samples_comp_extra = [];
% For evaluating fit
% samples_comp_eval = [];
% For analysis and representation purposes (plot, etc.)
if analysis
samples_timeline = cell(numel(splits),1);
for i = 1:numel(splits)
samples_timeline{i} = zeros(n_strategies,1);
end
% times = zeros(1,n_runs);
% Save other variables if necessary
end
%% 4. INITIAL SAMPLES
samples_comp_orig = generate_initial_samples_NEW(splits, dim, ...
initial_budget, discret, opt_function);
% % To avoid duplicates when proposing samples
samples_pos_comp_TRACK = [];
% Output variable
samples_OUTPUT = samples_comp_orig;
% Build a fast hash of already-used points
row2key = @(p) sprintf('%.12g_', p);
taken = containers.Map('KeyType','char','ValueType','logical');
for k = 1:size(samples_OUTPUT,1)
taken(row2key(samples_OUTPUT(k,:))) = true;
end
if size(samples_OUTPUT,1) < total_budget
% Create the model with the initial samples
X = samples_comp_orig(:,1:end-1);
y = samples_comp_orig(:,end);
Mdl = fitrensemble(X,y,'NumLearningCycles',50);
models_sts = repmat({Mdl}, 1, n_strategies); % save the models
clear X y Mdl
%% 5. FIRST RUNS (EACH STRATEGY ONCE)
samples_pos_tri_copy = samples_pos_tri_run;
samples_tri_copy = samples_tri_run;
samples_pos_err_copy = cell(size(splits));
st = fixed_strategy;
for s=1:n_strategies
% % Time performance
% if analysis
% tic
% end
if fixed_strategy == 0
st = s;
end
% To share information
samples_pos_err_subesp = cell(size(splits));
for i=1:length(splits)
% Structural information about the subspace
% (does not change over time)
% steps_spl not used
[spl,ndim_spl,dim_spl,~,discret_spl,dims_left] = ...
get_split_information(splits,ndims_run,dims_run, ...
steps_run,discrets_run,dims_left_run,i);
% Information about the samples we have so far
% samples_pos_tri = samples_pos_tri_run{i};
% samples_tri = samples_tri_run{i};
% T = triangs_run{i};
% Execute Strategy
[samples_pos_tri_copy, ...
samples_OUTPUT, ...
taken, ...
samples_pos_comp_TRACK, ...
samples_tri_copy, ...
samples_tri_sts, samples_comp_sts, ...
~, ...
samples_pos_err_subesp, err, ...
samples_pos_sts, ...
strategy1, strategy1_vals, ...
strategy2, strategy2_vals, ...
strategy3, strategy3_vals, ...
samples_tri_wm, samples_pos_err_wm, ...
store] = execute_strategy(st, ...
ndim_spl, dim_spl, discret_spl, ...
new_budget, ...
samples_pos_comp_TRACK, ...
samples_pos_tri_copy, ...
i, ...
spl, ...
dims_left, dim, ...
discret, ...
opt_function, ...
samples_OUTPUT, ...
taken, ...
samples_tri_copy, ...
samples_tri_sts, samples_comp_sts, ...
s, ...
splits, ...
models_sts, ...
error_function, ...
samples_pos_err_subesp, ...
samples_pos_sts, ...
strategy1, strategy1_vals, ...
strategy2, strategy2_vals, ...
strategy3, strategy3_vals, ...
samples_tri_wm, samples_pos_err_wm, ...
store);
% Save the information for the end of the initial strategy loop
samples_pos_err_copy{i} = [samples_pos_err_copy{i}; ...
samples_pos_err_subesp{i}];
% We store the error in the strategy and subspace compartment
% in order to calculate the mean for MAB
errs_sts{s,i} = err;
% We store the error of the first rounds
err_means{i}(1:n_strategies,s) = err;
end % [SPLIT/SUBSPACE LOOP]
% % Time performance
% if analysis
% tc = toc;
% times(s) = tc;
% % fprintf('%i - %f\n', s, tc);
% end
end % [STRATEGY LOOP]
% Update the strategy model with new samples
models_sts = update_models(n_strategies,models_sts, ...
samples_comp_orig,samples_comp_extra,samples_comp_sts);
% We keep the updated samples
samples_pos_tri_run = samples_pos_tri_copy;
samples_tri_run = samples_tri_copy;
% samples_pos_err_subesp = samples_pos_err_copy; % In reality, they are no longer positions (RENAME)
clear samples_pos_tri_copy samples_tri_copy samples_pos_err_copy
% st_ex = zeros(length(splits), n_runs);
% sam_ex = zeros(length(splits), n_runs);
% time_ex = zeros(length(splits), n_runs);
% cls = zeros(1, n_runs);
% cmb = zeros(1, n_runs);
% sam_mdl = zeros(n_strategies, n_runs);
% time_mdl = zeros(n_strategies, n_runs);
%% 6. NEXT RUNS
r = n_strategies+1;
% fixed_strategy = 3;
% for r=n_strategies+1:6
while size(samples_OUTPUT,1) < total_budget
% fprintf('Run %i\n', r)
% % Time performance
% if analysis
% tic
% end
% Duplicate errors
for j=1:length(splits)
err_means{j} = [err_means{j}; err_means{j}(end,:)];
end
% To share information
% samples_pos_err_subesp_prev = samples_pos_err_subesp;
samples_pos_err_subesp = cell(size(splits));
% For evaluating fit
% samples_comp_eval = [];
for i=1:length(splits)
% Structural information about the subspace
% (does not change over time)
% steps_spl not used
[spl,ndim_spl,dim_spl,~,discret_spl,dims_left] = ...
get_split_information(splits,ndims_run,dims_run, ...
steps_run,discrets_run,dims_left_run,i);
% STRATEGY SELECTION
if fixed_strategy == 0
argmax = epsilon_greedy(epsilon,err_means{i}(r,:), ...
n_strategies);
% If the strategy is not fixed, the index in which
% to store the results will be the one indicated by the
% selected strategy (argmax)
s = argmax;
else
argmax = fixed_strategy;
% If the strategy is fixed, the index in which
% to store the results will be 1 because there is only
% one strategy
s = 1;
end
% fprintf('Split %i. Strategy %i\n', i, argmax)
% tic
% Execute Strategy
[samples_pos_tri_run, ...
samples_OUTPUT, ...
taken, ...
samples_pos_comp_TRACK, ...
samples_tri_run, ...
samples_tri_sts, samples_comp_sts, ...
~, ...
samples_pos_err_subesp, err, ...
samples_pos_sts, ...
strategy1, strategy1_vals, ...
strategy2, strategy2_vals, ...
strategy3, strategy3_vals, ...
samples_tri_wm, samples_pos_err_wm, ...
store] = execute_strategy(argmax, ...
ndim_spl, dim_spl, discret_spl, ...
new_budget, ...
samples_pos_comp_TRACK, ...
samples_pos_tri_run, ...
i, ...
spl, ...
dims_left, dim, ...
discret, ...
opt_function, ...
samples_OUTPUT, ...
taken, ...
samples_tri_run, ...
samples_tri_sts, samples_comp_sts, ...
s, ...
splits, ...
models_sts, ...
error_function, ...
samples_pos_err_subesp, ...
samples_pos_sts, ...
strategy1, strategy1_vals, ...
strategy2, strategy2_vals, ...
strategy3, strategy3_vals, ...
samples_tri_wm, samples_pos_err_wm, ...
store);
% tc_ex = toc;
% fprintf('%i samples. Execution time: %fs\n', ...
% size(samples_tri,1), tc_ex)
% st_ex(i,r) = argmax;
% sam_ex(i,r) = size(samples_tri,1);
% time_ex(i,r) = tc_ex;
% We store the error in the strategy and subspace compartment
% in order to calculate the mean for MAB
errs_sts{s,i} = cat(1,errs_sts{s,i},err);
% The error is updated with the information that is obtained.
% That is, the new error is not concatenated, but the average
% of the errors so far is concatenated
err_means{i}(r,s) = mean(errs_sts{s,i});
% Information for analysis
if analysis
% strategy 'argmax' chosen
samples_timeline{i} = [samples_timeline{i}; argmax];
end
end % [SPLIT/SUBSPACE LOOP]
% Update the strategy model with new samples
models_sts = update_models(n_strategies,models_sts, ...
samples_comp_orig,samples_comp_extra,samples_comp_sts);
r = r+1;
% % Time performance
% if analysis
% tc = toc;
% times(r) = tc;
% fprintf('%i - %f\n', r, tc);
% end
fprintf('%i samples generated so far\n', size(samples_OUTPUT,1))
% disp(' ')
end % [RUN LOOP]
end % [IF initial_samples LOOP]
elapsed = toc;
% strategies = [samples_timeline{1}, samples_timeline{1}];
% fn = sprintf("experiments/ex%d_strategies.xlsx",ex);
% writematrix(strategies, fn);
filename = sprintf("experiments/%d/ex%d_%s_%s_%d_%d.mat",ex,ex, ...
f_name,func_name,dims,total_budget);
% _150_50_101_2
% _100_10_101_5_02_max_max
dataset = samples_OUTPUT;
save(filename, "dataset")
end
function argmax = epsilon_greedy(epsilon,err_means_v,n_strategies)
% EPSILON-GREEDY
% We use epsilon to encourage exploration.
% If we do not want so much exploration try 'epsilon-decreasing',
% 'Initial Optimism epsilon-greedy' or 'VDBE'
rand_val = rand;
if rand_val < epsilon
% Exploration: choose a strategy at random
argmax = randi(n_strategies);
else
% Exploitation: choose the best known strategy
% We want to focus on the strategy that yields the maximum errors
% (put more samples there)
[~, argmax] = max(err_means_v);
end
end
function errs = err_samples_prediction_stdev(gprMdl,samples_comp)
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
ypred = predict(gprMdl,samples_comp(:,1:end-1));
% [ypred,ysd,~] = predict(gprMdl,samples_comp(:,1:end-1));
diffs = abs(samples_comp(:,end) - ypred); % ./samples_comp(:,end)
errs = [diffs, zeros(size(diffs))]; % ysd
end
function grad_v = estimate_gradient(varargin)
% [areas_vols,grad,grad_v,grad_v_norm]
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
% Replacing `estimate_grad_fun` and `estimate_grad_crit`
% nargin = 2; % 3
T = varargin{1};
samples = varargin{2};
if nargin == 3
criticality = varargin{3};
end
ndims = size(samples,2)-1;
n_triang = size(T,1); % number of triangles
% x = samples(:,1);
% y = samples(:,2);
% z = samples(:,3);
%
% TR = triangulation(T.ConnectivityList,x,y,z);
% F = featureEdges(TR,pi/6)';
% figure
% plot3(x(F),y(F),z(F),'k');
% Precompute value sources based on nargin
if nargin == 2
% Gradient of the function values
get_value = @(vertex_idx) samples(vertex_idx, ndims+1); % get from samples
elseif nargin == 3
% Gradient of the criticalities
get_value = @(vertex_idx) criticality(vertex_idx); % get from criticality
end
if ndims == 2
% samples = [x y value]
vertices = T.ConnectivityList;
% Extract coordinates of vertices (i, j, k) for all triangles
% It is possible to change samples to T.Points
i_coords = samples(vertices(:,1), 1:ndims); % [n_triang x ndims]
j_coords = samples(vertices(:,2), 1:ndims); % [n_triang x ndims]
k_coords = samples(vertices(:,3), 1:ndims); % [n_triang x ndims]
% Extract function/criticality values for all vertices
i_f = get_value(vertices(:,1)); % [n_triang x 1]
j_f = get_value(vertices(:,2)); % [n_triang x 1]
k_f = get_value(vertices(:,3)); % [n_triang x 1]
% Compute edge vectors (i.e., triangle sides)
ik = i_coords - k_coords; % [n_triang x ndims]
ji = j_coords - i_coords; % [n_triang x ndims]
% Compute triangle areas
areas = 0.5 * ...
abs((j_coords(:,1) - i_coords(:,1)) .* (k_coords(:,2) - i_coords(:,2)) - ...
(k_coords(:,1) - i_coords(:,1)) .* (j_coords(:,2) - i_coords(:,2))); % [n_triang x 1]
% Alternative way
% area_t = 0.5 * abs(i(1)*j(2) + j(1)*k(2) + k(1)*i(2) - j(1)*i(2) - k(1)*j(2) - i(1)*k(2));
% Rotation matrix for 90 degrees
rotation_matrix = [0 -1; 1 0]; % 90-degree rotation in 2D
% Rotate vectors using the rotation matrix
ikr = ik * rotation_matrix'; % Rotate ik (results in [n_triang x 2])
jir = ji * rotation_matrix'; % Rotate ji (results in [n_triang x 2])
% ang = (pi/180) * 90; % 90 degrees
% % NORM IS THE SAME AFTER ROTATION
% % Rotate vector 1
% [th,r] = cart2pol(ik(1),ik(2));
% [xr1,yr1] = pol2cart(th+ang, r);
% % Rotate vector 2
% [th,r] = cart2pol(ji(1),ji(2));
% [xr2,yr2] = pol2cart(th+ang, r);
%
% ikr = [xr1 yr1];
% jir = [xr2 yr2];
grad = (j_f - i_f) .* (ikr ./ (2 * areas)) + ...
(k_f - i_f) .* (jir ./ (2 * areas));
% disp(grad)
elseif ndims == 3
% volums = zeros(n_triang,1);
grad = zeros(n_triang,ndims);
% samples = [x y z value]
vertices = T.ConnectivityList;
% Extract coordinates of vertices (i, j, k) for all triangles
% It is possible to change samples to T.Points
i_coords = samples(vertices(:,1), 1:ndims); % [n_triang x ndims]
j_coords = samples(vertices(:,2), 1:ndims); % [n_triang x ndims]
k_coords = samples(vertices(:,3), 1:ndims); % [n_triang x ndims]
h_coords = samples(vertices(:,4), 1:ndims); % [n_triang x ndims]
% Extract function/criticality values for all vertices
i_f = get_value(vertices(:,1)); % [n_triang x 1]
j_f = get_value(vertices(:,2)); % [n_triang x 1]
k_f = get_value(vertices(:,3)); % [n_triang x 1]
h_f = get_value(vertices(:,4)); % [n_triang x 1]
% Compute edge vectors (i.e., triangle sides)
ji = j_coords - i_coords; % [n_triang x ndims]
ki = k_coords - i_coords; % [n_triang x ndims]
hi = h_coords - i_coords; % [n_triang x ndims]
ik = i_coords - k_coords;
hk = h_coords - k_coords;
ih = i_coords - h_coords;
jh = j_coords - h_coords;
ji_f = j_f - i_f;
ki_f = k_f - i_f;
hi_f = h_f - i_f;
% Number of triangles
parfor t = 1:n_triang
volum_t = (1/6) * abs(det([ji(t,:); ki(t,:); hi(t,:)]));
if volum_t ~= 0
% volums(t) = volum_t;
grad(t,:) = (ji_f(t)) * (cross(ik(t,:),hk(t,:)) / (2*volum_t)) + ...
(ki_f(t)) * (cross(ih(t,:),jh(t,:)) / (2*volum_t)) + ...
(hi_f(t)) * (cross(ki(t,:),ji(t,:)) / (2*volum_t));
% If the volume is 0, we leave the gradient in the tetrahedron
% with value 0
% because the solid angle will be 0 (or practically 0)
% anyway and we can ignore its value
% When the 4 points are on the same plane,
% the volume could be 0 (det=0)
% % Example:
% P1 = [1.8000, 0.9500, 1.1000];
% P2 = [1.6500, 0.9500, 0.9000];
% P3 = [1.8500, 0.9000, 0.7500];
% P4 = [2.0000, 0.9000, 0.9500];
%
% X = [1.8000, 1.6500, 1.8500, 2.0000];
% Y = [0.9500, 0.9500, 0.9000, 0.9000];
% Z = [1.1000, 0.9000, 0.7500, 0.9500];
%
% % Points
% scatter3(X,Y,Z,'.','LineWidth',100)
% xlim([1.5, 2]);
% ylim([0.8, 1]);
% zlim([0.6, 1.2]);
%
% % Vectors
% PA = [P1;P2];
% PB = [P1;P3];
% PC = [P1;P4];
%
% plot3(PA(:,1),PA(:,2),PA(:,3),'r','LineWidth',2)
% hold on
% plot3(PB(:,1),PB(:,2),PB(:,3),'r','LineWidth',2)
% hold on
% plot3(PC(:,1),PC(:,2),PC(:,3),'r','LineWidth',2)
% grid on
% xlim([1.5, 2]);
% ylim([0.8, 1]);
% zlim([0.6, 1.2]);
end
end % [parfor]
% disp(grad)
end
% % TO RETURN
% if ndims == 2
% areas_vols = areas;
% elseif ndims == 3
% areas_vols = volums;
% end
% PLOT
% if ndims == 2
% for p = 1:size(T.Points,1)
% figure
% triplot(T)
% hold on
% triplot(T(V{p,:},:),samples(:,1),samples(:,2),'Color','r')
% hold on
% plot(T.Points(p,1),T.Points(p,2),'k.','MarkerSize',12)
% hold off
% end
% elseif ndims == 3
% for p = 1:size(T.Points,1)
% figure
% tetramesh(T,'FaceAlpha',0.3)
% hold on
% tetramesh(T(V{p,:},:),samples(:,1),samples(:,2),samples(:,3),'Color','r')
% hold on
% plot(T.Points(p,1),T.Points(p,2),T.Points(p,3),'k.','MarkerSize',12)
% hold off
% end
% end
%% AVERAGE GRADIENT ON STAR (AGS)
% Compute star (neighbourhood)
V = vertexAttachments(T);
% V{p,:}
% Extract points once for reuse
points = T.Points;
grad_v = zeros(size(points,1),ndims);
% grad_v_norm = zeros(size(points,1),1);
% % Create a reduced version of T.ConnectivityList for each vertex
% vertex_to_triangles = cell(size(points,1), 1);
% for p = 1:size(points,1)
% vertex_to_triangles{p} = T.ConnectivityList(V{p,:},:); % Extract relevant triangles
% end
if ndims == 2
% Number of vertex
for p = 1:size(points,1)
% Get triangle indices connected to vertex `p`
triangle_ids = V{p,:};
% Triangles
triangl = T(triangle_ids,:);
% Initialize storage for angles and gradient sums
num_triangles = size(triangl,1);
angles = zeros(num_triangles,1);
sum_grad = zeros(1,ndims);
% Loop over connected triangles to compute neighbours angles
for i = 1:num_triangles
tri_id = triangle_ids(i);
point_ids = triangl(i,:);
point_ids(point_ids==p) = [];
P1 = points(p,:);
P2 = points(point_ids(1),:);
P3 = points(point_ids(2),:);
% In radians
angle = atan2(2*areas(tri_id), dot(P2-P1,P3-P1));
% Convert to degrees
% angle = angle*180/pi;
% Accumulate weighted gradient
angles(i) = angle;
sum_grad = sum_grad + angle*grad(tri_id,:);
end
g = sum_grad/sum(angles); % The sum of the angles cannot be 0
% disp(g)
grad_v(p,:) = g;
% Euclidean norm
% grad_v_norm(p) = norm(g);
end
elseif ndims == 3
% Number of vertex
for p = 1:size(points,1)
% Get triangle indices connected to vertex `p`
triangle_ids = V{p,:};
% Triangles
triangl = T(triangle_ids,:);
% Initialize storage for angles and gradient sums
num_triangles = size(triangl,1);
angles = zeros(num_triangles,1);
sum_grad = zeros(1,ndims);
% Loop over connected triangles to compute neighbours angles
for i = 1:num_triangles
tri_id = triangle_ids(i);
point_ids = triangl(i,:);
point_ids(point_ids==p) = [];
P1 = points(p,:);
P2 = points(point_ids(1),:);
P3 = points(point_ids(2),:);
P4 = points(point_ids(3),:);
% In steradians
angle = abs(Solid_Angle_Triangle(P1,P2,P3,P4)); % without sign
% angle = solidangle(P2-P1,P3-P1,P4-P1);
% When the 3 edges forming the angle are on the same plane,
% the function 'solidangle' could return complex values
% % Example:
% P1 = [1.2000, 1.7000, 1.4000];
% P2 = [1.5000, 1.8000, 1.1000];
% P3 = [1.3000, 1.6000, 1.4000];
% P4 = [1.4000, 1.9000, 1.1000];
%
% X = [1.2000, 1.5000, 1.3000, 1.4000];
% Y = [1.7000, 1.8000, 1.6000, 1.9000];
% Z = [1.4000, 1.1000, 1.4000, 1.1000];
%
% % Points
% scatter3(X,Y,Z,'.','LineWidth',100)
% xlim([1, 1.6]);
% ylim([1.4, 2]);
% zlim([1, 1.6]);
%
% % Vectors
% PA = [P1;P2];
% PB = [P1;P3];
% PC = [P1;P4];
%
% plot3(PA(:,1),PA(:,2),PA(:,3),'r','LineWidth',2)
% hold on
% plot3(PB(:,1),PB(:,2),PB(:,3),'r','LineWidth',2)
% hold on
% plot3(PC(:,1),PC(:,2),PC(:,3),'r','LineWidth',2)
% grid on
% xlim([1, 1.6]);
% ylim([1.4, 2]);
% zlim([1, 1.6]);
% Accumulate weighted gradient
angles(i) = angle;
sum_grad = sum_grad + angle*grad(tri_id,:);
end
% To check (ndims == 3):
% - The sum of the angles of a vertex point must sum to (4*pi)/8 = 1.5708
% - The sum of an angle on one side of the cube must sum to (4*pi)/2 = 6.2832
% - The sum of an interior point must sum to 4*pi = 12.5664
% if ndims == 3
% if p<=8
% fprintf('corner: %f\n',sum(angles));
% elseif sum(angles)<12
% fprintf('point [%f, %f, %f]: %f\n',points(p,:),sum(angles));
% else
% fprintf('%f\n',sum(angles));
% end
% end
% The same could be done for 2 dimension
% Note that a center point has 4π sr.
% Therefore, a corner of the cube will have π/2 sr.
sa = sum(angles);
g = sum_grad/sa; % The sum of the angles cannot be 0
% disp(g)
% Condition to de-emphasize parameter space edges.
% If we are at an edge, we reduce the gradient value by 2 %%%%%%%% CHECK
if sa < 4*pi
grad_v(p,:) = g/2;
else
grad_v(p,:) = g;
end
% Euclidean norm
% grad_v_norm(p) = norm(g);
end
end
% CHECK:
% faceNormal
% nearestNeighbor
% vertexNormal
end
function [samples_pos_tri_run, ...
samples_OUTPUT, ...
taken, ...
samples_pos_comp_TRACK, ...
samples_tri_run, ...
samples_tri_sts, samples_comp_sts, ...
samples_comp_eval, ...
samples_pos_err_subesp, err, ...
samples_pos_sts, ...
strategy1, strategy1_vals, ...
strategy2, strategy2_vals, ...