-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAO.m
4075 lines (3466 loc) · 120 KB
/
AO.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 [X,F,Cp,PP,Hist,params] = AO(funopts)
% A (Bayesian) gradient descent optimisation routine, designed primarily
% for parameter estimation in nonlinear models.
%
% Getting started with default options:
%
% op = AO('options')
% op.fun = func; % function/model f(x0)
% op.x0 = x0(:); % start values: x0
% op.y = Y(:); % data we're fitting (for computation of objective fun, e.g. e = Y - f(x)
% op.V = V(:); % variance / step for each parameter, e.g. ones(length(x0),1)/8
%
% op.objective = 'loglik';
%
% Run the routine:
% [X,F,CV,~,Hi] = AO(op);
%
% change objective to 'sse', 'loglik' or 'fe' to use the free
% energy objective function. Defaults to loglikelihood
%
% By default, the ordinary gradient descent, Gauss-Newton,
% Levenberg-Marquardt and (Bayes) MAP, and a reduced-space MAP step are
% computed on each iteration; the best is selected - meaning that this
% routine switches between these algorithms throughout the optimisation.
% A line search and local sampling is also invoked.
%
% outputs:
%-------------------------------------------------------------------------
% X = posterior parameters
% F = fit value (depending on objective function specified)
% CP = parameter covariance
% Pp = posterior probabilites
% H = history
%
% *If the optimiser isn't working well, try making V smaller!
%
% dependencies
%-------------------------------------------------------------------------
% atcm -> https://github.com/alexandershaw4/atcm
% spm -> https://github.com/spm/
%
% references
%-------------------------------------------------------------------------
% "SOLVING NONLINEAR LEAST-SQUARES PROBLEMS WITH THE GAUSS-NEWTON AND
% LEVENBERG-MARQUARDT METHODS" CROEZE, PITTMAN, AND REYNOLDS
% https://www.math.lsu.edu/system/files/MunozGroup1%20-%20Paper.pdf
%
% "Computing the objective function in DCM" Stephan, Friston & Penny
% https://www.fil.ion.ucl.ac.uk/spm/doc/papers/stephan_DCM_ObjFcn_tr05.pdf
%
% "The free energy principal: a rough guide to the brain?" Friston
% https://www.fil.ion.ucl.ac.uk/~karl/The%20free-energy%20principle%20-%20a%20rough%20guide%20to%20the%20brain.pdf
%
% "Likelihood and Bayesian Inference And Computation" Gelman & Hill
% http://www.stat.columbia.edu/~gelman/arm/chap18.pdf
%
% For the nonlinear least squares MLE / Gauss Newton:
% https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm
%
% For an explanation of momentum in gradient methods:
% https://distill.pub/2017/momentum/
%
% Approximation of derivaives by finite difference methods:
% https://www.ljll.math.upmc.fr/frey/cours/UdC/ma691/ma691_ch6.pdf
%
% For an explanation of normalised gradients in gradient descent
% https://jermwatt.github.io/machine_learning_refined/notes/3_First_order_methods/3_9_Normalized.html
%
% AS2019/2020/2021
% Print the description of steps and exit
%--------------------------------------------------------------------------
if nargin == 1 && strcmp(lower(funopts),'options');
X = DefOpts; return;
end
% Inputs & Defaults...
%--------------------------------------------------------------------------
if isstruct(funopts)
parseinputstruct(funopts);
else
fprintf('You have to supply a funopts input struct now...\nTry AO(''options'')\n');
return;
end
% Set up log if requested
persistent loc ;
if writelog
name = datestr(now); name(name==' ') = '_';
name = [char(fun) '_' name '.txt'];
loc = fopen(name,'w');
else
loc = 1;
end
% If a feature selection function was passed, append it to the user fun
if ~isempty(FS) && isa(FS,'function_handle')
params.FS = FS;
end
% check functions, inputs, options... note: many of these are set/returned
% by the subfunctions parseinputstruct and DefOpts()
%--------------------------------------------------------------------------
aopt.x0x0 = x0;
aopt.order = order; % first or second order derivatives [-1,0,1,2]
if isDynamicalSS
% fun is fun(P,M)
rfun = fun;
fun = @(P) rfun(P,M);
aopt.fun = fun;
else
aopt.fun = fun; % (objective?) function handle
end
aopt.yshape = y;
aopt.y = y(:); % truth / data to fit
aopt.pp = x0(:); % starting parameters
aopt.Q = Q; % precision matrix
aopt.history = []; % error history when y=e & arg min y = f(x)
aopt.memory = gradmemory;% incorporate previous gradients when recomputing
aopt.fixedstepderiv = fsd;% fixed or adjusted step for derivative calculation
aopt.ObjectiveMethod = objective; % 'sse' 'fe' 'mse' 'rmse' (def sse)
aopt.hyperparameters = hyperparams;
aopt.mimo = ismimo; % derivatives w.r.t multiple output fun
aopt.parallel = doparallel; % compute dpdy in parfor
aopt.doimagesc = doimagesc; % change plot to a surface
aopt.factorise_gradients = factorise_gradients;
aopt.hypertune = hypertune;
aopt.verbose = verbose;
aopt.makevideo = makevideo;
givetol = allow_worsen; % Allow bad updates within a tolerance
params.userplotfun = userplotfun;
% save each iteration
if save_constant
name = ['optim_' date];
end
% if video, open project
if aopt.makevideo
aopt = setvideo(aopt);
end
% parameter and step vectors
x0 = full(x0(:));
V = full(V(:));
pC = diag(V);
% variance (in reduced space)
%--------------------------------------------------------------------------
V = eye(length(x0));
pC = V'*(pC)*V;
ipC = spm_inv(spm_cat(spm_diag({pC})));
red = (diag(pC));
% other start points
aopt.updateh = true; % update hyperpriors
aopt.pC = red; % store for derivative & objective function access
aopt.ipC = ipC; % store ^
% initial probs
aopt.pt = zeros(length(x0),1) + (1/length(x0));
params.aopt = aopt;
%initialise Q if running but empty
if isempty(Q);% && updateQ
Qc = VtoGauss(real(y(:)));
fun = @(x) full(atcm.fun.HighResMeanFilt(diag(x),1,4));
b = atcm.fun.lsqnonneg(Qc,y);
bi = find(b);
for iq = 1:length(bi);
Q{iq} = b(bi(iq))*fun(Qc(bi(iq),:));
end
aopt.Q = Q;
end
for i = 1:length(Q)
q = diag(Q{i});
Q{i} = diag(denan(q./sum(q),1));
end
aopt.Q = Q;
% put aopt in params
params.aopt = aopt;
% initial objective value (approx at this point as missing covariance data)
aopt.updatej = true; aopt.updateh = true; params.aopt = aopt;
[e0,df0,~,~,~,~,params] = obj(x0,params);
[e0] = obj(x0,params);
n = 0;
iterate = true;
aopt = params.aopt; % get versios with precomputed gradients
% initial error plot(s)
%--------------------------------------------------------------------------
if doplot
f = setfig(); params = makeplot(x0,x0,params); aopt.oerror = params.aopt.oerror;
pl_init(x0,params); drawnow;
end
% initialise counters
%--------------------------------------------------------------------------
n_reject_consec = 0;
% parameters (in reduced space)
%--------------------------------------------------------------------------
np = size(V,2);
p = x0;
ip = (1:np)';
Ep = p;
localminflag = 0; % triggers when stuck in local minima
% print options before we start printing updates
fprintf('User fun has %d varying parameters\n',length(find(red)));
% print start point - to console or logbook (loc)
refdate(loc);pupdate(loc,n,0,e0,e0,'start: ');
all_dx = [];
all_ex = [];
Hist.e = [];
% start optimisation loop
%==========================================================================
while iterate
% counter
%----------------------------------------------------------------------
n = n + 1; tic;
% Save each step if requested
if save_constant
save(name,'x0','Hist');
end
if WeightByProbability
aopt.pp = x0(:);
end
% if optimising parameters of a state-space dynamical system, find a
% fixed point in the system at the beginning of each optimisation
% iteration - assuming DCM-like 'M' structure was passed with M.x
% containing initial variables / hidden states
%----------------------------------------------------------------------
if isDynamicalSS
k = 1e-6;
if n > 0
fprintf('Search for fixed point...\n');
% trigger the fixed-point (Newton-Raphson) search function
FPSS = atcm.fun.alexfixed(spm_unvec(x0'*M.V,M.pE),M,k);
M.x = spm_unvec(FPSS,M.x);
% update function handles with new points
fun = @(P)rfun(P,M);
aopt.fun = fun;
params.aopt.fun = fun;
e0 = obj(x0,params);
end
end
% compute gradients J, & search directions
%----------------------------------------------------------------------
aopt.updatej = true; aopt.updateh = true; params.aopt = aopt;
params.aopt.n = n;
%if verbose; pupdate(loc,n,0,e0,e0,'gradnts',toc); end
pupdate(loc,n,0,e0,e0,'f: dfdp',toc);
% first order partial derivates of F w.r.t x0 using Jaco.m
if n > 1
[e0,df0,~,~,~,~,params] = obj(x0,params);
end
[e0,~,er] = obj(x0,params);
df0 = real(df0);
pupdate(loc,n,0,e0,e0,'-finish',toc);
% Gradient clipping
if normalise_gradients
if ~ismimo
df0 = df0./norm(df0);
elseif ismimo
df0 = df0./norm(df0);
thr = 2;
for i = 1:size(params.aopt.J,1);
params.aopt.J(i,:) = params.aopt.J(i,:)./(thr*norm(params.aopt.J(i,:)));
params.aopt.J(i,:) = denan(params.aopt.J(i,:));
end
end
end
% catch instabilities in the gradient s
df0(isinf(df0)) = 0;
% Update aopt structure and place in params
aopt = params.aopt;
aopt.er = er;
aopt.updateh = false;
aopt.ipC = ( (aopt.J*aopt.iS*aopt.J') + ipC ); % Update inverse covariance estimate
%aopt.ipC = ( (aopt.J*aopt.J') + ipC ); % Update inverse covariance estimate
params.aopt = aopt;
% print end of gradient computation (just so we know it's finished)
if verbose; pupdate(loc,n,0,e0,e0,'grd-fin',toc); end
% update hyperparameter tuning plot
if hypertune; plot_hyper(params.hyper_tau,[Hist.e e0]); end
% update h_opt plot
if hyperparams; plot_h_opt(params.h_opt); drawnow; end
J = df0;
% Log start of iteration (these are returned)
Hist.e(n) = e0;
Hist.p{n} = x0;
Hist.J{n} = df0;
Hist.Jfull{n} = aopt.J;
% update error plot
errordot(Hist.e)
% Make copies of error and param set for inner while loops
x1 = x0;
e1 = e0;
% Start counters
improve = true;
nfun = 0;
% check norm of gradients (def gradtol = 1e-4)
%----------------------------------------------------------------------
if norm(J) < gradtol
fprintf('Gradient step below tolerance (%d)\n',norm(J));
[X,F,Cp,PP] = finishup(V,x0,ip,e0,doparallel,params,J,Ep,red,writelog,loc,aopt);
return;
end
Hist.red(n,:) = red;
% iterative descent on this (-gradient) trajectory
%======================================================================
while improve
% Log number of function calls on this iteration
nfun = nfun + 1;
% Compute the LM and MAP steps
%---------------------------------------------------
[~,~,~,mp] = obj(x1,params);
res = y(:) - mp(:);
res = res./norm(res);
%rsd = 1./(length(y) - length(x0)) * sum((y - mp).^2);
%res = (1 - spm_Ncdf(0,abs(res),rsd));
% residual as a gaussian set with optimisable coefficients;
% hQ = ones(length(Q),1);
% [Mu,Cov,b,bv] = atcm.fun.agaussreg(tdQ(hQ,Q)',(res));
% Qi = tdQ(hQ,Q)';
% G = Qi*diag(Mu)*Qi';
% W = pinv(J*G*J')*J*G;
% J = W;
% project residual vector on a low dim Gaussian basis set then
% transform back to original features
% GCs = iterate_gauss(res,2);
% b = GCs'\res;
% bp = b.*GCs;
% J = pinv(J*bp')'*bp;
% regulariser for Levenberg-Marquardt step
lambda = .01;
diagJtJ = sum(abs(J').^2, 1);
zerosp = zeros(length(x0),1);
Jplus = [J'; diag(sqrt(lambda*diagJtJ))];
rplus = [res; zerosp];
% (1) Levenberg-Marquardt step
step = pinv(Jplus)*rplus;
LM = x1 + step;
% (2) Maximum aposteriori step
MAP = x1 + atcm.fun.aregress(J',res,'MAP');
% (3) Gauss-Newton step
GN = x1 + red.*spm_dx(J*J',J*res,1/8);
% (4) GN/MAP in reduced space
[u,v] = lu(J);
MAPr = x1 + (u*u')\(u*v*res);
% (5) Full GP / Bayesian step
[bx,bvx,mb,vb] = atcm.fun.agaussreg(J',res);
GPs = x1 - red.*bx;
% Compare steps, pick best
ES = [obj(LM,params) obj(MAP,params) obj(GN,params) obj(MAPr,params) obj(GPs,params)];
[~,MES] = min(ES);
if MES == 2
dx = MAP;
fprintf('| --> Using Maximum A Posteriori (MAP) solution\n');
routine = 'MAP';
elseif MES == 1
dx = LM;
fprintf('| --> Using Levenberg-Marquardt solution\n');
routine = 'LM';
elseif MES == 3
dx = GN;
fprintf('| --> Using Gauss-Newton solution\n');
routine = 'GN';
elseif MES == 4
dx = MAPr;
fprintf('| --> Using Reduced-Space MAP solution\n');
routine = 'MAPr';
elseif MES == 5
dx = GPs;
fprintf('| --> Using GP / Bayes solution\n');
end
% bayesian inference & check magnitude of update; solve step length
%------------------------------------------------------------------
bi = @(dx,x,red) (1 - spm_Ncdf(0,abs(dx-x),red)).*dx;
%bi = @(dx,x,red) (1 - (0.5 + 0.5*erf(real(full(dx-x0)'/sqrt(full(2*aopt.Cp))))')).*dx;
px = bi(dx,x1,red);
ddx = dx - x1;
magobj = @(umag) obj(x1 + umag .* ddx,params);
X = fminsearch(magobj,1);
dx = x1 + X .* ddx;
de = obj(dx,params);
% Probabilities Section
%---------------------------------------------------------------
% Compute the probabilities of each (predicted) new parameter
% coming from the same distribution defined by the prior (last best)
dx = real(dx);
x1 = real(x1);
red = real(red);
pt = zeros(1,length(x1));
dp = dx - x1;
pt = 1 - spm_Ncdf(0,abs(dp),red);
pt = denan(pt);
prplot(pt);
aopt.pt = [aopt.pt pt(:)];
% If WeightByProbability is set, use p(dx) as a weight on dx
% iteratively until n% of p(dx[i]) are > threshold
%------------------------------------------------------------------
if WeightByProbability
dx = x1 + ( pt(:).*(dx-x1) );
pupdate(loc,n,1,e1,e1,'OptP(p)',toc);
optimise = true;
num_optloop = 0;
while optimise
pdx = pt*0;
num_optloop = num_optloop + 1;
dp = dx - aopt.pp;
pt = 1 - spm_Ncdf(0,abs(dp),red);
pt = denan(pt);
% integrate (update) dx
dx = x1 + ( pt(:).*(dx-x1) );
% convergence
if length(find(pdx(~~red) > 0.8))./length(pdx(~~red)) > 0.7 || num_optloop > 2000
optimise = false;
end
end
de = obj(dx,params);
end
% Save for computing gradient ascent on probabilities
Hist.pt(:,n) = pt;
%------------------------------------------------------------------
aopt.updatej = false; % switch off objective fun triggers
aopt.updateh = false;
params.aopt = aopt;
% LINE SEARCHES...
%---------------------------------------------
% runge-kutta line-search / optimisation block: fine tune dx
%------------------------------------------------------------------
% so far we have established a new set of parameters (a small step
% for each param) by following the gradient flow... but what if the
% best next spot in the error landscape is just next to where the
% gradient landed us? --> a restricted line-search around our
% landing spot could identify a better update
if rungekutta > 0 || bayesoptls > 0 || agproptls > 0 || surrls > 0
% sub-problem
QR = atcm.fun.computereducedoperator(pC);
np = size(QR,1);
sp = ones(1,np)*0;
rv = diag(QR*pC*QR');
LB = QR*dx - (QR*pt(:))./rv;
UB = QR*dx + (QR*pt(:))./rv;
B = find(UB==LB);
LB(B) = dx(B) - 1;
UB(B) = dx(B) + 1;
if rungekutta
pupdate(loc,n,nfun,de,e1,'f: line',toc);
% Use the Runge-Kutta search algorithm
SearchAgents_no = rungekutta;
Max_iteration = rungekutta;
dim = length(dx);
fun = @(sp) obj((sp*QR)' + dx,params);
try
[Frk,rdx,~]=RUN(SearchAgents_no,Max_iteration,LB',UB',length(sp)',fun,sp',red(find(red)));
rdx = rdx(:);
rdx = (rdx'*QR)' + dx;
dde = obj(rdx,params);
if dde < de
dx = rdx;
de = dde;
end
if verbose; pupdate(loc,n,nfun,de,e1,'RK fini',toc); end
end
elseif surrls
fun = @(sp) obj((sp*QR)' + dx,params);
opts1 = optimoptions('surrogateopt','PlotFcn',[]);%'surrogateoptplot');
opts1.ObjectiveLimit = -1;%1e-3;
opts1.MaxFunctionEvaluations = surrls;
%opts1.InitialPoints=sp;
[rdx,F] = surrogateopt(fun,LB,UB,opts1);
rdx = rdx(:);
rdx = (rdx'*QR)' + dx;
dde = obj(rdx,params);
if dde < de
dx = rdx;
%dx = x1 + rdx(:).*ddx;
de = dde;
end
elseif bayesoptls
pupdate(loc,n,nfun,de,e1,'Baylnsr',toc);
Px = dx;
for ip = 1:length(Px)
name = sprintf('Par%d',ip);
xvar(ip) = optimizableVariable(name,[LB(ip) UB(ip)],'Optimize',true);
thename{ip} = name;
end
t = array2table(Px','VariableNames',thename) ;
objective = @(x) obj(x,params);
reps = bayesoptls;
explore = 0.2;
warning off;
RESULTS = bayesopt(objective,xvar,'IsObjectiveDeterministic',true,...
'ExplorationRatio',explore,'MaxObjectiveEvaluations',reps,...
'AcquisitionFunctionName','expected-improvement-plus','InitialX',t,...
'PlotFcn',{});
warning on;
% Best Actually observed model
% = RESULTS.MinObjective;
dde = RESULTS.MinObjective;
rdx = RESULTS.XAtMinObjective.Variables;
if dde < de
dx = rdx(:);
%dx = x1 + rdx(:).*ddx;
de = dde;
end
if verbose; pupdate(loc,n,nfun,de,e1,'BLSfini',toc); end
elseif agproptls
pupdate(loc,n,nfun,de,e1,'Surlnsr',toc);
if n > 1
pp = [cat(2,Hist.p{:})];
else
pp = x0;
end
[ddx,ex]=agpropt(@(x) obj(x,params),dx,red,agproptls,[],pp);
if obj(ddx,params) < obj(dx,params)
dx = ddx;
de = ex;
else
fprintf('SurOpt Fail\n');
end
end
end
% Evaluation of dx and report total parameter movement
thisdist = cdist(dx',x1');
if verbose; fprintf('| --> euc dist(dp) = %d\n',thisdist); end
% Update global parameter and error store
all_dx = [all_dx dx(:)];
all_ex = [all_ex de(:)];
% Tolerance on update error as function of iteration number
% - this can be helpful in functions with lots of local minima
if givetol == 1
etol = 1./1+exp(1./(n))/(maxit*2);
elseif givetol > 1
etol = givetol;
else; etol = 0;
end
deltap = cdist(dx',x1');
deltaptol = 1e-6;
% log deltaxs
Hist.dx(:,n) = dx;
% check last best x1/e1 and update dx/de
de = obj(dx,params);
% print prediction
pupdate(loc,n,nfun,de,e1,'predict',toc);
% Evaluation of the prediction(s)
%------------------------------------------------------------------
if de < ( obj(x1,params) + abs(etol) ) ;%&& (deltap > deltaptol)
% If the objective function has improved...
if verbose; if nfun == 1; pupdate(loc,n,nfun,de,e1,'improve',toc); end; end
% update the error & the (reduced) parameter set
%--------------------------------------------------------------
df = e1 - de;
e1 = de;
x1 = dx;
aopt.modpred(:,n) = spm_vec(params.aopt.fun(spm_unvec(x1,aopt.x0x0)));
else
% If it hasn't improved, flag to stop this loop...
improve = false;
% sampling
fprintf('Invoking Gaussian Sampling\n');
[dx,de] = opt_sample_gauss(aopt.fun,x1,red,y,10,10);
if de < ( obj(x1,params) + abs(etol) )
improve = true;
x1 = dx;
e1 = de;
end
end
% upper limit on the length of this loop (force recompute dfdx)
if nfun >= inner_loop
improve = false;
end
end % end while improve... ends iter descent on this trajectory
% ignore complex parameter values - for most functions, yes
%----------------------------------------------------------------------
x1 = (x1); % (put 'real' here)
% evaluate - accept/reject - plot - adjust rate
%======================================================================
if e1 < e0 ;%&& (deltap > deltaptol)
% Compute deltas & accept new parameters and error
%------------------------------------------------------------------
df = e1 - e0;
dp = x1 - x0;
x0 = dp + x0;
e0 = e1;
% Update best-so-far estimates
e0 = e1;
x0 = x1;
% store mode prediction
aopt.modpred(:,n) = spm_vec(params.aopt.fun(spm_unvec(x0,aopt.x0x0)));
% Print & plots success
%------------------------------------------------------------------
nupdate = [length(find(x0 - aopt.pp)) length(x0)];
pupdate(loc,n,nfun,e1,e0,'accept ',toc,nupdate); % print update
if doplot; params = makeplot(x0,aopt.pp,params);aopt.oerror = params.aopt.oerror; end % update plots
n_reject_consec = 0; % monitors consec rejections
else
% *If didn't improve: invoke much more selective parameter update
%==================================================================
pupdate(loc,n,nfun,e1,e0,'f: line',toc);
e_orig = e0;
if rungekutta > 0
% reset dx:
%dx = x1;
% Make the U/L bounds proportional to the probability over the
% prior variance (derived from feature scoring on jacobian)
LB = denan( x1 - ( abs(red)*8 ) );
UB = denan( x1 + ( abs(red)*8 ) );
B = find(UB==LB);
LB(B) = x1(B) - 1;
UB(B) = x1(B) + 1;
% Use the Runge-Kutta search algorithm
SearchAgents_no = rungekutta;
Max_iteration = rungekutta;
dim = length(dx);
fun = @(x) obj(x,params);
try
[Frk,rdx,~]=RUN(SearchAgents_no,Max_iteration,LB',UB',dim,fun,x1,red);
rdx = rdx(:);
dde = obj(rdx,params);
if dde < e1
df = dde - e1;
dx = rdx(:);
de = dde;
pupdate(loc,n,nfun,e1,e0,'accept ',toc);
if doplot;
params = makeplot(x0,aopt.pp,params);
aopt.oerror = params.aopt.oerror;
end
% actually just udpate
x1 = dx;x0 = x1;
e1 = de;e0 = e1;
else
df = 0;
pupdate(loc,n,nfun,e1,e0,'reject ',toc);
red = red + (red.*1/8);
end
if verbose; pupdate(loc,n,nfun,de,e1,'RK fini',toc); end
catch
df = 0;
end
else % just complain and carry on
% If we get here, then there were not gradient steps across any
% parameters which improved the objective! So...
pupdate(loc,n,nfun,e0,e0,'reject ',toc);
% decrease learning rate by 50%
red = red + (red.*1/8);
df = 0;
% Update global store of V & keep counting rejections
aopt.pC = red;
n_reject_consec = n_reject_consec + 1;
warning off; try df; catch df = 0; end; warning on;
end
end
% Stopping criteria, rules etc.
%======================================================================
crit = [ (abs(df(1)) < min_df) crit(1:end - 1) ];
clear df;
if all(crit)
localminflag = 3;
end
if localminflag == 3
fprintf(loc,'We''re either stuck or converged...stopping.\n');
[X,F,Cp,PP] = finishup(V,x0,ip,e0,doparallel,params,J,Ep,red,writelog,loc,aopt);
return;
end
% If 3 fails, reset the reduction term (based on the specified variance)
if n_reject_consec == 2
pupdate(loc,n,nfun,e1,e0,'resetv');
red = diag(pC);
aopt.pC = red;
if n == 1 && search_method~=100 ; a = red*0;
end
end
% stop at max iterations
if n == maxit
fprintf(loc,'Reached maximum iterations: stopping.\n');
[X,F,Cp,PP] = finishup(V,x0,ip,e0,doparallel,params,J,Ep,red,writelog,loc,aopt);
return;
end
% check for convergence
if e0 <= criterion
fprintf(loc,'Convergence.\n');
[X,F,Cp,PP] = finishup(V,x0,ip,e0,doparallel,params,J,Ep,red,writelog,loc,aopt);
return;
end
% give up after 10 failed iterations
if n_reject_consec == 6
fprintf(loc,'Failed to converge...\n');
[X,F,Cp,PP] = finishup(V,x0,ip,e0,doparallel,params,J,Ep,red,writelog,loc,aopt);
return;
end
end
end
% Subfunctions: Plotting & printing updates to the console / log...
%==========================================================================
% function [X,F,Cp,PP] = userstop(x,y,varargin)
%
% if strcmp(y.Character,'c')
% disp('User stop initiated');
%
% % send it back to the caller (AO.m)
% C = {'V','x0','ip','e0','doparallel','params','J','Ep','red','writelog','loc','aopt'};
%
%
% %st = dbstack('-completenames');
% % this = find(strcmp('AO',{st.name}));
%
%
% [X,F,Cp,PP] = finishup(V,x0,ip,e0,doparallel,params,J,Ep,red,writelog,loc,aopt);
% return;
%
% end
% end
function V = tdQ(h,Q)
for i = 1:length(h)
V(i,:) = ( (h(i))) * diag(Q{i});
end
end
function iS = tQ(h,Q)
iS = 0;
for i = 1:length(h)
iS = iS + ( (( (h(i))) * Q{i}) );
end
end
function errordot(e)
subplot(5,3,14);
plot((1:length(e))-1,e,'*',(1:length(e))-1,e);drawnow;
xlabel('Iteration'); ylabel('Error');
end
function dx = fixbounds(dx,x1,red)
limits = [(x1 - x1.*sqrt(red)*3) (x1 + x1.*sqrt(red)*3)];
for i = 1:size(limits,1)
if limits(i,1) > limits(i,2)
x = limits(i,1);
limits(i,1) = limits(i,2);
limits(i,2)=x;
end
end
ids = find(~(dx > limits(:,1) & dx < limits(:,2)));
for i = 1:length(ids)
if red(ids(i)) == 0
val = x1(ids(i));
else
val = dx(ids(i));
L = limits(ids(i),:);
I = findthenearest(L,val);
val = L(I);
end
dx(ids(i))=val;
end
end
function [X,F,Cp,PP] = finishup(V,x0,ip,e0,doparallel,params,J,Ep,red,writelog,loc,aopt);
fprintf(loc,'Finishing up...\n');
% Return current best
X = x0;
F = e0;
Cp = aopt.Cp;
% Use best covariance estimate
%if doparallel
% aopt = params.aopt;
% Cp = spm_inv( (J(:)*J(:)')*aopt.ipC );
%else
% Cp = aopt.Cp;
%end
% Peform Bayesian Inference
PP = BayesInf(x0,Ep,diag(red));
if writelog;fclose(loc);end
if aopt.makevideo; close(aopt.vidObj); end
end
function refdate(loc)
fprintf(loc,'\n');
fprintf(loc,'| ITERATION | FUN EVAL | CURRENT F | BEST F SO FAR | ACTION | TIME\n');
fprintf(loc,'|---------------|----------|-------------------|--------------------|---------|-------------\n');
end
function d = update_d(H,f,mu)
% added from github repo:
% /ezjong/matlab-levenberg-marquardt/blob/master/fminlev.m
% for trust region algorithms
ndim = size(f,1);
% closed-form solution to quadratic form
A = 0.5*(H + H') + mu^2*eye(ndim);
b = - f;
% solve in scaled space (plus regularization)
d = A \ b;
end
function s = prinfo(loc,it,nfun,nc,ncs)
s = sprintf(loc,'| Main It: %04i | nf: %04i | Selecting components: %01i of %01i\n',it,nfun,nc,ncs);
fprintf(loc,'| Main It: %04i | nf: %04i | Selecting components: %01i of %01i\n',it,nfun,nc,ncs);
end