1 | # Imports from Coopr and PyUtilib |
---|

2 | from coopr.pyomo import * |
---|

3 | from pyutilib.plugin.core import * |
---|

4 | from coopr.opt import * |
---|

5 | import random |
---|

6 | import copy |
---|

7 | |
---|

8 | class MySolver(object): |
---|

9 | |
---|

10 | # Declare that this is an IOptSolver plugin |
---|

11 | implements(IOptSolver) |
---|

12 | |
---|

13 | # Solve the specified problem and return |
---|

14 | # a SolverResults object |
---|

15 | def solve(self, instance, **kwds): |
---|

16 | print "Starting random heuristic" |
---|

17 | val, sol = self._random(instance) |
---|

18 | n = value(instance.N) |
---|

19 | # Setup results |
---|

20 | results = SolverResults() |
---|

21 | results.problem.name = instance.name |
---|

22 | results.problem.sense = ProblemSense.minimize |
---|

23 | results.problem.num_constraints = 1 |
---|

24 | results.problem.num_variables = n |
---|

25 | results.problem.num_objectives = 1 |
---|

26 | results.solver.status = SolverStatus.ok |
---|

27 | soln = results.solution.add() |
---|

28 | soln.value = val |
---|

29 | soln.status = SolutionStatus.feasible |
---|

30 | for j in range(1,n+1): |
---|

31 | soln.variable[instance.y[j].name] = sol[j-1] |
---|

32 | # Return results |
---|

33 | return results |
---|

34 | |
---|

35 | # Perform a random search |
---|

36 | def _random(self, instance): |
---|

37 | sol = [0]*instance.N.value |
---|

38 | for j in range(0,instance.P.value): |
---|

39 | sol[j] = 1 |
---|

40 | # Generate 100 random solutions, and keep the best |
---|

41 | best = None |
---|

42 | best_sol = [] |
---|

43 | for kk in range(100): |
---|

44 | random.shuffle(sol) |
---|

45 | # Compute value |
---|

46 | val=0.0 |
---|

47 | for j in range(1,instance.M.value+1): |
---|

48 | val += min([instance.d[i,j].value for i in range(1,instance.N.value+1) if sol[i-1] == 1]) |
---|

49 | if best is None or val < best: |
---|

50 | best=val |
---|

51 | best_sol=copy.copy(sol) |
---|

52 | return [best, best_sol] |
---|

53 | |
---|

54 | # Register the solver with the name 'random' |
---|

55 | SolverRegistration("random", MySolver) |
---|

56 | |
---|