In [1]:
%matplotlib inline
from pylab import *
from optoy import *
Equations of a ball in freefall:
$\dot{x}=v_x$
$\dot{y}=v_y$
$\dot{v_x}=0$
$\dot{v_y}=-g$
In [2]:
gravity = par()
states = struct(["x","y","vx","vy"])
# Ode model for a ball
# state params constant over stage
def f( x, dt,g ):
return dt*vertcat([
x[2],
x[3],
0,
-g
])
simulator = OdeSimulator(f,T=1)
In [3]:
stage1_x0 = var(shape=4) # Freefall
stage1_t = var()
stage2_x0 = var(shape=4) # Bounce
stage3_x0 = var(shape=4) # Freefall
stage3_t = var()
stage4_x = var(shape=4) # End
# For easier indexing using labels
state1 = states(stage1_x0)
state2 = states(stage2_x0)
state3 = states(stage3_x0)
state4 = states(stage4_x)
In [4]:
# Expression obtained by integrating the ode over symbolic input
xf1 = simulator(stage1_x0, stage1_t,gravity )
xf2 = stage2_x0*vertcat([1,1,1,-0.5])
xf3 = simulator(stage3_x0, stage3_t,gravity )
In [5]:
# Objective
f = -state4["x"]
g = [
state1["vx"]**2 + state1["vy"]**2 == 1, #normalized speed
state2["y"] == 0, # Ground contact
stage2_x0 == xf1, # Transition
stage3_x0 == xf2, # Transition
state4["y"] ==0, # Ground contact
stage4_x == xf3, # Transition
state1["x"] == 0,
state1["y"] == 0,
stage1_t >= 0,
stage3_t >= 0
]
stage1_x0.init = [0,0,1,1]
stage3_x0.init = [0,0,1,1]
stage1_t.init = stage3_t.init = 2
gravity.value = 1 # [m/s^2]
solver = minimize(f,g,verbose=True)
print value(stage4_x)
In [6]:
gravity.value = 2 # [m/s^2]
solver.update()
print value(stage4_x)
In [6]:
In [ ]: