I have the following code I want to convert to Python for .NET (so I want to embed Python in C#)
import numpy as np
from scipy.optimize import curve_fit
x = np.array([4, 3, 2, 1])
y = np.array([1.43, 1.84, 1.36, 1.08])
model = lambda t, a, b: a * np.exp(-b * t)
params = curve_fit(model, x, y)
how to convert this to Python for .NET?
PythonEngine.Initialize();
using (Py.GIL())
{
dynamic np = Py.Import("numpy");
dynamic sp = Py.Import("scipy.optimize");
var x = new List<double> { 1, 2, 3, 4 };
var y = new List<double> { 1.43, 1.84, 1.36, 1.08 };
var objective = (float t, float alpha, float kappa) => alpha * np.exp(-kappa * t);
dynamic parameters = sp.curve_fit(objective, x, y)
}
objective however is not accepted, anyone got an idea, I prefer a solution without something like
scope.Import("numpy");
scope.Exec("model = lambda t, a, b: a * numpy.exp(-b * t)");
var model = scope.Eval("model");
Not sure if it possible via C# functions, but you can use
PythonEngine.Evalto create the lambda:Note that
tin the lambda is actually isarray_likeand the func returnsarray_likein the original code (numpy.ndarrayif to be more precise).