source: coopr.opt/trunk/coopr/opt/base/solver.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: 8.9 KB
Line 
1#  _________________________________________________________________________
2#
3#  Coopr: A COmmon Optimization Python Repository
4#  Copyright (c) 2008 Sandia Corporation.
5#  This software is distributed under the BSD License.
6#  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
7#  the U.S. Government retains certain rights in this software.
8#  For more information, see the Coopr README.txt file.
9#  _________________________________________________________________________
10
11__all__ = ['ISolverRegistration', 'SolverRegistration',
12            'IOptSolver', 'OptSolver', 'SolverFactory']
13
14import os
15import sys
16from convert import convert_problem
17from formats import ResultsFormat, ProblemFormat
18import results
19from coopr.opt.results import SolverResults, SolverStatus
20
21from pyutilib.enum import Enum
22from pyutilib.component.core import *
23from pyutilib.component.config import *
24import pyutilib.common
25import pyutilib.misc
26
27import time
28
29
30class ISolverRegistration(Interface):
31    """An interface for accessing"""
32
33    def create(self, name=None):
34        """Create a solver, optionally specifying the name"""
35
36    def type(self):
37        """The type of solver supported by this service"""
38
39
40class SolverRegistration(Plugin):
41
42    implements(ISolverRegistration)
43
44    def __init__(self, type, cls):
45        self.name = type
46        self._type = type
47        self._cls = cls
48
49    def type(self):
50        return self._type
51
52    def create(self, **kwds):
53        return self._cls(**kwds)
54
55
56def SolverFactory(solver_name=None, **kwds):
57    ep = ExtensionPoint(ISolverRegistration)
58    if solver_name is None:
59        names = map(lambda x:x.name, ep())
60        names.sort()
61        return names
62    service = ep.service(solver_name)
63    if service is None:
64        ##print "Unknown solver=" + solver_name + " - no plugin registered for this solver type"
65        return None
66    else:
67        return ep.service(solver_name).create(**kwds)
68
69
70class IOptSolver(Interface):
71    """Interface class for creating optimization solvers"""
72
73    def available(self, exception_flag=True):
74        """Determine if this optimizer is available."""
75
76    def solve(self, *args, **kwds):
77        """Perform optimization and return an SolverResults object."""
78
79    def reset(self):
80        """Reset the state of an optimizer"""
81
82    def set_options(self, istr):
83        """Set the options in the optimizer from a string."""
84
85
86class OptSolver(ManagedPlugin):
87    """A generic optimization solver"""
88
89    implements(IOptSolver)
90
91    def __init__(self, **kwds):
92        """ Constructor """
93        ManagedPlugin.__init__(self,**kwds)
94        #
95        # The 'type' is the class type of the solver instance
96        #
97        if "type" in kwds:
98            self.type = kwds["type"]
99        else:                           #pragma:nocover
100            raise PluginError, "Expected option 'type' for OptSolver constructor"
101        #
102        # The 'name' is either the class type of the solver instance, or a
103        # assigned name.
104        #
105        if "name" in kwds:
106            self.name = kwds["name"]
107        else:
108            self.name = self.type
109        if "doc" in kwds:
110            self._doc = kwds["doc"]
111        else:
112            if self.type is None:           # pragma:nocover
113                self._doc = ""
114            elif self.name == self.type:
115                self._doc = "%s OptSolver" % self.name
116            else:
117                self._doc = "%s OptSolver (type %s)" % (self.name,self.type)
118        declare_option("options", cls=DictOption, section=self.name, doc=self._doc)
119        if 'options' in kwds:
120            for key in kwds['options']:
121                setattr(self.options,key,kwds['options'][key])
122        self._symbol_map=None
123        self._problem_format=None
124        self._results_format=None
125        self._valid_problem_formats=[]
126        self._valid_result_formats={}
127        self.results_reader=None
128        self.problem=None
129        self._assert_available=False
130        self._report_timing = False # timing statistics are always collected, but optionally reported.
131
132        # a fairly universal solver feature, at least when dealing
133        # with problems containing integers. promoted to a base class
134        # attribute to allow each sub-solver to automatically write
135        # out the appropriate option. default is None, meaning
136        # unassigned. currently not allowing the mipgap to be over-ridden
137        # via an argument to the solve() method, mainly because we don't
138        # want to persistence of this parameter to be violated.
139        self.mipgap = None
140
141    def available(self, exception_flag=True):
142        """ True if the solver is available """
143        if self._assert_available:
144            return True
145        tmp = self.enabled()
146        if exception_flag and not tmp:
147            raise pyutilib.common.ApplicationError, "OptSolver plugin %s is disabled" % self.name
148        return tmp
149
150    def warm_start_capable(self):
151       """ True is the solver can accept a warm-start solution """
152       return False
153
154    def solve(self, *args, **kwds):
155        """ Solve the problem """
156        initial_time = time.time()
157        self._presolve(*args, **kwds)
158        presolve_completion_time = time.time()
159        self._apply_solver()
160        solve_completion_time = time.time()
161        result = self._postsolve()
162        postsolve_completion_time = time.time()
163        result.symbol_map = self._symbol_map
164        if self._report_timing is True:
165           print "Presolve time="+str(presolve_completion_time-initial_time)
166           print "Solve time="+str(solve_completion_time - presolve_completion_time)
167           print "Postsolve time="+str(postsolve_completion_time-solve_completion_time)
168        return result
169
170    def _presolve(self, *args, **kwds):
171        self.available()
172        self._timelimit=None
173        self.tee=None
174        for key in kwds:
175          if key == "pformat":
176             self._problem_format=kwds[key]
177          elif key == "rformat":
178             self._results_format=kwds[key]
179          elif key == "logfile":
180             self.log_file=kwds[key]
181          elif key == "solnfile":
182             self.soln_file=kwds[key]
183          elif key == "timelimit":
184             self._timelimit=kwds[key]
185          elif key == "tee":
186             self.tee=kwds[key]
187          elif key == "options":
188             self.set_options(kwds[key])
189          elif key == "available":
190             self._assert_available=True
191          else:
192             raise ValueError, "Unknown option="+key+" for solver="+self.type
193
194        (self._problem_files,self._problem_format,self._symbol_map) = self._convert_problem(args, self._problem_format, self._valid_problem_formats)
195        if self._results_format is None:
196           self._results_format= self._default_results_format(self._problem_format)
197        #
198        # Disabling this check for now.  A solver doesn't have just _one_ results format.
199        #
200        #if self._results_format not in self._valid_result_formats[self._problem_format]:
201        #   raise ValueError, "Results format `"+str(self._results_format)+"' cannot be used with problem format `"+str(self._problem_format)+"' in solver "+self.name
202        if self._results_format == ResultsFormat.soln:
203            self.results_reader = None
204        else:
205            self.results_reader = results.ReaderFactory(self._results_format)
206
207    def _apply_solver(self):
208        """The routine that performs the solve"""
209        raise NotImplementedError       #pragma:nocover
210       
211    def _postsolve(self):
212        """The routine that does solve post-processing"""
213        return self.results
214       
215    def _convert_problem(self, args, pformat, valid_pformats):
216        #
217        # If the problem is not None, then we assume that it has already
218        # been appropriately defined.  Either it's a string name of the
219        # problem we want to solve, or its a functor object that we can
220        # evaluate directly.
221        #
222        if self.problem is not None:
223           return (self.problem,ProblemFormat.colin_optproblem,None)
224        #
225        # Otherwise, we try to convert the object explicitly.
226        #
227        return convert_problem(args, pformat, valid_pformats)
228
229    def _default_results_format(self, prob_format):
230        """Returns the default results format for different problem
231            formats.
232        """
233        return ResultsFormat.results
234
235    def reset(self):
236        """
237        Reset the state of the solver
238        """
239        pass
240
241    def set_options(self, istr):
242        istr = istr.strip()
243        if istr is '':
244            return
245        tokens = pyutilib.misc.quote_split('[ ]+',istr)
246        for token in tokens:
247            index = token.find('=')
248            if index is -1:
249                raise ValueError, "Solver options must have the form option=value"
250            try:
251                val = eval(token[(index+1):])
252            except:
253                val = token[(index+1):]
254            setattr(self.options, token[:index], val)
255           
256           
257   
Note: See TracBrowser for help on using the repository browser.