Changeset 1161


Ignore:
Timestamp:
Feb 13, 2009 1:17:09 AM (11 years ago)
Author:
wehart
Message:

I'm breaking coopr.opt with this commit, but the reorganization is
so extensive that I need to archive the intermediate
changes.

With luck, I'll have Coopr back on its feet tomorrow.

Location:
trunk/coopr/opt
Files:
11 added
1 deleted
13 edited
3 moved

Legend:

Unmodified
Added
Removed
  • trunk/coopr/opt/__init__.py

    r1010 r1161  
    1212#import mip
    1313import solvers
     14#
     15# Plugins
     16#
     17import mip
     18import converter
     19import writer
     20import reader
  • trunk/coopr/opt/base/__init__.py

    r1010 r1161  
    99#  _________________________________________________________________________
    1010
     11import opt_config
     12
    1113from solver import *
    1214from solution import *
     
    1416from problem import *
    1517from formats import *
    16 from factory import *
    17 from OS import *
    18 from sol import *
  • trunk/coopr/opt/base/convert.py

    r1155 r1161  
    99#  _________________________________________________________________________
    1010
     11__all__ = ['IProblemConverter', 'convert_problem']
    1112
    12 import tempfile
    1313import copy
    1414import os
    1515from formats import ProblemFormat
    16 import factory
    17 import pyutilib
    18 import coopr
    1916from pyutilib._exceptions import ApplicationError
    20 
    21 class Converter(object):
    22 
    23    registry = {}
     17from pyutilib.plugin import *
    2418
    2519
    26 def _apply_pyomo_conversion(*args):
    27     """
    28     Generate a NL or LP file from Pyomo, and then do subsequent
    29     conversions.
    30     """
    31     if args[1] is ProblemFormat.cpxlp:
    32        [problem_file_descriptor, problem_filename] = tempfile.mkstemp(suffix = '.pyomo.lp')
    33        os.close(problem_file_descriptor)
    34        args[2].write(filename=problem_filename,format=ProblemFormat.cpxlp)
    35        return problem_filename
    36     elif args[1] is ProblemFormat.mps:
    37        [problem_file_descriptor, problem_filename] = tempfile.mkstemp(suffix = '.pyomo.nl')
    38        os.close(problem_file_descriptor)
    39        args[2].write(filename=problem_filename,format=ProblemFormat.nl)
    40        ans = _apply_pico_convert(ProblemFormat.nl,ProblemFormat.mps,problem_filename)
    41        os.remove(problem_filename)
    42        return ans
    43     elif args[1] is ProblemFormat.nl:
    44        [problem_file_descriptor, problem_filename] = tempfile.mkstemp(suffix = '.pyomo.nl')
    45        os.close(problem_file_descriptor)
    46        args[2].write(filename=problem_filename,format=ProblemFormat.nl)
    47        return problem_filename
     20class IProblemConverter(object):
    4821
     22    def can_convert(self, from_type, to_type):
     23        """Returns true if this object supports the specified conversion"""
    4924
    50 def _apply_glpsol(*args):
    51     """
    52     Run the external glpsol utility to convert
    53     """
    54     if not isinstance(args[2],basestring):
    55        raise ValueError, "Can only apply glpsol to convert file data"
    56     if factory.config().glpsol is None or \
    57        not os.path.exists(factory.config().glpsol) or \
    58        not os.access(factory.config().glpsol,os.X_OK):
    59        raise ApplicationError, "The 'glpsol' application cannot be found"
    60     cmd = factory.config().glpsol+" --math"
    61     #
    62     # MPS->LP conversion is ignored in coverage because it's not being
    63     #   used; instead, we're using pico_convert for this conversion
    64     #
    65     if args[1] == ProblemFormat.mps: #pragma:nocover
    66        ofile="glpsol.mps"
    67        cmd = cmd + " --check --wfreemps "+ofile
    68     elif args[1] == ProblemFormat.cpxlp:
    69        ofile="glpsol.lp"
    70        cmd = cmd + " --check --wcpxlp "+ofile
    71     if len(args[2:]) == 1:
    72        cmd = cmd+" "+args[2]
    73     else:
    74        #
    75        # Create a temporary model file, since GLPSOL can only
    76        # handle one input file
    77        #
    78        OUTPUT=open("glpsol.mod","w")
    79        flag=False
    80        #
    81        # Read the model file
    82        #
    83        INPUT= open(args[2])
    84        for line in INPUT:
    85          line = line.strip()
    86          if line == "data;":
    87             raise ValueError, "Problem composing mathprog model and data files - mathprog file already has data in it!"
    88          if line != "end;":
    89             print >>OUTPUT, line
    90        INPUT.close()
    91        print >>OUTPUT, "data;"
    92        #
    93        # Read the data files
    94        #
    95        for file in args[3:]:
    96          INPUT= open(file)
    97          for line in INPUT:
    98            line = line.strip()
    99            if line != "end;" and line != "data;":
    100               print >>OUTPUT, line
    101          INPUT.close()
    102        print >>OUTPUT, "end;"
    103        OUTPUT.close()
    104        cmd = cmd+" glpsol.mod"
    105     pyutilib.run_command(cmd)
    106     if not os.path.exists(ofile):       #pragma:nocover
    107        raise pyutilib.ApplicationError, "Problem launching 'glpsol' to create "+ofile
    108     if os.path.exists("glpsol.mod"):
    109        os.remove("glpsol.mod")
    110     return ofile
    111 
    112 
    113 def _apply_pico_convert(*args):
    114     """
    115     Run the external pico_convert utility
    116     """
    117     if len(args) != 3:
    118        raise ValueError, "Cannot apply pico_convert with more than one filename or model"
    119     try:
    120        pico_convert_cmd = getattr(factory.config(),"pico_convert")
    121     except AttributeError:
    122        raise ApplicationError, "The 'pico_convert' application cannot be found"
    123     if pico_convert_cmd is None:   #pragma:nocover
    124        raise ApplicationError, "The 'pico_convert' application cannot be found"
    125     if not os.path.exists(pico_convert_cmd) or \
    126        not os.access(pico_convert_cmd,os.X_OK):
    127        raise ApplicationError, "The 'pico_convert' application is not an executable: "+pico_convert_cmd
    128     target=str(args[1])
    129     if target=="cpxlp":
    130        target="lp"
    131     # NOTE: if you have an extra "." in the suffix, the pico_convert program fails to output to the correct filename.
    132     [output_file_descriptor, output_filename]=tempfile.mkstemp(suffix = 'pico_convert.' + target, dir = factory.config().tempdir)
    133     os.close(output_file_descriptor)
    134     if not isinstance(args[2],basestring):
    135        fname=factory.config().tempdir+os.sep+"pico_convert."+str(args[0])
    136        args[2].write(filename=fname, format=args[1])
    137        cmd = pico_convert_cmd +" --output="+output_filename+" "+target+" "+fname
    138     else:
    139        cmd = pico_convert_cmd +" --output="+output_filename+" "+target
    140        for item in args[2:]:
    141          if not os.path.exists(item):
    142             raise ValueError, "File "+item+" does not exist!"
    143          cmd = cmd + " "+item
    144     print "Running command: "+cmd
    145     pyutilib.run_command(cmd)
    146     if not os.path.exists(output_filename):       #pragma:nocover
    147        raise pyutilib.ApplicationError, \
    148                     "Problem launching 'pico_convert' to create "+output_filename
    149     return output_filename
     25    def convert(self, from_type, to_type):
     26        """Convert an instance of one type into another"""
    15027
    15128
     
    21895    raise ValueError, "No conversion possible" 
    21996
    220 
    221 
    222 ##
    223 ## Register conversions
    224 ##
    225 Converter.registry[ProblemFormat.mod, ProblemFormat.cpxlp] = _apply_glpsol
    226 Converter.registry[ProblemFormat.mod, ProblemFormat.mps] = _apply_glpsol
    227 Converter.registry[ProblemFormat.nl, ProblemFormat.cpxlp] = _apply_pico_convert
    228 Converter.registry[ProblemFormat.nl, ProblemFormat.mps] = _apply_pico_convert
    229 Converter.registry[ProblemFormat.mps, ProblemFormat.cpxlp] = _apply_pico_convert
    230 Converter.registry[ProblemFormat.cpxlp, ProblemFormat.mps] = _apply_pico_convert
    231 Converter.registry[ProblemFormat.pyomo, ProblemFormat.nl] = _apply_pyomo_conversion
    232 Converter.registry[ProblemFormat.pyomo, ProblemFormat.cpxlp] = _apply_pyomo_conversion
    233 Converter.registry[ProblemFormat.pyomo, ProblemFormat.mps] = _apply_pyomo_conversion
    234 
  • trunk/coopr/opt/base/formats.py

    r1010 r1161  
    1212# The formats that are supported by Pyomo
    1313#
    14 import pyutilib.tpl.enum
     14__all__ = ['ProblemFormat', 'ResultsFormat']
     15
     16from pyutilib.tpl.enum import Enum
    1517
    1618#
     
    2729#                   command, or provide a runtime optimization problem)
    2830#
    29 ProblemFormat = pyutilib.tpl.enum.Enum('colin', 'pyomo', 'cpxlp', 'nl', 'mps', 'mod', 'lpxlp', 'ospl', 'colin_optproblem')
     31ProblemFormat = Enum('colin', 'pyomo', 'cpxlp', 'nl', 'mps', 'mod', 'lpxlp', 'ospl', 'colin_optproblem')
    3032
    3133#
     
    3537# results - A coopr.opt.SolverResults object
    3638#
    37 ResultsFormat = pyutilib.tpl.enum.Enum('sol', 'osrl', 'log', 'results')
     39ResultsFormat = Enum('sol', 'osrl', 'log', 'results')
    3840
  • trunk/coopr/opt/base/opt_config.py

    r1026 r1161  
    99#  _________________________________________________________________________
    1010
     11import pyutilib.plugin
     12import pyutilib.plugin.pyutilib
    1113
    12 import pyutilib
     14pyutilib.plugin.PluginGlobals.push_env( pyutilib.plugin.PluginEnvironment("coopr.opt") )
    1315
     16#
     17# Create plugins, which are automatically registered in the 'coopr.opt'
     18# namespace.
     19#
     20pyutilib.plugin.pyutilib.ExternalExecutable(name="PICO")
     21pyutilib.plugin.pyutilib.ExternalExecutable(name="pico_convert")
     22pyutilib.plugin.pyutilib.ExternalExecutable(name="glpsol")
     23pyutilib.plugin.pyutilib.ExternalExecutable(name="ampl")
     24pyutilib.plugin.pyutilib.ExternalExecutable(name="timer")
    1425
    15 class OptConfigPlugin(pyutilib.ConfigPlugin):
    16     """
    17     Derived Config plugin that adds options for coopr.opt external
    18     utilities.
    19     """
    20 
    21     def __init__(self):
    22         """
    23         Constructor that tries to find executables
    24         """
    25         pyutilib.ConfigPlugin.__init__(self)
    26         self.pico_convert_default = \
    27                 pyutilib.search_file("pico_convert",
    28                                 implicitExt=pyutilib.executable_extension,
    29                                 executable=True)
    30         self.glpsol_default = \
    31                 pyutilib.search_file("glpsol",
    32                                 implicitExt=pyutilib.executable_extension,
    33                                 executable=True)
    34         self.ampl_default = \
    35                 pyutilib.search_file("ampl",
    36                                 implicitExt=pyutilib.executable_extension,
    37                                 executable=True)
    38         self.timer_default = \
    39                 pyutilib.search_file("timer",
    40                                 implicitExt=pyutilib.executable_extension,
    41                                 executable=True)
    42 
    43     def add_options(self, parser):
    44         """
    45         Add options
    46         """
    47         parser.add_option(
    48             "--pico_convert", action="store", dest="pico_convert",
    49             default=self.pico_convert_default,
    50             help="The filename of the 'pico_convert' executable")
    51         parser.add_option(
    52             "--glpsol", action="store", dest="glpsol",
    53             default=self.glpsol_default,
    54             help="The filename of the 'glpsol' executable")
    55         parser.add_option(
    56             "--ampl", action="store", dest="ampl",
    57             default=self.ampl_default,
    58             help="The filename of the 'ampl' executable")
    59         parser.add_option(
    60             "--timer", action="store", dest="timer",
    61             default=self.timer_default,
    62             help="The filename of the 'timer' executable")
    63         return "opt",["pico_convert","glpsol","timer","ampl"]
    64 
    65     def configure(self, options, config):
    66         """
    67         Update the configuration object with option data
    68         """
    69         config.pico_convert = options.pico_convert
    70         config.glpsol = options.glpsol
    71         config.ampl = options.ampl
    72         config.timer = options.timer
    73 
  • trunk/coopr/opt/base/opt_globals.py.old

    r1160 r1161  
    1111
    1212import opt_config
    13 import pyutilib
     13import pyutilib.plugin
    1414
    1515
     
    2121  _ReaderFactory = pyutilib.Factory()
    2222  _WriterFactory = pyutilib.Factory()
    23   _SolverFactory = pyutilib.Factory()
     23  #_SolverFactory = pyutilib.Factory()
    2424
    25   _config = pyutilib.config()
     25  #_config = pyutilib.plugin.SimpleApplication("coopr")
    2626
    27 
    28 Globals._config.add_plugin(opt_config.OptConfigPlugin())
  • trunk/coopr/opt/base/problem.py

    r1010 r1161  
    99#  _________________________________________________________________________
    1010
    11 class AbstractProblemWriter(object):
     11__all__ = [ 'IWriterRegistration', 'WriterRegistration',
     12            'IProblemWriter', 'ProblemWriter',
     13            'WriterFactory' ]
     14
     15from pyutilib.plugin import *
     16
     17
     18class IWriterRegistration(Interface):
     19    """An interface for accessing"""
     20
     21    def create(self, name=None):
     22        """Create a writer, optionally specifying the name"""
     23
     24    def type(self):
     25        """The type of writer supported by this service"""
     26
     27
     28def WriterFactory(name=None):
     29    ep = ExtensionPoint(IWriterRegistration)
     30    ep.service(name).create(name)
     31
     32
     33class WriterRegistration(Plugin):
     34
     35    implements(IWriterRegistration)
     36
     37    def __init__(self, type, cls):
     38        self.name = type
     39        self._type = type
     40        self._cls = cls
     41
     42    def type(self):
     43        return self._type
     44
     45    def create(self, name=None):
     46        if name is None:
     47            return self._cls()
     48        return self._cls(name=name)
     49
     50
     51class IProblemWriter(Interface):
     52    """Interface for classes that can write optimization problems."""
     53
     54
     55class AbstractProblemWriter(Plugin):
     56    """Base class that can write optimization problems."""
     57
     58    implements(IProblemWriter)
    1259
    1360    def __init__(self, problem_format): #pragma:nocover
     
    2067        NotImplemented
    2168
     69
  • trunk/coopr/opt/base/results.py

    r1073 r1161  
    99#  _________________________________________________________________________
    1010
    11 class AbstractResultsReader(object):
     11__all__ = [ 'IReaderRegistration', 'ReaderRegistration',
     12            'IResultsReader', 'ResultsReader',
     13            'ReaderFactory' ]
     14
     15from pyutilib.plugin import *
     16
     17
     18class IReaderRegistration(Interface):
     19    """An interface for accessing"""
     20
     21    def create(self, name=None):
     22        """Create a reader, optionally specifying the name"""
     23
     24    def type(self):
     25        """The type of reader supported by this service"""
     26
     27
     28def ReaderFactory(name=None):
     29    ep = ExtensionPoint(IReaderRegistration)
     30    ep.service(name).create(name)
     31
     32
     33class ReaderRegistration(Plugin):
     34
     35    implements(IReaderRegistration)
     36
     37    def __init__(self, type, cls):
     38        self.name = type
     39        self._type = type
     40        self._cls = cls
     41
     42    def type(self):
     43        return self._type
     44
     45    def create(self, name=None):
     46        if name is None:
     47            return self._cls()
     48        return self._cls(name=name)
     49
     50
     51class IResultsReader(Interface):
     52    """Interface for classes that can read optimization results."""
     53
     54
     55class AbstractResultsReader(Plugin):
     56    """Base class that can read optimization results."""
     57
     58    implements(IResultsReader)
    1259
    1360    def __init__(self, results_format):
  • trunk/coopr/opt/base/solver.py

    r1156 r1161  
    99#  _________________________________________________________________________
    1010
     11__all__ = ['ISolverRegistration', 'SolverRegistration',
     12            'IOptSolver', 'OptSolver',
     13            'SolverFactory']
     14
    1115import os
    1216import sys
    1317import pyutilib
    14 import factory
    1518from convert import convert_problem
    1619from formats import ResultsFormat, ProblemFormat
    1720from pyutilib.tpl.enum import Enum
     21import results
    1822from solution import SolverResults, SolverStatus
     23import pyutilib.plugin
    1924
    20 class OptSolver:
     25
     26class ISolverRegistration(pyutilib.plugin.Interface):
     27    """An interface for accessing"""
     28
     29    def create(self, name=None):
     30        """Create a solver, optionally specifying the name"""
     31
     32    def type(self):
     33        """The type of solver supported by this service"""
     34
     35
     36class SolverRegistration(pyutilib.plugin.Plugin):
     37
     38    implements(ISolverRegistration)
     39
     40    def __init__(self, type, cls):
     41        self.name = type
     42        self._type = type
     43        self._cls = cls
     44
     45    def type(self):
     46        return self._type
     47
     48    def create(self, name=None):
     49        if name is None:
     50            return self._cls()
     51        return self._cls(name=name)
     52
     53
     54def SolverFactory(name=None):
     55    ep = ExtensionPoint(ISolverRegistration)
     56    ep.service(name).create(name)
     57
     58
     59class IOptSolver(pyutilib.plugin.Interface):
     60    """Interface class for creating optimization solvers"""
     61
     62
     63class OptSolver(pyutilib.plugin.Plugin):
    2164    """A generic optimization solver"""
    2265
    23     def __init__(self, name, options = []):
     66    pyutilib.plugin.implements(IOptSolver)
     67
     68    def __init__(self, **kwds):
    2469        """ Constructor """
    25         self.name = name
    26         self.options = options
     70        if "type" in kwds:
     71            self.type = kwds["type"]
     72        else:
     73            raise PluginError, "Expected option 'type' for OptSolver constructor"
     74        if "name" in kwds:
     75            self.name = kwds["name"]
     76        else:
     77            self.name = self.type
     78        if "doc" in kwds:
     79            self._doc = kwds["doc"]
     80        else:
     81            if self.type is None:
     82                self._doc = ""
     83            elif self.name == self.type:
     84                self._doc = "%s OptSolver" % self.name
     85            else:
     86                self._doc = "%s OptSolver (type %s)" % (self.name,self.type)
     87        add_option("options", cls=DictOption, section=self.type, doc=self._doc)
    2788        self._problem_format=None
    2889        self._results_format=None
     
    3495    def available(self, exception_flag=True):
    3596        """ True if the solver is available """
    36         return True
     97        return self.enable
    3798
    3899    def solve(self, *args, **kwds):
     
    59120        if self._results_format not in self._valid_result_formats[self._problem_format]:
    60121           raise ValueError, "Results format `"+str(self._results_format)+"' cannot be used with problem format `"+str(self._problem_format)+"' in solver "+self.name
    61         self.results_reader = factory.ReaderFactory(self._results_format)
     122        self.results_reader = results.ReaderFactory(self._results_format)
    62123        return self.actualSolve(problem_filename, timelimit=timelimit)       
    63124
     
    92153        pass
    93154
    94 
    95 class SystemCallSolver(OptSolver):
    96     """ A generic command line solver """
    97 
    98     def __init__(self, name, path = "", keepFiles = False, options = []):
    99         """ Constructor """
    100         self.executable=None
    101         OptSolver.__init__(self, name, options=options)
    102         self.keepFiles = keepFiles
    103         self.soln_file=None
    104         self.log_file=None
    105         self.tmpDir = factory.config().tempdir
    106         self._timelimit=None
    107 
    108     def available(self, exception_flag=True):
    109         """ True if the solver is available """
    110         OptSolver.available(self,exception_flag)
    111         if factory.config().timer is not None:
    112           if not os.path.exists(factory.config().timer) or \
    113              not os.access(factory.config().timer,os.X_OK):
    114              raise ApplicationError, "Bad path for the 'timer' application: "+factory.config().timer
    115           self._timer=factory.config().timer
    116         else:
    117           self._timer=""
    118         ans=self._executable(self.executable)
    119         if ans is None:
    120            if exception_flag:
    121               if self.executable is None:
    122                  raise pyutilib.ApplicationError, "No executable found for solver `"+self.name+"'"
    123               else:
    124                  raise pyutilib.ApplicationError, "Bad path for application `PICO' used by solver "+self.name+"': "+self.executable
    125            self.executable=ans
    126            return False
    127         self.executable=ans
    128         return True
    129 
    130     def create_command_line(self,executable,problem_file):
    131         """
    132         TODO
    133         """
    134         raise NotImplementedError       #pragma:nocover
    135 
    136     def process_logfile(self):
    137         """
    138         TODO
    139         """
    140         raise NotImplementedError       #pragma:nocover
    141 
    142     def process_other_data(self,results):
    143         """
    144         TODO
    145         """
    146         pass        #pragma:nocover
    147 
    148     def _executable(self, command):
    149         """
    150         Checks that the solver command is executable,
    151         And returns the actual path to it.
    152         """
    153         if command is None:
    154            return command
    155         if os.path.isabs(command):
    156            if os.access(command, os.X_OK):
    157               return command
    158         for path in os.environ.get("PATH", []).split(os.pathsep):
    159           if os.access(os.path.join(path, command), os.X_OK):
    160              return os.path.join(path, command)
    161         return None
    162 
    163     def remove_files(self):
    164         """
    165         Remove files after optimization.
    166         Includes the problem, log, and solution files.       
    167         NOTE: this might need to be over-ridden for solvers
    168         that generate/use files other than the problem file and
    169         log file.
    170         """
    171 
    172         #if pyutilib.debug("verbose"):
    173         #   print "Removing files"
    174 
    175         # assume the files exist, if you got this far in the solution process.
    176         if self.log_file is not None:
    177            try:
    178               os.remove(self.log_file)
    179            except OSError:
    180               print "Failed to remove log file=" + self.log_file
    181 
    182         if self.soln_file is not None:
    183            try:
    184               os.remove(self.soln_file)
    185            except OSError:
    186               print "Failed to remove solution file=" + self.soln_file                     
    187 
    188     def actualSolve(self, problem_filename, timelimit):
    189         """
    190         Solve a well formulated problem
    191         """
    192         self._timelimit=timelimit
    193         self.available()
    194         #
    195         # Verify that the input problem exists       
    196         #
    197         if not os.path.exists(self.tmpDir+problem_filename) and not os.path.exists(problem_filename):
    198            raise ValueError, "Solver failed to locate input problem file="+problem_filename       
    199         #
    200         # Create command line
    201         #
    202         command = self.create_command_line(self.executable,problem_filename)
    203         self.log_file=command.log_file
    204         #
    205         # Execute the command
    206         #
    207         if pyutilib.debug("verbose"):
    208            print "Running "+command.cmd
    209 
    210         # The pre-cleanup is probably unncessary, but also not harmful.
    211         if self.log_file is not None and os.path.exists(self.log_file):
    212            os.remove(self.log_file)
    213         if self.soln_file is not None and os.path.exists(self.soln_file):
    214            os.remove(self.soln_file)
    215         [rc,log] = self._execute_command(command)
    216         sys.stdout.flush()
    217         if self.log_file is not None:
    218            OUTPUT=open(self.log_file,"w")
    219            print >>OUTPUT, "Solver command line: "+command.cmd
    220            print >>OUTPUT, ""
    221            print >>OUTPUT, log
    222            OUTPUT.close()
    223 
    224         # JPW: The cleanup of the problem file probably shouldn't be here, but rather
    225         #      in the base OptSolver class. That would require movement of the keepFiles
    226         #      attribute and associated cleanup logic to the base class, which I didn't
    227         #      feel like doing at this present time. the base class remove_files method
    228         #      should clean up the problem file.           
    229 
    230         if self.log_file is not None and not os.path.exists(self.log_file):
    231            raise IOError, "File " + self.log_file + " not generated while executing "+self.path
    232         results = None
    233         if self._results_format is not None:
    234            results = self.process_output(rc)
    235            if not self.keepFiles:
    236               self.remove_files()
    237               os.remove(problem_filename)
    238            else:
    239               # output names so you know where to look when debugging
    240               if self.log_file is not None:
    241                  print "Retaining log file=" + self.log_file
    242               if self.soln_file is not None:
    243                  print "Retaining solution file=" + self.soln_file
    244               if problem_filename is not None:
    245                   print "Retaining problem file=" + problem_filename
    246         return results
    247 
    248     def _execute_command(self,command):
    249         """
    250         TODO
    251         """
    252         try:
    253            process = pyutilib.SubprocessMngr(command.cmd,stdout=pyutilib.subprocess.PIPE,env=command.env)
    254         except WindowsError, err:
    255            raise pyutilib.ApplicationError, "Could not execute the command: "+command.cmd+"\tError message: "+str(err)
    256         pyutilib.GlobalData.current_process = process
    257         sys.stdout.flush()
    258         #
    259         # WEH - this timelimit mechanism appears to cause problems.
    260         #   perhaps the issue arises when the solver itself recognizes the
    261         #   timelimit, and is trying to terminate at the same time that
    262         #   it is being shutdown by Python?
    263         #
    264         #rc = process.wait(self._timelimit)
    265         rc = process.wait()
    266         pyutilib.GlobalData.current_process = None
    267         log = process.stdout().read()
    268         return [rc,log]
    269 
    270     def process_output(self,rc):
    271         """
    272         TODO
    273         """
    274         if self._results_format is None:
    275            raise ValueError, "Results format is None"
    276         if self.results_reader is None:
    277            if self._results_format is ResultsFormat.log:
    278               results = self.process_logfile()
    279            else:
    280               raise ValueError, "Results format `"+str(self._results_format)+"' is has not been registered"
    281         else:
    282            results = self.results_reader(self.results_file)
    283         self.process_other_data(results)
    284         if rc != None:
    285            results.solver.error_rc=rc
    286            if rc != 0:
    287               results.solver.status=SolverStatus.error
    288         return results
    289 
    290     def _default_results_format(self, prob_format):
    291         """ Returns the default results format for different problem
    292             formats.
    293         """
    294         return ResultsFormat.log
    295 
    296 
  • trunk/coopr/opt/mip/CBC.py

    r1157 r1161  
    1313from coopr.opt.base import *
    1414import pyutilib
     15import pyutilib.plugin.pyutilib
    1516import tempfile
    1617import mockmip
     
    2425        # Call base constructor
    2526        #
    26         SystemCallSolver.__init__(self,"cbc",path=path, keepFiles=keepFiles, options=options)
     27        SystemCallSolver.__init__(self, type="cbc", path=path, keepFiles=keepFiles, options=options)
    2728        #
    2829        # Setup valid problem formats and valid results for each problem format
     
    3637        # Setup executable
    3738        #
    38         self.executable = config().cbc
    39         if self.executable is None:     #pragma:nocover
    40             raise pyutilib.ApplicationError, "The 'cbc' executable was not found for solver `cbc'"
     39        self.executable = self.executable_service["cbc"]
     40        if self.executable is None:
     41            pyutilib.plugin.PluginGlobals.env().error("Could not locate the 'cbc' executable, which is required for solver %s" % self.name)
     42            self.enable = False
    4143
    4244    def create_command_line(self,executable,problem_file):
     
    218220
    219221
    220 SolverFactory().register("cbc", CBC)
    221 SolverFactory().register("_mock_cbc", MockCBC)
    222 
    223 
    224 class CBCPlugin(pyutilib.ConfigPlugin):
    225     """
    226     Config plugin that adds options for coopr.opt CBC
    227     optimizer.
    228     """
    229 
    230     def __init__(self):
    231         """
    232         Constructor that tries to find the CBC executable
    233         """
    234         pyutilib.ConfigPlugin.__init__(self)
    235         self.cbc_default = \
    236                 pyutilib.search_file("cbc",
    237                                 implicitExt=pyutilib.executable_extension,
    238                                 executable=True)
    239 
    240     def add_options(self, parser):
    241         """
    242         Add options for CBC
    243         """
    244         parser.add_option(
    245             "--cbc", action="store", dest="cbc",
    246             default=self.cbc_default,
    247             help="The filename of the 'cbc' executable")
    248         return "cbc",["cbc"]
    249 
    250     def configure(self, options, config):
    251         """
    252         Update the configuration object with option data
    253         """
    254         config.cbc = options.cbc
    255         pass
    256 
    257 config().add_plugin(CBCPlugin())
     222pyutilib.plugin.pyutilib.ExternalExecutable(name="cbc")
     223SolverRegistration("cbc", CBC)
     224SolverRegistration("_mock_cbc", MockCBC)
  • trunk/coopr/opt/mip/CPLEX.py

    r1157 r1161  
    1515import mockmip
    1616import pyutilib
     17import pyutilib.plugin.pyutilib
    1718import tempfile
    1819import string
     20
    1921
    2022class CPLEX(SystemCallSolver):
     
    2628        # Call base class constructor
    2729        #
    28         SystemCallSolver.__init__(self,"cplex",path=path, keepFiles=keepFiles, options=options)
     30        SystemCallSolver.__init__(self, "cplex", path=path, keepFiles=keepFiles, options=options)
    2931
    3032        # We are currently invoking CPLEX via the command line, with input re-direction. As opposed
     
    4345        # Set up executable
    4446        #
    45         try:
    46             self.executable = config().cplex
    47         except AttributeError:
    48             raise coopr.ConfigurationError, "Must configure coopr before creating optimizers"           
    49 
    50         if self.executable is None:      #pragma:nocover
    51             raise pyutilib.ApplicationError, "Could not locate 'cplex' executable - required for solver type=CPLEX"
     47        self.executable = self.executable_service["cplex"]
     48        if self.executable is None:
     49            pyutilib.plugin.PluginGlobals.env().error("Could not locate the 'cplex' executable, which is required for solver %s" % self.name)
     50            self.enable = False
    5251
    5352    def create_command_line(self,executable,problem_file):
     
    188187
    189188
    190 SolverFactory().register("cplex", CPLEX)
    191 SolverFactory().register("_mock_cplex", MockCPLEX)
    192 
    193 
    194 class CPLEXPlugin(pyutilib.ConfigPlugin):
    195     """
    196     Config plugin that adds options for coopr.opt CPLEX
    197     optimizer.
    198     """
    199 
    200     def __init__(self):
    201         """
    202         Constructor that tries to find the CPLEX executable
    203         """
    204         pyutilib.ConfigPlugin.__init__(self)
    205         self.cplex_default = \
    206                 pyutilib.search_file("cplex",
    207                                 implicitExt=pyutilib.executable_extension,
    208                                 executable=True)
    209 
    210     def add_options(self, parser):
    211         """
    212         Add options for CPLEX
    213         """
    214         parser.add_option(
    215             "--cplex", action="store", dest="cplex",
    216             default=self.cplex_default,
    217             help="The filename of the 'cplex' executable")
    218 
    219         return "cplex",["cplex"]
    220 
    221     def configure(self, options, config):
    222         """
    223         Update the configuration object with option data
    224         """
    225         config.cplex = options.cplex
    226 
    227 config().add_plugin(CPLEXPlugin())
    228 
     189pyutilib.plugin.pyutilib.ExternalExecutable(name="cplex")
     190SolverRegistration("cplex", CPLEX)
     191SolverRegistration("_mock_cplex", MockCPLEX)
  • trunk/coopr/opt/mip/GLPK.py

    r1157 r1161  
    1616import mockmip
    1717import pyutilib
     18import pyutilib.plugin.pyutilib
    1819
    1920
     
    3839        # Setup executable
    3940        #
    40         try:
    41             self.executable = config().glpsol
    42         except AttributeError:
    43             raise coopr.ConfigurationError, "Must configure coopr before creating optimizers"
    44         if self.executable is None:     #pragma:nocover
    45             raise pyutilib.ApplicationError, "The 'glpsol' executable not found for solver `glpk'"
     41        self.executable = self.executable_service["glpsol"]
     42        if self.executable is None:
     43            pyutilib.plugin.PluginGlobals.env().error("Could not locate the 'glpsol' executable, which is required for solver %s" % self.name)
     44            self.enable = False
    4645
    4746    def create_command_line(self,executable,problem_file):
     
    324323           return (args[0],ProblemFormat.cpxlp)
    325324
    326      
    327 SolverFactory().register("glpk", GLPK)
    328 SolverFactory().register("_mock_glpk", MockGLPK)
    329 
    330 
    331 class GLPKPlugin(pyutilib.ConfigPlugin):
    332     """
    333     Config plugin that adds options for coopr.opt GLPK
    334     optimizer.
    335     """
    336 
    337     def __init__(self):
    338         """
    339         Constructor that tries to find the GLPK executable
    340         """
    341         pyutilib.ConfigPlugin.__init__(self)
    342 
    343     def add_options(self, parser):
    344         """
    345         Add options for GLPK
    346         """
    347         return "glpk",[]
    348 
    349     def configure(self, options, config):
    350         """
    351         Update the configuration object with option data
    352         """
    353         pass
    354 
    355 config().add_plugin(GLPKPlugin())
     325
     326pyutilib.plugin.pyutilib.ExternalExecutable(name="glpsol")
     327SolverRegistration("glpk", GLPK)
     328SolverRegistration("_mock_glpk", MockGLPK)
  • trunk/coopr/opt/mip/NLWRITE.py

    r1109 r1161  
    3030        return pyutilib.Bunch(cmd="/bin/true", log_file=None, env=None)
    3131
    32 
    33 SolverFactory().register("nlwrite", NLWRITE)
  • trunk/coopr/opt/mip/PICO.py

    r1157 r1161  
    1313from coopr.opt.base import *
    1414import pyutilib
     15import pyutilib.plugin.pyutilib
    1516import mockmip
    1617import os
     
    2627        # Call base constructor
    2728        #
    28         SystemCallSolver.__init__(self,"pico",path=path, keepFiles=keepFiles, options=options)
     29        SystemCallSolver.__init__(self, type="pico", path=path, keepFiles=keepFiles, options=options)
    2930        #
    3031        # Setup valid problem formats, and valid results for each problem format
     
    3839        # Setup executable
    3940        #
    40         try:
    41             self.executable = config().PICO
    42         except AttributeError:
    43             raise coopr.ConfigurationError, "Must configure coopr before creating optimizers"
    44         if self.executable is None:     #pragma:nocover
    45             raise pyutilib.ApplicationError, "The 'PICO' executable not found for solver `pico'"
     41        self.executable = self.executable_service["pico"]
     42        if self.executable is None:
     43            pyutilib.plugin.PluginGlobals.env().error("Could not locate the 'PICO' executable, which is required for solver %s" % self.name)
     44            self.enable = False
    4645
    4746    def create_command_line(self,executable,problem_file):
     
    229228
    230229
    231 SolverFactory().register("pico", PICO)
    232 SolverFactory().register("_mock_pico", MockPICO)
    233 
    234 
    235 class PICOPlugin(pyutilib.ConfigPlugin):
    236     """
    237     Config plugin that adds options for coopr.opt PICO
    238     optimizer.
    239     """
    240 
    241     def __init__(self):
    242         """
    243         Constructor that tries to find the PICO executable
    244         """
    245         pyutilib.ConfigPlugin.__init__(self)
    246         self.PICO_default = \
    247                 pyutilib.search_file("PICO",
    248                                 implicitExt=pyutilib.executable_extension,
    249                                 executable=True)
    250 
    251     def add_options(self, parser):
    252         """
    253         Add options for PICO
    254         """
    255         parser.add_option(
    256             "--pico", action="store", dest="PICO",
    257             default=self.PICO_default,
    258             help="The filename of the 'PICO' executable")
    259         return "pico",["PICO"]
    260 
    261     def configure(self, options, config):
    262         """
    263         Update the configuration object with option data
    264         """
    265         config.PICO = options.PICO
    266 
    267 config().add_plugin(PICOPlugin())
    268 
     230pyutilib.plugin.pyutilib.ExternalExecutable(name="pico")
     231SolverRegistration("pico", PICO)
     232SolverRegistration("_mock_pico", MockPICO)
  • trunk/coopr/opt/reader/OS.py

    r1160 r1161  
    314314
    315315
    316 import opt_globals
    317316import results
    318317from formats import *
     
    369368
    370369
    371 opt_globals.Globals._ReaderFactory.register(str(ResultsFormat.osrl), ResultsReader_osrl)
    372 
    373 
     370results.ReaderRegistration(str(ResultsFormat.osrl), ResultsReader_osrl)
     371
  • trunk/coopr/opt/reader/sol.py

    r1160 r1161  
    110110
    111111
    112 opt_globals.Globals._ReaderFactory.register(str(ResultsFormat.sol), ResultsReader_sol)
     112results.ReaderRegistration(str(ResultsFormat.sol), ResultsReader_sol)
    113113
    114114
Note: See TracChangeset for help on using the changeset viewer.