def solve(localsolver, solvername, instance, logfilename='logfile_loadobjective.log', get_suffixes=True, solver_options=None, outputfile=None): # Wall time - clock starts. starttime_modelsolve = time.time() if localsolver: solver = SolverFactory(solvername) # Configure with solver options # file_print_levels (Output Level-of-Detail): # 4 for just # of iterations, and final objective, infeas,etc. values # 6 for summary information about all iterations, but not variable values # 8 for variable values at all iterations # 10 for all iterations if solver_options: for k, v in solver_options.items(): solver.options[k] = v solver.options['OF_mumps_mem_percent'] = '5' # "OF_" prefix signals to Pyomo to create a temporary options file solver.options['OF_output_file'] = outputfile if get_suffixes: instance.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT) instance.ipopt_zL_out = pyo.Suffix(direction=pyo.Suffix.IMPORT) instance.ipopt_zU_out = pyo.Suffix(direction=pyo.Suffix.IMPORT) setattr(instance, 'lambda', pyo.Suffix(direction=pyo.Suffix.IMPORT)) # use setattr because 'lambda' is reserved keyword try: results = solver.solve(instance, tee=True, symbolic_solver_labels=True, keepfiles=False, logfile=logfilename) except pyutilib.common._exceptions.ApplicationError: traceback.print_exc() return None else: opt = SolverFactory("cbc") solver_manager = SolverManagerFactory('neos') instance.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT) instance.rc = pyo.Suffix(direction=pyo.Suffix.IMPORT) instance.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT_EXPORT) # self.instance.slack = pyo.Suffix(direction=pyo.Suffix.IMPORT) opt.options["display_width"] = 170 opt.options["display"] = '_varname, _var.rc, _var.lb, _var, _var.ub, _var.slack' results = solver_manager.solve(instance, opt=opt, solver=solvername, logfile=logfilename) results.write() # Wall time - clock stops. _endtime_modelsolve = time.time() timefor_modelsolve = _endtime_modelsolve - starttime_modelsolve logger.info('*solving done* <- it took %f seconds>' % timefor_modelsolve) feasible = check_whether_feasible(instance, results) return instance, results, feasible
return ( sum( modelo.tiempo_produccion[planta, producto] * modelo.produccion[producto] for producto in modelo.productos ) <= modelo.tiempo_disponible[planta] ) modelo.disponibilidad_tiempo = Constraint( modelo.plantas, rule=funcion_disponibilidad_tiempo ) def funcion_ganancias(modelo): return sum( modelo.ganancia_unitaria[producto] * modelo.produccion[producto] for producto in modelo.productos ) modelo.ganancias = Objective(rule=funcion_ganancias, sense=maximize) instancia = modelo.create_instance("wyndor.dat") opt = SolverFactory("cbc") solver_manager = SolverManagerFactory('neos') resultados = solver_manager.solve(instancia, opt=opt) # resolver en la nube # resultados = opt.solve(instancia) # resolver localmente instancia.display()
from pyomo.environ import * from pyomo.opt import SolverFactory, SolverManagerFactory from DiseaseEstimation import model # create the instance instance = model.create('DiseaseEstimation.dat') # define the solver and its options solver = 'ipopt' opt = SolverFactory(solver) if opt is None: raise ValueError, "Problem constructing solver `" + str(solver) opt.set_options('max_iter=2') # create the solver manager solver_manager = SolverManagerFactory('serial') # solve results = solver_manager.solve(instance, opt=opt, tee=True, timelimit=None) instance.load(results) # display results display(instance)
def solve_model(model): # Custom Solve Method import datetime trial_pool = { 'sample1':{'solution_file':None,'aspiration':None}, 'sample2':{'solution_file':None,'aspiration':None}, 'sample3':{'solution_file':None,'aspiration':None} } #model1 = copy.deepcopy(model) #model2 = copy.deepcopy(model) #model3 = copy.deepcopy(model) print ("success! \n loading solver......") mip_gap = 0.005 solver_timeout = 300 number_of_trials = 2 solver_sh = 'cplex' #initialization Setting engage_neos = True #initialization Setting j = 1 timeout_arguments = {'cplex':'timelimit','cbc':'sec'} gap_arguments = {'cplex':'mipgap','cbc':'ratio'} # Cplex Local Executable Take : "mip_tolerance_mipgap", mipgap is for neos version # NEOS Server Library Dependency # pyro4 # suds # openopt while j < number_of_trials + 1: from pyomo.opt import SolverFactory, SolverManagerFactory #model.pprint() opt = SolverFactory(solver_sh, solver_io = 'lp') print ('\ninterfacing solver shell :',solver_sh) if engage_neos: solver_manager = SolverManagerFactory('neos') opt.options[timeout_arguments[solver_sh]]= solver_timeout opt.options[gap_arguments[solver_sh]] = mip_gap #opt.symbolic_solver_labels=True #opt.options['slog'] = 1 #opt.enable = 'parallel' print ('\tsolver options >> \n\n\tTolerance Limits:\n\tmip_gap = %s \n\ttimeout = %s'%(str(mip_gap),str(solver_timeout))) print ("\nProcessing Trial Number :",j) print ("\nJob Triggered at :",str(datetime.datetime.now())) print ('\ngenerating production plan...... !! please wait !! \n to interrupt press ctrl+C\n') try: if engage_neos: results = solver_manager.solve(model,opt = opt, tee= True) else: opt.options['threads'] = 3 results = opt.solve(model) #,tee=True) # Method Load Solutions is not available in pyomo versions less than 4.x except: j = j+1 mip_gap = (j-1)*mip_gap solver_sh = 'cplex' engage_neos = True continue #results.write(filename='results'+str(datetime.date.today())+'.json',format = 'json') #print (results) if str(results['Solver'][0]['Termination condition']) in ['infeasible','maxTimeLimit','maxIterations','intermediateNonInteger']: j = j+1 mip_gap = (j-1)*mip_gap solver_sh = 'cplex' engage_neos = True if j == number_of_trials + 1: #print (results['Problem']) #print (results['Solver']) raise AssertionError("Solver Failed with Termination Status : %s"%(str(results['Solver'][0]['Termination condition']))) exit(0) print ('Terminated by:',str(results['Solver'][0]['Termination condition'])) print ("\n\nRetrying...\n\n") else: print ("solution captured") model.solutions.store_to(results) #post_process_results() break print (results['Problem']) print (results['Solver']) print ("\nSolution Retrived at:",str(datetime.datetime.now())) return [model,results]
def solve_model(model, p_summary=False, p_log=False): # Custom Solve Method import datetime # Choose the best solution from the trial pool # trial_pool = { # 'sample1':{'solution_file':None,'aspiration':None}, # 'sample2':{'solution_file':None,'aspiration':None}, # 'sample3':{'solution_file':None,'aspiration':None} # } #model1 = copy.deepcopy(model) #model2 = copy.deepcopy(model) #model3 = copy.deepcopy(model) import configparser config = configparser.ConfigParser() config.read('../start_config.ini') #initialization Setting mip_gap = float(config['solver']['mip_gap']) solver_timeout = int(config['solver']['solver_timeout']) solver_sh = config['solver']['solver_sh'] number_of_trials = int(config['solver']['number_of_trials']) engage_neos = bool(int( config['solver']['engage_neos'])) #initialization Setting threads = int(config['solver']['threads']) if solver_sh not in set(["cbc", "cplex"]): raise AssertionError("Invalid Solver!, Error Code : 200B") logger.info("success! \n loading solver......") j = 1 timeout_arguments = {'cplex': 'timelimit', 'cbc': 'sec'} gap_arguments = { 'cplex': 'mipgap', 'cbc': 'ratio' } # Cplex Local Executable will take : "mip_tolerance_mipgap", mipgap is for neos version # NEOS Server Library Dependency # pyro4 # suds # openopt while j < number_of_trials + 1: from pyomo.opt import SolverFactory, SolverManagerFactory #model.pprint() opt = SolverFactory(solver_sh, solver_io='lp') # print ('\ninterfacing solver shell :',solver_sh) logger.debug('interfacing solver shell : %s' % (solver_sh)) if engage_neos: solver_manager = SolverManagerFactory('neos') opt.options[timeout_arguments[solver_sh]] = solver_timeout opt.options[gap_arguments[solver_sh]] = mip_gap #opt.symbolic_solver_labels=True # #opt.enable = 'parallel' print( '\tsolver options >> \n\n\tTolerance Limits:\n\tmip_gap = %s \n\ttimeout = %s' % (str(mip_gap), str(solver_timeout))) # print ("\nProcessing Trial Number :",j) # print ("\nJob Triggered at :",str(datetime.datetime.now())) print( '\ngenerating solution ...... !! please wait !! \n to interrupt press ctrl+C\n' ) # logger.debug('\tsolver options >> \n\n\tTolerance Limits:\n\tmip_gap = %s \n\ttimeout = %s'%(str(mip_gap),str(solver_timeout))) logger.debug('Processing Trial Number :%d' % (j)) logger.debug("Job Triggered") try: if engage_neos: p_log = False results = solver_manager.solve(model, opt=opt, tee=True) else: opt.options['threads'] = threads if p_log: opt.options['slog'] = 1 results = opt.solve( model ) # Method Load Solutions is not available in pyomo versions less than 4.x except: j = j + 1 mip_gap = (j - 1) * mip_gap solver_sh = 'cplex' engage_neos = True continue #results.write(filename='results'+str(datetime.date.today())+'.json',format = 'json') #print (results) if str(results['Solver'][0]['Termination condition']) in [ 'infeasible', 'maxTimeLimit', 'maxIterations', 'intermediateNonInteger', 'unbounded' ]: j = j + 1 mip_gap = (j - 1) * mip_gap solver_sh = 'cplex' engage_neos = True if j == number_of_trials + 1: #print (results['Problem']) #print (results['Solver']) raise AssertionError( "Solver Failed with Termination Status : %s \nError Code : 200C" % (str(results['Solver'][0]['Termination condition']))) exit(0) # print ('Terminated by:',str(results['Solver'][0]['Termination condition'])) # print ("\n\nRetrying...\n\n") logger.info('Terminated by:', str(results['Solver'][0]['Termination condition'])) logger.info("\n\nRetrying...\n\n") else: # print ("SUCCESS: Solution Captured!") logger.info("Solution Captured!") model.solutions.store_to(results) #post_process_results() break if p_summary: print(results['Problem']) # print (results['Solver']) # print ("\nSolution Retrived at:",str(datetime.datetime.now())) # logger.info("Solution Retrived") return [model, results]
from pyomo.core import * from pyomo.opt import SolverFactory, SolverManagerFactory from DiseaseEstimation import model # create the instance instance = model.create('DiseaseEstimation.dat') # define the solver and its options solver = 'ipopt' opt = SolverFactory( solver ) if opt is None: raise ValueError, "Problem constructing solver `"+str(solver) opt.set_options('max_iter=2') # create the solver manager solver_manager = SolverManagerFactory( 'serial' ) # solve results = solver_manager.solve(instance, opt=opt, tee=True, timelimit=None) instance.load(results) # display results display(instance)
modelo.ganancias = Objective(rule=funcion_ganancias, sense=maximize) def funcion_capacidad_doug(modelo): return modelo.produccion["madera"] <= 6 modelo.capacidad_doug = Constraint(rule=funcion_capacidad_doug) def funcion_capacidad_linda(modelo): return modelo.produccion["aluminio"] <= 4 modelo.capacidad_linda = Constraint(rule=funcion_capacidad_linda) def funcion_capacidad_bob(modelo): return ( modelo.produccion["madera"]*6 + modelo.produccion["aluminio"]*8 <= 48 ) modelo.capacidad_bob = Constraint(rule=funcion_capacidad_bob) opt = SolverFactory("cbc") solver_manager = SolverManagerFactory('neos') resultados = solver_manager.solve(modelo, opt=opt) # resolver en la nube # resultados = opt.solve(modelo) # resolver localmente modelo.display()