【问题标题】:How to add this constraint to a problem using python-constraint如何使用 python-constraint 将此约束添加到问题中
【发布时间】:2020-11-15 13:38:02
【问题描述】:

我正在尝试使用 python-constraint 来解决组合问题,但我似乎无法将我需要的约束添加到问题中。我的问题是我必须放置 9 个方形图块,并且每个图块都可以旋转到 4 个位置之一,我已将图块编码为矢量,并且需要特定的元素对添加到零。

使用带有两个图块的示例:

piece_1 = np.array([-1,-3, 4, 2])

piece_2 = np.array([-2, -1, 3, 2])

每个向量可以滚动形成一组 4 个向量:

piece_1_set = [np.roll(piece_1, i) for i in range(4)]

piece_2_set = [np.roll(piece_2, i) for i in range(4)]

我已将它们添加到问题中:

problem.addVariable("1", piece_1_set)

problem.addVariable("2", piece_2_set)

我想做的是从每个集合中找到一个向量,使得第一个向量的第二个元素和第二个向量的第四个元素总和为 0。

我尝试过各种版本的:

problem.addConstraint(lambda i,j: i[1] + j[3] == 0, ("1", "2"))

problem.addConstraint(lambda i,j: np.any(i[1]) + np.any(j[3]) == 0, ("1", "2"))

但我总是返回以下内容:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

有谁知道如何表达这个约束,以便我可以添加它们以获得问题的解决方案?

【问题讨论】:

    标签: python arrays numpy constraint-programming


    【解决方案1】:

    问题似乎只是您试图将 numpy 数组与 python-constraint 库一起使用,而不是内置的 python 列表。您需要按照下面的解决方案将它们转换回来。

    import numpy as np
    from constraint import *
    
    problem = Problem()
    
    piece_1 = np.array([-1,-3, 4, 2])
    piece_2 = np.array([-2, -1, 3, 2])
    piece_1_set = [list(np.roll(piece_1, i)) for i in range(4)]
    piece_2_set = [list(np.roll(piece_2, i)) for i in range(4)]
    
    problem.addVariable("1", piece_1_set)
    problem.addVariable("2", piece_2_set)
    
    problem.addConstraint(lambda i, j: i[0] == j[0], ("1", "2"))
    problem.getSolutions()
    
    

    【讨论】:

    • 太好了,谢谢你,我没有考虑过!
    猜你喜欢
    • 1970-01-01
    • 2019-07-12
    • 2021-09-09
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 2021-02-27
    • 2012-06-16
    • 2019-11-29
    相关资源
    最近更新 更多