Is the best way to deal with a linear programming?
-
There's a lot of masses, each element of which is a set of seven floats.
There is a set on the i-point of each mass, which should be as high as possible (i for each mass different).
We need to find these float parameters to make them home.
sum(p*x for p,x in zip(params, pack)) --->> max for each array
The amount of the set was as high as possible, i.e. the set up at I don't know.
Please tell me your ideas.
Thank you.
Edit:
# Для простоты рассмотрим для 2х floats # Дано: array1 = [(1,4),(2,7),(3,1)] (i=2) array2 = [(1,4),(2,5),(3,6)] (i=1) ...
Найти:
p1 и p2
чтобы p1 * array1[i][0] + p2 * array1[i][1] --->> max
очевидно, что надо увеличивать те координаты набора,
которые уже больше, чем у остальных,
и уменьшать те координаты, которые у набора меньше
Мой вариант решения:
p1, p2 = 1, 1
for array in [array1, array2, ...]:
array = np.array(array)stats, means = [], [] for column in array.T: # 5-я порядковая статистика от максимума stats.append(np.partition(column, -5)[-5]) means.append(np.mean(column)) for j,coord in enumerate(array[i,:]): # Если координата искомого вектора достаточно велика # относительно других наборов в массиве - # делаем её ещё больше if stats[j] <= coord: p[i] += means[i] # p1 | p2 else: # иначе делаем её по меньше p[i] += 1. / means[i] # p1 | p2
В конце делим на количество массивов
p1 /= len(arrays)
p2 /= len(arrays)
-
The task is complicated, but interesting.
Let's just say the decision vector. x The reference setting shall be defined with precision to the arbitrary positive multiplier.
1. Target setting
Conditions of type sum(ajxj) verbal sum(b)jxj) easily referenced sum(s)jxj) vent 0♪
If the aim is to minimize the amount of places occupied by designated recruitments on their lists, the target function is now the number of inequities that are met by the decision-makers.
The target function is non-linear, so the optimization of the calculations in the same way as the symple-method is not possible.
2. Geometric interpretation
Each inequality n variables corresponding n- Measly semi-space, which passes through the beginning of the coordinates.
At the same time, each unborn system from n inequities n-- border corner n- a mortal area with a verb at the beginning of the coordinates.
Theing of the task is a multifaceted angle that is part of the rest.
Therefore, it is sufficient to build all allowed multiple angles, take a test point within each of them and set it in inequality.3. Jordan method of exception
Let us have a system. m inequality n variables (n
y0 = s00x0 + c01x1 + ... +c0,n-1xn-1 0
y1 = s10x0 + c11x1 + ... + c1,n-1xn-1 0
y2 = s20x0 + c21x12 + ... + c2,n-1xn-10ym-1 = sm-1.0x0 + cm-1.1x1 + cm-1,n-1xn-10
Jordan ' s method of exception is to move from a rectangular base. {x0, x1..., xn-1♪ to the multi-dimensional angle {y0y1♪n-1♪♪ Each variable xi expressed through variable yi with the same index. To choose another base, it is sufficient to change inequalities in places.
Jordan ' s method is understandable and works well on rectangular matrices.
First of the equation for yi Expressed xiand the resulting coefficients shall be recorded at the location of the equation used. Then expressed for xi be inserted into the other equations of the system, which results in adjustments to their coefficients.The exclusion of variables on Jordan can be arbitrary. But the most diagonal element should be chosen to achieve a sustainable outcome.
At the end of the procedure n rows of the matrix provide expressions for the vector component xthe remaining inequalities in the new base.4. Inequal check
Inequalities shall be checked in the selected base.
The test vector y = [1,1,...,1] shall be selected for inspection and this shall immediately ensure that the basic inequities are met. The remaining inequities are checked by the test vector in the last (m-n) equations and the checking of the output mark.The rank of the system (number of independent inequities) is not less than the number of independent variables.
We'll note that the equation system can be decided instead of the p.3-4. y1=1, y2=1, ♪ ♪ for each selected base, and the decision x to enter unused system equations.
5. Description of programme
The programme has the following functions:
print_1d(), print_2d(), print_3d()
- 1-2-3-dimensional withdrawal;array_sub()
- the variety of vectors;array_scale()
multiplying the vector by number;task_to_unequals()
- Transforming the baseline task into an unequal system;gen_combi()
- Comparison generator;rows_to_order()
- Stopping the matrix in order;jordan()
- Jordan ' s exemption method for diagonal elements (with the choice of the permit element);rank()
- the number of inequities performed;test_subs()
- testing of substations;coeff_to_x
- calculation of independent variables x For a test vector with a single coordinate.The Programme is implementing the following actions:
- Transforms the original objective into the system of inequality
- Generates all possible bases (system inequities).
- Describes a target function for the remittances received, discontinuing the calculation when reaching the maximum possible result.
- Exit results, including the number of inequities and the decision vector.
6. Programme text (PHP)
$task = [ [2,[1,4],[2,7],[3,1]], [1,[1,4],[2,5],[3,6]] ];
// Вывод одномерного массива
function print_1d($text, $v){
$eps = 1e-7;
print "$text"."[";
$flag = false;
foreach($v as $key=>$item){
if($flag) print ", ";
$flag = true;
if(abs((int)$item - $item) > $eps){
printf("%.3f", $item);
}else{
print $item;
}
}
print "], ";
}// Вывод двумерного массива
function print_2d($text, $v){
print "$text"."[";
foreach($v as $key => $item){
//print " $key => ";
print_1d("", $item);
}
print "], ";
}// Вывод трёхмерного массива
function print_3d($text, $data){
print "<br>$text"."[";
foreach($data as $key=>$item){
print "<br> $key => [";
foreach($item as $v){
if(is_numeric($v)){
print "$v, ";
}else{
print_1d("",$v);
}
}
print "],";
}
print "<br>],";
}// Разность векторов
function array_sub($v1, $v2){
$sub = array_map(function($a, $b){
return $a - $b;
}, $v1, $v2);
return $sub;
}// Умножение вектора на число
function array_scale($v, $factor){
return array_map(function($item) use($factor){
return $item * $factor;
}, $v);
}// Преобразование задачи в систему неравенств
function task_to_unequals($task){
$u = [];
foreach($task as $arr){
foreach($arr as $key => $item){
if(is_numeric($item)){
$key_g = $item;
$goal = $arr[$item];
}elseif($key != $key_g){
$u[] = array_sub($goal, $item);
}
}
}
return $u;
}// генератор сочетаний
function gen_combi($n, $m, $all_subs = null){
$new_subs = [];
if($m == 1){
for($i = 0; $i < $n; $i++){
$new_subs[] = [$i];
}
}else{
$all_subs = gen_combi($n, $m-1, $all_subs);
foreach($all_subs as $subs){
for($k = end($subs)+1; $k < $n; $k++){
$s = $subs;
$s[] = $k;
$new_subs[] = $s;
}
}
}
return $new_subs;
}// Перестановка строк матрицы в заданном порядке
function rows_to_order($matrix, $subs){
$columns = count($matrix[0]);
foreach($subs as $l => $k){
$c[$l] = $matrix[$k];
}
$rows = count($matrix);
for($k = 0; $k < $rows; $k++){
if(!(in_array($k, $subs))){
$c[] = $matrix[$k];
}
}
return $c;
}// Йордановы исключения x[i] -> y[i]
function jordan(&$c){
$eps = 1e-7;
$rows = count($c);
$cols = count($c[0]);
$queue = range(0, $cols-1);
while(!empty($queue)){
print_1d("<br>не обработано: ", $queue);
// Выбор наибольшего по модулю диагонального элемента из очереди
$max_abs = 0;
foreach($queue as $key){
$cur = abs($c[$key][$key]);
if($cur > $max_abs){
$i = $key;
$max_abs = $cur;
}
}
unset($queue[$i]); // удаление выбранного элемента из очереди
if($max_abs < $eps){ // если выбранный элемент нуль, результат - ошибка
$c = false;
return;
}else{
$beta = 1/$c[$i][$i];
$c[$i] = array_scale($c[$i], -$beta);
$c[$i][$i] = $beta;
for($k = 0; $k < $rows; $k++){
if($k != $i){
$gamma = $c[$k][$i];
$c[$k] = array_sub($c[$k], array_scale($c[$i], -$gamma));
$c[$k][$i] = $gamma*$beta;
}
}
}
print_2d(" выбрано: $i  результат: ", $c);
}
}// подсчёт количества выполненных неравенств
function rank($c){
//print_2d("<br>rank: c = ", $c);
$cols = count($c[0]);
$r = $cols;
foreach($c as $key => $v){
if (($key >= $cols) && (array_sum($v) > 0)){
$r++;
}
}
return $r;
}// тестирование подстановок
function test_subs($unequals, $all_subs){
$rows = count($unequals);
$cols = count($unequals[0]);
$rank = 0;
foreach($all_subs as $subs){
$r = 0;
print_1d("<br><br>Базис: ", $subs);
$c = rows_to_order($unequals, $subs);
print_2d("<br>перестановка строк:<br>", $c);
print("<br>исключение переменных по Йордану");
jordan($c);
if($c !== false){
print_1d("<br>Тестовый вектор: y = ", array_fill(0,$cols,1));
$r = rank($c);
$x = coeff_to_x($c);
print "<br>Выполнено неравенств: $r";
}else{
print"<br>Выполнено неравенств: 0";
}
if($r > $rank){
$rank = $r;
$coeff = $c;
}
if($r == $rows){
break;
}
}
return $coeff;
}// вычисление независимых переменных по коэффициентам матрицы
function coeff_to_x($coeff){
$cols = count($coeff[0]);
$x = [];
for($i= 0; $i < $cols; $i++){
$x[] = array_sum($coeff[$i]);
}
return $x;
}print_3d("Исходная задача:<br>", $task);
$unequals = task_to_unequals($task);
$rows = count($unequals);
$cols = count($unequals[0]);
print_2d("<br><br>Массив неравенств:<br>", $unequals);
print("<br><br>Генератор базисов:<br>");
$all_subs = gen_combi($rows, $cols);
print_2d("all_subs = ", $all_subs);
$coeff = test_subs($unequals, $all_subs);
print_2d("<br><br>РЕЗУЛЬТАТЫ<br>Система в оптимальном базисе: ", $coeff);
print_1d("<br>Bектор в оптимальном базисе: y = ", array_fill(0,$cols,1));
$r = rank($coeff);
$x = coeff_to_x($coeff);
print_1d("<br>Выполнено неравенств: $r<br><br>РЕШЕНИЕ: x = ", $x);
7. Results
Baseline:
[grunting]
0 = section [2, [1, 4], [2, 7], [3, 1], ]
1 = sector [1, [1, 4], [2, 5], [3, 6], ]
]Inequalities:
[[1, 3], [-1, 6], [-1, -1], [2], ]Base generator:
all_subs = [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3], ],Base: [0, 1]
Stop line:
[[1, 3], [-1, 6], [-1, -1], [2], ]
Removal of variables to Jordan
Not processed: [0, 1], selected: 1 result: [1.500, 0.500], [0.167, 0.167], [-1.167, -0.167], [-2.333, -0.333], ]
Not processed: [0], selected: 0 result: [[0.667, -0.333], [0.111, 0.111], [-0.778, 0.222], [-1.556, 0.444], ]
Test vector: y = [1, 1]
Inequalities: 2Base: [0, 2]
Stop line:
[[1, 3], [-1, -1], [-1, 6], [2], ]
Removal of variables to Jordan
Not processed: [0, 1], selected: 0 result: [[1, -3], [-1, 2], [-1, 9], [-2, 4], ]
Not processed: [1], selected: 1 result: [[-0.500, -1.500], [0.500, 0.500], [3.500, 4.500], [0, 2], ]
Test vector: y = [1, 1]
Inequalities: 4RESULTS
System in optimum base: [[-0.500, -1.500], [0.500, 0.500], [3.500, 4.500], [0, 2], ],
Best reference vector: y = [1, 1]
Inequalities: 4DECISION: x = [2, 1]