【问题标题】:Constrained minimization of multivariate function using Jython使用 Jython 对多元函数进行约束最小化
【发布时间】:2013-02-04 21:13:20
【问题描述】:

我有一个在 Jython 下运行的 python 程序(使用第三方 Java API),我想在其中计算一个多元函数的约束最小化。

Scipy 有一个可以完美运行的模块 (scipy.optimize) 但不幸的是,您不能在 Jython 中使用 scipy。有谁知道在 Jython 中有一个好的图书馆/任何其他方式来做到这一点?如果我可以在 Jython 下运行它,我就准备好了:

def func(x, sign=1.0):
    """ Objective function -- minimize this """
    return sign*(2*x[0]*x[1] + 2*x[0] - x[0]**2 - 2*x[1]**2)

def func_deriv(x, sign=1.0):
    """ Derivative of objective function """
    dfdx0 = sign*(-2*x[0] + 2*x[1] + 2)
    dfdx1 = sign*(2*x[0] - 4*x[1])
    return np.array([ dfdx0, dfdx1 ])

cons = ({'type': 'eq',
         'fun' : lambda x: np.array([x[0]**3 - x[1]]),
         'jac' : lambda x: np.array([3.0*(x[0]**2.0), -1.0])}, #partial derivative of fun
        {'type': 'ineq',
         'fun' : lambda x: np.array([x[1] - 1]),
         'jac' : lambda x: np.array([0.0, 1.0])})   #partial derivative of fun

res = minimize(func, [-1.0,1.0], args=(-1.0,), jac=func_deriv, 
               method='SLSQP', constraints=cons, options={'disp': True})

谢谢! -迈克尔

【问题讨论】:

    标签: python jython mathematical-optimization jython-2.5


    【解决方案1】:

    这可能不是针对您的特定用例的最佳解决方案,因为您已经在 J​​ython 中拥有了应用程序,但是 JPype (link) 允许 CPython 程序与在 JVM 上运行的程序通信,我没有我自己尝试过,但找到了一个 hello world 示例 here

    基本上你创建你的 Java 类,把它编译成一个 jar,然后在 CPython 中做

    import jpype
    import os.path
    
    jarpath = os.path.join(os.path.abspath('.'), 'build/jar')
    jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % jarpath)
    
    # get the class
    hello_world = jpype.JClass('com.stackoverflow.HelloWorld')
    t = hello_world()  # create an instance of the class
    t.helloWorld("Say hello")  # try to call one of the class methods
    jpype.shutdownJVM()
    

    我意识到这会颠倒您的应用程序逻辑。另一种选择是使用subprocess 并序列化输入/输出。

    更新

    我最近遇到了一个类似的问题,并决定试一试JPype,现在可以说它非常值得使用,尽管至少在 OSX 上安装它存在一些问题,请参阅帮助here(一些JVM 路径需要在setup.py 中更改)。

    【讨论】:

    • 谢谢!我会调查的。如果必须,子流程始终是一种选择。
    【解决方案2】:

    如果您的项目使用 Jython,您可以使用 Slsqp4j 在 JVM 上本地执行求解,并完全绕过编写 SciPy 代码。 Slsqp4j 是 SciPy 中包含的 SLSQP 求解器的 Java 包装器。该 api 与 SciPy 的非常相似。它托管在这里: https://github.com/skew-opensource/slsqp4j

    (披露:我是作者)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 2016-05-27
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    相关资源
    最近更新 更多