public static Replace ( System.Linq.Expressions.ParameterExpression parameter, |
||
parameter | System.Linq.Expressions.ParameterExpression | |
expr | ||
variables | int>.IDictionary | |
return |
public static Expression Replace(ParameterExpression parameter,
Expression expr, IDictionary<string, int> variables)
{
if (expr == null)
return null;
BinaryExpression eb = expr as BinaryExpression;
MemberExpression em = expr as MemberExpression;
UnaryExpression eu = expr as UnaryExpression;
MethodCallExpression ec = expr as MethodCallExpression;
NewArrayExpression ea = expr as NewArrayExpression;
if (em != null) // member expression
{
string varName = em.Member.Name;
int index = variables[varName];
ConstantExpression indexExpression = Expression.Constant(index);
return Expression.ArrayAccess(parameter, indexExpression);
}
else if (eb != null) // binary expression
{
var left = Replace(parameter, eb.Left, variables);
var right = Replace(parameter, eb.Right, variables);
return eb.Update(left, eb.Conversion, right);
}
else if (eu != null) // unary expression
{
var op = Replace(parameter, eu.Operand, variables);
return eu.Update(op);
}
else if (ec != null) // call expression
{
List<Expression> args = new List<Expression>();
foreach (var a in ec.Arguments)
args.Add(Replace(parameter, a, variables));
return ec.Update(ec.Object, args);
}
else if (ea != null) // new array expression
{
List<Expression> values = new List<Expression>();
foreach (var v in ea.Expressions)
values.Add(Replace(parameter, v, variables));
return ea.Update(values);
}
else
{
return expr;
}
}
}
/// <summary> /// Creates a new objective function specified through a string. /// </summary> /// /// <param name="function">A <see cref="Expression{T}"/> containing /// the function in the form of a lambda expression.</param> /// <param name="gradient">A <see cref="Expression{T}"/> containing /// the the gradient of the <paramref name="function">objective function</paramref>.</param> /// public NonlinearObjectiveFunction( Expression <Func <double> > function, Expression <Func <double[]> > gradient = null) { variables = new Dictionary <string, int>(); indices = new Dictionary <int, string>(); var list = new SortedSet <string>(); ExpressionParser.Parse(list, function.Body); int index = 0; foreach (string variable in list) { variables.Add(variable, index); indices.Add(index, variable); index++; } NumberOfVariables = index; // Generate lambda functions var func = ExpressionParser.Replace(function, variables); var grad = ExpressionParser.Replace(gradient, variables); this.Function = func.Compile(); this.Gradient = grad.Compile(); }