B u `V@s$dZddlZddlZddlZddlZddlmZmZmZddl m Z ddl m Z ddl mZddlmZddlmZdd lmZdd lmZmZddlZddlZdd lmZdd lmZed Zd ddZ Gddde!Z"Gddde Z#e#dZ$ddZ%d!ddZ&Gddde!Z'd"ddZ(dS)#) OptSolver SolverFactory UnknownSolvercheck_available_solversN) ConfigBlock ConfigList ConfigValue)Factory)ApplicationError)Options) quote_split)ProblemConfigFactory)convert_problem) ResultsFormat ProblemFormat) iteritems)xrangez pyomo.optcCsd|kr|dksttd|}|dk r>tddt|DStd|}|dk rtdd|d d d|D}xt||kr|d 7}qzW|SdS) zG Attempts to extract solver version information from a string. rz [t,T]runkNcss|]}tdVqdS)infN)float).0ir:/tmp/pip-unpacked-wheel-n62dbgi3/pyomo/opt/base/solvers.py 8sz#_extract_version..z[0-9]+(\.[0-9]+){1,3}css|]}t|VqdS)N)int)rrrrrr;sr.)r)AssertionErrorresearchtuplergroupsplitlen)xlengthmversionrrr_extract_version-s  & r)c@sfeZdZddZddZddZddd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ dS)rcOs2d|kr|d|_ntdi|_||_||_dS)Ntypez4Expected option 'type' for UnknownSolver constructor)r* ValueErroroptions_args_kwds)selfargskwdsrrr__init__Ds zUnknownSolver.__init__cCs|S)Nr)r/rrr __enter__XszUnknownSolver.__enter__cCsdS)Nr)r/tv tracebackrrr__exit__[szUnknownSolver.__exit__TcCs|rtdt|jdS)z)Determine if this optimizer is available.zSolver (%s) not availableF)r strname)r/exception_flagrrr available^szUnknownSolver.availablecCsdS)z5 True is the solver can accept a warm-start solution.Fr)r/rrrwarm_start_capabledsz UnknownSolver.warm_start_capablecOs|ddS)z8Perform optimization and return an SolverResults object.solveN) _solver_error)r/r0r1rrrr=hszUnknownSolver.solvecCs|ddS)zReset the state of an optimizerresetN)r>)r/rrrr?lszUnknownSolver.resetcCs|ddS)z/Set the options in the optimizer from a string. set_optionsN)r>)r/istrrrrr@pszUnknownSolver.set_optionscCs|S)N)r;)r/rrr__bool__tszUnknownSolver.__bool__cCs||dS)N)r>)r/attrrrr __getattr__wszUnknownSolver.__getattr__cCsLtd|j|fdddt|jDd|jfd|jfdS)NaAAttempting to use an unavailable solver. The SolverFactory was unable to create the solver "%s" and returned an UnknownSolver object. This error is raised at the point where the UnknownSolver object was used as if it were valid (by calling method "%s"). The original solver was created with the following parameters: z css|]}d|VqdS)z%s: %sNr)rrrrrrsz.UnknownSolver._solver_error..z _args: %sz options: %s) RuntimeErrorr*joinsortedr.itemsr-r,)r/ method_namerrrr>zs zUnknownSolver._solver_errorN)T)__name__ __module__ __qualname__r2r3r7r;r<r=r?r@rBrDr>rrrrrBs rc@seZdZdddZdS)SolverFactoryClassNcKsj|dkr |St|}d|kr6|dd\}}||d<nd|krH|d}nd}d}y||jkrn|j|f|}nx|dd}|dkrd}ddi}d|kr||d<||kr|||jkrtd|j||f|}|dk r|d |Wn.td}t d ||fd}YnX|dk rD|d krD|dk rD|d ||dkrft fd |i|}||_ |S) N:rsolverZ solver_ionlZasl executablezl The solver plugin was not registered. Please confirm that the 'pyomo.environ' package has been imported.zsolver=z*Failed to create solver with name '%s': %spyr*) r8r#_clsgetrEr@sysexc_infologgerwarningrr9)r/_namer1Z subsolveroptmodeZ_implicit_solverserrrrr__call__sJ        zSolverFactoryClass.__call__)N)rJrKrLr]rrrrrMsrMz solver typec Gsddlm}ddlm}ddlm}ttjg}x|D]}t |t sT|}|f}n|d}t |}|dksvt |t r|d}n~|ddkr| sd}nd|ddkr| sd}nJ|ddks|dd kr| sd}n$|jdd ot|d  p|dk }|r:||q:Wttj|S) Nr) GUROBISHELL) BARONSHELL) MOSEKDirectFZgurobiZbaronZ mosek_directZmosek_persistent)r:rQ)Z$pyomo.solvers.plugins.solvers.GUROBIr^Z#pyomo.solvers.plugins.solvers.BARONr_Z*pyomo.solvers.plugins.solvers.mosek_directr`loggingdisableWARNING isinstancer!rrZlicense_is_validr;hasattrrQappendNOTSET) r0r^r_r`ansargr9rZr;rrrrs:            rcCstd||fdS)NzThe property '%s' can no longer be set directly on the solver object. It should instead be passed as a keyword into the solve method%s. It will automatically be reset to its default value after each invocation of solve.)AttributeError)r9keywordrrr_raise_ephemeral_errorsrmc@seZdZdZddZddZeddZejddZed d Z e jd d Z ed d Z e jdd Z eddZ e jddZ eddZ e jddZ eddZ e jddZ eddZejddZeddZejddZddZed d!Zd"d#Zd$d%Zd&d'Zd(d)Zd*d+Zd,d-Zd.d/Zd0d1Zd2d3ZdSd5d6Zd7d8Zd9d:Zd;d<Zd=d>Z d?d@Z!dAdBZ"dCdDZ#dEdFZ$dGdHZ%dTdJdKZ&dLdMZ'dUdNdOZ(dVdQdRZ)dIS)WrzA generic optimization solvercCs|S)Nr)r/rrrr3szOptSolver.__enter__cCsdS)Nr)r/r4r5r6rrrr7szOptSolver.__exit__cCs tddS)Ntee)rm)r/rrrrnsz OptSolver.teecCs tddS)Nrn)rm)r/valrrrrnscCs tddS)Nsuffixes)rm)r/rrrrpszOptSolver.suffixescCs tddS)Nrp)rm)r/rorrrrpscCs tddS)N keepfiles)rm)r/rrrrq szOptSolver.keepfilescCs tddS)Nrq)rm)r/rorrrrqscCs tddS)N soln_file)rm)r/rrrrrszOptSolver.soln_filecCs tddS)Nrr)rm)r/rorrrrrscCs tddS)Nlog_file)rm)r/rrrrsszOptSolver.log_filecCs tddS)Nrs)rm)r/rorrrrsscCs tddS)Nsymbolic_solver_labels)rm)r/rrrrt!sz OptSolver.symbolic_solver_labelscCs tddS)Nrt)rm)r/rorrrrt$scCstddddS)Nwarm_start_solvez (warmstart))rl)rm)r/rrrru(szOptSolver.warm_start_solvecCstddddS)Nruz (warmstart))rl)rm)r/rorrrru+scCstddddS)Nwarm_start_file_namez (warmstart_file))rl)rm)r/rrrrv/szOptSolver.warm_start_file_namecCstddddS)Nrvz (warmstart_file))rl)rm)r/rorrrrv2scKsRd|kr|d|_ntdd|kr0|d|_n|j|_d|krL|d|_n>|jdkr^d|_n,|j|jkrxd|j|_nd|j|jf|_t|_d |kr|d dk rx&|d D]}t|j||d |qWd|_d |_d |_ d |_ g|_ d|_ d|_ d|_d |_d|_g|_d|_i|_d|_d|_d|_d |_d|_d |_i|_t|_dS) z Constructor r*z0Expected option 'type' for OptSolver constructorr9docNrjz %s OptSolverz%s OptSolver (type %s)r,TrF)r*r+r9_docr r,setattr_smap_id_load_solutions _select_index_report_timing _suffixes _log_file _soln_file_default_variable_value_assert_available_problem_format_valid_problem_formats_results_formatZ_valid_result_formats_results_reader_problem_problem_filesZ _metasolver_version_allow_callbacks _callback _capabilities)r/r1keyrrrr26sL     zOptSolver.__init__cCsi}|}|s|S|ddks,|ddkr4t|}td|}xp|D]h}|d}|dkrftd|yt||dd}Wn||dd}YnX|||d|<qDW|S) Nr'"z[ ]+=z4Solver options must have the form option=value: '%s'r)stripevalr findr+)rArhtokenstokenindexrorrr_options_string_to_dicts$    z!OptSolver._options_string_to_dictcCs|jS)N)r)r/rrrdefault_variable_valuesz OptSolver.default_variable_valuecCs|S)N)r;)r/rrrrBszOptSolver.__bool__cCs|jdkr||_|jS)zM Returns a 4-tuple describing the solver executable version. N)r _get_version)r/rrrr(s  zOptSolver.versioncCsdS)Nr)r/rrrrszOptSolver._get_versioncCs|jS)z5 Returns the current problem format. )r)r/rrrproblem_formatszOptSolver.problem_formatcCs4||jkr||_ntd||f||j|_dS)z Set the current problem format (if it's valid) and update the results format to something valid for this problem format. z5%s is not a valid problem format for solver plugin %sN)rrr+_default_results_formatr)r/formatrrrset_problem_formats   zOptSolver.set_problem_formatcCs|jS)z5 Returns the current results format. )r)r/rrrresults_formatszOptSolver.results_formatcCs<|j|jkr$||j|jkr$||_ntd||j|fdS)zh Set the current results format (if it's valid for the current problem format). zL%s is not a valid results format for problem format %s with solver plugin %sN)rZ_valid_results_formatsrr+)r/rrrrset_results_formats  zOptSolver.set_results_formatcCsTt|ts2tddttttt|fn|jt|}|dkrLdS|SdS)a Returns a boolean value representing whether a solver supports a specific feature. Defaults to 'False' if the solver is unaware of an option. Expects a string. Example: # prints True if solver supports sos1 constraints, and False otherwise print(solver.has_capability('sos1') # prints True is solver supports 'feature', and False otherwise print(solver.has_capability('feature') Parameters ---------- cap: str The feature Returns ------- val: bool Whether or not the solver has the specified capability. z*Expected argument to be of type '%s', not z'%s'.NF)rdr8 TypeErrorr*r)r/caprorrrhas_capabilitys $zOptSolver.has_capabilityTcCsdS)z! True if the solver is available Tr)r/r:rrrr;szOptSolver.availablecCsdS)z5 True is the solver can accept a warm-start solution Fr)r/rrrr<szOptSolver.warm_start_capablecOs|jddddlm}ddl}ddlm}ddl}d}x|D]}t|||fr>t||rr|srt d|j f|}t||rt dd |j j j|D}n2t||stt d d |j jjj|dd d D}t|dkr>|d g} x|D]} | | kr| | qWq>W|j} t|_|j| |j|di|j||ddzHt} |j||t} |jrtd| | |dk r||| }t!|dr|`"t!|dst#$dnh|j%r:t#&d|j |j%f|j'rt#&dn(t!|dr,|j(r,t#&dt)|j(t*d|j t}|jrZtd|| |+}|j,|_,d|_-|r~t||r0t|j.dkrt/|d|j,|.d_0|j1|.d_2|j3r|4|.dnt|j.dksttt/|ddkstt5|d|`,|j3r~t|j.dkr~t#&dnN|j3r`|j6j7||j8|j1dd|_,|j.9n|j6j0|j,|_-|j6:|j,t}|jrtd||Wd| |_X|S) z Solve the problem T)r:r) _BlockDataN)IBlockz.css|] }|jVqdS)N)Z storage_key)rrrrrrsF)activeZ descend_intorpr,options_stringrjz) %6.2f seconds required for presolve_transformation_datarczSolver (%s) did not return a solver status code. This is indicative of an internal solver plugin error. Please report this to the Pyomo developers.z.Solver (%s) returned non-zero return code (%s)z4See the solver log above for diagnostic information.logz Solver log: z!Solver (%s) did not exit normallyz' %6.2f seconds required for solverrz ._symbol_mapszNo solution is available)selectrz* %6.2f seconds required for postsolve);r;Zpyomo.core.base.blockrZpyomo.core.base.suffixZpyomo.core.kernel.blockrZpyomo.core.kernel.suffixrdZis_constructedrEr9listcorebasesuffixZactive_import_suffix_generatorrkernelZimport_suffix_generatorr$ setdefaultrfr,r updatepoprtime _presolver}print_initialize_callbacks _apply_solverrerrWrXrerror_teerr8r _postsolverzZ_smapZsolutiongetattrZ symbol_maprrr{Z load_solutiondelattrZ solutionsZ load_fromr|clearZdelete_symbol_map)r/r0r1rpyomor_modelriZmodel_suffixesZ kwds_suffixesr9Z orig_optionsZ initial_timeZpresolve_completion_timeZ_statusZsolve_completion_timeresultZpostsolve_completion_timerrrr=s                         zOptSolver.solvecOs|dd|_|dd|_|dd|_|dd|_|dd|_|dd |_|d d |_|d d|_|d g|_ | |j rt }|j ||j |jf|\|_|_ |_t |}|jrtd |n4t|r td|jddddt|Dtjrt}nt}t|jttfkrRt|jd|sR|jd|_|jdkrl||j |_|jt j!krd|_"nt#j$j%j&'|j|_"dS)NlogfileZsolnfilerrZload_solutionsTZ timelimitZ report_timingFrnr;rpz* %6.2f seconds required to write filezSolver=z! passed unrecognized keywords: z css|]\}}d||fVqdS)z%s = %sNr)rkr5rrrrsz&OptSolver._presolve..)(rrrr|r{Z _timelimitr}rrr~r;rr_convert_problemrrrzrr$r+r*rFrsixPY3r8 basestringrr!rdrrrZsolnrrrZrresultsZ ReaderFactory)r/r0r1Zwrite_start_timeZ total_timeZ compare_typerrrrsB  (  zOptSolver._presolvecCsdS)zInitialize call-back functionsNr)r/modelrrrrszOptSolver._initialize_callbackscCstdS)z#The routine that performs the solveN)NotImplementedError)r/rrrrszOptSolver._apply_solvercCs|jS)z+The routine that does solve post-processing)r)r/rrrrszOptSolver._postsolvecKs,|jdk r|jtjdfSt||||jf|S)N)rrZcolin_optproblemrr)r/r0rZvalid_problem_formatsr1rrrrs zOptSolver._convert_problemcCstjS)zVReturns the default results format for different problem formats. )rr)r/Z prob_formatrrrrsz!OptSolver._default_results_formatcCsdS)z/ Reset the state of the solver Nr)r/rrrr?szOptSolver.resetNcCs||dkr|j}g}x^|D]V}||}t|tjrTd|krT|dt|t|fq|dt|t|fqWd|S)N z%s="%s"z%s=%s)r,rdr string_typesrfr8rF)r/r,rhrrorrr_get_options_strings zOptSolver._get_options_stringcCsFt|tjr||}x*|D]"}||dk rt|j|||qWdS)N)rdrrrryr,)r/rArrrrr@s     zOptSolver.set_optionscCs>|jstd|j|dkr0||jkr:|j|=n ||j|<dS)a Set the callback function for a named callback. A call-back function has the form: def fn(solver, model): pass where 'solver' is the native solver interface object and 'model' is a Pyomo model instance object. z Callbacks disabled for solver %sN)rr r9r)r/r9Z callback_fnrrr set_callbacks    zOptSolver.set_callbackFcCst||d\}}|S)N)init)default_config_block)r/rconfigblocksrrr config_blockszOptSolver.config_block)T)N)N)F)*rJrKrL__doc__r3r7propertyrnsetterrprqrrrsrtrurvr2 staticmethodrrrBr(rrrrrrr;r<r=rrrrrrr?rr@rrrrrrrsZ        U   !  8  rFc Cs$td|\}}t}|dtdtdd|dtdtddd|d tdtd d|d td td d|dtdtdd|dtdtdd|dtdtdtdddd|dtdtdd|dtgtdtdddd||d<|dtg|dd}||d dj d dd!|d dj d"d#d$d%|d d j d&d'd(d%|d d j d)d*d+d%|d dj d,d-d!|d dj d.d/d!|d dj d0d1d2d%|d dj d3d4d!|d5tgtdtd6dd7dj d5d!|d8t}|d9td:t d;dj dd!|d?tdtd@dj dAdBd$d%|dCtd:t dDdj dEd!|dFtdtdGdj dHdId(d%j dJdIdKdLdMdN|dOtd:t dPdj dOd!||d8<|dQ}|dRtd:t dSdj dTdUd!|dVtd:t dWdj dXdYdZd!||fS)[Ndefaultz solver nameZglpkz Solver namezsolver executablez3The solver executable used by the solver interface.aYThe solver executable used by the solver interface. This option is only valid for those solver interfaces that interact with a local executable through the shell. If unset, the solver interface will attempt to find an executable within the search path of the shell's environment that matches a name commonly associated with the solver interface.)rdomain descriptionrwz io formatzThe type of IO used to execute the solver. Different solvers support different types of IO, but the following are common options: lp - generate LP files, nl - generate NL files, python - direct Python interface, os - generate OSiL XML files.managerserialz7The technique that is used to manage solver executions.z pyro hostz=The hostname to bind on when searching for a Pyro nameserver.z pyro portz9The port to bind on when searching for a Pyro nameserver.r,Tz Solver optionzOptions passed into the solver)ZimplicitZimplicit_domainrzoptions stringz String describing solver optionsrpZSuffixzSolution suffixes that will be extracted by the solver (e.g., rc, dual, or slack). The use of this option is not required when a suffix has been declared on the model using Pyomo's Suffix component.rOZsolverszEList of solvers. The first solver in this list is the master solver.rz--solver)destz--solver-executableZsolver_executableFILE)rmetavarz --solver-ioZ io_formatZFORMATz--solver-managerZ smanager_typeZTYPEz --pyro-hostZ pyro_hostz --pyro-portZ pyro_portz--solver-optionsrSTRINGz--solver-suffixZsolver_suffixes postprocessModulez>Specify a Python module that gets executed after optimization. postsolvez print logfileFz7Print the solver logfile after performing optimization.z-lz--logrz save resultsz4Specify the filename to which the results are saved.z--save-resultsZ save_resultsz show resultsz,Print the results object after optimization.Z show_resultszresults formatz*Specify the results format: json or yaml.z--results-formatrz--json store_constjsonzStore results in JSON format)ractionconsthelpsummaryz;Summarize the final solution after performing optimization.runtimez only instancez(Generate a model instance, and then exitz--instance-onlyZ only_instancez stream outputzLStream the solver output to provide information about the solver's progress.z--stream-outputz--stream-solverrn) r rrZdeclarerr8rrrfrTZdeclare_as_argumentbool)rOrrrZ solver_listrrrrrr!s           $r)r)rj)F))__all__rrUrraZpyomo.common.configrrrZ pyomo.commonr Zpyomo.common.errorsr Zpyomo.common.collectionsr Z pyutilib.miscr Zpyomo.opt.base.problemr Zpyomo.opt.base.convertrZpyomo.opt.base.formatsrrZpyomo.opt.base.resultsrrrZ six.movesr getLoggerrWr)objectrrMrrrmrrrrrr s:         G-& 8