Decision Optimization

 View Only
Expand all | Collapse all

SparsePair usage in linear constraint construction in CPLEX Python API (not docplex)

  • 1.  SparsePair usage in linear constraint construction in CPLEX Python API (not docplex)

    Posted Tue July 07, 2020 11:02 AM
    Hi everyone,
    I was trying to use numpy together with cplex, since I thought numpy will enable me to write the constraints easier considering the constraints on different dimensions of my model. 
    In the following code snippet, the cplex variable indices "shipment" is  a numpy ndarray with 4 dimensions with the 3rd dimension to be the market index. 

    # the following code doesn't working, mysteriously
    cpx.linear_constraints.add(
        lin_expr=[cplex.SparsePair(shipment[i,j,:,t].tolist() +[duration_p[i,j,t]],
          [1]*len(market) + [-vaData.max_cap[i]*vaData.max_pen])
          for i in range(len(plant))
          for j in range(len(prog))
          for t in range(len(time))],
        senses=["L"] * len(rownames),
        rhs=[0] * len(rownames),
        names=rownames)
    

    The error msg for the first code snippet is " ValueError: (' invalid matrix input type -- ', 331044)". 
    I also tried the following. 

    cpx.linear_constraints.add(
        lin_expr=[cplex.SparsePair(np.append(shipment[i,j,:,t], duration_p[i,j,t]).tolist(),
          [1]*len(market) + [-vaData.max_cap[i]*vaData.max_pen])
          for i in range(len(plant))
          for j in range(len(prog))
          for t in range(len(time))],
        senses=["L"] * len(rownames),
        rhs=[0] * len(rownames),
        names=rownames)
    ​

    and this is working. However, in the meantime we have

    np.append(shipment[i, j, :, t], duration_p[i, j, t]).tolist() == shipment[i,j,:,t].tolist() +[duration_p[i,j,t]]
    
    >>> True

    Can anyone gives an explanation why the first one is not working?

    Regards



    ------------------------------
    Rax
    ------------------------------

    #DecisionOptimization


  • 2.  RE: SparsePair usage in linear constraint construction in CPLEX Python API (not docplex)

    Posted Tue July 07, 2020 11:17 AM
    Can you please add a backtrace for this error you get?

    ------------------------------
    Daniel Junglas
    ------------------------------



  • 3.  RE: SparsePair usage in linear constraint construction in CPLEX Python API (not docplex)

    Posted Tue July 07, 2020 02:27 PM
    Edited by System Test Fri January 20, 2023 04:50 PM

    Hi Daniel, 
    Thanks for the quick response. Following is the traceback info. 

    ValueError                                Traceback (most recent call last)
    <ipython-input-111-aec32d29074e> in <module>
          7     senses=["L"] * len(rownames),
          8     rhs=[0] * len(rownames),
    ----> 9     names=rownames)
    
    ~/Programs/anaconda3/lib/python3.7/site-packages/cplex/_internal/_subinterfaces.py in add(self, lin_expr, senses, rhs, range_values, names)
       1257             lin_expr, senses, rhs, range_values, names)
       1258         return self._add_iter(self.get_num, self._add,
    -> 1259                               lin_expr, senses, rhs, range_values, names)
       1260
       1261     def delete(self, *args):
    
    ~/Programs/anaconda3/lib/python3.7/site-packages/cplex/_internal/_baseinterface.py in _add_iter(getnumfun, addfun, *args, **kwargs)
         39         """non-public"""
         40         old = getnumfun()
    ---> 41         addfun(*args, **kwargs)
         42         return range(old, getnumfun())
         43
    
    ~/Programs/anaconda3/lib/python3.7/site-packages/cplex/_internal/_subinterfaces.py in _add(self, lin_expr, senses, rhs, range_values, names)
       1183         if lin_expr:
       1184             with CPX_PROC.chbmatrix(lin_expr, self._cplex._env_lp_ptr,
    -> 1185                                     0) as (rmat, nnz):
       1186                 CPX_PROC.addrows(self._env._e, self._cplex._lp, 0,
       1187                                  num_new_rows, nnz, rhs, senses,
    
    ~/Programs/anaconda3/lib/python3.7/contextlib.py in __enter__(self)
        110         del self.args, self.kwds, self.func
        111         try:
    --> 112             return next(self.gen)
        113         except StopIteration:
        114             raise RuntimeError("generator didn't yield") from None
    
    ~/Programs/anaconda3/lib/python3.7/site-packages/cplex/_internal/_procedural.py in chbmatrix(lolmat, env_lp_ptr, r_c)
        153 def chbmatrix(lolmat, env_lp_ptr, r_c):
        154     """See matrix_conversion.c:Pylolmat_to_CHBmat()."""
    --> 155     mat = Pylolmat_to_CHBmat(lolmat, env_lp_ptr, r_c)
        156     try:
        157         # yields ([matbeg, matind, matval], nnz)
    
    ~/Programs/anaconda3/lib/python3.7/site-packages/cplex/_internal/_procedural.py in Pylolmat_to_CHBmat(lolmat, env_lp_ptr, r_c)
        162
        163 def Pylolmat_to_CHBmat(lolmat, env_lp_ptr, r_c):
    --> 164     return CR.Pylolmat_to_CHBmat(lolmat, env_lp_ptr, r_c)
        165
        166
    
    ~/Programs/anaconda3/lib/python3.7/site-packages/cplex/_internal/_pycplex.py in Pylolmat_to_CHBmat(lolmat, env_lp_ptr, py_row_col)
       1624
       1625 def Pylolmat_to_CHBmat(lolmat: 'PyObject *', env_lp_ptr: 'PyObject *', py_row_col: 'PyObject *') -> "PyObject *":
    -> 1626     return _pycplex_platform.Pylolmat_to_CHBmat(lolmat, env_lp_ptr, py_row_col)
       1627
       1628 def free_CHBmat(HBMat: 'PyObject *') -> "void":
    
    ValueError: (' invalid matrix input type -- ', 331044)
    ​


    ------------------------------
    Rax
    ------------------------------