总结
我想设计一个类来保存我所有的问题数据,以便其成员函数可用于将信息传递给第三方成员函数。如何为以下两个功能执行此操作?
我的问题:
我正在编写一个用于科学计算的程序。为了解决我的问题,我必须使用一些第三方库。目前我正在使用 Ipopt(用于数值优化(。
要使用 Ipopt,我必须通过以下方式提供足够的信息。
首先,我需要创建一个应该继承第三方类 TNLP 的类。
然后,我必须提供 8 个虚拟函数的实现,其中两个及其实现如下。
// MyNLP is the class which I coded to inherit from TNLP.
bool MyNLP::get_starting_point(Index n, bool init_x, Number* x,
bool init_z, Number* z_L, Number* z_U,
Index m, bool init_lambda,
Number* lambda)
{
// Here, we assume we only have starting values for x, if you code
// your own NLP, you can provide starting values for the others if
// you wish.
assert(init_x == true);
assert(init_z == false);
assert(init_lambda == false);
// we initialize x in bounds, in the upper right quadrant
x[0]=0.5;
x[1]=1.5;
return true;
}
和
bool MyNLP::eval_f(Index n, const Number* x, bool new_x, Number&
obj_value)
{
// return the value of the objective function
Number x2 = x[1];
obj_value = -(x2 - 2.0) * (x2 - 2.0);
return true;
}
在上面的实现中,我直接为函数调用中的参数提供了值。现在为了使程序更通用,而不是直接在上述函数中输入所需的信息,我希望使用一个包含有关我的问题的所有信息的类,并在第三方虚函数中使用函数成员。
例如,如果NLP
是保存我的问题内容的类,m_nlp
是它在类MyNLP
中的事件,那么我将重写虚函数,如下所示。
bool MyNLP::get_starting_point(Index n, bool init_x, Number* x,
bool init_z, Number* z_L, Number* z_U,
Index m, bool init_lambda,
Number* lambda)
{
// Here, we assume we only have starting values for x, if you code
// your own NLP, you can provide starting values for the others if
// you wish.
assert(init_x == true);
assert(init_z == false);
assert(init_lambda == false);
x = m_nlp->get_initial_values();
}
和
bool MyNLP::eval_f(Index n, const Number* x, bool new_x, Number&
obj_value)
{
// return the value of the objective function
obj_value = m_nlp->get_obj_value();
}
但是我不能以上述方式执行此操作,因为第二个函数使用x
来计算object_val
。如何设计一个类来保存所有数据,并使用其成员函数向 Ipopt 提供所需的信息。
我认为的解决方案:
将std::vector<Number> values
定义为类nlp
并将x
指向values
的第一个元素。
x = &(m_nlp->get_values()).at(0);
在第二个函数中,我可以修改values
而不是x
并计算obj_val
。
你可以从MyNLP派生一个类。 或
class NLPWithStuff : public MyNLP {
//...
virtual bool get_starting_point(/*...*/)
{
// optional boost::signals that do their stuff ??
// do my stuff, set flags so that no-one touches my stuff
// don't assert
return MyNLP::get_starting_point(/*.+.*/);
}
};
您必须声明MyNLP::get_starting_point
virtual
才能使其正常工作。