Converting Mathematica optimization problem to Python

Viewed 123

I'm having some trouble to convert this Mathematica code to Python. This code solves a minimization problem involving a catenary equation. I'm having trouble putting latex inside Stack Overflow, so I'm going to post a print from the math.stackexchange that I found the code.

You can find the full question and answer here: https://math.stackexchange.com/questions/3732954/finding-yx-using-a-minimization-problem/3733882#3733882

enter image description here

This is the code that solves the minimization problem proposed in the print.

Clear[lambda, c1, c2, y, x]
L = y[x] Sqrt[1 + y'[x]^2] + lambda (Sqrt[1 + y'[x]^2] - 3/2)
eq1 = D[L, y[x]] - D[D[L, y'[x]], x] // FullSimplify // Numerator
soly = DSolve[eq1 == 0, y, x][[1]] /. {C[1] -> c1, C[2] -> c2}
yx = y[x] /. soly;
r1 = yx /. {x -> 0}
r2 = yx /. {x -> 2}
int = Integrate[Evaluate[Sqrt[1 + y'[x]^2] /. soly], {x, 0, 2}]
solc1c2 = NMinimize[{r1^2 + r2^2 + (int - 3)^2, lambda > 1}, {c1, c2, lambda}]
yx0 = y[x] /. soly /. solc1c2[[2]]
Plot[yx0, {x, 0, 2}]

What I've tried so far

I'm having trouble in defining the proper functions to the problem, I'm not so interested in the minimization part of the problem. I've created a class called CatenaryOptimization loaded with the functions that i think that are necessary to solve this problem.

import numpy as np
from scipy.misc import derivative

class CatenaryOptimization:
    
    @staticmethod
    def y(x, c1, c2, lam):
        
        return 0.5*(np.e**(-np.e**c1*(c2+x)-2c1 + np.e**((np.e**c1)c1*(c2+x) + -2*lam)
       
    def L(self, x, c1, c2, lam):
        l1 = self.y(self, x, c1, c2, lam)*np.sqrt(1 + derivative(self.y(self, x, c1, c2, lam), x)
        l2 = lam*(np.sqrt(1 + derivative(self.y(self, x, c1, c2, lam), x) - 3/2)
        return l1 + l2

The trouble

There are some variables in the Mathematica code that I can't parse, like eq1 and soly, in to a Python variable, how can I do this?

0 Answers
Related