-
Notifications
You must be signed in to change notification settings - Fork 0
/
iGB5DOF.m
7049 lines (5988 loc) · 236 KB
/
iGB5DOF.m
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 varargout = iGB5DOF(P, Q, mdl, nv)
arguments
P(3, 3, :) double
Q(3, 3, :) double
mdl = []
nv.return_model(1, 1) logical = false
nv.numNearest(1, 1) {mustBeInteger} = 50
end
% GB5DOF computes the energy of an arbitrary boundary in FCC metals (BRK energy function)
%
% en = GB5DOF(P,Q) computes the energy of a boundary
% described by two rotation matrices P and Q. The character string
% variable AlCuParameter can take on one of four values: 'Al', 'Ni',
% 'Au', or 'Cu'. The output variable en is the computed boundary energy
% in units J/m^2.
%
% P and Q are two properly normalized 3x3 rotation matrices defining
% orientations of the two grains with respect to a laboratory (sample)
% frame. For any vector V expressed in the cube frame of grain P (or Q),
% P*V (or Q*V) expresses the same vector in the laboratory frame. By
% convention, the first row of P (or Q) is the row vector of the boundary
% plane normal Np = P(1,:) (or Nq = Q(1,:)) written in the cube frame
% of grain P (or Q). Thus, P*Np' = Q*Nq' = [1 0 0]'.
%
% Examples
%
% With P and Q matrices defined as follows
%
% P = [ 0.5774 0.5774 0.5774 ;
% 0.7071 -0.7071 0 ;
% 0.4082 0.4082 -0.8165 ]
%
% Q = [ 0.5774 0.5774 0.5774 ;
% [-0.7071 0.7071 0 ;
% -0.4082 -0.4082 0.8165 ]
return_model = nv.return_model;
if isempty(mdl)
[qm, nA, y] = get_olmsted_ni_data();
numNearest = nv.numNearest;
[~, ~, mdl, ~] = interp5DOF(qm, nA, y, 'nNN', numNearest, 'mygpropts', {'PredictMethod', 'exact', 'Sigma', 0.01});
end
npts = size(Q, 3);
o2 = zeros(npts, 8);
for i = 1:npts
o2(i, :) = om2oct(P(:, :, i), Q(:, :, i));
end
[qm2, nA2] = oct2five(o2);
y_pred = mdl.interpfn(qm2, nA2);
varargout{1} = y_pred;
if return_model
varargout{2} = mdl;
end
end
function [ypred, interpfn, mdl, mdlpars] = interp5DOF(qm, nA, y, qm2, nA2, method, epsijk, nv)
arguments
qm %input misorientation quaternions
nA %input BP normals
y(:, 1) %property values
qm2 = [] %query misorientations
nA2 = [] %query BP normals
method char {mustBeMember(method, {'gpr', 'sphgpr', 'pbary', 'sphbary', 'idw', 'nn', 'avg'})} = 'gpr'
epsijk(1, 1) double = 1
nv.pgnum(1, 1) double = 32 %m-3m (i.e. m\overbar{3}m) FCC symmetry default
nv.databary = [] %for use with bary methods
nv.facetIDs = [] %for use with bary methods
nv.ytrue = [] %user-specified "true" values for error calculations
nv.modelparsspec = struct()
nv.brkQ(1, 1) logical = false %whether to compute BRK values as ytrue
nv.sigma(1, 1) double = 0 %noise to add to property values
nv.mygpropts = struct.empty %for use with gpr methods 'gpr' or 'sphgpr'
nv.r double = [] %for use with 'idw' method, alternatively set to [] for automatic estimation
nv.uuid(1, 8) char = get_uuid() %unique ID associated with this interpolation run
nv.o = [] %input octonions, specify these or qm/nA pairs
nv.o2 = [] %query octonions, specify these or qm2/nA2 pairs
nv.oref = get_ocubo(1, 'random', [], 10)
nv.nforce double = 1
nv.nforceQ(1, 1) logical = false
nv.dispQ(1, 1) logical = true
nv.IncludeTies(1, 1) {mustBeLogical} = true
nv.nNN(1, 1) double = 1
nv.projQ(1, 1) logical = true
end
% INTERP5DOF Convert misorientation and boundary plane normal 5DOF input
% data to a closed, octonion, hyperspherical mesh and interpolate property
% values for arbitrary grain boundaries using spherical barycentric
% coordinates, planar barycentric coordinates, or a Gaussian process
% regression.
%--------------------------------------------------------------------------
% Inputs:
% qm - list of misorientation quaternions (data), as in qmult(qB,qinv(qA))
% for grains A and B, where qA and qB are in the sample frame (same for
% qm2)
%
% nA - list of boundary plane Cartesian unit normals (grain A frame)
%
% propList - property value for each grain boundary (GB)
%
% qm2 - list of misorientation quaternions for query GBs
%
% nA2 - list of boundary plane Cartesian unit normals for query GBs (grain
% A frame)
%
% method - interpolation scheme to use. Possible methods are:
% 'sphbary' - spherical barycentric coordinates
% 'pbary' - planar barycentric coordinates
% 'gpr' - Gaussian process regression
% 'nn' - nearest neighbor interpolation
% 'insertnamehere' - no functionality, but contains instructions for
% implementing your own interpolation scheme
%
% nv - method-specific name-value pairs
% method == 'sphbary' or 'pbary'
% 'databary' - supply barycentric coordinates to reduce redundant
% computation if repeating interp5DOF calls for same list of qm/nA
% pairs, even if property values are different. I.e. the interpolation
% is calculated via a simple table lookup and a dot product.
% facetprops must also be supplied.
%
% 'facetprops' - supply properties of each facet vertex (i.e. same
% size as databary) for barycentric data interpolation. databary must
% also be supplied
%
% 'brkQ' - logical, whether or not to calculate BRK energy values for
% the query points to use for error calculations. If false and
% ytrue is not supplied, then data.props is assigned a NaN vector
% of the same size as mesh.props
%
% 'ytrue' - user supplied properties for query points for error
% calculations. If not supplied, data.props depends on brkQ
%
% 'modelparsspec' - user supplied struct of model-specific
% parameters, only gets used if databary and facetprops also supplied
% via name-value pairs
%
% method == 'gpr'
% 'gpropts' - options structure that will be passed to fitrgp() in place
% of the defaults that are supplied later in this function.
%
% Outputs:
% propOut - interpolated property values of queried grain boundaries
%
% varargout
% method == 'gpr'
% varargout{1} - gprMdl, a Guassian Process Regression Object
% varargout{2} - ysd, standard deviations of predicted values (propOut)
% varargout{3} - yint, 95% confidence intervals of predicted values
%
% method == 'sphbary' or 'pbary'
% varargout{1} - databary, barycentric coordinates
% varargout{2} - fname, which contains get_interp() workspace
%
% Usage:
% propOut = interp5DOF(qm,nA,propList,qm2,nA2,'gpr')
% propOut = interp5DOF(qm,nA,propList,qm2,nA2,'sphbary')
% propOut = interp5DOF(qm,nA,propList,qm2,nA2,'pbary')
%
% [propOut,gprMdl] = interp5DOF(qm,nA,propList,qm2,nA2,'gpr')
% [propOut,gprMdl,ysd,yint] = interp5DOF(qm,nA,propList,qm2,nA2,'gpr')
%
% [propOut] = interp5DOF(qm,nA,propList,qm2,nA2,'gpr','gpropts',gpropts);
%
% [propOut,databary,fname] = interp5DOF(qm,nA,propList,qm2,nA2,'sphbary')
% [propOut,databary,fname] = interp5DOF(qm,nA,propList,qm2,nA2,'pbary')
%
% Simple Example Data
% npts = 100;
% qm = get_cubo(npts); nA = normr(rand(npts,3)); %random (qm,nA) pairs
% propList = rand(npts); %random property values
% qm2 = get_cubo(npts); nA2 = normr(rand(npts,3)); %random (qm,nA) pairs
% %(I suggest you look at interp5DOF_test.m instead)
%
% Dependencies:
% MATLAB 2019b or higher (mainly for the "arguments" syntax checking at
% the beginning of functions, which is used extensively throughout)
%
% Toolboxes
% -Statistics and Machine Learning Toolbox
% -Symbolic Math Toolbox (optional, for numStabBary.m)
%
% Functions
% see "FUNCTION DEPENDENCIES" section at end of this file (prior to "CODE
% GRAVEYARD" section)
%
% Notes:
% Simpler, plug & play, input/output version of run.m (different options)
%
% Dependencies updated 2020-09-03 SGB
%
% *If you have the Computer Vision toolbox, normr.m will be shadowed by
% the corresponding function in the toolbox. However, both should produce
% the same results for the purposes here.
%
% **If you have addpathdir.m available on your path, all the other
% dependencies should be added as long as the functions are in a
% sub-folder of your current working directory. Alternatively, call the
% following line of code while in the "code" directory, and then move
% to your directory of choice:
% addpathdir({'normr.m','GB5DOF_setup.m','cu2qu.m','q2rod.m','five2oct.m','correctdis.m'})
%
% In the context of this function, mesh is equivalent to predictors &
% predictor responses, and data is equivalent to the query points you want
% to interpolate or predict at.
%
% Test functions (e.g. five2oct_test.m, get_octpairs_test.m) are
% available for many of the functions listed in "FUNCTION DEPENDENCIES" at
% the end which can help with understanding and visualizing what each
% function does. These are also very useful for debugging. The test
% functions may have other dependencies than the ones listed in this file,
% such as plot5DOF.m. There is also a "test" function for this function
% (interp5DOF.m), namely interp5DOF_test.m
%
% If you want to implement a custom interpolation scheme other than the
% three available here, see the instructions beneath case 'insertnamehere'
% in the switch method statement.
%
% You can minimize this preamble text in MATLAB by clicking the "minus"
% symbol at the top-left.
%
% Author(s): Sterling Baird
%
% Date: 2020-09-03
%--------------------------------------------------------------------------
%unpack (some) name-value pairs
pgnum = nv.pgnum;
brkQ = nv.brkQ;
uuid = nv.uuid;
ytrue = nv.ytrue;
sigma = nv.sigma;
nforceQ = nv.nforceQ;
nforce = nv.nforce;
dispQ = nv.dispQ;
o2 = nv.o2;
IncludeTies = nv.IncludeTies;
nNN = nv.nNN;
projQ = nv.projQ;
%display method
if dispQ
disp(['method = ' method])
end
% add relevant folders to path (by searching subfolders for functions)
addpath(genpath('.'))
% addpathdir({'normr.m','GB5DOF_setup.m','cu2qu.m','q2rod.m','five2oct.m',...
% 'correctdis.m','interp_gpr.m'})
%% convert to octonions & symmetrize
tic
%predictor points
if isempty(qm) && isempty(nA) && ~isempty(nv.o)
predinput = 'octonion';
otmp = nv.o;
else
predinput = '5dof';
otmp = five2oct(qm, nA, epsijk);
end
%query points
if isempty(qm2) && isempty(nA2) && ~isempty(o2)
queryinput = 'octonion';
otmp2 = o2;
elseif ~isempty(qm2) && ~isempty(nA2) && isempty(o2)
queryinput = '5dof';
otmp2 = five2oct(qm2, nA2, epsijk);
elseif isempty(qm2) && isempty(nA2) && isempty(o2)
queryinput = 'octonion';
otmp2 = get_ocubo(1, 'random', [], []); %dummy variable
end
%symmetrization
% wtol = 1e-6;
[o, oref, ~, ids] = get_octpairs(otmp, 'pgnum', pgnum, 'oref', nv.oref, 'IncludeTies', IncludeTies, 'nNN', nNN);
ninputpts = size(o, 1);
%symmetrization
[o2, oref2] = get_octpairs(otmp2, 'pgnum', pgnum, 'oref', nv.oref, 'IncludeTies', false, 'nNN', 1);
npredpts = size(o2, 1);
%make sure that reference octonions are identical within tolerance
if ~ismembertol(oref, oref2, 'ByRows', true)
disp(['oref == ' num2str(oref)])
disp(['oref2 == ' num2str(oref2)])
warning('oref ~= oref2')
end
symruntime = toc;
[~, ~, nnmu, nnsigma] = get_knn(o, 'omega', 1);
if dispQ
disp(['ninputpts = ' int2str(ninputpts) ', npredpts = ' int2str(npredpts)])
end
%% projection
%important to project both sets together so they use same SVD decomposition
projtol = 1e-4;
zeroQ = false;
o = normr(o);
o2 = normr(o2);
[a, usv] = proj_down([o; o2], projtol, 'zero', zeroQ, 'force', nforceQ, 'nforcedim', nforce);
d = size(a, 2);
%projected points
if d <= 8
ppts = proj_down(o, projtol, usv, 'zero', zeroQ, 'force', nforceQ, 'nforcedim', nforce);
ppts2 = proj_down(o2, projtol, usv, 'zero', zeroQ, 'force', nforceQ, 'nforcedim', nforce);
else
error("Input doesn't have degenerate dimension or has too few (i.e. check input data), or try reducing proj_down tolerance input (tol)")
end
%% mesh and data struct setup
%mesh
mesh.pts = o;
mesh.ppts = ppts;
mesh.npts = ninputpts;
%data
data.pts = o2;
data.ppts = ppts2;
data.npts = npredpts;
%mesh property values
if brkQ
if ~isempty(y)
warning('overriding "y" values with BRK values')
end
pA = o(:, 1:4);
pB = o(:, 5:8);
mA = [0 0 1];
y = GB5DOF_setup(pA, pB, mA, 'Ni', epsijk);
% add noise to BRK values
noisetype = 'normal';
switch noisetype
case 'normal'
% y = normrnd(y,sigma);
y = y + abs(normrnd(zeros(size(y)), sigma));
case 'uniform'
y = y + sigma * 2 * (rand(size(y)) - 0.5); %uniform
end
elseif isempty(y)
y = nan(size(ppts2, 1), 1);
end
y = y(ids); %data augmentation for property values
mesh.props = y;
%data property values
if brkQ
if ~isempty(ytrue)
warning('overriding "ytrue" values with BRK values')
end
pA = o2(:, 1:4);
pB = o2(:, 5:8);
mA = [0 0 1];
ytrue = GB5DOF_setup(pA, pB, mA, 'Ni', epsijk);
% add noise to BRK values if applicable
noisetype = 'normal';
switch noisetype
case 'normal'
% ytrue = normrnd(ytrue,sigma);
ytrue = ytrue + abs(normrnd(zeros(size(ytrue)), sigma));
case 'uniform'
ytrue = ytrue + sigma * 2 * (rand(size(ytrue)) - 0.5); %uniform
end
elseif isempty(ytrue)
ytrue = nan(size(ppts2, 1), 1);
end
data.props = ytrue;
%% additional variables
% current date and time
starttime = datetime(clock);
% number of cores (i.e. parfor workers)
p = gcp;
ncores = p.NumWorkers;
%git commit version
gitcommit = get_gitcommit();
%% package into struct
%general model variables
mdlgen = var_names(method, projtol, zeroQ, usv, starttime, ncores, ninputpts, npredpts, ...
gitcommit, uuid, predinput, queryinput, projQ, oref, oref2, nnmu, nnsigma, symruntime, ...
IncludeTies, nNN);
%general parameters
mdlparsgen = var_names(method, projtol, zeroQ, starttime, ninputpts, ...
npredpts, ncores, gitcommit, uuid, predinput, queryinput, projQ, oref, oref2, nnmu, nnsigma, ...
symruntime, IncludeTies, nNN);
%% method-specific interpolation
tic
switch method
case {'sphbary', 'pbary'}
if isempty(nv.databary)
%% get triangulation
[pptstmp, usvtri] = proj_down(o, projtol, 'zero', true);
K = sphconvhulln(pptstmp);
mesh.pts = proj_up(pptstmp, usvtri);
%% compute intersecting facet IDs
nnMax = 10;
inttol = 0.01;
disp('intersect_facet')
intfacetIDs = intersect_facet(ppts, K, ppts2, inttol, 'inttype', 'planar', 'nnMax', nnMax);
%% mesh triangulation and filename
mesh.sphK = K;
%% interpolation
disp('interpolation')
%method-specific parameters
switch method
case 'sphbary'
barytol = 0.2;
barytype = 'spherical';
mesh.ppts = normr(mesh.ppts);
data.ppts = normr(data.ppts);
case 'pbary'
barytol = 0.1;
barytype = 'planar';
end
%interpolation
[ypred, databary, facetprops, facetIDs, barypars] = get_interp(mesh, data, intfacetIDs, barytype, barytol);
%model command and interpolation function
mdlcmd = @(mesh, data, intfacetIDs, barytype, barytol) get_interp(mesh, data, intfacetIDs, barytype, barytol);
interpfn = @(qm2, nA2) interp_bary(mesh, [], qm2, nA2, usv, zeroQ, barytype, barytol, projtol, nnMax, brkQ);
%unpack intersection metrics
nints = barypars.nints;
numnonints = barypars.numnonints;
int_fraction = barypars.int_fraction;
%unpack NN extrapolation RMSE and MAE values
nn_rmse = barypars.nn_errmetrics.rmse;
nn_mae = barypars.nn_errmetrics.mae;
%model-specific variables
mdlspec = var_names(databary, facetprops, barytol, barytype, inttol, ...
intfacetIDs, nnMax, facetIDs, barypars, nn_rmse, nn_mae);
%model-specific parameters
mdlparsspec = var_names(barytol, barytype, inttol, nnMax, ...
nn_rmse, nn_mae, nints, numnonints, int_fraction, barypars);
else
%unpack
databary = nv.databary;
facetIDs = nv.facetIDs;
%interpolate using supplied barycentric coordinates
[ypred, facetprops, NNextrapID, nnList] = interp_bary_fast(ppts, ppts2, meshprops, databary, facetIDs);
%model command and interp function
mdlcmd = @(databary, facetprops) dot(databary, facetprops, 2);
interpfn = @(propList) interp_bary_fast(ppts, ppts2, meshprops, databary, facetIDs);
%model-specific variables
mdlspec = var_names(databary, facetprops, NNextrapID, nnList, facetIDs);
%model-specific parameters
mdlparsspec = nv.modelparsspec;
end
case {'sphgpr', 'gpr'}
if projQ
X = ppts;
X2 = ppts2;
else
X = o;
X2 = o2;
end
%gpr options
if isempty(nv.mygpropts)
%% interp5DOF's default gpr options
thresh = Inf;
if ninputpts <= thresh
PredictMethod = 'fic';
else
PredictMethod = 'bcd';
gpropts = {'BlockSize', 10000};
end
if exist('gpropts', 'var') ~= 1
gpropts = {};
end
gpropts = [gpropts {'PredictMethod', PredictMethod}];
% gpropts = {'PredictMethod',PredictMethod};
if strcmp(method, 'sphgpr')
%squared exponential kernel function with octonion distance
kfcn = @(XN, XM, theta) (exp(theta(2))^2) * exp(- (pdist2(XN, XM, @get_alen).^2) / (2 * exp(theta(1))^2));
theta0 = [deg2rad(10), std(y) / sqrt(2)]; %initial length scale and noise
gpropts = [gpropts, {'KernelFunction', kfcn, 'KernelParameters', theta0}];
end
else
% user-supplied gpr options
gpropts = nv.mygpropts;
numopts = length(gpropts);
gproptnames = gpropts(1:2:numopts);
gproptvals = gpropts(2:2:end);
gproptstruct = cell2struct(gproptvals, gproptnames, 2);
%extract parameters (for table)
G = gproptstruct;
if isempty(fieldnames(G))
error('user-specified gpropts is empty')
end
gproptshort = struct();
if isfield(G, 'HyperparameterOptimizationOptions')
G1 = G.HyperparameterOptimizationOptions;
if isfield(G1, 'UseParallel')
gprParallelQ = G1.UseParallel;
gproptshort.gprParallelQ = gprParallelQ;
end
if isfield(G1, 'Optimizer')
hyperoptimizer = G1.Optimizer;
gproptshort.hyperoptimizer = hyperoptimizer;
end
if isfield(G1, 'MaxObjectiveEvaluations')
maxhyperobj = G1.MaxObjectiveEvaluations;
gproptshort.maxhyperobj = maxhyperobj;
end
end
if isfield(G, 'PredictMethod')
PredictMethod = G.PredictMethod;
gproptshort.PredictMethod = PredictMethod;
end
if isfield(G, 'ActiveSetMethod')
ActiveSetMethod = G.ActiveSetMethod;
gproptshort.ActiveSetMethod = ActiveSetMethod;
end
if isfield(G, 'FitMethod')
FitMethod = G.FitMethod;
gproptshort.FitMethod = FitMethod;
end
end
%Gaussian process regression
if ~isempty(gpropts)
gprMdl = fitrgp(X, y, gpropts{:});
else
gprMdl = fitrgp(X, y);
end
%compact the model
cgprMdl = compact(gprMdl);
%predictions ("interpolated" points)
switch PredictMethod
case 'fic'
[ypred, ysd, yint] = predict(gprMdl, X2);
case 'bcd'
ypred = predict(cgprMdl, X2);
otherwise
[ypred, ysd, yint] = predict(gprMdl, X2);
end
switch PredictMethod
case 'fic'
mdlcmd = @(gprMdl, X2) predict(gprMdl, X2);
interpfn = @(qm2, nA2) interp_gpr(gprMdl, qm2, nA2, oref, projtol, usv, zeroQ);
mdlspec = var_names(gprMdl, cgprMdl, gpropts, ysd, yint);
otherwise
mdlcmd = @(cgprMdl, X2) predict(cgprMdl, X2);
interpfn = @(qm2, nA2) interp_gpr(cgprMdl, qm2, nA2, oref, projtol, usv, zeroQ);
mdlspec = var_names(cgprMdl, gpropts, ysd, yint);
end
%model-specific parameters
if exist('gproptshort', 'var') == 1
if ~isempty(fieldnames(gproptshort))
if isfield(G, 'HyperparameterOptimizationOptions')
mdlparsspec = var_names(maxhyperobj, gproptshort);
else
mdlparsspec = var_names(gproptshort);
end
else
evalc([(gproptstruct{end}) ' = G.(gproptstruct{end}']);
warning(['no tracked options were contained in user-specified gpropts. Consider tracking all. Tracking added via evalc() for ' ...
gproptstruct{end - 1}])
if isstruct(gproptshort.(gproptstruct{end}))
error(['Tracking automatically added for ' gproptstruct{end - 1} ' but the added tracking option cannot be a struct'])
end
mdlparsspec = struct(gproptstruct{end - 1}, gproptshort.gproptstruct{end});
end
else
mdlparsspec = var_names(PredictMethod);
end
mdlspec.KernelInformation = cgprMdl.KernelInformation;
mdlparsspec.KernelType = cgprMdl.KernelInformation.Name;
mdlparsspec.KernelParameters = cgprMdl.KernelInformation.KernelParameters;
mdlparsspec.KernelParameterNames = cgprMdl.KernelInformation.KernelParameterNames;
mdlparsspec.Beta = cgprMdl.Beta;
mdlparsspec.Sigma = cgprMdl.Sigma;
case 'idw' % inverse distance weighting
%whether to remove degenerate dimension or not
if projQ
X = ppts;
X2 = ppts2;
else
X = o;
X2 = o2;
end
r = nv.r;
L = 2; %norm-power (i.e. L == 2 --> Euclidean norm)
%different from Tovar's FEX idw.m implementation, but should be
%similar or same output
[ypred, W, r, nints, numnonints, int_fraction] = idw(X, X2, y, r, L);
mdlcmd = @(X, X2, propList, r, L) idw(X, X2, propList, r, L);
interpfn = @(qm2, nA2) interp_idw(X, qm2, nA2, y, r, L);
%model-specific variables
mdlspec = var_names(L, W, r, nints, numnonints, int_fraction);
%model-specific parameters
mdlparsspec = var_names(L, r, nints, numnonints, int_fraction);
case 'nn' %nearest neighbors
nnList = dsearchn(ppts, ppts2);
mdlcmd = @(ppts, ppts2, propList) propList(dsearchn(ppts, ppts2));
interpfn = @(qm2, nA2) interp_nn(ppts, qm2, nA2, projtol, usv, y);
%assign NN property values
ypred = y(nnList);
%model-specific variables
mdlspec.nnList = nnList;
%model-specific parameters
mdlparsspec = struct();
case 'avg'
% "interpolation" (just constant model)
[ypred, yavg] = interp_avg(y, npredpts);
mdlcmd = @(propList, ndatapts) interp_avg(propList, ndatapts);
interpfn = @(qm2, nA2) repelem(yavg, npredpts, 1); %any new point gets assigned yavg
%model-specific variables
mdlspec.yavg = yavg;
%model-specific parameters
mdlparsspec = struct();
end
runtime = toc; %time elapsed to do the interpolation (method-specific portion)
%% append extra general variables
%parity variables
parity.ypred = ypred;
parity.ytrue = ytrue;
%model
mdlgen.ypred = ypred;
mdlgen.mdlcmd = mdlcmd;
mdlgen.interpfn = interpfn;
mdlgen.runtime = runtime;
mesh.ids = ids;
mdlgen.mesh = mesh;
mdlgen.data = data;
mdlgen.parity = parity;
%parameters
mdlparsgen.runtime = runtime;
mdlparsgen.parity = parity;
%% concatenate structs
%model variables
mdl = structhorzcat(mdlgen, mdlspec);
%model parameters
mdlpars = structhorzcat(mdlparsgen, mdlparsspec);
end
function props = interp_gpr(gprMdl, qm2, nA2, oref, projtol, usv, zeroQ)
% INTERP_GPR interpolate using Gaussian Process Regression model (gprMdl) and predict()
pts2 = get_pts(qm2, nA2, oref);
ppts2 = get_ppts(pts2, projtol, usv, zeroQ);
props = predict(gprMdl, ppts2);
end
function ppts = get_ppts(pts, projtol, usv, zeroQ)
% GET_PPTS get projected points via proj_down.m
ppts = proj_down(pts, projtol, usv, 'zero', zeroQ);
end
function pts = get_pts(qm, nA, oref)
% GET_PTS get symmetrized octonions from qm/nA pairs
pts = normr(get_octpairs(five2oct(qm, nA), 'oref', oref));
end
function [dataprops, facetprops, NNextrapID, nnList] = ...
interp_bary_fast(ppts, ppts2, meshprops, databary, facetIDs)
arguments
ppts double
ppts2 double
meshprops double
databary double
facetIDs double
end
% INTERP_BARY_FAST short-circuit barycentric interpolation (same input/prediction points, new mesh property values)
% Cannot be used with new prediction points.
%find NaN values & replace with NN values (NN extrapolation)
[NNextrapID, ~] = isnan(databary);
nnList = dsearchn(ppts2(NNextrapID), ppts);
d = size(databary, 2);
%properties of each vertex of each intersecting facet
facetprops = get_facetprops(ppts, meshprops, facetIDs);
% adjust NaN values to do NN extrapolation
% e.g. databary == [NaN NaN NaN], facetprops == [NaN NaN NaN]
% --> [1 0 0], [1.213 0 0], such that dot([1 0 0],[1.213 0 0])
% == 1.213, where 1.213 is the extrapolated NN value
databary(NNextrapID, 1) = 1;
databary(NNextrapID, 2:d) = 0;
facetprops(NNextrapID, 1) = meshprops(nnList);
facetprops(NNextrapID, 2:d) = 0;
dataprops = dot(databary, facetprops, 2);
end
%% HELPER FUNCTION(S)
function facetprops = get_facetprops(ppts, props, facetIDs)
arguments
ppts double
props double
facetIDs double
end
ndatapts = size(facetIDs, 1);
facetprops = nan([ndatapts size(ppts, 2)]);
for i = 1:ndatapts
vtxIDs = facetIDs(i, :);
facetprops(i, :) = props(vtxIDs).'; %properties of vertices of facet
end
end
function props = interp_bary(mesh, intfacetIDs, qm2, nA2, usv, zeroQ, barytype, barytol, projtol, nnMax, brkQ, NV)
arguments
mesh(1, 1) struct {mustContainFields(mesh, {'pts', 'ppts', 'props', 'sphK'})}
intfacetIDs cell
qm2(:, 4) double
nA2(:, 3) double
usv(1, 1) struct
zeroQ(1, 1) logical = false
barytype char {mustBeMember(barytype, {'spherical', 'planar'})} = 'spherical'
barytol(1, 1) double = 0.2
projtol(1, 1) double = 1e-4
nnMax(1, 1) double = 10
brkQ(1, 1) logical = false
NV.databary = []
NV.propList = []
end
% INTERP_BARY interpolate using spherical or planar barycentric coordinates
pts2 = get_pts(qm2, nA2);
ppts2 = get_ppts(pts2, projtol, usv, zeroQ);
%% when barycentric coordinates aren't specified (new predict points)
if isempty(intfacetIDs)
intfacetIDs = intersect_facet(mesh.ppts, mesh.sphK, ppts2, inttol, 'inttype', 'planar', 'nnMax', nnMax);
end
data = struct('pts', pts2, 'ppts', ppts2);
if brkQ
five = struct('q', qm2, 'nA', nA2);
data.props = GB5DOF_setup(five);
else
data.props = nan(size(pts2));
end
props = get_interp(mesh, data, intfacetIDs, barytype, barytol);
end
function yq = interp_idw(X, qm2, nA2, y, r, L)
arguments
X(:, 8) double %input points
qm2(:, 4) double %query misorientations
nA2(:, 3) double %query BP normals
y(:, 1) double %property values
r double = [] %radius
L double = 2 % default is Euclidean norm
end
% INTERP_IDW interpolate using inverse-distance weighting and misorientation/BP normal query input pairs
Xq = get_pts(qm2, nA2);
yq = idw(X, Xq, y, r, L);
end
function props = interp_nn(ppts, qm2, nA2, projtol, usv, zeroQ, propList)
% INTERP_NN nearest neighbor interpolation
if isempty(usv)
error('usv should not be empty')
end
pts = get_pts(qm2, nA2);
props = propList(dsearchn(ppts, get_ppts(pts, projtol, usv, zeroQ)));
end
function [gitcommit, comment, warnedQ] = get_gitcommit()
% GET_GITCOMMIT get git commit version (or return empty '' if error)
[status, cmdout] = system('git rev-parse HEAD');
if status == 0
gitcommit = cmdout(1:7);
comment = cmdout(9:end);
else
gitcommit = '';
comment = '';
end
[status, cmdout] = system('git status --untracked-files=no --porcelain');
if status == 0
if ~isempty(cmdout)
warning('Working directory not clean (i.e. uncommitted/unpushed) files exist. Use !git commit -am "<message>", then !git push')
warnedQ = true;
else
warnedQ = false;
end
end
end
function uuid = get_uuid()
% GET_UUID get unique ID (8 characters, mixture of numbers and letters) via java.util.UUID.randomUUID
temp = java.util.UUID.randomUUID;
uuidtmp = char(temp.toString);
uuid = uuidtmp(1:8);
end
function Sout = structhorzcat(S)
arguments (Repeating)
S(1, 1) struct
end
% STRUCTHORZCAT "horizontally" concatenate structures with different variables
% (no overlapping variables, scalar struct).
%--------------------------------------------------------------------------
% Author(s): Sterling Baird
%
% Date: 2020-09-05
%
% Inputs:
% S - struct, where each struct corresponds to a set of e.g.
% conditions/parameters/results for a unique experiment, and each struct
% can have different numbers of rows and same and/or different variables*
%
% Outputs:
% Sout - "horizontally" concatenated structure
%
% Usage:
% Sout = tblvertcat(S1,S2);
% Sout = tblvertcat(S1,S2,S3);
%
% Dependencies:
%
% Notes:
%--------------------------------------------------------------------------
% convert structures to tables
T = cellfun(@(S) struct2table(S, 'AsArray', true), S, 'UniformOutput', false);
% concatenate tables
Tcat = horzcat(T{:});
% convert back to structure
Sout = table2struct(Tcat);
end
function out = var_names(varargin)
% VAR_NAMES take variables and output a combined struct with each of the variable names
%--------------------------------------------------------------------------
% https://www.mathworks.com/matlabcentral/answers/79281#answer_89015
%--------------------------------------------------------------------------
for n = 1:nargin
out.(inputname(n)) = varargin{n};
end
end
function rad = deg2rad(deg)
rad = deg / 180 * pi;
end
function A = allcomb(varargin)
% ALLCOMB All combinations (Cartesian Product)
% B = ALLCOMB(A1,A2,A3,...,AN) returns all combinations of the elements
% in the arrays A1, A2, ..., and AN. B is P-by-N matrix where P is the product
% of the number of elements of the N inputs.
% This functionality is also known as the Cartesian Product. The
% arguments can be numerical and/or characters, or they can be cell arrays.
%
% Examples:
% allcomb([1 3 5],[-3 8],[0 1]) % numerical input:
% % -> [ 1 -3 0
% % 1 -3 1
% % 1 8 0
% % ...
% % 5 -3 1
% % 5 8 1 ] ; % a 12-by-3 array
%
% allcomb('abc','XY') % character arrays
% % -> [ aX ; aY ; bX ; bY ; cX ; cY] % a 6-by-2 character array
%
% allcomb('xy',[65 66]) % a combination -> character output
% % -> ['xA' ; 'xB' ; 'yA' ; 'yB'] % a 4-by-2 character array
%
% allcomb({'hello','Bye'},{'Joe', 10:12},{99999 []}) % all cell arrays
% % -> { 'hello' 'Joe' [99999]
% % 'hello' 'Joe' []
% % 'hello' [1x3 double] [99999]
% % 'hello' [1x3 double] []
% % 'Bye' 'Joe' [99999]
% % 'Bye' 'Joe' []
% % 'Bye' [1x3 double] [99999]
% % 'Bye' [1x3 double] [] } ; % a 8-by-3 cell array
%
% ALLCOMB(..., 'matlab') causes the first column to change fastest which
% is consistent with matlab indexing. Example:
% allcomb(1:2,3:4,5:6,'matlab')
% % -> [ 1 3 5 ; 1 4 5 ; 1 3 6 ; ... ; 2 4 6 ]
%
% If one of the N arguments is empty, ALLCOMB returns a 0-by-N empty array.
%
% See also NCHOOSEK, PERMS, NDGRID
% and NCHOOSE, COMBN, KTHCOMBN (Matlab Central FEX)
% Tested in Matlab R2015a and up
% version 4.2 (apr 2018)
% (c) Jos van der Geest