-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimise_model.m
69 lines (56 loc) · 1.58 KB
/
optimise_model.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
function [model,R] = optimise_model(model, params, fcn)
vars0 = [];
entry = [];
name = {};
group = {};
constraint = [];
for j=1:size(params,1)
for k=1:size(params,2)
entry(end+1) = j;
name{end+1} = params(j,k).name;
group{end+1} = params(j,k).group;
constraint(end+1,:) = params(j,k).constraint;
vars0(end+1) = model.(group{end}).(name{end});
end
end
for j=1:length(vars0)
vars0(j) = map(vars0(j),constraint(j,:));
end
opts = optimset('MaxIter',5000);
[vars] = fminsearch(@evalmodel,vars0,opts);
[R,model] = evalmodel(vars);
function [R,m] = evalmodel(vars)
for i=1:length(vars)
vars(i) = unmap(vars(i),constraint(i,:));
end
m = model;
for i=1:length(vars)
m(entry(i)).(group{i}).(name{i}) = vars(i);
end
R = fcn(m);
end
end
function x = map(p,constraint)
if all(isfinite(constraint))
x = (p - constraint(1)) / (constraint(2) - constraint(1));
x = (x - 0.5) * pi;
x = tan(x);
elseif isfinite(constraint(1))
x = p - constraint(1);
x = log(x);
else
x = p;
end
end
function p = unmap(x,constraint)
if all(isfinite(constraint))
p = atan(x);
p = (p / pi) + 0.5;
p = p * (constraint(2) - constraint(1)) + constraint(1);
elseif isfinite(constraint(1))
p = exp(x);
p = p + constraint(1);
else
p = x;
end
end