source: coopr.pyomo/trunk/examples/pyomo/p-median/solver1.py @ 2201

Last change on this file since 2201 was 2201, checked in by wehart, 10 years ago

Update to Coopr to account for changes in PyUtilib? package names.

File size: 2.3 KB
Line 
1# Imports from Coopr and PyUtilib
2from coopr.pyomo import *
3from pyutilib.component.core import *
4from coopr.opt import *
5
6class MySolver(object):
7
8    # Declare that this is an IOptSolver plugin
9    implements(IOptSolver)
10
11    # Solve the specified problem and return
12    # a SolverResults object
13    def solve(self, instance, **kwds):
14        print "Starting greedy heuristic"
15        val, instance = self._greedy(instance)
16        n = value(instance.N)
17        # Setup results
18        results = SolverResults()
19        results.problem.name = instance.name
20        results.problem.sense = ProblemSense.minimize
21        results.problem.num_constraints = 1
22        results.problem.num_variables = n
23        results.problem.num_objectives = 1
24        results.solver.status = SolverStatus.ok
25        soln = results.solution.add()
26        soln.value = val
27        soln.status = SolutionStatus.feasible
28        for j in xsequence(n):
29            if instance.y[j].value is 1:
30                soln.variable[instance.y[j].name] = 1
31        return results
32
33    # Perform a greedy search
34    def _greedy(self, instance):
35        p = value(instance.P)
36        n = value(instance.N)
37        m = value(instance.M)
38        fixed=set()
39        # Initialize
40        for j in xsequence(n):
41            instance.y[j].value=0
42        # Greedily fix the next best facility
43        for i in xsequence(p):
44            best = None
45            ndx=j
46            for j in xsequence(n):
47                if j in fixed:
48                    continue
49                instance.y[j].value=1
50                # Compute value
51                val = 0.0
52                for kk in xsequence(m):
53                    tmp=copy.copy(fixed)
54                    tmp.add(j)
55                    tbest = None
56                    for jj in tmp:
57                        if tbest is None or instance.d[jj,kk].value < tbest:
58                            tbest = instance.d[jj,kk].value
59                    val += tbest
60                # Keep best greedy choice
61                if best is None or val < best:
62                    best=val
63                    ndx=j
64                instance.y[j].value=0
65            fixed.add(ndx)
66            instance.y[ndx].value=1
67        return [best, instance]
68
69# Register the solver with the name 'greedy'
70SolverRegistration("greedy", MySolver)
71
Note: See TracBrowser for help on using the repository browser.