Ticket #7723: trac_7723-coo_format.patch

File trac_7723-coo_format.patch, 25.9 KB (added by dagss, 11 years ago)
  • sage/matrix/constructor.py

    # HG changeset patch
    # User Dag Sverre Seljebotn <dagss@student.matnat.uio.no>
    # Date 1261056859 -3600
    # Node ID d6da8c3188cc4733e04b367efd952c774f476ba9
    # Parent  25f413c99ea3becff7701c12da9feda75323f831
    [mq]: coo_format
    
    diff -r 25f413c99ea3 -r d6da8c3188cc sage/matrix/constructor.py
    a b  
    4040   
    4141    The entries of a matrix can be specified as a flat list of
    4242    elements, a list of lists (i.e., a list of rows), a list of Sage
    43     vectors, or a dictionary having positions as keys and matrix
    44     entries as values (see the examples). You can create a matrix of
    45     zeros by passing an empty list or the integer zero for the entries.
    46     To construct a multiple of the identity (`cI`), you can
    47     specify square dimensions and pass in `c`. Calling matrix()
    48     with a Sage object may return something that makes sense. Calling
    49     matrix() with a NumPy array will convert the array to a matrix.
     43    vectors, a dictionary having positions as keys and matrix entries
     44    as values, or by passing coordinates and associated values (see
     45    examples). You can create a matrix of zeros by passing an empty
     46    list or the integer zero for the entries. To construct a multiple
     47    of the identity (`cI`), you can specify square dimensions and pass
     48    in `c`. Calling matrix() with a Sage object may return something
     49    that makes sense. Calling matrix() with a NumPy array will convert
     50    the array to a matrix.
    5051   
    5152    The ring, number of rows, and number of columns of the matrix can
    5253    be specified by setting the ring, nrows, or ncols parameters or by
     
    5556    or cannot be determined from the entries. If the numbers of rows
    5657    and columns are not specified and cannot be determined, then an
    5758    empty 0x0 matrix is returned.
    58    
     59
     60    INPUT:
    5961   
    6062    -  ``ring`` - the base ring for the entries of the
    6163       matrix.
     
    6567    -  ``ncols`` - the number of columns in the matrix.
    6668   
    6769    -  ``sparse`` - create a sparse matrix. This defaults
    68        to True when the entries are given as a dictionary, otherwise
    69        defaults to False.
    70    
     70       to True when the entries are given as a dictionary or through
     71       a ``coo`` argument, otherwise defaults to False.
     72
     73    - ``coo`` - gives the entries in coordinate format, that is, as a
     74       tuple ``(i, j, v)`` where ``i`` is a list of row indices, ``j``
     75       is a list of column indices, and ``v`` is a list of associated
     76       values (i.e. ``self[i[k],j[k]] == v[k]`` for all ``k``). This
     77       is an efficient way of constructing huge sparse
     78       matrices. Vectors or NumPy arrays are accepted as well as lists.
     79       ``coo`` must be given as a keyword argument.
    7180   
    7281    OUTPUT:
    7382   
     
    123132        [  0   2]
    124133        [  0 2/5]
    125134        Full MatrixSpace of 2 by 2 sparse matrices over Rational Field
    126    
     135
     136    Construction using coordinate format works for any ring, and is fast
     137    for sparse double fields::
     138
     139        sage: m=matrix(coo=([0, 1], [1, 1], [2, 2/5])); m; m.parent()
     140        [  0   2]
     141        [  0 2/5]
     142        Full MatrixSpace of 2 by 2 sparse matrices over Rational Field
     143        sage: import numpy
     144        sage: i = j = numpy.arange(29, -1, -1)
     145        sage: values = numpy.arange(1, 31).astype(numpy.double)
     146        sage: m=matrix(coo=(i,j,values)); m
     147        30 x 30 sparse matrix over Real Double Field
     148        sage: m == diagonal_matrix(RDF, range(30, 0, -1))
     149        True
     150       
    127151    ::
    128152   
    129153        sage: m=matrix(QQ,2,3,{(1,1): 2}); m; m.parent()
     
    419443        ValueError: List of rows is not valid (rows are wrong types or lengths)
    420444        sage: matrix(vector(RR,[1,2,3])).parent()
    421445        Full MatrixSpace of 1 by 3 dense matrices over Real Field with 53 bits of precision
     446        sage: matrix(RDF, coo=([0,1,2],[2,1,0],[1,2,3]))
     447        [0.0 0.0 1.0]
     448        [0.0 2.0 0.0]
     449        [3.0 0.0 0.0]
     450        sage: matrix(RDF, coo=(vector([0,1,2]),vector(QQ, [2,1,0]),vector(CDF, [1,2,3])))
     451        [0.0 0.0 1.0]
     452        [0.0 2.0 0.0]
     453        [3.0 0.0 0.0]
    422454   
    423455    AUTHORS:
    424456
     
    427459    - Jason Grout (2008-03): almost a complete rewrite, with bits and
    428460      pieces from the original implementation
    429461    """
     462
    430463    args = list(args)
    431     sparse = kwds.get('sparse',False)
    432     # if the first object already knows how to make itself into a
    433     # matrix, try that, defaulting to a matrix over the integers.
    434     if len(args) == 1 and hasattr(args[0], '_matrix_'):
    435         try:
     464    sparse = kwds.get('sparse', False)
     465
     466    coo = kwds.get('coo', None)
     467    if coo is None:
     468        # if the first object already knows how to make itself into a
     469        # matrix, try that, defaulting to a matrix over the integers.
     470        if len(args) == 1 and hasattr(args[0], '_matrix_'):
     471            try:
    436472                return args[0]._matrix_(sparse=sparse)
    437         except TypeError:
     473            except TypeError:
    438474                return args[0]._matrix_()
    439     elif len(args) == 2:
    440         if hasattr(args[0], '_matrix_'):
    441             try:
    442                 return args[0]._matrix_(args[1], sparse=sparse)
    443             except TypeError:
    444                 return args[0]._matrix_(args[1])               
    445         elif hasattr(args[1], '_matrix_'):
    446             try:
    447                 return args[1]._matrix_(args[0], sparse=sparse)
    448             except TypeError:
    449                 return args[1]._matrix_(args[0])               
     475        elif len(args) == 2:
     476            if hasattr(args[0], '_matrix_'):
     477                try:
     478                    return args[0]._matrix_(args[1], sparse=sparse)
     479                except TypeError:
     480                    return args[0]._matrix_(args[1])               
     481            elif hasattr(args[1], '_matrix_'):
     482                try:
     483                    return args[1]._matrix_(args[0], sparse=sparse)
     484                except TypeError:
     485                    return args[1]._matrix_(args[0])               
    450486
    451     if len(args) == 0:
    452         # if nothing was passed return the empty matrix over the
    453         # integer ring.
    454         return matrix_space.MatrixSpace(rings.ZZ, 0, 0, sparse=sparse)([])
    455            
     487        if len(args) == 0:
     488            # if nothing was passed return the empty matrix over the
     489            # integer ring.
     490            return matrix_space.MatrixSpace(rings.ZZ, 0, 0, sparse=sparse)([])
     491        # end of non-coo case
     492       
    456493    if len(args) >= 1 and rings.is_Ring(args[0]):
    457494        # A ring is specified
    458495        if kwds.get('ring', args[0]) != args[0]:
     
    490527
    491528    # Now we've taken care of initial ring, nrows, and ncols arguments.
    492529    # We've also taken care of the Sage object case.
     530
     531    if coo is not None:
     532        if len(args) > 0:
     533            raise ValueError, 'Entries cannot both be provided through coo argument and as a positional argument'
     534        sparse = kwds.get('sparse', True) # default to sparse
     535        i, j, values = coo
     536        i = prepare_coo_index_array(i)
     537        j = prepare_coo_index_array(j)
     538        values, entry_ring = prepare_coo_value_array(values)
     539        if not (len(i) == len(j) == len(values)):
     540            raise ValueError, 'coo arrays must have same length'
     541        if nrows is None and len(i) > 0:
     542            nrows = max(i) + 1
     543        if ncols is None and len(j) > 0:
     544            ncols = max(j) + 1
     545        entries = (i, j, values)
    493546   
    494     # Now the rest of the arguments are a list of
     547    # Otherwise, the rest of the arguments are a list of
    495548    # rows, a flat list of entries, a dict, a numpy array, or a single
    496549    # value.
    497     if len(args) == 0:
     550    elif len(args) == 0:
    498551        # If no entries are specified, pass back a zero matrix
    499552        entries = 0
    500553        entry_ring = rings.ZZ
     
    609662        nrows = 0
    610663    if ncols is None:
    611664        ncols = nrows
    612 
    613665       
    614666    if ring is None:
    615667        try:
    616668            ring = entry_ring
    617669        except NameError:
    618670            ring = rings.ZZ
    619            
    620     return matrix_space.MatrixSpace(ring, nrows, ncols, sparse=sparse)(entries)
     671
     672    if coo is not None:
     673        format = 'coo'
     674    else:
     675        format = None
     676
     677    return matrix_space.MatrixSpace(ring, nrows, ncols, sparse=sparse)(entries, format=format)
    621678       
    622679
    623680
     
    690747    entries, ring = prepare(X)
    691748    return dict([(Z[i][0],entries[i]) for i in xrange(len(entries))]), ring
    692749
     750
     751def prepare_coo_index_array(indices):
     752    """
     753    Given a list/vector/array of integers, return a NumPy array of indices
     754    with dtype numpy.intp (pointer sized int).
     755
     756    This is for internal use by the matrix function.
     757   
     758    INPUT:
     759
     760    - ``indices`` - List/vector/array interpretable by NumPy
     761
     762    OUTPUT:
     763
     764    NumPy array with dtype intp
     765
     766    EXAMPLES::
     767   
     768        sage: sage.matrix.constructor.prepare_coo_index_array([1,2,"3"]).tolist()
     769        [1, 2, 3]
     770        sage: sage.matrix.constructor.prepare_coo_index_array(vector(ZZ, [1,2,"3"])).tolist()
     771        [1, 2, 3]       
     772        sage: sage.matrix.constructor.prepare_coo_index_array([[1],[2]]).tolist()
     773        Traceback (most recent call last):
     774            ...
     775        ValueError: must supply indices as list/vector/1D array of integers
     776        sage: sage.matrix.constructor.prepare_coo_index_array([[1],[2,3]]).tolist()
     777        Traceback (most recent call last):
     778            ...
     779        ValueError: must supply indices as list/vector/1D array of integers
     780    """
     781    import numpy
     782    try:
     783        result = numpy.asarray(indices, dtype=numpy.intp)
     784        if result.ndim != 1:
     785            raise ValueError   
     786    except ValueError:
     787        raise ValueError, "must supply indices as list/vector/1D array of integers"
     788    return result
     789
     790def prepare_coo_value_array(x):
     791    """
     792    Ensure that ``x`` makes sense as a list/vector/array of values to
     793    insert into a matrix, and return in a uniform format. A ring
     794    is also deduced.
     795
     796    If indices is a real or complex floating point NumPy array, it
     797    is returned as-is. Other NumPy arrays are currently rejected.
     798    Objects convertible to vectors will be converted and the base ring
     799    queried. Finally, constructing a Sequence is attempted.
     800
     801    INPUT:
     802
     803    - ``x`` - See above
     804
     805    OUTPUT:
     806
     807    array/vector/sequence, ring
     808
     809    EXAMPLES::
     810
     811        sage: sage.matrix.constructor.prepare_coo_value_array([1.25, 3.25])
     812        ([1.25000000000000, 3.25000000000000], Real Field with 53 bits of precision)
     813        sage: parent(sage.matrix.constructor.prepare_coo_value_array([1.25, 3.25])[0])
     814        Category of sequences in Real Field with 53 bits of precision
     815        sage: sage.matrix.constructor.prepare_coo_value_array([1.25r, 3.25r])
     816        ([1.25, 3.25], Real Double Field)
     817        sage: sage.matrix.constructor.prepare_coo_value_array(vector([0,1,2]))
     818        ((0, 1, 2), Integer Ring)
     819        sage: import numpy
     820        sage: sage.matrix.constructor.prepare_coo_value_array(numpy.array([1.25, 3.25]))
     821        (array([ 1.25,  3.25]), Real Double Field)
     822        sage: sage.matrix.constructor.prepare_coo_value_array(numpy.array([1.25+1j, 3.25+1j]))
     823        (array([ 1.25+1.j,  3.25+1.j]), Complex Double Field)
     824        sage: sage.matrix.constructor.prepare_coo_value_array(numpy.array([1, 2]))
     825        Traceback (most recent call last):
     826            ...
     827        ValueError: Unsupported NumPy dtype for value array
     828        sage: sage.matrix.constructor.prepare_coo_value_array(numpy.array([[1], [2]]))
     829        Traceback (most recent call last):
     830            ...
     831        ValueError: Wrong number of dimensions for value array
     832
     833    """
     834    import numpy
     835    if isinstance(x, numpy.ndarray):
     836        if x.ndim != 1:
     837            raise ValueError, 'Wrong number of dimensions for value array'
     838        str_dtype = str(x.dtype)
     839        if str_dtype.count("complex") == 1:
     840            ring = sage.rings.complex_double.CDF
     841        elif str_dtype.count("float") == 1:
     842            ring = sage.rings.real_double.RDF
     843        else:
     844            raise ValueError, 'Unsupported NumPy dtype for value array'
     845        return x, ring
     846    elif hasattr(x, '_vector_'):
     847        x = x._vector_()
     848        return x, x.base_ring()
     849    else:
     850        import constructor
     851        return constructor.prepare(x)
     852
    693853def nrows_from_dict(d):
    694854    """
    695855    Given a dictionary that defines a sparse matrix, return the number
  • sage/matrix/matrix_double_sparse.pyx

    diff -r 25f413c99ea3 -r d6da8c3188cc sage/matrix/matrix_double_sparse.pyx
    a b  
    148148        [ -0.166666666667 - 0.333333333333*I 0.0833333333333 + 0.0833333333333*I]
    149149    """
    150150   
    151     def __cinit__(self, Parent parent, entries, copy, coerce):
     151    def __cinit__(self, Parent parent, entries, copy, coerce, format=None):
    152152        """
    153153        Set up a new matrix
    154154
     
    192192    def __richcmp__(Matrix self, right, int op):  # always need for mysterious reasons.
    193193        return self._richcmp(right, op)
    194194
    195     def __init__(self, parent, entries, copy, coerce):
     195    def __init__(self, parent, entries, copy, coerce, format=None):
    196196        """
    197197        Fill the matrix with entries. 
    198198
     
    260260            return # leave _entries_csc as None
    261261        shape = (self._nrows, self._ncols)
    262262
     263        if format == 'coo':
     264            i_arr, j_arr, values = entries
     265            M = scipy_sparse.coo_matrix((values, (i_arr, j_arr)), copy=copy,
     266                                        dtype=self._numpy_dtype)
     267            self._entries_csc = M.tocsc()
     268            return
     269
     270        # Otherwise, start interpreting what entries is.
     271
    263272        # Below is taken verbatim from matrix_generic_sparse.pyx.
    264273        # Something should be done to avoid copying code like this
    265274        # across all the matrix classes and a couple of places in
  • sage/matrix/matrix_space.py

    diff -r 25f413c99ea3 -r d6da8c3188cc sage/matrix/matrix_space.py
    a b  
    254254            self.__ncols = nrows
    255255        else:
    256256            self.__ncols = ncols
    257         self.__matrix_class = self._get_matrix_class()
     257        self.__matrix_class, self.__constructor_formats = self._get_matrix_constructor_info()
    258258
    259259    def __reduce__(self):
    260260        """
     
    268268        """
    269269        return MatrixSpace, (self.base_ring(), self.__nrows, self.__ncols, self.__is_sparse)
    270270
    271     def __call__(self, entries=0, coerce=True, copy=True, rows=None):
     271    def __call__(self, entries=0, coerce=True, copy=True, rows=None, format=None):
    272272        """
    273273        EXAMPLES::
    274274       
     
    341341            sage: MS(g)
    342342            [1 1]
    343343            [0 1]
     344
    344345        """
    345346        if entries is None:
    346347            entries = 0
     
    348349        if entries == 0 and hasattr(self, '__zero_matrix'):
    349350            return self.zero_matrix()
    350351
     352        if format is not None:
     353            return self.matrix(entries, copy=copy, coerce=coerce, rows=rows, format=format)
     354
    351355        if isinstance(entries, (list, tuple)) and len(entries) > 0 and \
    352356           sage.modules.free_module_element.is_FreeModuleElement(entries[0]):
    353357            #Try to determine whether or not the entries should
     
    362366                    rows = False
    363367                else:
    364368                    raise ValueError, "incorrect dimensions"
    365            
     369
    366370            if self.__is_sparse:
    367371                e = {}
    368372                zero = self.base_ring()(0)
     
    392396             or isinstance(entries, sage.modular.arithgroup.arithgroup_element.ArithmeticSubgroupElement):
    393397            return self(entries.matrix(), copy=False)
    394398
    395         return self.matrix(entries, copy=copy, coerce=coerce, rows=rows)
     399        return self.matrix(entries, copy=copy, coerce=coerce, rows=rows, format=format)
    396400
    397401    def change_ring(self, R):
    398402        """
     
    807811                   yield self(entries=[base_elements[i] for i in iv], rows=True)
    808812
    809813         
    810     def _get_matrix_class(self):
     814    def _get_matrix_constructor_info(self):
    811815        """
    812         Returns the class of self
     816        OUTPUT:
     817
     818        (class, string) The class to use for constructing matrices in
     819        this matrix space, and a tuple indicating accepted data
     820        formats which the constructor can accept as the ``entries``
     821        argument. (Currently this is either empty, for the default, or
     822        ('coo',)).
    813823       
    814824        EXAMPLES::
    815825       
    816826            sage: MS1 = MatrixSpace(QQ,4)
    817827            sage: MS2 = MatrixSpace(ZZ,4,5,true)
    818             sage: MS1._get_matrix_class()
    819             <type 'sage.matrix.matrix_rational_dense.Matrix_rational_dense'>
    820             sage: MS2._get_matrix_class()
    821             <type 'sage.matrix.matrix_integer_sparse.Matrix_integer_sparse'>
     828            sage: MS1._get_matrix_constructor_info()
     829            (<type 'sage.matrix.matrix_rational_dense.Matrix_rational_dense'>, ())
     830            sage: MS2._get_matrix_constructor_info()
     831            (<type 'sage.matrix.matrix_integer_sparse.Matrix_integer_sparse'>, ())
     832            sage: MatrixSpace(RDF,4,5,sparse=True)._get_matrix_constructor_info()
     833            (<type 'sage.matrix.matrix_double_sparse.Matrix_double_sparse'>, ('coo',))           
    822834            sage: type(matrix(SR, 2, 2, 0))
    823835            <type 'sage.matrix.matrix_symbolic_dense.Matrix_symbolic_dense'>
    824836            sage: type(matrix(RDF, 2, 2, 0))
     
    831843            <type 'sage.matrix.matrix_double_sparse.Matrix_double_sparse'>
    832844        """
    833845        R = self.base_ring()
     846        formats = () # the defaults only -- list and dict
    834847        if self.is_dense():
    835848            if sage.rings.integer_ring.is_IntegerRing(R):
    836                 return matrix_integer_dense.Matrix_integer_dense
     849                return (matrix_integer_dense.Matrix_integer_dense, formats)
    837850            elif sage.rings.rational_field.is_RationalField(R):
    838                 return matrix_rational_dense.Matrix_rational_dense
     851                return (matrix_rational_dense.Matrix_rational_dense, formats)
    839852            elif sage.rings.number_field.number_field.is_CyclotomicField(R):
    840853                import matrix_cyclo_dense
    841                 return matrix_cyclo_dense.Matrix_cyclo_dense
     854                return (matrix_cyclo_dense.Matrix_cyclo_dense, formats)
    842855            elif R==sage.rings.real_double.RDF:
    843856                import matrix_real_double_dense
    844                 return matrix_real_double_dense.Matrix_real_double_dense
     857                return (matrix_real_double_dense.Matrix_real_double_dense, formats)
    845858            elif R==sage.rings.complex_double.CDF:
    846859                import matrix_complex_double_dense
    847                 return matrix_complex_double_dense.Matrix_complex_double_dense
     860                return (matrix_complex_double_dense.Matrix_complex_double_dense, formats)
    848861            elif sage.rings.integer_mod_ring.is_IntegerModRing(R) and R.order() < matrix_modn_dense.MAX_MODULUS:
    849862                if R.order() == 2:
    850                     return matrix_mod2_dense.Matrix_mod2_dense
    851                 return matrix_modn_dense.Matrix_modn_dense
     863                    return (matrix_mod2_dense.Matrix_mod2_dense, formats)
     864                return (matrix_modn_dense.Matrix_modn_dense, formats)
    852865            elif sage.rings.polynomial.multi_polynomial_ring_generic.is_MPolynomialRing(R) and R.base_ring().is_field():
    853                 return matrix_mpolynomial_dense.Matrix_mpolynomial_dense
     866                return (matrix_mpolynomial_dense.Matrix_mpolynomial_dense, formats)
    854867            #elif isinstance(R, sage.rings.padics.padic_ring_capped_relative.pAdicRingCappedRelative):
    855868            #    return padics.matrix_padic_capped_relative_dense
    856869            # the default     
     
    858871                from sage.symbolic.ring import SR   # causes circular imports
    859872                if R is SR:
    860873                    import matrix_symbolic_dense
    861                     return matrix_symbolic_dense.Matrix_symbolic_dense
    862                 return matrix_generic_dense.Matrix_generic_dense
     874                    return (matrix_symbolic_dense.Matrix_symbolic_dense, formats)
     875                return (matrix_generic_dense.Matrix_generic_dense, formats)
    863876       
    864877        else:           
    865878            if sage.rings.integer_mod_ring.is_IntegerModRing(R) and R.order() < matrix_modn_sparse.MAX_MODULUS:
    866                 return matrix_modn_sparse.Matrix_modn_sparse
     879                return (matrix_modn_sparse.Matrix_modn_sparse, formats)
    867880            elif sage.rings.rational_field.is_RationalField(R):
    868                 return matrix_rational_sparse.Matrix_rational_sparse
     881                return (matrix_rational_sparse.Matrix_rational_sparse, formats)
    869882            elif sage.rings.integer_ring.is_IntegerRing(R):
    870                 return matrix_integer_sparse.Matrix_integer_sparse
     883                return (matrix_integer_sparse.Matrix_integer_sparse, formats)
    871884            elif R == sage.rings.real_double.RDF or R == sage.rings.complex_double.CDF:
    872885                import matrix_double_sparse
    873                 return matrix_double_sparse.Matrix_double_sparse
     886                return (matrix_double_sparse.Matrix_double_sparse, ('coo',))
    874887            # the default
    875             return matrix_generic_sparse.Matrix_generic_sparse
     888            return (matrix_generic_sparse.Matrix_generic_sparse, formats)
    876889           
    877890       
    878891    def basis(self):
     
    10431056        """
    10441057        return self.dimension()
    10451058 
    1046     def matrix(self, x=0, coerce=True, copy=True, rows=True):
     1059    def matrix(self, x=0, coerce=True, copy=True, rows=True, format=None):
    10471060        """
    1048         Create a matrix in self. The entries can be specified either as a
    1049         single list of length nrows\*ncols, or as a list of lists.
     1061        Create a matrix in self. The entries ``x`` can be specified
     1062        either as a single list of length ``nrows\*ncols``, or as a
     1063        list of lists. If the matrix space is sparse the entries can
     1064        also be given as a dict mapping entry coordinates to
     1065        values. If ``format=='coo'``, ``x`` should specify the entries
     1066        in coordinate format (see the ``matrix?`` constructor
     1067        docstring for a description).
    10501068       
    10511069        EXAMPLES::
    10521070       
     
    10631081            sage: M.matrix([1,2,3,4],rows=False)
    10641082            [1 3]
    10651083            [2 4]
     1084            sage: M.matrix(([0,1],[1,0],[1,2]), format='coo')
     1085            [0 1]
     1086            [2 0]
    10661087        """
    1067         if isinstance(x, (types.GeneratorType, xrange)):
    1068             x = list(x)
    1069         elif isinstance(x, (int, integer.Integer)) and x==1:
    1070             return self.identity_matrix()
    1071         if matrix.is_Matrix(x):
    1072             if x.parent() is self:
    1073                 if x.is_immutable():
    1074                     return x
    1075                 else:
    1076                     return x.__copy__()
    1077             x = x.list()
    1078         if isinstance(x, list) and len(x) > 0:
    1079             if isinstance(x[0], list):
    1080                 x = sum(x,[])
    1081             elif hasattr(x[0], "is_vector"): # TODO: is this the best way to test that?
    1082                 e = []
    1083                 for v in x:
    1084                     e = e + v.list()
    1085                 copy = False # deep copy?
    1086                 x = e
    1087             elif isinstance(x[0], tuple):
    1088                 x = list(sum(x,()))
     1088        if format == 'coo':
     1089            if 'coo' not in self.__constructor_formats:
     1090                # Convert coo to dict
     1091                i_list, j_list, value_list = x
     1092                x = {}
     1093                for i, j, value in zip(i_list, j_list, value_list):
     1094                    x[(int(i), int(j))] = value
     1095                if not self.__is_sparse:
     1096                    x = dict_to_list(x, self.__nrows, self.__ncols)
     1097                format = None
     1098        else:
     1099            if isinstance(x, (types.GeneratorType, xrange)):
     1100                x = list(x)
     1101            elif isinstance(x, (int, integer.Integer)) and x==1:
     1102                return self.identity_matrix()
     1103            if matrix.is_Matrix(x):
     1104                if x.parent() is self:
     1105                    if x.is_immutable():
     1106                        return x
     1107                    else:
     1108                        return x.__copy__()
     1109                x = x.list()
     1110            if isinstance(x, list) and len(x) > 0:
     1111                if isinstance(x[0], list):
     1112                    x = sum(x,[])
     1113                elif hasattr(x[0], "is_vector"): # TODO: is this the best way to test that?
     1114                    e = []
     1115                    for v in x:
     1116                        e = e + v.list()
     1117                    copy = False # deep copy?
     1118                    x = e
     1119                elif isinstance(x[0], tuple):
     1120                    x = list(sum(x,()))
    10891121
    1090             if not rows:
    1091                 new_x = []
    1092                 for k in range(len(x)):
    1093                     i = k % self.__ncols
    1094                     j = k // self.__ncols
    1095                     new_x.append( x[ i*self.__nrows + j ] )
    1096                 x = new_x
    1097         return self.__matrix_class(self, entries=x, copy=copy, coerce=coerce)
     1122                if not rows:
     1123                    new_x = []
     1124                    for k in range(len(x)):
     1125                        i = k % self.__ncols
     1126                        j = k // self.__ncols
     1127                        new_x.append( x[ i*self.__nrows + j ] )
     1128                    x = new_x
     1129        if format is not None:
     1130            return self.__matrix_class(self, entries=x, copy=copy, coerce=coerce, format=format)
     1131        else:
     1132            return self.__matrix_class(self, entries=x, copy=copy, coerce=coerce)
    10981133     
    10991134    def matrix_space(self, nrows=None, ncols=None, sparse=False):
    11001135        """
     
    12361271            s = 'RMatrixSpace(%s,%s,%s)'%(K, self.__nrows, self.__ncols)
    12371272        return s
    12381273
     1274
    12391275def dict_to_list(entries, nrows, ncols):
    12401276    """
    12411277    Given a dictionary of coordinate tuples, return the list given by
     
    12871323                d[(col,row)] = x
    12881324    return d
    12891325
    1290 
    1291 
    12921326# sage: m = matrix(F, 0,0, sparse=False)
    12931327# sage: m.determinant()
    12941328# 0