
    khJm                         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
 d dlmZmZmZmZ dZd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   )	constants)DictListOptionalTuplescipfscipc                      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               x/var/www/html/SchoolMeal/SchoolMeal/pds_admin_SchoolMeal/Backend/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)executableExtension	scip_pathr!   s    r"   defaultPathzSCIP_CMD.defaultPathp   s    ''	22r$   c                 8    | j                  | j                        S True if the solver is available
executabler   r,   s    r"   	availablezSCIP_CMD.availables       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       | j-                         }t/        j0                  |||       ||j3                          t4        j                  j7                  |      st        d | j                  z         | j9                  |      \  }}i }|j;                         D ]+  }|j=                  |j                  d!      ||j                  <   - |j?                  |       |jA                  |       | jC                  |||       |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         )"r2   r   r   create_tmp_filesnamewriteLPr   appendoptionsDictintwarningswarnr   extendr   iterr   
startswithnextopenwritejoinget_piper   
check_callcloseosexistsreadsol	variablesgetassignVarsValsassignStatusdelete_tmp_files)r!   r8   tmpLptmpSol
tmpOptionsfile_optionscommandr   optionargumentoptions_filepipestatusvalues	finalValsvs                   r"   actualSolvezSCIP_CMD.actualSolvew   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 }}gd4@ JJLww~~f%!"@499"LMMf-	 	8A &

1663 7Iaff	8 	)$
eVZ8+	8 	8s   !P  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 }	 |j                         }|j                  d      }|d   dk(  sJ t        |      dk(  sJ t        |d   j                                |D ]'  }	 |j                         }t        |d         ||d   <   ) t        j                  }||fcddd       S # t        $ r t        d      w xY w# t        $ r ||fcY cddd       S 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   objective valueNzCan't read SCIP solver output: )r[   readlinesplitlen	Exceptionr   r   SCIP_STATUSESre   stripr	   LpStatusUndefinedfloatLpStatusOptimal)filenameflinecompsrr   rs   s         r"   rc   zSCIP_CMD.readsol   s    (^ %	"qQzz|

4(Qx#44445zQ& ++//a )"="=F F&zz|

4(Qx#44445zQ&eAhnn&'  VV JJLE',U1XF58$V ..F6>K%	" %	"  Q%(Fth&OPPQ  &v~%1%	" %	",&V),KD8*TUUA%	" %	"s`   E6;D,	AE6AE#E6)$E#E6,EE6E E6E  E6#E33E66E?NTFTNNNNNNN)__name__
__module____qualname____doc__rP   r    r	   r   LpStatusNotSolvedr   LpStatusInfeasibleLpStatusUnboundedr}   NO_SOLUTION_STATUSESr-   r3   rv   staticmethodrc    r$   r"   r   r   *   s   &D (
V ..#55'99$-$?$?$-$?$?'99 ) ; ;&66"+"="=.7.I.I!*!<!<"+";";2200#,#>#>M$ 	$$####3*IV '" '"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*   
fscip_pathr,   s    r"   r-   zFSCIP_CMD.defaultPath)  s    ''
33r$   c                 8    | j                  | j                        S r/   r1   r,   s    r"   r3   zFSCIP_CMD.available,  r4   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       | j-                         }t/        j0                  |||       ||j3                          t4        j                  j7                  |      st        d| j                  z         | j9                  |      \  }}i }|j;                         D ]+  }|j=                  |j                  d      ||j                  <   - |j?                  |       |jA                  |       | jC                  ||||       |S # 1 sw Y   <xY w# 1 sw Y   xY w)r6   r7   r8   r9   r:   prmNr;   r   r<   r   r=   r   r>   r?   zNoPreprocessingInLC = TRUEr@   z-fsolrA   r   rB   r   z-sthrC   /rD   rH   rI   rJ   rM   rN   )"r2   r   r   rO   rP   rQ   r   rR   rS   r   rU   rV   rW   r   rX   r   rY   rZ   silent_remover[   r\   r]   r^   r   r_   r`   ra   rb   rc   rd   re   rf   rg   rh   )r!   r8   ri   rj   rk   	tmpParamsrl   file_parametersrm   r   rn   ro   is_file_optionsrp   parameters_filerq   rr   rs   rt   ru   s                       r"   rv   zFSCIP_CMD.actualSolve0  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"<=	> }}gd4@JJLww~~f%!"@499"LMMf-	 	8A &

1663 7Iaff	8 	)$
eVZC-	8 	8	> 	>s   +!Q !QQQ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   rx   )rz   r{   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   )rz   r{   r   r   )r   r   rP   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: )r[   ry   r   r   r   r   r   r   )r   filestatus_linerr   objective_liner   rd   variable_linevariablerP   r   s              r"   rc   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   rP   r    r	   r   r   r   r   r   r   r-   r3   rv   r   strr   rT   r   r   r   r   r   rc   r   r$   r"   r   r      s   ND (
V !22#33N
 	$$####4*Tl 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constraintsrs   getSlacksolverConstraintslackrg   LpSolutionOptimalLpSolutionIntegerFeasibleLpSolutionNoSolutionFound)	r!   r8   solutionStatusscip_to_pulp_status possible_solution_found_statusesrr   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)r0   Tr   r,   s    r"   r3   zSCIP_PY.availableS  s     r$   c                 8    |j                   j                          y)zSolves the problem with scipN)r   rF   r!   r8   s     r"   
callSolverzSCIP_PY.callSolverX  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?   rD   r   )maxsplitBCIrN   )rP   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   )consrP   r   F)3r   ModelrP   r   senser	   
LpMaximizesetMaximizesetMinimizer   
hideOutputr   setParamrS   
setLogfilerT   rU   rV   r   rX   r   rz   rZ   LpBinaryLpContinuous	LpIntegerrd   addVarcatlowBoundupBoundr   re   r   LpConstraintLEoperatorleLpConstraintGEgeLpConstraintEQeqr   r   addConsquicksumconstantr   createPartialSolr   	setSolValaddSol)r!   r8   r   rn   rP   r   category_to_vtypevarsense_to_operatorr   ss              r"   buildSolverModelzSCIP_PY.buildSolverModel\  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   rs   )r!   r8   r   r   r   s        r"   rv   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   rP   r   s     r"   actualResolvezSCIP_PY.actualResolve  s"     "tyyk!EF r$   c                      y)r0   Fr   r,   s    r"   r3   zSCIP_PY.available  s    r$   c                 4    t        d| j                   d      )r6   r  z solver is not availabler  r   s     r"   rv   zSCIP_PY.actualSolve  s    !D3K"LMMr$   )
TTNNNNNNNF)r   r   r   r   rP   	pyscipoptr   r    r   r3   r   r  rv   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  ra   sysrU   corer   r   r   r    r	   typingr
   r   r   r   r+   r   r   SCIPr   FSCIPr   r   r$   r"   <module>r#     sf   6  	 
  E E  . .	
@"| @"F ^% ^%B 	h r$   