开发者

python-constraint: setting a constraint dependent on a function's output

I've been making a system that takes in data about drivers, potential passengers and their locations, and attempts to optimise the number of passengers that can get a lift with a driver given some constraints. I am using the python-constraint module, and the decision variables are represented thusly:

p = [(passenger, driver) for driver in drivers for passenger in passengers]
driver_set = [zip(passengers, [e1]*len(drivers)) for e1 in drivers]
passenger_set = [zip([e1]*len(passengers), drivers) for e1 in passengers]
self.problem.addVariables(p, [0,1])

So, when I print the value of p and the driver_set and passenger_set, I 开发者_开发知识库get the following output (given the test data I provided):

[(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1)] # p
[[(0, 0), (0, 1)], [(1, 0), (1, 1)], [(2, 0), (2, 1)]] # passenger_set
[[(0, 0), (1, 0)], [(0, 1), (1, 1)]] # driver_set

So, there are 3 passengers and 2 drivers: the variable (2,0) would mean that passenger 2 is in car 0, and so on. I have added the following constraints to make sure that no passenger goes in more than one car, and that a driver can't have more people than seats:

for passenger in passenger_set:
        self.problem.addConstraint(MaxSumConstraint(1), passenger)
for driver in driver_set:
        realdriver = self.getDriverByOpId(driver[0][1])
        self.problem.addConstraint(MaxSumConstraint(realdriver.numSeats), driver)

This worked - all the solutions generated satisfied these constraints. However, I would now like to add constraints saying that any solution shouldn't involve the drivers going more than a certain distance. I have a function that takes in a driver (same format as an entity from driver_set) and calculates the shortest distance for the driver to pick up all passengers. I have tried to add the constraints like this:

for driver in driver_set:
        self.problem.addConstraint(MaxSumConstraint(MAX_DISTANCE), [self.getRouteDistance(self.getShortestRoute(driver))])

This gave the following error:

KeyError: 1.8725031790578293

I'm not sure how this constraint should be defined for python-constraint: there's only one shortest distance value for each driver. Should I use a lambda function for this?

EDIT

I tried implementing a lambda version of this, however I don't seem to have the lambda syntax down. I've looked everywhere but can't seem to find what's wrong with this. Basically I replaced the last snippet of code (adding the constraint to limit the value of getRouteDistance(driver)) and instead put this:

for driver in driver_set:
    self.problem.addConstraint(lambda d: self.getRouteDistance(d) <= float(MAX_DISTANCE), driver)

But then I got this error (notice it's not called from the line I edited, it's from problem.getSolutions() which comes after):

File "allocation.py", line 130, in buildProblem
for solution in self.problem.getSolutions():
File "/Users/wadben/Documents/Dev/Python/sp-allocation/constraint.py", line 236, in getSolutions
return self._solver.getSolutions(domains, constraints, vconstraints)
File "/Users/wadben/Documents/Dev/Python/sp-allocation/constraint.py", line 529, in getSolutions
return list(self.getSolutionIter(domains, constraints, vconstraints))
File "/Users/wadben/Documents/Dev/Python/sp-allocation/constraint.py", line 506, in getSolutionIter
pushdomains):
File "/Users/wadben/Documents/Dev/Python/sp-allocation/constraint.py", line 939, in __call__
self.forwardCheck(variables, domains, assignments)))
File "/Users/wadben/Documents/Dev/Python/sp-allocation/constraint.py", line 891, in forwardCheck
if not self(variables, domains, assignments):
File "/Users/wadben/Documents/Dev/Python/sp-allocation/constraint.py", line 940, in __call__
return self._func(*parms)
TypeError: <lambda>() takes exactly 1 argument (3 given)

Has anyone else tried to do anything like this? I can't see why the constraint library wouldn't allow this.


The lambda form in Python provides a way to create anonymous (nameless) functions. The following two definitions are equivalent:

name = lambda arguments: expression

def name(arguments):
    return expression

Since the body of a lambda expression is itself an expression, the body may not contain any statements (like print).

When adding a function constraint to a problem, one must make sure that the function accepts as many arguments as there are variables. When the constraint is applied, each argument is passed a value (according to your convention, 1 for driver and passenger riding together, 0 otherwise) currently bound to the corresponding variable.

Since the number of variables associated with a given driver (equal to the number of passengers) may change, it would be sensible for the function in the constraint to accept an arbitrary number of arguments. This can be accomplished in Python using positional arguments. Thus, for a given set of driver variables (one uses the name driver_variables here), the constraint takes the following form:

problem.addConstraint(FunctionConstraint(lambda *values: ...), driver_variables)

The argument values binds to a list of values currently bound to corresponding variables in the driver_variables list. The lambda body should be written so as to do the following:

  1. Make a list to associate each value (0 or 1) in the values list with the corresponding variable in the driver_variables list;
  2. From this list, choose variables that have the value 1 (corresponding to passengers riding with the driver)--this list forms the route taken by the driver;
  3. Find the route distance (using get_route_distance function in this example) and compare against the maximum (maximum_distance).

One may use zip for (1) (the order of values is guaranteed to be the same as the order of variables), list comprehension for (2) and a simple function call and comparison for (3). This yields a function that takes the following lambda form:

lambda *values: get_route_distance([variable for variable, value in zip(driver_variables, values) if value == 1]) <= maximum_distance

It may prove beneficial for readability of code to write this function explicitly using def.

On a separate note, there is a bug in the code for defining driver_set above. The proper value for driver_set should be:

[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)]]

In the above example, since len(drivers) is 2, zip(passengers, [e1]*len(drivers)) is truncated to only two items. One way to fix this is to use the expression zip(passengers, [e1]*len(passengers)) for driver_set (and make a similar change for passenger_set). However, there is a more Pythonic way.

One may generate correct passenger and driver sets (passengers_variables and drivers_variables in this example) using the following statements:

passengers_variables = [[(passenger, driver) for driver in drivers] for passenger in passengers]
drivers_variables = [[(passenger, driver) for passenger in passengers] for driver in drivers]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜