# Moonlander Example

Arthur Bryson - Dynamic Optimization

## Problem description

```% Copyright (c) 2007-2008 by Tomlab Optimization Inc.
```

## Problem setup

```toms t
toms tf
p = tomPhase('p', t, 0, tf, 60);
setPhase(p);

tomStates altitude speed mass
tomControls thrust

% Initial guess
x0 = {tf == 1.5
icollocate({
altitude == 1-t/tf
speed == -0.783+0.783*t/tf
mass == 1-0.99*t/tf
})
collocate(thrust == 0)};

% Box constraints
cbox = {
0  <= tf                   <= 1000
-20  <= icollocate(altitude) <= 20
-20  <= icollocate(speed)    <= 20
0.01  <= icollocate(mass)     <= 1
0  <= collocate(thrust)    <= 1.227};

% Boundary constraints
cbnd = {initial({altitude == 1; speed == -0.783; mass == 1})
final({altitude == 0; speed == 0})};

% ODEs and path constraints
exhaustvelocity = 2.349;
gravity         = 1;
ceq = collocate({
dot(altitude) == speed
dot(speed) == -gravity + thrust./mass
dot(mass) == -thrust./exhaustvelocity});

% Objective
objective = integrate(thrust);
```

## Solve the problem

```options = struct;
options.name = 'Moon Lander';
solution = ezsolve(objective, {cbox, cbnd, ceq}, x0, options);
t  = subs(collocate(t),solution);
altitude = subs(collocate(altitude),solution);
speed  = subs(collocate(speed),solution);
mass   = subs(collocate(mass),solution);
thrust = subs(collocate(thrust),solution);
```
```Problem type appears to be: qpcon
===== * * * =================================================================== * * *
TOMLAB - Tomlab Optimization Inc. Development license  999001. Valid to 2010-02-05
=====================================================================================
Problem: ---  1: Moon Lander                    f_k       1.420346223929196400
sum(|constr|)      0.000000000902441291
f(x_k) + sum(|constr|)      1.420346224831637600
f(x_0)      0.000000000000000000

Solver: snopt.  EXIT=0.  INFORM=1.
SNOPT 7.2-5 NLP code
Optimality conditions satisfied

FuncEv    1 ConstrEv   60 ConJacEv   60 Iter   19 MinorIter 1491
CPU time: 0.828125 sec. Elapsed time: 0.859000 sec.
```

## Plot result

```subplot(2,1,1)
plot(t,altitude,'*-',t,speed,'*-',t,mass,'*-');
legend('altitude','speed','mass');
title('Moon Lander state variables');

subplot(2,1,2)
plot(t,thrust,'+-');
legend('thrust');
title('Moon Lander control');
``` 