I am new in python. The following code for minimization of a mechanical system works with no error.
However, it is slow and to me there are unnecessary steps or loops that make it heavy!
Would you make comment, and preferably a modified version of the code.
The code:
from os.path import join
import numpy as np
from scipy.optimize import minimize
import matplotlib.pyplot as plt
nu = 30
nv = 5
k = float(10)
def Us(i, j, uu):
uu = uu.reshape((nu + 1, nv + 1))
return i + np.sign(i) * uu[np.abs(i), j + nv]
def Vs(i, j, vv):
vv = vv.reshape((nu + 1, nv + 1))
return 2 * j + vv[np.abs(i), j + nv]
def Enrgy(varlbs):
uu = varlbs[:(nu + 1) * (nv + 1)].reshape((nu + 1, nv + 1))
vv = varlbs[(nu + 1) * (nv + 1) : 2 * (nu + 1) * (nv + 1)].reshape((nu + 1, nv + 1))
sumsp = np.sum(np.fromiter(
((((Us(i + 1, j, uu) - Us(i, j, uu)) ** 2 + (Vs(i + 1, j, vv) - Vs(i, j, vv)) ** 2) ** (1/2) - 1) ** 2
for i in range(-nu, nu)
for j in range(-nv, 1)), dtype=float))
return 0.5 * k * sumsp - .5 * Vs(0, -2, vv)
def con1(varlbs):
uu = varlbs[:(nu + 1) * (nv + 1)].reshape((nu + 1, nv + 1))
return np.array([uu[nu, j + nv] for j in range(-nv, 1)])
def con2(varlbs):
vv = varlbs[(nu + 1) * (nv + 1) : 2 * (nu + 1) * (nv + 1)].reshape((nu + 1, nv + 1))
return np.array([vv[i, 0] for i in range(0, nu)])
con12 = [{'type': 'eq', 'fun': lambda varlbs: con1(varlbs)}, {'type': 'eq', 'fun': lambda varlbs: con2(varlbs)}]
initialvals = np.zeros((2 * (nu + 1) * (nv + 1))).flatten()
minoutput = minimize(lambda varlbs: Enrgy(varlbs), initialvals, constraints=con12)
print(minoutput)
I tried use of sum (with no np.fromiter) instead np.sum.
I tried dropping reshape in definition of functions.
I tried even Sum by “sympy” (although not sure I used it correctly).
I expect code runs in 10 seconds instead 110 secs or more!
Thanks.
Amir H. Fatollahi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.