[英]Making C++ to use output from Python functions
这更多是一个工程设计问题。 MiniSAT是解决SAT问题的基础库。 它具有许多内置的优化功能。 我目前正在努力加快该代码的一部分。 但是,我的代码是用Python编写的,并且我希望C ++代码使用代码的输出来执行代码。
我一直在考虑在MiniSAT中编写C ++代码的包装,以便在python中调用。
这是我关注的代码: https : //github.com/niklasso/minisat/blob/master/minisat/core/Solver.cc
Lit Solver::pickBranchLit()
{
Var next = var_Undef;
// Random decision:
if (drand(random_seed) < random_var_freq && !order_heap.empty()){
next = order_heap[irand(random_seed,order_heap.size())];
if (value(next) == l_Undef && decision[next])
rnd_decisions++; }
// Activity based decision:
while (next == var_Undef || value(next) != l_Undef || !decision[next])
if (order_heap.empty()){
next = var_Undef;
break;
}else
next = order_heap.removeMin();
// Choose polarity based on different polarity modes (global or per-variable):
if (next == var_Undef)
return lit_Undef;
else if (user_pol[next] != l_Undef)
return mkLit(next, user_pol[next] == l_True);
else if (rnd_pol)
return mkLit(next, drand(random_seed) < 0.5);
else
return mkLit(next, polarity[next]);
}
每当在C ++中调用pickBranchLit()时,我都希望在C ++中使用Python函数。 我还希望Python从C ++代码获得有关变量当前状态的返回。 当我使用在Python中设计的启发式方法时,我想测试求解器的性能。
这是我第一次处理围绕C ++的Python包装器 ,因此我对我的解决方案没有信心。 这是我一直在想的 :
C ++函数:
Lit Solver::pickBranchLit()
{
// wait for python to return (variable, value) to assign
// update the order_heap
// return mkLit(variable, value)
}
Python功能:
CNF = get_cnf(filename)
c_solver.solve(filename) # loads up CNF in C++
while True:
# python function to decide variable and the value to assign
variable, value = python_decide_variable(CNF)
# this one calls C++ pickBranchLit
result, new_variables, values = python_sat_solver.assign_value(variable, value)
if result == "SATISFIABLE":
break
我是c ++菜鸟,但是,我掌握了很多Python。 我的设计正确吗? 如何更改C ++ pickBranchLit代码以侦听Python?
实际上不可能在C ++中使用Python变量,它们需要转换为适当的C ++类型。 对于本机类型,Cython会通过复制值自动执行此操作。
在您的情况下,您希望C ++函数接受Python参数。 这意味着修改Solver::pickBranchLit
以接受其使用的变量的参数。
另一个选择是在Python中实现pickBranchLit
并返回由C ++ pickBranchLit
返回的Lit
C ++结构。 然后可以按原样在其余C ++函数中使用它。
该选项可能是最简单的-因为您已经在使用Python生成pickBranchLit
使用的值,修改其C ++代码以接受这些值作为参数不会产生任何性能上的好处。
为了能够从Python返回Lit
结构,将需要为该结构编写Cython包装器,例如:
cdef extern from "SolverTypes.h" namespace "Minisat":
ctypedef int Var
struct Lit:
int x
# Use this as a constructor:
Lit mkLit(Var, bool)
然后在Cython代码中,可以使用mkLit(int_from_py, <True/False>)
创建一个可用于调用C ++代码的Lit
结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.