B @`K@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-bi3529v6/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@sneZdZddZddZddZddd Zd d Zd d ZddZ ddZ ddZ ddZ ddZ ddZdS)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)zETrue if the solver is present and has a valid license (if applicable)Fr)r/rrrlicense_is_validdszUnknownSolver.license_is_validcCsdS)z5 True is the solver can accept a warm-start solution.Fr)r/rrrwarm_start_capablehsz UnknownSolver.warm_start_capablecOs|ddS)z8Perform optimization and return an SolverResults object.solveN) _solver_error)r/r0r1rrrr>lszUnknownSolver.solvecCs|ddS)zReset the state of an optimizerresetN)r?)r/rrrr@pszUnknownSolver.resetcCs|ddS)z/Set the options in the optimizer from a string. set_optionsN)r?)r/istrrrrrAtszUnknownSolver.set_optionscCs|S)N)r;)r/rrr__bool__xszUnknownSolver.__bool__cCs||dS)N)r?)r/attrrrr __getattr__{szUnknownSolver.__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?~s zUnknownSolver._solver_errorN)T)__name__ __module__ __qualname__r2r3r7r;r<r=r>r@rArCrEr?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#_clsgetrFrAsysexc_infologgerwarningrr9)r/_namer1Z subsolveroptmodeZ_implicit_solverserrrrr__call__sJ        zSolverFactoryClass.__call__)N)rKrLrMr^rrrrrNsrNz solver typecGsddlm}ddlm}ddlm}ttjg}x|D]x}t |t sT|}|f}n|d}t |}|dks:t |t rxq:|j ddsq:t|dr|dkrq:|sq:||q:Wttj|S)Nr) GUROBISHELL) BARONSHELL) MOSEKDirectF)r:rR)Z$pyomo.solvers.plugins.solvers.GUROBIr_Z#pyomo.solvers.plugins.solvers.BARONr`Z*pyomo.solvers.plugins.solvers.mosek_directraloggingdisableWARNING isinstancer!rrr;hasattrrRr<appendNOTSET)r0r_r`raansargr9r[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_errorsrnc@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/Zd0d1Zd2d3ZdUd5d6Zd7d8Zd9d:Zd;d<Zd=d>Z d?d@Z!dAdBZ"dCdDZ#dEdFZ$dGdHZ%dIdJZ&dVdLdMZ'dNdOZ(dWdPdQZ)dXdSdTZ*dKS)YrzA generic optimization solvercCs|S)Nr)r/rrrr3szOptSolver.__enter__cCsdS)Nr)r/r4r5r6rrrr7szOptSolver.__exit__cCs tddS)Ntee)rn)r/rrrrosz OptSolver.teecCs tddS)Nro)rn)r/valrrrroscCs tddS)Nsuffixes)rn)r/rrrrqszOptSolver.suffixescCs tddS)Nrq)rn)r/rprrrrqscCs tddS)N keepfiles)rn)r/rrrrr szOptSolver.keepfilescCs tddS)Nrr)rn)r/rprrrrrscCs tddS)N soln_file)rn)r/rrrrsszOptSolver.soln_filecCs tddS)Nrs)rn)r/rprrrrsscCs tddS)Nlog_file)rn)r/rrrrtszOptSolver.log_filecCs tddS)Nrt)rn)r/rprrrrtscCs tddS)Nsymbolic_solver_labels)rn)r/rrrru!sz OptSolver.symbolic_solver_labelscCs tddS)Nru)rn)r/rprrrru$scCstddddS)Nwarm_start_solvez (warmstart))rm)rn)r/rrrrv(szOptSolver.warm_start_solvecCstddddS)Nrvz (warmstart))rm)rn)r/rprrrrv+scCstddddS)Nwarm_start_file_namez (warmstart_file))rm)rn)r/rrrrw/szOptSolver.warm_start_file_namecCstddddS)Nrwz (warmstart_file))rm)rn)r/rprrrrw2scKsRd|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 constructorr9docNrkz %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+)rBritokenstokenindexrprrr_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/rrrrCszOptSolver.__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)rer8 TypeErrorr*r)r/caprprrrhas_capabilitys $zOptSolver.has_capabilityTcCsdS)z! True if the solver is available Tr)r/r:rrrr;szOptSolver.availablecCsdS)zETrue if the solver is present and has a valid license (if applicable)Tr)r/rrrr<szOptSolver.license_is_validcCsdS)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)rrrrrr sF)activeZ descend_intorqr,options_stringrkz) %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.suffixreZis_constructedrFr9listcorebasesuffixZactive_import_suffix_generatorrkernelZimport_suffix_generatorr$ setdefaultrgr,r updatepoprtime _presolver~print_initialize_callbacks _apply_solverrfrrXrYrerror_teerr8r _postsolver{Z_smapZsolutiongetattrZ symbol_maprrr|Z load_solutiondelattrZ solutionsZ load_fromr}clearZdelete_symbol_map)r/r0r1rpyomor_modelrjZmodel_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_timingFror;rqz* %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~rrrr;rr_convert_problemrrr{rr$r+r*rGrsixPY3r8 basestringrr!rerrrZsolnrrr[rresultsZ 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,rer string_typesrgr8rG)r/r,rirrprrr_get_options_strings zOptSolver._get_options_stringcCsFt|tjr||}x*|D]"}||dk rt|j|||qWdS)N)rerrrrzr,)r/rBrrrrrAs     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_callback s    zOptSolver.set_callbackFcCst||d\}}|S)N)init)default_config_block)r/rconfigblocksrrr config_block szOptSolver.config_block)T)N)N)F)+rKrLrM__doc__r3r7propertyrosetterrqrrrsrtrurvrwr2 staticmethodrrrCr(rrrrrrr;r<r=r>rrrrrrr@rrArrrrrrrs\        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 descriptionrxz 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 optionsrqZSuffixzSolution 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.rPZsolverszEList 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-solverro) r rrZdeclarerr8rrrgrUZdeclare_as_argumentbool)rPrrrZ solver_listrrrrrr%s             r)r)rk)F))__all__rrVrrbZpyomo.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 getLoggerrXr)objectrrNrrrnrrrrrr s:         K-" <