Changeset 2215


Ignore:
Timestamp:
Jan 31, 2010 10:48:54 PM (10 years ago)
Author:
wehart
Message:

Creating an ASL solver interface for
optimizers based on the ASL solver interface.

Location:
coopr.plugins/trunk/coopr/plugins
Files:
2 added
2 edited
1 moved

Legend:

Unmodified
Added
Removed
  • coopr.plugins/trunk/coopr/plugins/mip/ASL.py

    r2208 r2215  
    1818import pyutilib.common
    1919import pyutilib.component.core
     20import pyutilib.component.config
    2021import mockmip
    2122import os
     
    2324
    2425
    25 class NLOPT(SystemCallSolver):
    26     """A generic NL optimizer
     26class ASL(SystemCallSolver):
     27    """A generic optimizer that uses the AMPL Solver Library to interface with applications.
    2728    """
    2829
     
    3132        # Call base constructor
    3233        #
    33         kwds["type"] = "nlopt"
     34        kwds["type"] = "asl"
    3435        SystemCallSolver.__init__(self, **kwds)
    3536        #
     
    4142
    4243    def executable(self):
    43         executable = pyutilib.services.registered_executable(options.solver)
     44        #
     45        # We register the ASL executables dynamically, since _any_ ASL solver could be
     46        # executed by this solver.
     47        #
     48        try:
     49            pyutilib.services.register_executable(self.options.solver)
     50        except pyutilib.component.config.OptionError:
     51            raise ValueError, "No solver option specified for ASL solver interface"
     52        executable = pyutilib.services.registered_executable(self.options.solver)
    4453        if executable is None:
    45             pyutilib.component.core.PluginGlobals.env().log.error("Could not locate the '%s' executable, which is required for solver %s" % (self.name, options.solver))
     54            pyutilib.component.core.PluginGlobals.env().log.error("Could not locate the '%s' executable, which is required for solver %s" % (self.options.solver, self.name))
    4655            self.enable = False
    4756            return None
     
    5362        #
    5463        if self.log_file is None:
    55            self.log_file = pyutilib.services.TempfileManager.create_tempfile(suffix="nlopt.log")
     64           self.log_file = pyutilib.services.TempfileManager.create_tempfile(suffix="_asl.log")
    5665        fname = problem_files[0].split(os.sep)[-1]
    5766        if '.' in fname:
     
    7281        env=copy.copy(os.environ)
    7382        if self._problem_format is None or self._problem_format == ProblemFormat.nl:
    74             if "debug" in self.options:
    75                 opts = []
    76             else:
    77                 opts = ["debug=2"]
     83            opt=[]
    7884            for key in self.options:
    7985                if key is 'solver':
     
    8490                    opt.append(key+"="+str(self.options[key]))
    8591           
    86             envstr = "%s_options" % executable
    87             env[envstr] = " ".join(opts)
     92            envstr = "%s_options" % self.options.solver
     93            env[envstr] = " ".join(opt)
    8894            proc = self._timer + " " + executable + " " + problem_files[0] + " -AMPL"
    8995        return pyutilib.misc.Bunch(cmd=proc, log_file=self.log_file, env=env)
    9096
    91     def process_logfile(self):
     97    def _default_results_format(self, prob_format):
     98        return ResultsFormat.sol
     99
     100    def Xprocess_soln_file(self,results):
    92101        """
    93         Process a logfile
     102        Process the SOL file
    94103        """
    95         results = SolverResults()
    96         #
    97         # Initial values
    98         #
    99         soln = results.solution.add()
    100         soln.objective['f'].value = None
    101         #
    102         # Process logfile
    103         #
    104         OUTPUT = open(self.log_file)
    105         output = "".join(OUTPUT.readlines())
    106         OUTPUT.close()
    107         #
    108         # Parse logfile lines
    109         #
    110         for line in output.split("\n"):
    111           tokens = re.split('[ \t]+',line.strip())
    112           if len(tokens) > 3 and tokens[0] == "ABORTED:":
    113              results.solver.status=SolverStatus.aborted
    114           elif len(tokens) == 5 and tokens[0] == "Final" and tokens[1] == "Solution:":
    115              soln.objective['f'].value = tokens[4]
    116              soln.status = SolutionStatus.optimal
    117           elif len(tokens) == 3 and tokens[0] == "LP" and tokens[1] == "value=":
    118              soln.objective['f'].value = tokens[2]
    119              soln.status=SolutionStatus.optimal
    120              if results.problem.sense == ProblemSense.minimize:
    121                 results.problem.lower_bound = tokens[2]
    122              else:
    123                 results.problem.upper_bound = tokens[2]
    124           elif len(tokens) == 2 and tokens[0] == "Bound:":
    125              if results.problem.sense == ProblemSense.minimize:
    126                 results.problem.lower_bound = tokens[1]
    127              else:
    128                 results.problem.upper_bound = tokens[1]
    129           elif len(tokens) == 3 and tokens[0] == "Created":
    130              results.solver.statistics.branch_and_bound.number_of_created_subproblems = tokens[1]
    131           elif len(tokens) == 3 and tokens[0] == "Bounded":
    132              results.solver.statistics.branch_and_bound.number_of_bounded_subproblems = tokens[1]
    133           elif len(tokens) == 2 and tokens[0] == "sys":
    134              results.solver.system_time=tokens[1]
    135           elif len(tokens) == 2 and tokens[0] == "user":
    136              results.solver.user_time=tokens[1]
    137           elif len(tokens) == 3 and tokens[0] == "Solving" and tokens[1] == "problem:":
    138              results.problem.name = tokens[2]
    139           elif len(tokens) == 4 and tokens[2] == "constraints:":
    140              results.problem.number_of_constraints = tokens[3]
    141           elif len(tokens) == 4 and tokens[2] == "variables:":
    142              results.problem.number_of_variables = tokens[3]
    143           elif len(tokens) == 4 and tokens[2] == "nonzeros:":
    144              results.problem.number_of_nonzeros = tokens[3]
    145           elif len(tokens) == 3 and tokens[1] == "Sense:":
    146              if tokens[2] == "minimization":
    147                 results.problem.sense = ProblemSense.minimize
    148              else:
    149                 results.problem.sense = ProblemSense.maximize
    150 
    151         if results.solver.status is SolverStatus.aborted:
    152            soln.optimality=SolutionStatus.unsure
    153         if soln.status is SolutionStatus.optimal:
    154            soln.gap=0.0
    155            if results.problem.sense == ProblemSense.minimize:
    156                 results.problem.lower_bound = soln.objective['f'].value
    157                 if "upper_bound" in dir(results.problem):
    158                     del results.problem.upper_bound
    159            else:
    160                 results.problem.upper_bound = soln.objective['f'].value
    161                 if "lower_bound" in dir(results.problem):
    162                     del results.problem.lower_bound
    163         if results.solver.status is SolverStatus.error:
    164            results.solution.delete(0)
    165         return results
    166 
    167     def process_soln_file(self,results):
    168         #print "HERE",self._results_format, self._results_format is ResultsFormat.sol, self.results_reader
    169         if self._results_format is ResultsFormat.sol:
    170            return
    171 
    172         #if os.path.exists(self.sol_file):
    173             #results_reader = ReaderFactory(ResultsFormat.sol)
    174             #results = results_reader(self.sol_file, results, results.solution(0))
    175             #return
    176 
    177         if not os.path.exists(self.soln_file):
    178            return
    179         soln = results.solution(0)
    180         results.problem.num_objectives=1
    181         tmp=[]
    182         flag=False
    183         INPUT = open(self.soln_file,"r")
    184         lp_flag=None
    185         for line in INPUT:
    186             tokens = re.split('[ \t]+',line.strip())
    187             if len(tokens) == 0 or (len(tokens) == 1 and tokens[0]==''):
    188                 continue
    189             if tokens[0] == "Objective":
    190                 continue
    191             #print "LINE",tokens
    192             if lp_flag is None:
    193                 lp_flag = (tokens[0] == "LP")
    194                 continue
    195             if tokens[0] == "Dual" and tokens[1] == "solution:":
    196                 # It looks like we've just been processing primal
    197                 # variables.
    198                 for (var,val) in tmp:
    199                     soln.variable[var] = val
    200                 tmp=[]
    201                 continue
    202             if len(tokens) < 3:
    203                 print "ERROR", line,tokens
    204             tmp.append( (tokens[0],eval(tokens[2])) )
    205         if lp_flag:
    206             for (var,val) in tmp:
    207                 soln.constraint[var].dual = val
    208         else:
    209             for (var,val) in tmp:
    210                 soln.variable[var] = val
    211         INPUT.close()
     104        if os.path.exists(self.sol_file):
     105            results_reader = ReaderFactory(ResultsFormat.sol)
     106            results = results_reader(self.sol_file, results, results.solution(0))
     107            return
    212108
    213109
    214 class MockPICO(PICO,mockmip.MockMIP):
    215     """A Mock PICO solver used for testing
     110class MockASL(ASL,mockmip.MockMIP):
     111    """A Mock ASL solver used for testing
    216112    """
    217113
    218114    def __init__(self, **kwds):
    219115        try:
    220            PICO.__init__(self,**kwds)
     116           ASL.__init__(self,**kwds)
    221117        except pyutilib.common.ApplicationError: #pragma:nocover
    222118           pass                        #pragma:nocover
    223         mockmip.MockMIP.__init__(self,"pico")
     119        mockmip.MockMIP.__init__(self,"asl")
    224120
    225121    def available(self, exception_flag=True):
    226         return PICO.available(self,exception_flag)
     122        return ASL.available(self,exception_flag)
    227123
    228124    def create_command_line(self,executable,problem_files):
    229         command = PICO.create_command_line(self,executable,problem_files)
     125        command = ASL.create_command_line(self,executable,problem_files)
    230126        mockmip.MockMIP.create_command_line(self,executable,problem_files)
    231127        return command
     
    238134
    239135
    240 pyutilib.services.register_executable(name="pico")
    241 SolverRegistration("pico", PICO)
    242 SolverRegistration("_mock_pico", MockPICO)
     136SolverRegistration("asl", ASL)
     137SolverRegistration("_mock_asl", MockASL)
  • coopr.plugins/trunk/coopr/plugins/mip/__init__.py

    r2201 r2215  
    1616from GLPK import GLPK, MockGLPK
    1717from CPLEX import CPLEX, MockCPLEX
    18 #from NLOPT import NLOPT, MockNLOPT
     18from ASL import ASL, MockASL
    1919#from NLWRITE import NLWRITE
    2020
  • coopr.plugins/trunk/coopr/plugins/tests/mip/test_factory.py

    r2201 r2215  
    6666        ans = coopr.opt.SolverFactory()
    6767        ans.sort()
    68         tmp = ['_mock_cbc', '_mock_cplex', '_mock_glpk', '_mock_pico', 'cbc', 'cplex', 'glpk', 'pico', 'stest']
     68        tmp = ['_mock_asl', '_mock_cbc', '_mock_cplex', '_mock_glpk', '_mock_pico', 'cbc', 'cplex', 'glpk', 'pico', 'stest', 'asl']
    6969        tmp.sort()
    7070        self.failUnless(set(tmp) <= set(ans), msg="Set %s is not a subset of set %s" %(tmp,ans))
Note: See TracChangeset for help on using the changeset viewer.