Changeset 2146


Ignore:
Timestamp:
Jan 12, 2010 12:19:42 AM (11 years ago)
Author:
wehart
Message:

Other updates from my laptop...

Location:
coopr.pyomo/trunk
Files:
8 added
1 edited
1 moved

Legend:

Unmodified
Added
Removed
  • coopr.pyomo/trunk/coopr/pyomo/scripting/pyomo.py

    r2132 r2146  
    1010
    1111
    12 import sys
    13 import os
    1412from optparse import OptionParser
    15 #
    16 # Finish imports
    17 #
    18 from coopr.pyomo import *
     13from coopr.pyomo import pyomo
    1914from coopr.opt.base import SolverFactory
    20 from coopr.opt.parallel import SolverManagerFactory
    21 import pyutilib.services
    22 import pyutilib.misc
    23 import textwrap
    24 import traceback
    25 import cProfile
    26 import pstats
    27 import gc
     15from pyutilib.misc import Options, Container
     16
     17import util
    2818
    2919#
     
    198188
    199189
    200 def run_pyomo(options, args):
    201     #
    202     # Run the a command that executes a Pyomo script
    203     #
     190def run_pyomo(options=Options(), args=()):
    204191    if options.help_components:
    205         print ""
    206         print "----------------------------------------------------------------"
    207         print "Pyomo Model Components:"
    208         print "----------------------------------------------------------------"
    209         components = pyomo.model_components()
    210         index = pyutilib.misc.sort_index(components)
    211         for i in index:
    212             print ""
    213             print " "+components[i][0]
    214             for line in textwrap.wrap(components[i][1], 59):
    215                 print "    "+line
    216         print ""
    217         print "----------------------------------------------------------------"
    218         print "Pyomo Virtual Sets:"
    219         print "----------------------------------------------------------------"
    220         pyomo_sets = pyomo.predefined_sets()
    221         index = pyutilib.misc.sort_index(pyomo_sets)
    222         for i in index:
    223             print ""
    224             print " "+pyomo_sets[i][0]
    225             print "    "+pyomo_sets[i][1]
     192        util.print_components(options)
     193        return Container()
     194    if not util.setup_environment(options, args):
    226195        return
    227 
    228     #
    229     # Process command-line options
    230     #
    231     if options.disable_gc:
    232         gc.disable()
    233     if options.verbose:
    234        pyomo.set_debugging("verbose")
    235     if options.debug is not None:
    236        for val in options.debug:
    237          pyomo.set_debugging( val )
    238     if not options.logfile is None:
    239         pyutilib.misc.setup_redirect(options.logfile)
    240     if not options.tempdir is None:
    241         if not os.path.exists(options.tempdir):
    242             raise ValueError, "Directory for temporary files does not exist: "+options.tempdir
    243         pyutilib.services.TempfileManager.tempdir = options.tempdir
    244 
    245     filter_excepthook=True
    246     def pyomo_excepthook(etype,value,tb):
    247       print ""
    248       if filter_excepthook:
    249          print "ERROR: Unexpected exception while loading Pyomo model "+args[0]
    250       else:
    251          print "ERROR: Unexpected exception while running Pyomo model "+args[0]
    252       print "  ",value
    253       print ""
    254       tb_list = traceback.extract_tb(tb,None)
    255       i=0
    256       if not pyomo.debug("all") and filter_excepthook:
    257          while i < len(tb_list):
    258            if args[0] in tb_list[i][0]:
    259               break
    260            i += 1
    261       print "Pyomo Traceback (most recent call last):"
    262       for item in tb_list[i:]:
    263         print "  File \""+item[0]+"\", line "+str(item[1])+", in "+item[2]
    264         if item[3] is not None:
    265            print "    "+item[3]
    266       sys.exit(1)
    267    
    268     sys.excepthook = pyomo_excepthook
    269 
    270     #
    271     # Apply preprocessing steps
    272     #
    273     for file in options.preprocess:
    274         preprocess = pyutilib.misc.import_file(file)
    275        
    276     #
    277     #
    278     # Setup solver and model
    279     #
    280     #
    281     if len(args) == 0:
    282        parser.print_help()
    283        return
    284     for file in args:
    285       if not os.path.exists(file):
    286          print "File "+file+" does not exist!"
    287          sys.exit(1)
    288 
    289     #
    290     # Create Model
    291     #
    292     usermodel = pyutilib.misc.import_file(args[0])
    293     filter_excepthook=False
    294     if options.model_name in dir(usermodel):
    295         model = getattr(usermodel, options.model_name)
    296         if model is None:
    297             print ""
    298             raise SystemExit, "'%s' object equals 'None' in module %s" % (options.model_name, args[0])
    299             sys.exit(0)
    300     elif 'create_model' in dir(usermodel):
    301         model = getattr(usermodel, 'create_model')( pyutilib.misc.Container(*options.model_options) )
    302     else:
    303        print ""
    304        raise SystemExit, "Neither '%s' nor 'create_model' are available in module %s" % (options.model_name,args[0])
    305        #sys.exit(0)
    306     #
    307     # Create Problem Instance
    308     #
    309     if len(args) == 2:
    310        suffix = (args[1]).split(".")[-1]
    311        if suffix == "dat":
    312           instance = model.create(args[1])
    313        elif suffix == "py":
    314           userdata = pyutilib.misc.import_file(args[1])
    315           if "modeldata" not in dir(userdata):
    316              print ""
    317              print "pyomo: No 'modeldata' object created in module "+args[1]
    318              sys.exit(0)
    319           if userdata.modeldata is None:
    320              print ""
    321              raise SystemExit, "Exiting pyomo: 'modeldata' object equals 'None' in module "+args[1]
    322           userdata.modeldata.read(model)
    323           instance = model.create(userdata.modeldata)
    324        else:
    325           raise ValueError, "Unknown data file type: "+args[1]
    326     else:
    327        instance = model.create()
    328     if pyomo.debug("instance"):
    329        print "MODEL INSTANCE"
    330        instance.pprint()
    331        print ""
    332        options.save_model = 'unknown.lp'
    333        print "Model instance written in file",options.save_model,"to allow debugging"
    334 
    335     if not options.save_model is None:
    336         instance.write(filename=options.save_model, format=None)
    337         if not os.path.exists(options.save_model):
    338             print "ERROR: file "+options.save_model+" has not been created!"
    339 
     196    if not util.apply_preprocessing(options, parser, args):
     197        return Container()
     198    instance = util.create_model(options, args)
    340199    if options.only_instance:
    341         return [instance, None]
    342 
    343     #
    344     # Create Solver and Perform Optimization
    345     #
    346     opt = SolverFactory( options.solver )
    347     if opt is None:
    348        raise ValueError, "Unknown problem constructing solver `"+str(options.solver)+"'"
    349     opt.keepFiles=options.keepfiles or options.log
    350     if options.timelimit == 0:
    351        options.timelimit=None
    352     if options.solver_mipgap is not None:
    353        opt.mipgap = options.solver_mipgap
    354     solver_mngr = SolverManagerFactory( options.smanager_type )
    355     if solver_mngr is None:
    356        raise ValueError, "Problem constructing solver manager `"+str(options.smanager_type)+"'"
    357     results = solver_mngr.solve(instance, opt=opt, tee=options.tee, timelimit=options.timelimit, options=" ".join(options.solver_options))
    358     if results == None:
    359             raise ValueError, "opt.solve returned None"
    360    
    361     if options.log:
    362        print ""
    363        print "=========================================================="
    364        print "Solver Logfile:",opt.log_file
    365        print "=========================================================="
    366        print ""
    367        INPUT = open(opt.log_file, "r")
    368        for line in INPUT:
    369          print line,
    370        INPUT.close()
    371    
    372     try:
    373         instance.load(results)
    374     except Exception, e:
    375         print "Problem loading solver results"
    376         raise
    377     print ""
    378     results.write(num=1)
    379    
    380     if options.summary:
    381        print ""
    382        print "=========================================================="
    383        print "Solution Summary"
    384        print "=========================================================="
    385        if len(results.solution(0).variable) > 0:
    386           print ""
    387           display(instance)
    388        else:
    389           print "No solutions reported by solver."
    390 
    391     for file in options.postprocess:
    392         postprocess = pyutilib.misc.import_file(file)
    393         if "postprocess" in dir(postprocess):
    394             postprocess.postprocess(instance,results)
    395        
    396     #
    397     # Return the model instance and optimization results
    398     #
    399     return [instance,results]
     200        return Container(instance=instance)
     201    results = apply_optimizer(options, instance)
     202    if not util.process_results(options, results):
     203        return Container(instance=instance, results=results)
     204    util.apply_postprocessing(options, instance, results)
     205    return Container(instance=instance, results=results)
    400206
    401207
    402208def run(args=None):
    403     #
    404     # Top-level command that executes a Pyomo script.  This
    405     # is segregated from run_pyomo to enable Pyomo profiling.
    406     #
    407 
    408     #
    409     #
    410     # Parse command-line options
    411     #
    412     #
    413     try:
    414        (options, args) = parser.parse_args(args=args)
    415     except SystemExit:
    416        # the parser throws a system exit if "-h" is specified - catch
    417        # it to exit gracefully.
    418        return
    419 
    420     #
    421     # Call the main Pyomo runner with profiling
    422     #
    423     if options.profile > 0:
    424         tfile = pyutilib.services.TempfileManager.create_tempfile(suffix=".profile")
    425         tmp = cProfile.runctx('run_pyomo(options,args)',globals(),locals(),tfile)
    426         p = pstats.Stats(tfile).strip_dirs()
    427         p.sort_stats('time', 'cum')
    428         options.profile = eval(options.profile)
    429         p = p.print_stats(options.profile)
    430         p.print_callers(options.profile)
    431         p.print_callees(options.profile)
    432         p = p.sort_stats('cum','calls')
    433         p.print_stats(options.profile)
    434         p.print_callers(options.profile)
    435         p.print_callees(options.profile)
    436         p = p.sort_stats('calls')
    437         p.print_stats(options.profile)
    438         p.print_callers(options.profile)
    439         p.print_callees(options.profile)
    440         pyutilib.services.TempfileManager.clear_tempfiles()
    441         ans = [tmp, None]
    442     else:
    443         #
    444         # Call the main Pyomo runner without profiling
    445         #
    446         try:
    447             ans = run_pyomo(options, args)
    448         except SystemExit, err:
    449             if pyomo.debug('errors'):
    450                 sys.exit(0)
    451             print 'Exiting pyomo:', str(err)
    452             ans = None
    453         except Exception, err:
    454             if pyomo.debug('errors'):
    455                 raise
    456             print ""
    457             print "ERROR:",str(err)
    458             ans = None
    459 
    460     gc.enable()
    461     return ans
    462 
     209    return util.run_command(run_pyomo, parser, args=args, name='pyomo')
     210
  • coopr.pyomo/trunk/scripts/pyomo

    r2145 r2146  
    1717import traceback
    1818import sys
    19 if sys.version_info[0:2] < (2,4):
     19if sys.version_info[0:2] < (2,5,3):
    2020   print ""
    21    print "ERROR: Pyomo requires Python 2.4 or newer"
     21   print "ERROR: Pyomo requires Python 2.5.3 or newer"
    2222   sys.exit(1)
    2323from os.path import abspath, dirname
    2424import os
    25 import pyutilib.common
    2625sys.path.insert(0, dirname(dirname(abspath(__file__))))
    2726sys.path.append(".")
     
    4847    curr = os.path.dirname(curr)
    4948
    50 import coopr.pyomo.main_script
     49import coopr.pyomo.scripting.pyomo
    5150
    5251try:
    53     coopr.pyomo.main_script.run()
     52    coopr.pyomo.scripting.pyomo.run(args=sys.argv[1:])
    5453except SystemExit:
    5554    pass
    56 except:
    57    print "Encountered unhandled exception"
    58    traceback.print_exc()
Note: See TracChangeset for help on using the changeset viewer.