创建 Python 包来优化成本方程
支持的平台:Windows®、Linux®、Mac
此示例演示了如何使用 MATLAB® 函数 fminsearch 来解决一个优化问题。然后,您使用 MATLAB Compiler SDK™ 创建一个 Python® 包,并将其集成到一个调用该函数的 Python 应用程序中。
创建 MATLAB 函数
在这个库存管理示例中,您的公司需要确定最佳订购数量以最大限度地降低成本,并且对订购数量没有特定的约束。
假设贵公司的成本函数(表示与管理库存相关的总成本)定义如下:
D 是年需求量
Q 是订单数量
S 是每笔订单的订单成本
H 是每年每单位的持有成本
P 是每单位的采购成本
创建一个名为 fms.m 的函数,该函数接受订单数量、年需求量、每笔订单的成本、每年每单位的持有成本和每单位的采购成本的初始猜测值,并输出最优订单数量和成本。您可以使用函数 MATLAB 和 fminsearch 来找到使总成本 C(Q) 最小的订单数量 Q。
function [Q_optimal, cost_optimal] = fms(Q_initial_guess, D, S, H, P) cost_function = @(Q) D/Q * S + Q/2 * H + D * P; [Q_optimal, cost_optimal] = fminsearch(cost_function, Q_initial_guess); end
生成 Python 包
使用以下方式构建 Python 包 compiler.build.pythonPackage 函数。
buildResults = compiler.build.pythonPackage('fms.m','PackageName','fminsearch');
compiler.build.Results 对象 buildResults 包含有关编译类型、生成的文件、包含的支持包和编译选项的信息。
该函数在您当前工作目录中名为 fminsearchpythonPackage 的文件夹中生成 Python 文件。
另外,如果您想使用图形界面创建 Python 包,请参阅使用 Python 包编译器创建 Python 包。
在 Python 中运行 MATLAB 函数
创建 Python 包后,您可以从 Python 应用程序调用该包。下面提供了一个使用指定输入调用该函数的简单应用程序。
#!/usr/bin/env python
"""
Sample script that uses the fminsearch package created using
MATLAB Compiler SDK.
Refer to the MATLAB Compiler SDK documentation for more information.
"""
import fminsearch
# Import the matlab module only after you have imported
# MATLAB Compiler SDK generated Python modules.
import matlab
try:
my_fminsearch = fminsearch.initialize()
except Exception as e:
print('Error initializing fminsearch package\\n:{}'.format(e))
exit(1)
try:
initial_guess = matlab.double([100], size=(1, 1))
D = matlab.double([10000], size=(1, 1)); # Annual demand
S = matlab.double([50], size=(1, 1)); # Order cost per order
H = matlab.double([0.5], size=(1, 1)); # Holding cost per unit per year
P = matlab.double([10], size=(1, 1)); # Purchase cost per unit
Out1, Out2 = my_fminsearch.fms(initial_guess, D, S, H, P, nargout = 2)
print("Order Quantity:", Out1, "\n", "Order Cost:", Out2)
except Exception as e:
print('Error occurred during program execution\\n:{}'.format(e))
my_fminsearch.terminate()
此代码在 Python 中生成以下输出。
Order Quantity: 1414.2135620117188 Order Cost: 100707.10678118655
另请参阅
compiler.build.pythonPackage | Python 包编译器