a b/Application/Examples/BikeSpring/Model/anyoptgrad.m
1
% Unconstrained optimization in the AnyBody Modeling System
2
% using a golden section method and steeoest descen search
3
% directions. Notice that this may not work if the problem
4
% is non-smooth.
5
% The side constraints, xmin and xmax, are handled by means of
6
% an exterior penalty function.
7
8
nOptimParam = 6;  % Number of design variables
9
10
% Design variables as they appear in the AnyScript model
11
    % AnyVar L0 = 0.24;             //Spring slack length
12
    % AnyVar F1 = 100;              //Spring force at 50% strain
13
    % AnyVar SpringRad = 0.15;      //Radius of spring attachment on the crank
14
    % AnyVar SpringAngle = 45;      //Angle of spring attachment points on the crank
15
    % AnyVar SpringX = -0.10;       //X coordinate of spring attachment on frame
16
    % AnyVar SpringY = 0.30
17
    
18
% Initialize 
19
%        L0        F1    SpringRad  SpringAngle   SpringY
20
xmin = [0.1       0.0      0.01        0.0         0.1];   % Lower bound
21
x =    [0.20    150.0      0.11       56.0         0.3];   % Initial guess
22
xmax = [0.4    1000.0      0.40      180.0         0.5];   % Upper bound
23
24
% Compute initial objective function value
25
F = ObjectivePenal(xmin,x,xmax);
26
27
% do optimization
28
maxiter = 10;
29
evals = 0;
30
delta = 0.1;  % Relative perturbation
31
32
while evals<maxiter
33
    % Compute gradient
34
    for j=1:length(x)
35
        xp = x;
36
        pert = (xmax(j)-xmin(j))*delta;
37
        xp(j) = xp(j)+pert;
38
        Fp = ObjectivePenal(xmin,xp,xmax);
39
        d(j) = -(Fp-F)/pert;
40
    end
41
    [x F] = goldengrad(xmin,x,xmax,d,10);    % Perform golden section optimization in that direction
42
    evals = evals + 1;
43
end
44