Skip to content

Instantly share code, notes, and snippets.

@myjr52
Created January 1, 2015 23:11
Show Gist options
  • Save myjr52/99af58acaad6656f1275 to your computer and use it in GitHub Desktop.
Save myjr52/99af58acaad6656f1275 to your computer and use it in GitHub Desktop.
find optimal spring and damping constants using minimize in scipy
def cost_function(x):
k_spring, c_damper = x
# import functions
from numpy import linspace, max, abs
from scipy.integrate import odeint
import msd_ode
# define constants
init_cond = [0.3, -0.1]
t_init = 0.0
t_final = 100.0
time_step = 0.005
num_data =int((t_final-t_init)/time_step)
# integrate
t_all = linspace(t_init, t_final, num_data)
y_all = odeint(msd_ode.mass_spring_damper, init_cond, t_all,
args=([k_spring, c_damper],))
# find maximum undershoot
xout = y_all[:,0]
x_negative = abs(xout[xout<0])
max_undershoot = max(x_negative)
return max_undershoot
def mass_spring_damper(state, t, k_c_set):
x, x_dot = state
k_spring, c_damper = k_c_set
f = [x_dot,
-k_spring*x - c_damper*x_dot]
return f
from scipy.optimize import minimize
import cost_function as cf
x0 = [0.1,0.1]
bnds = ((0, None), (0, None))
result = minimize(cf.cost_function, x0, method='SLSQP', bounds=bnds)
print(result.x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment