移植过来的python codes

import numpy as np
from scipy.optimize import linear_sum_assignment

RECTANGULAR_LSAP_INFEASIBLE = -1
RECTANGULAR_LSAP_INVALID    = -2

def solve_rectangular_linear_sum_assignment(nr, nc, cost, maximize, a, b):
    return solve(nr, nc, cost, maximize, a, b)

def linear_sum_assignment__(cost_matrix):
    maximize = 0
    if len(cost_matrix.shape) != 2:
        exit(-1)
    num_rows, num_cols = cost_matrix.shape
    # cost_matrix = np.flatten(cost_matrix)
    dim = num_rows if num_rows < num_cols else num_cols
    a_ptr = np.zeros(dim, dtype = np.int64)
    b_ptr = np.zeros(dim, dtype = np.int64)
    ret = solve_rectangular_linear_sum_assignment(num_rows, num_cols, cost_matrix, maximize, a_ptr, b_ptr)
    return ret

def solve(nr, nc, cost, maximize, a, b):
    if nr==0 or nc==0:
        return 0
    transpose = nc < nr
    if transpose:
        cost = cost.T
        nc, nr = nr, nc
    if maximize:
        cost = -cost
    inf = (cost == -np.inf) | (cost == np.inf) | (cost != cost)
    if inf.any():
        return RECTANGULAR_LSAP_INVALID
    u = np.zeros((nr))
    v = np.zeros((nc))
    shortestPathCosts = np.ones((nc))
    path    = -1 * np.ones((nc), dtype=np.int64)
    col2row = -1 * np.ones((nr), dtype=np.int64)
    row2col = -1 * np.ones((nc), dtype=np.int64)
    SR = np.zeros((nr), dtype = np.bool_)
    SC = np.zeros((nc), dtype=np.bool_)

    for curRow in range(nr):
        minVal = [0]
        sink = augmenting_path(nc, cost, u, v, path, row2col,
                                shortestPathCosts, curRow, SR, SC,
                                minVal)
        if sink < 0:
            return RECTANGULAR_LSAP_INFEASIBLE
        u[curRow] += minVal[0]
        for i in range(nr):
            if SR[i] and i!=curRow:
                u[i] += minVal[0] - (shortestPathCosts[col2row[i]]  if col2row[i] > 0 else 0)
        for j in range(nc):
            if SC[j]:
                v[j] -= minVal[0] - shortestPathCosts[j]
        j = sink
        while True:
            i = int(path[j])
            if j==-1:
                i = 0
            row2col[j] = i
            col2row[i], j = j, col2row[i]
            if i == curRow:
                break
    if transpose:
        i = 0
        argind = np.argsort(col2row)
        for j in argind:
            a[i] =col2row[j]
            b[i] = j
            i += 1
    else:
        for i in range(nr):
            a[i] = i
            b[i] = col2row[i]
    return a,b

def augmenting_path(nc, cost, u, v, path, row2col,  \
                    shortestPathCosts, i, SR, SC,  \
                    p_minVal):
    minVal = 0
    num_remaining = nc
    remaining = np.arange(nc)[::-1]
    shortestPathCosts[...] = np.inf
    SR[...] = False
    SC[...] = False
    sink = -1
    while sink==-1:
        index = -1
        lowest = np.inf
        SR[i] = True
        for it in range(num_remaining):
            j = remaining[it]
            r = minVal + cost[i, j] - u[i] - v[j]
            if r < shortestPathCosts[j]:
                path[j] = i
                shortestPathCosts[j] = r
            if shortestPathCosts[j] < lowest or (shortestPathCosts[j]==lowest and row2col[j] == -1):
                lowest = shortestPathCosts[j]
                index = it
        minVal = lowest
        if minVal==np.inf:
            return -1
        j = remaining[index]
        if row2col[j] == -1:
            sink = j
        else:
            i = row2col[j]
        SC[j] = True
        num_remaining = num_remaining - 1
        remaining[index] = remaining[num_remaining]

    p_minVal[0] = minVal
    return sink

if __name__ == "__main__":
    # np.random.seed(666666666)
    np.random.seed(np.random.randint(999999999))
    cost_matrix = np.random.randint(0, 100000000, (3, 3))
    ret_off = linear_sum_assignment(cost_matrix)
    ret= linear_sum_assignment__(cost_matrix)
    com = (ret[0] == ret_off[0]) & (ret[1]==ret_off[1])
    if np.sum(~com)==0:
        k = 0
    kk = 0

对应的C++ codes

scipy/scipy/optimize/rectangular_lsap/rectangular_lsap.cpp at main · scipy/scipy (github.com)

/*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above
   copyright notice, this list of conditions and the following
   disclaimer in the documentation and/or other materials provided
   with the distribution.

3. Neither the name of the copyright holder nor the names of its
   contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


This code implements the shortest augmenting path algorithm for the
rectangular assignment problem.  This implementation is based on the
pseudocode described in pages 1685-1686 of:

    DF Crouse. On implementing 2D rectangular assignment algorithms.
    IEEE Transactions on Aerospace and Electronic Systems
    52(4):1679-1696, August 2016
    doi: 10.1109/TAES.2016.140952

Author: PM Larsen
*/

#include <cmath>
#include <vector>
#include <numeric>
#include <algorithm>
#include <stdint.h>
#include<iostream>

#define RECTANGULAR_LSAP_INFEASIBLE -1
#define RECTANGULAR_LSAP_INVALID -2

using namespace std;

template <typename T> std::vector<intptr_t> argsort_iter(const std::vector<T> &v)
{
    std::vector<intptr_t> index(v.size());
    std::iota(index.begin(), index.end(), 0);
    std::sort(index.begin(), index.end(), [&v](intptr_t i, intptr_t j)
              {return v[i] < v[j];});
    return index;
}

static intptr_t
augmenting_path(intptr_t nc, double *cost, std::vector<double>& u,
                std::vector<double>& v, std::vector<intptr_t>& path,
                std::vector<intptr_t>& row4col,
                std::vector<double>& shortestPathCosts, intptr_t i,
                std::vector<bool>& SR, std::vector<bool>& SC,
                std::vector<intptr_t>& remaining, double* p_minVal)
{
    double minVal = 0;

    // Crouse's pseudocode uses set complements to keep track of remaining
    // nodes.  Here we use a vector, as it is more efficient in C++.
    intptr_t num_remaining = nc;
    for (intptr_t it = 0; it < nc; it++) {
        // Filling this up in reverse order ensures that the solution of a
        // constant cost matrix is the identity matrix (c.f. #11602).
        remaining[it] = nc - it - 1;
    }

    std::fill(SR.begin(), SR.end(), false);
    std::fill(SC.begin(), SC.end(), false);
    std::fill(shortestPathCosts.begin(), shortestPathCosts.end(), INFINITY);

    // find shortest augmenting path
    intptr_t sink = -1;
    while (sink == -1) {

        intptr_t index = -1;
        double lowest = INFINITY;
        SR[i] = true;

        for (intptr_t it = 0; it < num_remaining; it++) {
            intptr_t j = remaining[it];

            double r = minVal + cost[i * nc + j] - u[i] - v[j];
            if (r < shortestPathCosts[j]) {
                path[j] = i;
                shortestPathCosts[j] = r;
            }

            // When multiple nodes have the minimum cost, we select one which
            // gives us a new sink node. This is particularly important for
            // integer cost matrices with small co-efficients.
            if (shortestPathCosts[j] < lowest ||
                (shortestPathCosts[j] == lowest && row4col[j] == -1)) {
                lowest = shortestPathCosts[j];
                index = it;
            }
        }

        minVal = lowest;
        if (minVal == INFINITY) { // infeasible cost matrix
            return -1;
        }

        intptr_t j = remaining[index];
        if (row4col[j] == -1) {
            sink = j;
        } else {
            i = row4col[j];
        }

        SC[j] = true;
        remaining[index] = remaining[--num_remaining];
    }

    *p_minVal = minVal;
    return sink;
}

static int
solve(intptr_t nr, intptr_t nc, double* cost, bool maximize,
      int64_t* a, int64_t* b)
{
    // handle trivial inputs
    if (nr == 0 || nc == 0) {
        return 0;
    }

    // tall rectangular cost matrix must be transposed
    bool transpose = nc < nr;

    // make a copy of the cost matrix if we need to modify it
    std::vector<double> temp;
    if (transpose || maximize) {
        temp.resize(nr * nc);

        if (transpose) {
            for (intptr_t i = 0; i < nr; i++) {
                for (intptr_t j = 0; j < nc; j++) {
                    temp[j * nr + i] = cost[i * nc + j];
                }
            }

            std::swap(nr, nc);
        }
        else {
            std::copy(cost, cost + nr * nc, temp.begin());
        }

        // negate cost matrix for maximization
        if (maximize) {
            for (intptr_t i = 0; i < nr * nc; i++) {
                temp[i] = -temp[i];
            }
        }

        cost = temp.data();
    }

    // test for NaN and -inf entries
    for (intptr_t i = 0; i < nr * nc; i++) {
        if (cost[i] != cost[i] || cost[i] == -INFINITY) {
            return RECTANGULAR_LSAP_INVALID;
        }
    }

    // initialize variables
    std::vector<double> u(nr, 0);
    std::vector<double> v(nc, 0);
    std::vector<double> shortestPathCosts(nc);
    std::vector<intptr_t> path(nc, -1);
    std::vector<intptr_t> col4row(nr, -1);
    std::vector<intptr_t> row4col(nc, -1);
    std::vector<bool> SR(nr);
    std::vector<bool> SC(nc);
    std::vector<intptr_t> remaining(nc);

    // iteratively build the solution
    for (intptr_t curRow = 0; curRow < nr; curRow++) {

        double minVal;
        intptr_t sink = augmenting_path(nc, cost, u, v, path, row4col,
                                        shortestPathCosts, curRow, SR, SC,
                                        remaining, &minVal);
        if (sink < 0) {
            return RECTANGULAR_LSAP_INFEASIBLE;
        }

        // update dual variables
        u[curRow] += minVal;
        for (intptr_t i = 0; i < nr; i++) {
            if (SR[i] && i != curRow) {
                int ind = col4row[i];
                float pc = shortestPathCosts[col4row[i]];
                u[i] += minVal - shortestPathCosts[col4row[i]];
            }
        }

        for (intptr_t j = 0; j < nc; j++) {
            if (SC[j]) {
                v[j] -= minVal - shortestPathCosts[j];
            }
        }

        // augment previous solution
        intptr_t j = sink;
        while (1) {
            intptr_t i = path[j];
            row4col[j] = i;
            std::swap(col4row[i], j);
            if (i == curRow) {
                break;
            }
        }
    }

    if (transpose) {
        intptr_t i = 0;
        for (auto v: argsort_iter(col4row)) {
            a[i] = col4row[v];
            b[i] = v;
            i++;
        }
    }
    else {
        for (intptr_t i = 0; i < nr; i++) {
            a[i] = i;
            b[i] = col4row[i];
        }
    }

    return 0;
}

// #ifdef __cplusplus
// extern "C" {
// #endif

int solve_rectangular_linear_sum_assignment(intptr_t nr, intptr_t nc,
                                            double* input_cost, bool maximize,
                                            int64_t* a, int64_t* b)
{
    return solve(nr, nc, input_cost, maximize, a, b);
}

// #ifdef __cplusplus
// }
// #endif

int main(void) {
    bool maximize = false;
    // double* input_cost = (double *)malloc(sizeof(double) * 9);
    // int64_t* a = (int64_t *)malloc(sizeof(int64_t) * 3);
    // int64_t* b = (int64_t *)malloc(sizeof(int64_t) * 3);

    // double input_cost[] = {67, 26, 6, 0, 2, 76, 68, 7, 9};
    double input_cost[] = {0, 2, -1, 0};
    float length = sizeof(input_cost) / (float)sizeof(*input_cost);
    intptr_t nr = sqrt(length);
    intptr_t nc = nr;
    int64_t a[] = {0, 0};
    int64_t b[] = {0, 0}; 
    int ret = solve_rectangular_linear_sum_assignment(nr, nc, input_cost, maximize, a, b);

    return 0;
}


https://zhuanlan.zhihu.com/p/651582726

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐