
    gl                         d dl Z d dlZd dlZd dlZddlmZmZmZmZ ddlm	Z	m
Z
 ddlmZ d dlmZmZmZmZ  G d d	e      ZeZ G d
 de      ZeZ G d de      Zy)    N   )LpSolver_CMDLpSolver
subprocessPulpSolverError)	scip_path
fscip_path   )	constants)DictListOptionalTuplec                      e Zd ZdZd Z	 	 	 	 	 	 	 	 	 	 	 d	dZej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  ej                  dZej                  ej                  ej                  hZd Zd Zd Zed        Zy)
SCIP_CMDzThe SCIP optimization solverNc                 F    t        j                  | |||||||||	||
       y)a+  
        :param bool mip: if False, assume LP even if integer variables
        :param bool msg: if False, no log is shown
        :param list options: list of additional options to pass to solver
        :param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
        :param str path: path to the solver binary
        :param float timeLimit: maximum time for solver (in seconds)
        :param float gapRel: relative gap tolerance for the solver to stop (in fraction)
        :param float gapAbs: absolute gap tolerance for the solver to stop
        :param int maxNodes: max number of nodes during branching. Stops the solving when reached.
        :param int threads: sets the maximum number of threads
        :param str logPath: path to the log file
        mipmsgoptionspath	keepFiles	timeLimitgapRelgapAbsmaxNodesthreadslogPathNr   __init__)selfr   r   r   r   r   r   r   r   r   r   r   s               O/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/pulp/apis/scip_api.pyr    zSCIP_CMD.__init__,   6    6 		
    )unknownzuser interruptznode limit reachedztotal node limit reachedzstall node limit reachedztime limit reachedzmemory limit reachedzgap limit reachedzsolution limit reachedz"solution improvement limit reachedzrestart limit reachedzoptimal solution found
infeasible	unboundedzinfeasible or unboundedc                 ,    | j                  t              S N)executableExtensionr   r!   s    r"   defaultPathzSCIP_CMD.defaultPathm   s    ''	22r$   c                 8    | j                  | j                        S True if the solver is available
executabler   r+   s    r"   	availablezSCIP_CMD.availablep       tyy))r$   c                    | j                  | j                        st        d| j                  z         | j                  |j                  ddd      \  }}}|j                  |       g }| j                  |j                  d| j                          d| j                  v r!|j                  d| j                  d           d	| j                  v r!|j                  d
| j                  d	           d| j                  v r!|j                  d| j                  d           d| j                  v r0t        | j                  d         dkD  rt        j                  d       | j                  s"t        j                  | j                   d       g }|j                  | j                         |j                  d|g       | j                  s|j                  d       d| j                  v r |j                  d| j                  d   g       t        | j                         }|D ]Z  }|j#                  d      rt%        |      }	|j                  ||	g       3d|vrt%        |      }	|d|	 z  }|j                  |       \ |j                  dd| dg       |j                  ddg       |j                  dd| dg       |j                  ddg       t'        |d      5 }
|
j)                  dj+                  |             ddd       t-        j.                  |t0        j2                  t0        j4                         t6        j                  j9                  |      st        d | j                  z         | j;                  |      \  }}i }|j=                         D ]+  }|j?                  |j                  d!      ||j                  <   - |jA                  |       |jC                  |       | jE                  |||       |S # 1 sw Y   xY w)""Solve a well formulated lp problemPuLP: cannot execute lpsolsetNlimits/time=r   limits/gap=r   limits/absgap=r   limits/nodes=r   r   zUSCIP can only run with a single thread - use FSCIP_CMD for a parallel version of SCIP' does not allow a problem to be relaxed-s-qr   -l-=z-czread ""optimizezwrite solution "quitw
stdoutstderrPuLP: Error while executing         )#r1   r   r   create_tmp_filesnamewriteLPr   appendoptionsDictintwarningswarnr   extendr   iterr   
startswithnextopenwritejoinr   
check_callsysrJ   rK   osexistsreadsol	variablesgetassignVarsValsassignStatusdelete_tmp_files)r!   r7   tmpLptmpSol
tmpOptionsfile_optionscommandr   optionargumentoptions_filestatusvalues	finalValsvs                  r"   actualSolvezSCIP_CMD.actualSolvet   s   tyy)!"9DII"EFF$($9$9"''4PU$V!vz


5"$>>%,t~~.> ?@t'''+d.>.>x.H-I JKt'''.1A1A(1K0L MN)))-0@0@0L/M NO(((S1A1A)1L-MPQ-QMMg xxMMTYYK'NOPtyy!j)*xxNN4 (((NND$"2"29"=>?t||$ 	,F  %=12 f$#G}H(n,F##F+	, 	ugQ/01j)* 0:;<f~&*c" 	8ltyy67	8gcjjLww~~f%!"@499"LMMf-	 	8A &

1663 7Iaff	8 	)$
eVZ8	8 	8s   !O::Pc                     t        |       5 }	 |j                         }|j                  d      }|d   dk(  sJ t        |      dk(  sJ 	 t        j                  j                  |d   j                         t        j                        }i }|t        j                  v r||fcddd       S 	 |j                         }|j                  d      }|d   dk(  sJ t        |      dk(  sJ t        |d   j                                |D ]'  }	 |j                         }t        |d         ||d   <   ) ||fcddd       S # t        $ r t        d      w xY w# t        $ r t        d	|      w xY w#  t        d
|      xY w# 1 sw Y   yxY w)zRead a SCIP solution filez: r   zsolution statusr
   zCan't get SCIP solver status: r   Nobjective valuez!Can't get SCIP solver objective: zCan't read SCIP solver output: )rZ   readlinesplitlen	Exceptionr   r   SCIP_STATUSESrc   stripr   LpStatusUndefinedNO_SOLUTION_STATUSESfloat)filenameflinecompsro   rp   s         r"   ra   zSCIP_CMD.readsol   s    (^ $	"qQzz|

4(Qx#44445zQ& ++//a )"="=F F666v~!$	" $	"&Tzz|

4(Qx#44445zQ&eAhnn&'
  VV JJLE',U1XF58$V 6>I$	" $	"  Q%(Fth&OPPQ$  T%(I$&RSSTV),KD8*TUUE$	" $	"sT   F;D;	AF+AEF$E1,F;EFE..F1FFFNTFTNNNNNNN)__name__
__module____qualname____doc__rO   r    r   r|   LpStatusNotSolvedLpStatusOptimalLpStatusInfeasibleLpStatusUnboundedrz   r}   r,   r2   rs   staticmethodra    r$   r"   r   r   '   s   &D (
V ..#55'99$-$?$?$-$?$?'99 ) ; ;&66"+"="=.7.I.I!*!<!<"+";";2200#,#>#>M$ 	$$####3*CJ &" &"r$   r   c                   6   e Zd ZdZd Z	 	 	 	 	 	 	 	 	 	 	 ddZej                  ej                  dZ	ej                  ej                  ej                  hZd Zd Zd Zeded	ee   fd
       Zeded	ee   fd       Zeded	eeeef      fd       Zed        Zy)	FSCIP_CMDzDThe multi-threaded FiberSCIP version of the SCIP optimization solverNc                 F    t        j                  | |||||||||	|
|       y)a+  
        :param bool msg: if False, no log is shown
        :param bool mip: if False, assume LP even if integer variables
        :param list options: list of additional options to pass to solver
        :param bool keepFiles: if True, files are saved in the current directory and not deleted after solving
        :param str path: path to the solver binary
        :param float timeLimit: maximum time for solver (in seconds)
        :param float gapRel: relative gap tolerance for the solver to stop (in fraction)
        :param float gapAbs: absolute gap tolerance for the solver to stop
        :param int maxNodes: max number of nodes during branching. Stops the solving when reached.
        :param int threads: sets the maximum number of threads
        :param str logPath: path to the log file
        r   Nr   )r!   r   r   r   r   r   r   r   r   r   r   r   s               r"   r    zFSCIP_CMD.__init__   r#   r$   )zNo SolutionzFinal Solutionc                 ,    | j                  t              S r)   )r*   r	   r+   s    r"   r,   zFSCIP_CMD.defaultPath  s    ''
33r$   c                 8    | j                  | j                        S r.   r0   r+   s    r"   r2   zFSCIP_CMD.available"  r3   r$   c                 $	   | j                  | j                        st        d| j                  z         | j                  |j                  dddd      \  }}}}|j                  |       g }| j                  |j                  d| j                          d| j                  v r!|j                  d	| j                  d           d
| j                  v r!|j                  d| j                  d
           d| j                  v r!|j                  d| j                  d           | j                  s"t        j                  | j                   d       g }|j                  d       g }|j                  | j                         |j                  |       |j                  |       |j                  d|g       |j                  d|g       | j                  s|j                  d       d| j                  v r |j                  d| j                  d   g       d| j                  v r!|j                  d| j                  d    g       t        | j                        }	|	D ]r  }
|
j!                  d      rt#        |	      }|j                  |
|g       3d|
v }d|
vrt#        |	      }|
d| z  }
|r|j                  |
       b|j                  |
       t | j%                  |       t'        |d      5 }|j)                  dj+                  |             ddd       t'        |d      5 }|j)                  dj+                  |             ddd       t-        j.                  || j                  rt0        j2                  nt,        j4                  | j                  rt0        j6                  nt,        j4                         t8        j                  j;                  |      st        d| j                  z         | j=                  |      \  }}i }|j?                         D ]+  }|jA                  |j                  d      ||j                  <   - |jC                  |       |jE                  |       | jG                  ||||       |S # 1 sw Y   nxY w# 1 sw Y   FxY w)r5   r6   r7   r8   r9   prmNr:   r   r;   r   r<   r   r=   r>   zNoPreprocessingInLC = TRUEr?   z-fsolr@   r   rA   r   z-sthrB   /rC   rG   rH   rI   rL   rM   )$r1   r   r   rN   rO   rP   r   rQ   rR   r   rT   rU   rV   r   rW   r   rX   rY   silent_removerZ   r[   r\   r   r]   r^   rJ   DEVNULLrK   r_   r`   ra   rb   rc   rd   re   rf   )r!   r7   rg   rh   ri   	tmpParamsrj   file_parametersrk   r   rl   rm   is_file_optionsrn   parameters_filero   rp   rq   rr   s                      r"   rs   zFSCIP_CMD.actualSolve&  s   tyy)!"9DII"EFF/3/D/DGGT5%0
,vz9 	

5"$>>%,t~~.> ?@t'''+d.>.>x.H-I JKt'''.1A1A(1K0L MN)))-0@0@0L/M NOxxMMTYYK'NOP%';<tyy!y!uj)*()xxNN4 (((NND$"2"29"=>?(((NNFt'7'7	'B&CEFt||$ 	3F  %=12 #&- f$#G}H(n,F" ''/#**62%	3* 	6"*c" 	8ltyy67	8)S! 	>_!!$))O"<=	>!%3::z/A/A!%3::z/A/A	
 ww~~f%!"@499"LMMf-	 	8A &

1663 7Iaff	8 	)$
eVZC+	8 	8	> 	>s   +!Q8 !R8RRstringreturnc                 `    t         j                  j                         D ]  \  }}|| v s|c S  y r)   )r   FSCIP_STATUSESitems)r   fscip_statuspulp_statuss      r"   parse_statuszFSCIP_CMD.parse_status{  s8    )2)A)A)G)G)I 	#%L+v%""	# r$   c                     | j                  d      }t        |      dk7  ry |\  }}|dk7  ry |j                         }	 t        |      }|S # t        $ r Y y w xY w)N:r
   ru   )rw   rx   r{   r~   
ValueError)r   fieldslabel	objectives       r"   parse_objectivezFSCIP_CMD.parse_objective  sl    c"v;!!y%%OO%		i(I   		s   A
 
	AAc                     | j                         }t        |      dk  ry |d d \  }}	 t        |      }||fS # t        $ r Y y w xY w)Nr
   )rw   rx   r~   r   )r   r   rO   values       r"   parse_variablezFSCIP_CMD.parse_variable  sX    v;?Raje	%LE U{  		s   8 	AAc                    t        |       5 }|j                         }t        j                  |      }|t	        d|      |t        j
                  v r|i fcddd       S |j                         }t        j                  |      }|t	        d|      i }|D ]1  }t        j                  |      }|t	        d|      |\  }	}
|
||	<   3 ||fcddd       S # 1 sw Y   yxY w)zRead a FSCIP solution fileNzCan't get FSCIP solver status: z"Can't get FSCIP solver objective: z Can't read FSCIP solver output: )rZ   rv   r   r   r   r}   r   r   )r   filestatus_linero   objective_liner   rb   variable_linevariablerO   r   s              r"   ra   zFSCIP_CMD.readsol  s    (^ 	%t--/K++K8F~%(G&WXX777rz	% 	% "]]_N!11.AI %88JK 
 +-I!% ($33MB#):=:KL  'e"'	$( 9$=	% 	% 	%s   AC!A0CC$r   )r   r   r   r   rO   r    r   r   r   r   r   r   r}   r,   r2   rs   r   strr   rS   r   r~   r   r   r   ra   r   r$   r"   r   r      s   ND (
V !22#33N
 	$$####4*Sj S Xc]      " s xc5j0A'B    %  %r$   r   c                        e Zd ZdZd Z	 ddla	 	 	 	 	 	 	 	 	 	 d fd	Zd Zd Z	d Z
d Zd	 Zd
 Z xZS # e$ r d Z	d ZY  xZS w xY w)SCIP_PYa  
    The SCIP Optimization Suite (via its python interface)

    The SCIP internals are available after calling solve as:
    - each variable in variable.solverVar
    - each constraint in constraint.solverConstraint
    - the model in problem.solverModel
    r   Nc                 8    t         |   |||||||||	|

       y)a  
            :param bool mip: if False, assume LP even if integer variables
            :param bool msg: if False, no log is shown
            :param list options: list of additional options to pass to solver
            :param float timeLimit: maximum time for solver (in seconds)
            :param float gapRel: relative gap tolerance for the solver to stop (in fraction)
            :param float gapAbs: absolute gap tolerance for the solver to stop
            :param int maxNodes: max number of nodes during branching. Stops the solving when reached.
            :param str logPath: path to the log file
            :param int threads: sets the maximum number of threads
            :param bool warmStart: if True, the solver will use the current value of variables as a start
            )
r   r   r   r   r   r   r   r   r   	warmStartN)superr    )r!   r   r   r   r   r   r   r   r   r   r   	__class__s              r"   r    zSCIP_PY.__init__  s5    2 G#!#  r$   c                 x   d|_         |j                  j                         }t        j                  t        j
                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  t        j                  d}d}||   }||v r	 |j                  j                         }|j                  D ]  }||j                     |_         |j                  j                         D ]-  }|j                  j                  |j                   |      |_        / |t        j                  k(  r!|j%                  |t        j&                         n0t        j                  }|j%                  |t        j(                         |S |j%                  |       |S #  |j%                  |t        j*                         Y |S xY w)NT)optimalr'   r&   	inforunbd	timelimituserinterrupt	nodelimittotalnodelimitstallnodelimitgaplimitmemlimitsollimitbestsollimitrestartlimitr%   )r   r   r   r   r   r   r   r   )	resolveOKsolverModel	getStatusr   r   r   r   r   r|   
getBestSol
_variables	solverVarvarValueconstraintsrp   getSlacksolverConstraintslackre   LpSolutionOptimalLpSolutionIntegerFeasibleLpSolutionNoSolutionFound)	r!   r7   solutionStatusscip_to_pulp_status possible_solution_found_statusesro   solutionr   
constraints	            r"   findSolutionValueszSCIP_PY.findSolutionValues  s   BL^^557N$44&88'::&88&88!*!<!<&88"+"="="+"="=%77%77%77 ) ; ; ) ; ;$66#"	0, )8F!AAQ!~~88:H$&MM I,4X5G5G,H)I&(nn&;&;&= 
+->>+B+B&77,
( !:!::	0K0KL!*!:!:	0S0ST M ' MQOOFI,O,OP Ms   C-H "H9c                      y)r/   Tr   r+   s    r"   r2   zSCIP_PY.availableH  s     r$   c                 8    |j                   j                          y)zSolves the problem with scipN)r   rE   r!   r7   s     r"   
callSolverzSCIP_PY.callSolverM  s    NN##%r$   c                 	   t         j                  |j                        |_        |j                  t
        j                  k(  r|j                  j                          n|j                  j                          | j                  s|j                  j                          | j                  &|j                  j                  d| j                         d| j                  v r)|j                  j                  d| j                  d          d| j                  v r)|j                  j                  d| j                  d          d| j                  v r)|j                  j                  d| j                  d          d	| j                  v r(|j                  j                  | j                  d	          d
| j                  v r>t        | j                  d
         dkD  r#t!        j"                  d| j                   d       | j$                  s"t!        j"                  | j                   d       t'        | j(                        }|D ]F  }d|v r|j+                  dd      \  }}n|t-        |      }}|j                  j                  ||       H t
        j.                  dt
        j0                  dt
        j2                  di}|j5                         D ]l  }|j                  j7                  |j                  ||j8                     |j:                  |j<                  |j>                  jA                  |d            |_!        n t
        jD                  tF        jH                  t
        jJ                  tF        jL                  t
        jN                  tF        jP                  i}|jR                  jU                         D ]n  \  }}	|j                  jW                   ||	j                     t         jY                  d |	jU                         D              |	jZ                         |      |	_.        p | j                  jA                  dd      r|j                  j_                         }
|j5                         D ]@  }|j`                  |j                  jc                  |
|jB                  |j`                         B |j                  je                  |
       yy)zU
            Takes the pulp lp model and translates it into a scip model
            Nzlimits/timer   z
limits/gapr   zlimits/absgapr   zlimits/nodesr   r   r   zThe solver z" can only run with a single threadr>   rC   r
   )maxsplitBCIrM   )rO   vtypelbubobjc              3   @   K   | ]  \  }}||j                   z    y wr)   )r   ).0r   coefficients      r"   	<genexpr>z+SCIP_PY.buildSolverModel.<locals>.<genexpr>  s'      & 5+ ((*<*<<&s   )consrO   r   F)3scipModelrO   r   senser   
LpMaximizesetMaximizesetMinimizer   
hideOutputr   setParamrR   
setLogfilerS   rT   rU   r   rW   r   rw   rY   LpBinaryLpContinuous	LpIntegerrb   addVarcatlowBoundupBoundr   rc   r   LpConstraintLEoperatorleLpConstraintGEgeLpConstraintEQeqr   r   addConsquicksumconstantr   createPartialSolr   	setSolValaddSol)r!   r7   r   rl   rO   r   category_to_vtypevarsense_to_operatorr   ss              r"   buildSolverModelzSCIP_PY.buildSolverModelQ  s    "ZZ0BNxx9///**,**,
 88))+~~)''t~~F4+++''d6F6Fx6PQ4+++''9I9I(9STT---''8H8H8TUD,,,))$*:*:9*EFD,,,T5E5Ei5P1QTU1U!$)),NO 88+RST4<<(G! 5&="(,,sQ,"?KD%"($w-%D''e45 ""C&&##S!
 ||~  " 5 5+CGG4||{{((c2 !6 ! (((++(((++(((++!
 %'NN$8$8$: 
 j.0nn.D.D<*:+;+;< &9C9I9I9K&  $,,,  /E 	/
+
 ##K7NN335<<> QC||/00CMM3<<PQ %%a( 8r$   c                     | j                  |       | j                  |       | j                  |      }|j                  D ]	  }d|_         |j
                  j                         D ]	  }d|_         |S )z
            Solve a well formulated lp problem

            creates a scip model, variables and constraints and attaches
            them to the lp model which it then solves
            F)r  r   r   r   modifiedr   rp   )r!   r7   r   r   r   s        r"   rs   zSCIP_PY.actualSolve  ss     !!"%OOB!44R8NMM *$)!* nn335 ,
&+
#,!!r$   c                 4    t        d| j                   d      )z
            Solve a well formulated lp problem

            uses the old solver and modifies the rhs of the modified constraints
            The z$ solver does not implement resolvingr   rO   r   s     r"   actualResolvezSCIP_PY.actualResolve  s"     "tyyk!EF r$   c                      y)r/   Fr   r+   s    r"   r2   zSCIP_PY.available  s    r$   c                 4    t        d| j                   d      )r5   r  z solver is not availabler  r   s     r"   rs   zSCIP_PY.actualSolve  s    !D3K"LMMr$   )
TTNNNNNNNF)r   r   r   r   rO   	pyscipoptr   r    r   r2   r   r  rs   r  ImportError__classcell__)r   s   @r"   r   r     s~     Ds   $	L;	z	
	&Z	)x	" 	I  N		NNs   5 AAr   )r   r_   r^   rT   corer   r   r   r   r   r	    r   typingr   r   r   r   r   SCIPr   FSCIPr   r   r$   r"   <module>r      s_   6  	 
  E E '  . .y"| y"x ]% ]%@ 	h r$   