Python for .NET - python lambda parameter in function definition called from C#

68 Views Asked by At

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");
1

There are 1 best solutions below

4
Guru Stron On

Not sure if it possible via C# functions, but you can use PythonEngine.Eval to create the lambda:

using (Py.GIL())
{
    dynamic np = Py.Import("numpy");
    dynamic sp1 = Py.Import("scipy.optimize");
    List<int> x = [4, 3, 2, 1];
    List<double> y = [1.43, 1.84, 1.36, 1.08];
    var globals = new PyDict();
    globals.SetItem("np", np);
    var objective = PythonEngine.Eval("lambda t, a, b: a * np.exp(-b * t)", globals);
    dynamic parameters = sp1.curve_fit(objective, x, y);
}

Note that t in the lambda is actually is array_like and the func returns array_like in the original code (numpy.ndarray if to be more precise).