<commit_before>"""LInked List sparse matrix class
"""

from __future__ import division, print_function, absolute_import

__docformat__ = "restructuredtext en"

__all__ = ['lil_matrix','isspmatrix_lil']

from bisect import bisect_left

import numpy as np
from scipy.lib.six.moves import xrange

from .base import spmatrix, isspmatrix
from .sputils import getdtype, isshape, issequence, isscalarlike, ismatrix

from warnings import warn
from .base import SparseEfficiencyWarning


class lil_matrix(spmatrix):
    """Row-based linked list sparse matrix

    This is an efficient structure for constructing sparse
    matrices incrementally.

    This can be instantiated in several ways:
        lil_matrix(D)
            with a dense matrix or rank-2 ndarray D

        lil_matrix(S)
            with another sparse matrix S (equivalent to S.tolil())

        lil_matrix((M, N), [dtype])
            to construct an empty matrix with shape (M, N)
            dtype is optional, defaulting to dtype='d'.

    Attributes
    ----------
    dtype : dtype
        Data type of the matrix
    shape : 2-tuple
        Shape of the matrix
    ndim : int
        Number of dimensions (this is always 2)
    nnz
        Number of nonzero elements
    data
        LIL format data array of the matrix
    rows
        LIL format row index array of the matrix

    Notes
    -----

    Sparse matrices can be used in arithmetic operations: they support
    addition, subtraction, multiplication, division, and matrix power.

    Advantages of the LIL format
        - supports flexible slicing
        - changes to the matrix sparsity structure are efficient

    Disadvantages of the LIL format
        - arithmetic operations LIL + LIL are slow (consider CSR or CSC)
        - slow column slicing (consider CSC)
        - slow matrix vector products (consider CSR or CSC)

    Intended Usage
        - LIL is a convenient format for constructing sparse matrices
        - once a matrix has been constructed, convert to CSR or
          CSC format for fast arithmetic and matrix vector operations
        - consider using the COO format when constructing large matrices

    Data Structure
        - An array (``self.rows``) of rows, each of which is a sorted
          list of column indices of non-zero elements.
        - The corresponding nonzero values are stored in similar
          fashion in ``self.data``.


    """

    def __init__(self, arg1, shape=None, dtype=None, copy=False):
        spmatrix.__init__(self)
        self.dtype = getdtype(dtype, arg1, default=float)

        # First get the shape
        if isspmatrix(arg1):
            if isspmatrix_lil(arg1) and copy:
                A = arg1.copy()
            else:
                A = arg1.tolil()

            if dtype is not None:
                A = A.astype(dtype)

            self.shape = A.shape
            self.dtype = A.dtype
            self.rows  = A.rows
            self.data  = A.data
        elif isinstance(arg1,tuple):
            if isshape(arg1):
                if shape is not None:
                    raise ValueError('invalid use of shape parameter')
                M, N = arg1
                self.shape = (M,N)
                self.rows = np.empty((M,), dtype=object)
                self.data = np.empty((M,), dtype=object)
                for i in range(M):
                    self.rows[i] = []
                    self.data[i] = []
            else:
                raise TypeError('unrecognized lil_matrix constructor usage')
        else:
            #assume A is dense
            try:
                A = np.asmatrix(arg1)
            except TypeError:
                raise TypeError('unsupported matrix type')
            else:
                from .csr import csr_matrix
                A = csr_matrix(A, dtype=dtype).tolil()

                self.shape = A.shape
                self.dtype = A.dtype
                self.rows  = A.rows
                self.data  = A.data

    def __iadd__(self,other):
        self[:,:] = self + other
        return self

    def __isub__(self,other):
        self[:,:] = self - other
        return self

    def __imul__(self,other):
        if isscalarlike(other):
            self[:,:] = self * other
            return self
        else:
            raise NotImplementedError

    def __itruediv__(self,other):
        if isscalarlike(other):
            self[:,:] = self / other
            return self
        else:
            raise NotImplementedError

    # Whenever the dimensions change, empty lists should be created for each
    # row

    def getnnz(self):
        return sum([len(rowvals) for rowvals in self.data])
    nnz = property(fget=getnnz)

    def __str__(self):
        val = ''
        for i, row in enumerate(self.rows):
            for pos, j in enumerate(row):
                val += "  %s\t%s\n" % (str((i, j)), str(self.data[i][pos]))
        return val[:-1]

    def getrowview(self, i):
        """Returns a view of the 'i'th row (without copying).
        """
        new = lil_matrix((1, self.shape[1]), dtype=self.dtype)
        new.rows[0] = self.rows[i]
        new.data[0] = self.data[i]
        return new

    def getrow(self, i):
        """Returns a copy of the 'i'th row.
        """
        new = lil_matrix((1, self.shape[1]), dtype=self.dtype)
        new.rows[0] = self.rows[i][:]
        new.data[0] = self.data[i][:]
        return new

    def _get1(self, i, j):

        if i < 0:
            i += self.shape[0]
        if i < 0 or i >= self.shape[0]:
            raise IndexError('row index out of bounds')

        if j < 0:
            j += self.shape[1]
        if j < 0 or j >= self.shape[1]:
            raise IndexError('column index out of bounds')

        row  = self.rows[i]
        data = self.data[i]

        pos = bisect_left(row, j)
        if pos != len(data) and row[pos] == j:
            return self.dtype.type(data[pos])
        else:
            return self.dtype.type(0)

    def _slicetoseq(self, j, shape):
        if j.start is not None and j.start < 0:
            start =  shape + j.start
        elif j.start is None:
            start = 0
        else:
            start = j.start
        if j.stop is not None and j.stop < 0:
            stop = shape + j.stop
        elif j.stop is None:
            stop = shape
        else:
            stop = j.stop
        j = list(range(start, stop, j.step or 1))
        return j


    def __getitem__(self, index):
        """Return the element(s) index=(i, j), where j may be a slice.
        This always returns a copy for consistency, since slices into
        Python lists return copies.
        """
        try:
            i, j = index
        except (AssertionError, TypeError):
            if isinstance(index, (list, np.ndarray, slice)):
                i = index
                j = slice(None)
            else:
                raise IndexError('invalid index')

        if not np.isscalar(i) and np.isscalar(j):
            warn('Indexing into a lil_matrix with multiple indices is slow. '
                 'Pre-converting to CSC or CSR beforehand is more efficient.',
                 SparseEfficiencyWarning)

        if isinstance(i, np.ndarray) and i.ndim==0:
            i = int(i)
        if isinstance(j, np.ndarray) and j.ndim==0:
            j = int(j)
        if np.isscalar(i):
            if np.isscalar(j):
                return self._get1(i, j)
            if isinstance(j, slice):
                j = self._slicetoseq(j, self.shape[1])
            if issequence(j):
                return self.__class__([[self._get1(i, jj) for jj in j]])
        elif ismatrix(i) or ismatrix(j):
            if isinstance(i, slice) or isinstance(j, slice):
                raise IndexError('invalid index')
            i = np.atleast_2d(i)
            j = np.atleast_2d(j)
            if i.shape[1] != j.shape[1]:
                raise ValueError('shape mismatch: objects cannot be broadcast'+
                                 ' to a single shape')
            elif i.shape[0]==j.shape[0]:
                return self.__class__([[self._get1(iii, jjj) for (iii, jjj) in
                                        zip(ii, jj)] for (ii, jj) in zip(i, j)])
            if i.shape[0]==1:
                return self.__class__([[self._get1(iii, jjj) for (iii, jjj)
                                        in zip(i[0], jj)] for jj in j])
            elif j.shape[0]==1:
                return self.__class__([[self._get1(iii, jjj) for (iii, jjj)
                                        in zip(ii, j[0])] for ii in i])
            else:
                raise ValueError('shape mismatch: objects cannot be broadcast'+
                                 ' to a single shape')
        elif issequence(i) and issequence(j):
            return self.__class__([[self._get1(ii, jj) for (ii, jj) in zip(i, j)]])
        elif issequence(i) or isinstance(i, slice):
            if isinstance(i, slice):
                i = self._slicetoseq(i, self.shape[0])
            if np.isscalar(j):
                return self.__class__([[self._get1(ii, j)] for ii in i])
            if isinstance(j, slice):
                j = self._slicetoseq(j, self.shape[1])
            if issequence(j):
                return self.__class__([[self._get1(ii, jj) for jj in j] for ii in i])
        else:
            raise IndexError

    def _insertat2(self, row, data, j, x):
        """ helper for __setitem__: insert a value in the given row/data at
        column j. """

        if j < 0: #handle negative column indices
            j += self.shape[1]

        if j < 0 or j >= self.shape[1]:
            raise IndexError('column index out of bounds')

        if not np.isscalar(x):
            raise ValueError('setting an array element with a sequence')

        try:
            x = self.dtype.type(x)
        except:
            raise TypeError('Unable to convert value (%s) to dtype [%s]' % (x,self.dtype.name))

        pos = bisect_left(row, j)
        if x != 0:
            if pos == len(row):
                row.append(j)
                data.append(x)
            elif row[pos] != j:
                row.insert(pos, j)
                data.insert(pos, x)
            else:
                data[pos] = x
        else:
            if pos < len(row) and row[pos] == j:
                del row[pos]
                del data[pos]

    def _setitem_setrow(self, row, data, j, xrow, xdata, xcols):
        if isinstance(j, slice):
            j = self._slicetoseq(j, self.shape[1])
        if issequence(j):
            if xcols == len(j):
                for jj, xi in zip(j, xrange(xcols)):
                    pos = bisect_left(xrow, xi)
                    if pos != len(xdata) and xrow[pos] == xi:
                        self._insertat2(row, data, jj, xdata[pos])
                    else:
                        self._insertat2(row, data, jj, 0)
            elif xcols == 1:           # OK, broadcast across row
                if len(xdata) > 0 and xrow[0] == 0:
                    val = xdata[0]
                else:
                    val = 0
                for jj in j:
                    self._insertat2(row, data, jj,val)
            else:
                raise IndexError('invalid index')
        elif np.isscalar(j):
            if not xcols == 1:
                raise ValueError('array dimensions are not compatible for copy')
            if len(xdata) > 0 and xrow[0] == 0:
                self._insertat2(row, data, j, xdata[0])
            else:
                self._insertat2(row, data, j, 0)
        else:
            raise ValueError('invalid column value: %s' % str(j))

    def __setitem__(self, index, x):
        try:
            i, j = index
        except (ValueError, TypeError):
            if isinstance(index, (list, np.ndarray, slice)):
                i = index
                j = slice(None)
            else:
                raise IndexError('invalid index')

        # shortcut for common case of single entry assign:
        if np.isscalar(x) and np.isscalar(i) and np.isscalar(j):
            self._insertat2(self.rows[i], self.data[i], j, x)
            return

        # shortcut for common case of full matrix assign:
        if isspmatrix(x):
            if isinstance(i, slice) and i == slice(None) and \
               isinstance(j, slice) and j == slice(None):
                x = lil_matrix(x, dtype=self.dtype)
                self.rows = x.rows
                self.data = x.data
                return

        # can't index lists with tuple
        if isinstance(i, tuple):       
            i = list(i)
        if isinstance(i, np.ndarray) and i.ndim==0:
            i = int(i)
        if isinstance(j, np.ndarray) and j.ndim==0:
             j = int(j)
        if np.isscalar(i):
            rows = [self.rows[i]]
            datas = [self.data[i]]
        elif ismatrix(i):
            pass
        else:
            rows = self.rows[i]
            datas = self.data[i]

        x = lil_matrix(x, copy=False)
        xrows, xcols = x.shape
        if ismatrix(i) or ismatrix(j):
            if xrows!=1 or xcols!=1:
                raise NotImplementedError
            if isinstance(i, slice) or isinstance(j, slice):
                raise IndexError('invalid index')
            i = np.atleast_2d(i)
            j = np.atleast_2d(j)
            if i.shape[1] != j.shape[1]:
                if i.ndim==0:
                    i = int(i)*np.ones(j.shape, dtype=int)
                elif j.ndim==0:
                    j = int(j)*np.ones(i.shape, dtype=int)
                else:
                    raise ValueError('shape mismatch: objects cannot be ' +
                                     'broadcast to a single shape')
            if i.shape[0]==j.shape[0]:
                for ii, jj in zip(i, j):
                    for row, data, col in zip(self.rows[ii], self.data[ii], 
                                              jj):
                        self._setitem_setrow(row, data, col, x.rows[0], 
                                             x.data[0], xcols)
            elif i.shape[0]==1:
                for jj in j:
                    for row, data, col in zip(self.rows[i[0]], self.data[i[0]],
                                              jj):
                        self._setitem_setrow(row, data, col, x.rows[0], 
                                             x.data[0], xcols)
            elif j.shape[0]==1:
                for ii in i:
                    for row, data, col in zip(self.rows[ii], self.data[ii], 
                                              j[0]):
                        self._setitem_setrow(row, data, col, x.rows[0], 
                                             x.data[0], xcols)
        # if one of the indexes is a slice, copy all entries in i X j
        elif (isinstance(i, slice) or isinstance(j, slice) or np.isscalar(i)
            or np.isscalar(j)):
            if xrows == len(rows):    # normal rectangular copy
                for row, data, xrow, xdata in zip(rows, datas, x.rows, x.data):
                    self._setitem_setrow(row, data, j, xrow, xdata, xcols)
            # needed to pass 'test_lil_sequence_assignement' unit test:
            # -- set row from column of entries --
            elif xcols == len(rows):
                x = x.T
                for row, data, xrow, xdata in zip(rows, datas, x.rows, x.data):
                    self._setitem_setrow(row, data, j, xrow, xdata, xrows)
            elif xrows == 1:          # OK, broadcast down column
                for row, data in zip(rows, datas):
                    self._setitem_setrow(row, data, j, x.rows[0], x.data[0], 
                                         xcols)
            else:
                raise IndexError('invalid index')
        # else: only copy (i[0], j[0]), (i[1], j[1]) ...
        elif issequence(i) and issequence(j):
            if len(i)==len(j):
                if xrows==1:
                    if xcols==1:
                        for (row, data, col) in zip(rows, datas, j):
                            self._insertat2(row, data, col, x.data[0][0])
                    elif xcols==len(i):
                        for (row, data, col, val) in zip(rows, datas, j, 
                                                         x.data[0]):
                            self._insertat2(row, data, col, val)
            else:
                raise ValueError('shape mismatch')
        else:
            return IndexError('invalid index')
    def _mul_scalar(self, other):
        if other == 0:
            # Multiply by zero: return the zero matrix
            new = lil_matrix(self.shape, dtype=self.dtype)
        else:
            new = self.copy()<commit_msg>Updated code using ravel() and now able to set values based on an array. A tradeoff has to be made between code duplication and memory usage. Making everything into the same shape would be the most elegant, but A[:, :] = 1 would generate three arrays (i, j, x) all having the same size as A. If there is desire to simplify the code, that can be easily done.<commit_after>"""LInked List sparse matrix class
"""

from __future__ import division, print_function, absolute_import

__docformat__ = "restructuredtext en"

__all__ = ['lil_matrix','isspmatrix_lil']

from bisect import bisect_left

import numpy as np
from scipy.lib.six.moves import xrange

from .base import spmatrix, isspmatrix
from .sputils import getdtype, isshape, issequence, isscalarlike, ismatrix

from warnings import warn
from .base import SparseEfficiencyWarning


class lil_matrix(spmatrix):
    """Row-based linked list sparse matrix

    This is an efficient structure for constructing sparse
    matrices incrementally.

    This can be instantiated in several ways:
        lil_matrix(D)
            with a dense matrix or rank-2 ndarray D

        lil_matrix(S)
            with another sparse matrix S (equivalent to S.tolil())

        lil_matrix((M, N), [dtype])
            to construct an empty matrix with shape (M, N)
            dtype is optional, defaulting to dtype='d'.

    Attributes
    ----------
    dtype : dtype
        Data type of the matrix
    shape : 2-tuple
        Shape of the matrix
    ndim : int
        Number of dimensions (this is always 2)
    nnz
        Number of nonzero elements
    data
        LIL format data array of the matrix
    rows
        LIL format row index array of the matrix

    Notes
    -----

    Sparse matrices can be used in arithmetic operations: they support
    addition, subtraction, multiplication, division, and matrix power.

    Advantages of the LIL format
        - supports flexible slicing
        - changes to the matrix sparsity structure are efficient

    Disadvantages of the LIL format
        - arithmetic operations LIL + LIL are slow (consider CSR or CSC)
        - slow column slicing (consider CSC)
        - slow matrix vector products (consider CSR or CSC)

    Intended Usage
        - LIL is a convenient format for constructing sparse matrices
        - once a matrix has been constructed, convert to CSR or
          CSC format for fast arithmetic and matrix vector operations
        - consider using the COO format when constructing large matrices

    Data Structure
        - An array (``self.rows``) of rows, each of which is a sorted
          list of column indices of non-zero elements.
        - The corresponding nonzero values are stored in similar
          fashion in ``self.data``.


    """

    def __init__(self, arg1, shape=None, dtype=None, copy=False):
        spmatrix.__init__(self)
        self.dtype = getdtype(dtype, arg1, default=float)

        # First get the shape
        if isspmatrix(arg1):
            if isspmatrix_lil(arg1) and copy:
                A = arg1.copy()
            else:
                A = arg1.tolil()

            if dtype is not None:
                A = A.astype(dtype)

            self.shape = A.shape
            self.dtype = A.dtype
            self.rows  = A.rows
            self.data  = A.data
        elif isinstance(arg1,tuple):
            if isshape(arg1):
                if shape is not None:
                    raise ValueError('invalid use of shape parameter')
                M, N = arg1
                self.shape = (M,N)
                self.rows = np.empty((M,), dtype=object)
                self.data = np.empty((M,), dtype=object)
                for i in range(M):
                    self.rows[i] = []
                    self.data[i] = []
            else:
                raise TypeError('unrecognized lil_matrix constructor usage')
        else:
            #assume A is dense
            try:
                A = np.asmatrix(arg1)
            except TypeError:
                raise TypeError('unsupported matrix type')
            else:
                from .csr import csr_matrix
                A = csr_matrix(A, dtype=dtype).tolil()

                self.shape = A.shape
                self.dtype = A.dtype
                self.rows  = A.rows
                self.data  = A.data

    def __iadd__(self,other):
        self[:,:] = self + other
        return self

    def __isub__(self,other):
        self[:,:] = self - other
        return self

    def __imul__(self,other):
        if isscalarlike(other):
            self[:,:] = self * other
            return self
        else:
            raise NotImplementedError

    def __itruediv__(self,other):
        if isscalarlike(other):
            self[:,:] = self / other
            return self
        else:
            raise NotImplementedError

    # Whenever the dimensions change, empty lists should be created for each
    # row

    def getnnz(self):
        return sum([len(rowvals) for rowvals in self.data])
    nnz = property(fget=getnnz)

    def __str__(self):
        val = ''
        for i, row in enumerate(self.rows):
            for pos, j in enumerate(row):
                val += "  %s\t%s\n" % (str((i, j)), str(self.data[i][pos]))
        return val[:-1]

    def getrowview(self, i):
        """Returns a view of the 'i'th row (without copying).
        """
        new = lil_matrix((1, self.shape[1]), dtype=self.dtype)
        new.rows[0] = self.rows[i]
        new.data[0] = self.data[i]
        return new

    def getrow(self, i):
        """Returns a copy of the 'i'th row.
        """
        new = lil_matrix((1, self.shape[1]), dtype=self.dtype)
        new.rows[0] = self.rows[i][:]
        new.data[0] = self.data[i][:]
        return new

    def _get1(self, i, j):

        if i < 0:
            i += self.shape[0]
        if i < 0 or i >= self.shape[0]:
            raise IndexError('row index out of bounds')

        if j < 0:
            j += self.shape[1]
        if j < 0 or j >= self.shape[1]:
            raise IndexError('column index out of bounds')

        row  = self.rows[i]
        data = self.data[i]

        pos = bisect_left(row, j)
        if pos != len(data) and row[pos] == j:
            return self.dtype.type(data[pos])
        else:
            return self.dtype.type(0)

    def _slicetoseq(self, j, shape):
        step = j.step or 1
        if j.start is not None and j.start < 0:
            start =  shape + j.start
        elif j.start is None:
            if step > 0:
                start = 0
            else:
                start = shape
        else:
            start = j.start
        if j.stop is not None and j.stop < 0:
            stop = shape + j.stop
        elif j.stop is None:
            if step > 0:
                stop = shape
            else:
                stop = -1
        else:
            stop = j.stop
        j = list(range(start, stop, step))
        return j


    def __getitem__(self, index):
        """Return the element(s) index=(i, j), where j may be a slice.
        This always returns a copy for consistency, since slices into
        Python lists return copies.
        """
        try:
            i, j = index
        except (AssertionError, TypeError):
            if isinstance(index, (list, np.ndarray, slice)):
                i = index
                j = slice(None)
            else:
                raise IndexError('invalid index')

        if not np.isscalar(i) and np.isscalar(j):
            warn('Indexing into a lil_matrix with multiple indices is slow. '
                 'Pre-converting to CSC or CSR beforehand is more efficient.',
                 SparseEfficiencyWarning)

        if isinstance(i, np.ndarray) and i.ndim==0:
            i = int(i)
        if isinstance(j, np.ndarray) and j.ndim==0:
            j = int(j)
        if np.isscalar(i):
            if np.isscalar(j):
                return self._get1(i, j)
            if isinstance(j, slice):
                j = self._slicetoseq(j, self.shape[1])
            if issequence(j):
                return self.__class__([[self._get1(i, jj) for jj in j]])
        elif ismatrix(i) or ismatrix(j):
            if isinstance(i, slice) or isinstance(j, slice):
                raise IndexError('invalid index')
            i = np.atleast_2d(i)
            j = np.atleast_2d(j)
            if i.shape[1] != j.shape[1]:
                raise ValueError('shape mismatch: objects cannot be broadcast'+
                                 ' to a single shape')
            elif i.shape[0]==j.shape[0]:
                return self.__class__([[self._get1(iii, jjj) for (iii, jjj) in
                                        zip(ii, jj)] for (ii, jj) in zip(i, j)])
            if i.shape[0]==1:
                return self.__class__([[self._get1(iii, jjj) for (iii, jjj)
                                        in zip(i[0], jj)] for jj in j])
            elif j.shape[0]==1:
                return self.__class__([[self._get1(iii, jjj) for (iii, jjj)
                                        in zip(ii, j[0])] for ii in i])
            else:
                raise ValueError('shape mismatch: objects cannot be broadcast'+
                                 ' to a single shape')
        elif issequence(i) and issequence(j):
            return self.__class__([[self._get1(ii, jj) for (ii, jj) in zip(i, j)]])
        elif issequence(i) or isinstance(i, slice):
            if isinstance(i, slice):
                i = self._slicetoseq(i, self.shape[0])
            if np.isscalar(j):
                return self.__class__([[self._get1(ii, j)] for ii in i])
            if isinstance(j, slice):
                j = self._slicetoseq(j, self.shape[1])
            if issequence(j):
                return self.__class__([[self._get1(ii, jj) for jj in j] for ii in i])
        else:
            raise IndexError

    def _insertat2(self, row, data, j, x):
        """ helper for __setitem__: insert a value in the given row/data at
        column j. """

        if j < 0: #handle negative column indices
            j += self.shape[1]

        if j < 0 or j >= self.shape[1]:
            raise IndexError('column index out of bounds')

        if not np.isscalar(x):
            raise ValueError('setting an array element with a sequence')

        try:
            x = self.dtype.type(x)
        except:
            raise TypeError('Unable to convert value (%s) to dtype [%s]' % (x,self.dtype.name))

        pos = bisect_left(row, j)
        if x != 0:
            if pos == len(row):
                row.append(j)
                data.append(x)
            elif row[pos] != j:
                row.insert(pos, j)
                data.insert(pos, x)
            else:
                data[pos] = x
        else:
            if pos < len(row) and row[pos] == j:
                del row[pos]
                del data[pos]

    def _setitem_setrow(self, row, data, j, xrow, xdata, xcols):
        if isinstance(j, slice):
            j = self._slicetoseq(j, self.shape[1])
        if issequence(j):
            if xcols == len(j):
                for jj, xi in zip(j, xrange(xcols)):
                    pos = bisect_left(xrow, xi)
                    if pos != len(xdata) and xrow[pos] == xi:
                        self._insertat2(row, data, jj, xdata[pos])
                    else:
                        self._insertat2(row, data, jj, 0)
            elif xcols == 1:           # OK, broadcast across row
                if len(xdata) > 0 and xrow[0] == 0:
                    val = xdata[0]
                else:
                    val = 0
                for jj in j:
                    self._insertat2(row, data, jj,val)
            else:
                raise IndexError('invalid index')
        elif np.isscalar(j):
            if not xcols == 1:
                raise ValueError('array dimensions are not compatible for copy')
            if len(xdata) > 0 and xrow[0] == 0:
                self._insertat2(row, data, j, xdata[0])
            else:
                self._insertat2(row, data, j, 0)
        else:
            raise ValueError('invalid column value: %s' % str(j))

    def __setitem__(self, index, x):
        try:
            i, j = index
        except (ValueError, TypeError):
            if isinstance(index, (list, np.ndarray, slice)):
                i = index
                j = slice(None)
            else:
                raise IndexError('invalid index')

        # shortcut for common case of full matrix assign:
        if (isspmatrix(x) and isinstance(i, slice) and i == slice(None) and
            isinstance(j, slice) and j == slice(None)):
            x = lil_matrix(x, dtype=self.dtype)
            self.rows = x.rows
            self.data = x.data
            return

        # Transform data into numpy arrays to enable ravel()
        if isinstance(i, slice) or isinstance(j, slice):
            if isinstance(i, slice):
                i = self._slicetoseq(i, self.shape[0])
                if not i:
                    return
            i = np.atleast_1d(i).ravel()
            if isinstance(j, slice):
                j = self._slicetoseq(j, self.shape[1])
                if not j:
                    return
            j = np.atleast_1d(j).ravel()
            if j.shape[0]==1:
                j = j[0]*np.ones((1, i.shape[0]), dtype=int)
                i = np.atleast_2d(i)
            else:
                j = np.vstack([j]*i.shape[0])
                i = np.outer(i, np.ones(j.shape[1], dtype=int))
        else:
            i = np.atleast_2d(i)
            j = np.atleast_2d(j)
        # Make i and j into same shape
            if j.shape==i.shape:
                pass
            elif i.shape==(1, 1):
                i = i[0][0]*np.ones(j.shape, dtype=int)
            elif j.shape==(1, 1):
                j = j[0][0]*np.ones(i.shape, dtype=int)
            elif i.shape[1]==j.shape[1]:
                if i.shape[0]==1:
                    i = np.vstack([i]*j.shape[0])
                elif j.shape[0]==1:
                    j = np.vstack([j]*i.shape[0])
                else:
                    raise ValueError('shape mismatch: objects cannot be '+\
                                         'broadcast to a single shape')
            else:
                raise ValueError('shape mismatch: objects cannot be '+\
                                     'broadcast to a single shape')

        # If input is a sparse matrix, handle separately
        if isspmatrix(x):
            if x.shape==(1, 1):
                for ii, jj in zip(i.ravel(), j.ravel()):
                    self._insertat2(self.rows[ii], self.data[ii], 
                                    j[jj], x[0, 0])
                return
            elif x.shape==i.shape:
                for ii, jj, xx in zip(i.ravel(), j.ravel(), 
                                      x.toarray().ravel()):
                    self._insertat2(self.rows[ii], self.data[ii], jj, xx)
                return
            elif x.shape[1]==i.shape[1] and x.shape[0]==1:
                for ii, jj in zip(i.ravel(), j.ravel(), 
                                  np.concatenat([x.toarry()]*i.shape[1])):
                    self._insertat2(self.rows[ii], self.data[ii], jj, xx)
                return
            else:
                raise ValueError('shape mismatch: objects cannot be '+\
                                     'broadcast to a single shape')

        x = np.atleast_2d(np.asarray(x))
        # Shortcut for scalar x
        if x.shape==(1, 1):
            for ii, jj in zip(i.ravel(), j.ravel()):
                self._insertat2(self.rows[ii], self.data[ii], 
                                jj, x[0, 0])
            return
        # Make x and i into the same shape
        if i.shape==x.shape:
            pass
        elif x.shape[1]==i.shape[1] and x.shape[0]==1:
            x = np.vstack([x]*i.shape[0])
        else:
            raise ValueError('shape mismatch: objects cannot be '+\
                                 'broadcast to a single shape')
        # Set values
        for ii, jj, xx in zip(i.ravel(), j.ravel(), x.ravel()):
            self._insertat2(self.rows[ii], self.data[ii], jj, xx)


    def _mul_scalar(self, other):
        if other == 0:
            # Multiply by zero: return the zero matrix
            new = lil_matrix(self.shape, dtype=self.dtype)
        else:
            new = self.copy()
{'fraction_non_alphanumeric': 0.1052012309177578, 'fraction_numerical': 0.00820611838532553, 'mean_word_length': 1.442847667477338, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 40, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6570115', 'n_tokens_mistral': 9890, 'n_tokens_neox': 9434, 'n_words': 2975}