source: coopr.pyomo/trunk/coopr/pyomo/scripting/pyomo.py @ 3000

Last change on this file since 3000 was 3000, checked in by jwatson, 9 years ago

Fixed minor bug in assignment of temporary variable.

  • Property svn:executable set to *
File size: 10.5 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
12from optparse import OptionParser, OptionGroup
13from coopr.pyomo import pyomo
14from coopr.opt.base import SolverFactory
15from coopr.opt.parallel import SolverManagerFactory
16from pyutilib.misc import Options, Container
17try:
18    import IPython
19    IPython_available=True
20    from IPython.Shell import IPShellEmbed
21    ipshell = IPShellEmbed([''],
22                banner = '\n# Dropping into Python interpreter',
23                exit_msg = '\n# Leaving Interpreter, back to Pyomo\n')
24except ImportError:
25    IPython_available=False
26
27import util
28
29def create_parser():
30    #
31    #
32    # Setup command-line options
33    #
34    #
35    solver_help=\
36    "This option specifies the type of solver that is used "\
37    "to solve the Pyomo model instance.  The following solver "\
38    "types are are currently supported:"
39    solver_list = SolverFactory.services()
40    solver_list = sorted( filter(lambda x: '_' != x[0], solver_list) )
41    solver_help += " %s.  Default: glpk." % ', '.join(solver_list)
42    debug_help=\
43    "This option is used to turn on debugging output. This option "\
44    "can be specified multiple times to turn on different debugging"\
45    "output. The following debugging options can be specified:"
46    debug_choices=[]
47    for item in pyomo.Debug:
48      if str(item) != "none":
49         debug_choices.append( str(item) )
50         debug_help += "\n.."+str(item)
51
52    parser = OptionParser()
53    parser.usage = 'pyomo [options] <model.py> [<model.dat>]'
54
55    solverOpts = OptionGroup( parser, 'Solver Options')
56    outputOpts = OptionGroup( parser, 'Output Options')
57    otherOpts  = OptionGroup( parser, 'Other Options')
58    parser.add_option_group( solverOpts )
59    parser.add_option_group( outputOpts )
60    parser.add_option_group( otherOpts )
61
62
63    solverOpts.add_option('--instance-only',
64        help='Generate a model instance, and then return',
65        action='store_true',
66        dest='only_instance',
67        default=False)
68    solverOpts.add_option('--model-name',
69        help='The name of the model object that is created in the specified ' \
70             'Pyomo module',
71        action='store',
72        dest='model_name',
73        type='string',
74        default='model')
75    solverOpts.add_option('--model-options',
76        help='Options passed into a create_model() function to construct the '\
77             'model',
78        action='append',
79        dest='model_options',
80        type='string',
81        default=[])
82    solverOpts.add_option('--postprocess',
83        help='Specify a Python module that gets executed after optimization.' \
84             'If this option is specified multiple times, then the modules '  \
85             'are executed in the specified order.',
86        action='append',
87        dest='postprocess',
88        default=[])
89    solverOpts.add_option('--preprocess',
90        help='Specify a Python module that gets immediately executed (before '\
91             'the optimization model is setup).  If this option is specified '\
92             'multiple times, then the modules are executed in the specified '\
93             'order.',
94        action='append',
95        dest='preprocess',
96        default=[])
97    solverOpts.add_option('--solver',
98        help=solver_help,
99        action='store',
100        dest='solver',
101        type='choice',
102        choices=solver_list,
103        default='glpk')
104    solverOpts.add_option('--solver-manager',
105        help='Specify the technique that is used to manage solver executions.',
106        action='store',
107        dest='smanager_type',
108        type='choice',
109        choices=SolverManagerFactory.services(),
110        default='serial')
111    solverOpts.add_option('--solver-mipgap',
112        help='The solver termination mipgap',
113        action='store',
114        dest='solver_mipgap',
115        type='float',
116        default=None)
117    solverOpts.add_option('--solver-options',
118        help='Options passed into the solver',
119        action='append',
120        dest='solver_options',
121        type='string',
122        default=[])
123    solverOpts.add_option('--solver-suffixes',
124        help='One or more solution suffixes to be extracted by the solver',
125        action='append',
126        dest='solver_suffixes',
127        type='string',
128        default=[])
129    solverOpts.add_option('--timelimit',
130        help='Limit to the number of seconds that the solver is run',
131        action='store',
132        dest='timelimit',
133        type='int',
134        default=0)
135
136    outputOpts.add_option('--debug',
137        help='This option is meant only for Pyomo developers.  Most users '   \
138             'will want the --warning option.',
139        action='append',
140        dest='debug',
141        type='choice',
142        choices=debug_choices,
143        default=[])
144    outputOpts.add_option('-l','--log',
145        help='Print the solver logfile after performing optimization',
146        action='store_true',
147        dest='log',
148        default=False)
149    outputOpts.add_option('--logfile',
150        help='Redirect output to the specified logfile',
151        action='store',
152        dest='logfile',
153        type='string',
154        default=None)
155    outputOpts.add_option('-q','--quiet',
156        help='Turn off solver output',
157        action='store_true',
158        dest='quiet',
159        default=False)
160    outputOpts.add_option('--save-model',
161        help='Specify the filename to which the model is saved.  The suffix ' \
162             'of this filename specifies the file format.  If debugging is '  \
163             "on, then this defaults to writing the file 'unknown.lp'.",
164        action='store',
165        dest='save_model',
166        type='string',
167        default=None)
168    outputOpts.add_option('--stream-output',
169        help='Stream the solver output to provide information about the '     \
170             "solver's progress.",
171        action='store_true',
172        dest='tee',
173        default=False)
174    outputOpts.add_option('-s','--summary',
175        help='Summarize the final solution after performing optimization',
176        action='store_true',
177        dest='summary',
178        default=False)
179    outputOpts.add_option('-v','--verbose',
180        help='Make solver output verbose',
181        action='store_true',
182        dest='verbose',
183        default=False)
184    outputOpts.add_option('-w', '--warning',
185        help='Warning level.  Use this option to set the level of '           \
186             'informational output from Pyomo.  Levels include quiet, '       \
187             'warning, and info.  Default: warning.',
188        action='store',
189        dest='warning',
190        default='warning')
191
192    otherOpts.add_option('--disable-gc',
193        help='Disable the garbage collecter',
194        action='store_true',
195        dest='disable_gc',
196        default=False)
197    otherOpts.add_option('--help-components',
198        help='Print information about modeling components supported by Pyomo',
199        action='store_true',
200        dest='help_components',
201        default=False)
202    otherOpts.add_option('-i', '--interactive',
203        help='After executing Pyomo, launch an interactive Python shell.  If IPython is installed, this shell is an IPython shell.',
204        action='store_true',
205        dest='interactive',
206        default=False)
207    otherOpts.add_option('-k','--keepfiles',
208        help='Keep temporary files',
209        action='store_true',
210        dest='keepfiles',
211        default=False)
212    otherOpts.add_option('--path',
213        help='Give a path that is used to find the Pyomo python files',
214        action='store',
215        dest='path',
216        type='string',
217        default='.')
218    otherOpts.add_option('--profile',
219        help='Enable profiling of Python code.  The value of this option is ' \
220             'the number of functions that are summarized.',
221        action='store',
222        dest='profile',
223        type='int',
224        default=0)
225    otherOpts.add_option('--tempdir',
226        help='Specify the directory where temporary files are generated',
227        action='store',
228        dest='tempdir',
229        type='string',
230        default=None)
231    parser.add_option("--skip-canonical-repn",
232            help="Do not create the canonical representation. This is not necessary for solvers that do not require it.",
233            action="store_true",
234            dest="skip_canonical_repn",
235            default=False)
236    #
237    # These options are depricated until we have a specific use-case for them
238    #
239    ##if False:
240    ##  parser.add_option("--seed",
241    ##        help="Specify a seed to derandomize the solver",
242    ##        action="store",
243    ##        dest="seed",
244    ##        type="int",
245    ##        default=0)
246    ##  parser.add_option("--first-feasible",
247    ##        help="Terminate after the first feasible incumbent",
248    ##        action="store_true",
249    ##        dest="ff",
250    ##        default=False)
251
252    return parser
253
254
255def run_pyomo(options=Options(), args=(), parser=None):
256    if options.help_components:
257        util.print_components(options)
258        return Container()
259    if not util.setup_environment(options, args):
260        return Container()                                   #pragma:nocover
261    if not util.apply_preprocessing(options, parser, args):
262        return Container()                                   #pragma:nocover
263    model_data = util.create_model(options, args)
264    if options.save_model or options.only_instance:
265        return Container(instance=model_data.instance)
266    results, opt = util.apply_optimizer(options, model_data.instance)
267    if not util.process_results(options, model_data.instance, results, opt):
268        return Container(instance=model_data.instance, results=results) #pragma:nocover
269    util.apply_postprocessing(options, model_data.instance, results)
270    model=model_data.model
271    instance=model_data.instance
272    if options.interactive:
273        if IPython_available:
274            ipshell()
275        else:
276            import code
277            shell = code.InteractiveConsole(locals())
278            print '\n# Dropping into Python interpreter'
279            shell.interact()
280            print '\n# Leaving Interpreter, back to Pyomo\n'
281    return Container(instance=model_data.instance, results=results)
282
283
284def run(args=None):
285    return util.run_command(run_pyomo, create_parser(), args=args, name='pyomo')
286
Note: See TracBrowser for help on using the repository browser.