uestla/simplex-calculator

线性规划问题解决的简单工具

1.0.8 2023-02-17 12:29 UTC

This package is auto-updated.

Last update: 2024-09-24 13:54:07 UTC


README

关于

PHP 库,使用对偶单纯形算法解决线性规划问题。

注意:未实现基重复检测。

安装

推荐使用 Composer

composer require uestla/simplex-calculator

您也可以下载最新版本的 发布版 作为 ZIP 文件。

约定

请将所有输入变量命名为 x<n>,其中 <n> 是自然数(详细信息请见下方的示例)。

用法

加载库

// using Composer
require_once __DIR__ . '/vendor/autoload.php';

// using manual download
require_once __DIR__ . '/Simplex/simplex.php';

定义和解决单纯形任务

// define task: Maximize x1 + 2x2
$task = new Simplex\Task(new Simplex\Func(array(
	'x1' => 1,
	'x2' => 2,
)));

// add constraints

// 3x1 + 2x2 <= 24
$task->addRestriction(new Simplex\Restriction(array(
	'x1' => 3,
	'x2' => 2,

), Simplex\Restriction::TYPE_LOE, 24));

// -2x1 - 4x2 >= -32
$task->addRestriction(new Simplex\Restriction(array(
	'x1' => -2,
	'x2' => -4,

), Simplex\Restriction::TYPE_GOE, -32));

// create solver
$solver = new Simplex\Solver($task);

// get solutions
$solution = $solver->getSolution(); // array('x1' => 0, 'x2' => 8, 'x3' => 8, 'x4' => 0)
$alternativeSolutions = $solver->getAlternativeSolution(); // array(array('x1' => 4, 'x2' => 6, 'x3' => 0, 'x4' => 0))

// get optimal value
$optimum = $solver->getSolutionValue($solution); // 16

// print solutions
$printer = new Simplex\Printer;
$printer->printSolution($solver);

// or print the whole solution process
$printer->printSolver($solver);

解决方案

$solver->getSolutions() 返回主最优解。值可以是三种类型之一

  • array - 包含每个输入变量的最优系数的向量
  • false - 最优解不存在
  • null - 没有足够的步骤找到解决方案

默认情况下,求解器在完成 16 个单纯形表后停止计算。您可以通过第二个参数增加最大步骤限制

$solver = new Simplex\Solver($task, 32);

$solver->getAlternativeSolutions() 返回一个包含其他最优解的数组(如果找到)。它可以返回

  • array - 包含其他最优解向量的数组
  • null - 未找到其他最优解