Ticket #4492: trac_4492-block-matrix-reviewer.patch

File trac_4492-block-matrix-reviewer.patch, 13.0 KB (added by rbeezer, 11 years ago)
  • sage/matrix/constructor.py

    # HG changeset patch
    # User Rob Beezer <beezer@ups.edu>
    # Date 1294899948 28800
    # Node ID 14c4ac8842b826f252d961ffe56e9ca6742507c9
    # Parent  373a94ced8192f81f04b0448f95cc66e72953dbb
    4492: block matrix constructor, reviewer edits
    
    diff -r 373a94ced819 -r 14c4ac8842b8 sage/matrix/constructor.py
    a b  
    13821382    return matrix_space.MatrixSpace(ring, nrows, ncols, sparse).matrix([1]*nents)
    13831383
    13841384def _determine_block_matrix_grid(sub_matrices):
    1385     """
     1385    r"""
    13861386    For internal use. This tries to determine the dimensions
    13871387    of rows/columns when assembling the matrices in sub_matrices in a
    13881388    rectangular grid. It returns a pair of lists containing
     
    14431443                        changing = True
    14441444                        col_widths[j] = sub_width
    14451445                    elif col_widths[j] != sub_width:
    1446                         raise ValueError, "Incompatible submatrix widths"
     1446                        raise ValueError("incompatible submatrix widths")
    14471447                if sub_height is not None:
    14481448                    if row_heights[i] is None:
    14491449                        changing = True
    14501450                        row_heights[i] = sub_height
    14511451                    elif row_heights[i] != sub_height:
    1452                         raise ValueError, "Incompatible submatrix heights"
     1452                        raise ValueError("ncompatible submatrix heights")
    14531453   
    14541454    if None in row_heights or None in col_widths:
    14551455        if None in row_heights or None in col_widths:
    1456             raise ValueError, "Insufficient information to determine dimensions."
     1456            raise ValueError("insufficient information to determine dimensions.")
    14571457
    14581458    return (row_heights, col_widths)
    14591459
     
    15061506                if height is None:
    15071507                    height = M.nrows()
    15081508                elif height != M.nrows():
    1509                     raise ValueError, "Incompatible submatrix heights"
     1509                    raise ValueError("incompatible submatrix heights")
    15101510            elif not M:
    15111511                found_zeroes = True
    15121512        if len(R) == 0:
     
    15251525            if total_width is None:
    15261526                total_width = width
    15271527            elif total_width != width:
    1528                 raise ValueError, "Incompatible submatrix widths"
     1528                raise ValueError("incompatible submatrix widths")
    15291529            row_heights[i] = height
    15301530        else:
    15311531            # We don't set height here even if we know it,
     
    15331533            unknowns = True
    15341534
    15351535    if total_width is None:
    1536         raise ValueError, "Insufficient information to determine submatrix widths"
     1536        raise ValueError("insufficient information to determine submatrix widths")
    15371537
    15381538    if unknowns:
    15391539        # Do a second pass and see if the remaining rows can be
     
    15721572            if height is not None:
    15731573                remaining_width -= scalars * height
    15741574                if remaining_width < 0:
    1575                     raise ValueError, "Incompatible submatrix widths"
     1575                    raise ValueError("incompatible submatrix widths")
    15761576                if remaining_width > 0 and zero_state == 3:
    1577                     raise ValueError, "Insufficient information to determine submatrix widths"
     1577                    raise ValueError("insufficient information to determine submatrix widths")
    15781578                if remaining_width > 0 and zero_state == 0:
    1579                     raise ValueError, "Incompatible submatrix widths"
     1579                    raise ValueError("ncompatible submatrix widths")
    15801580                # otherwise, things fit
    15811581                row_heights[i] = height
    15821582                zero_widths[i] = remaining_width
    15831583            elif zero_state != 0:
    15841584                # if we don't know the height, and there are zeroes,
    15851585                # we can't determine the height
    1586                 raise ValueError, "Insufficient information to determine submatrix heights"
     1586                raise ValueError("insufficient information to determine submatrix heights")
    15871587            elif total_width % len(R) != 0:
    1588                 raise ValueError, "Incompatible submatrix widths"
     1588                raise ValueError("incompatible submatrix widths")
    15891589            else:
    15901590                height = int(total_width / len(R))
    15911591                row_heights[i] = height
     
    15931593    # If we got this far, then everything fits
    15941594    return (row_heights, zero_widths, total_width)
    15951595
    1596 def block_matrix(*args, **kwds): #sub_matrices, nrows=None, ncols=None, subdivide=True):
    1597     """
     1596def block_matrix(*args, **kwds):
     1597    r"""
    15981598    Returns a larger matrix made by concatenating submatrices
    15991599    (rows first, then columns). For example, the matrix
    16001600
     
    16051605   
    16061606    is made up of submatrices A, B, C, and D.
    16071607   
    1608     INPUT: The block_matrix command takes a list of submatrices to add
     1608    INPUT:
     1609   
     1610    The block_matrix command takes a list of submatrices to add
    16091611    as blocks, optionally preceded by a ring and the number of block rows
    16101612    and block columns, and returns a matrix.
    16111613
     
    16731675        [    3     9|   -3    -9|-5/12   3/8|  300   900]
    16741676        [    6    10|   -6   -10|  1/4  -1/8|  600  1000]
    16751677   
    1676     ::
    1677    
    16781678        sage: block_matrix([A, -A, ~A, 100*A], nrows=1)
    16791679        [    3     9|   -3    -9|-5/12   3/8|  300   900]
    16801680        [    6    10|   -6   -10|  1/4  -1/8|  600  1000]
     
    16881688        [-----------+-----------]
    16891689        [    0     0|x - 1     0]
    16901690        [    0     0|    0 x - 1]
     1691       
    16911692        sage: block_matrix(2, 2, [1/2, A, 0, x-1]).parent()
    16921693        Full MatrixSpace of 4 by 4 dense matrices over Univariate Polynomial Ring in x over Rational Field
    16931694   
     
    17191720        sage: block_matrix([ [ A ], [ A ] ], sparse=False).parent()
    17201721        Full MatrixSpace of 4 by 2 dense matrices over Integer Ring
    17211722
     1723    Consecutive zero submatrices are consolidated.  ::
     1724   
     1725        sage: B = matrix(2, range(4))
     1726        sage: C = matrix(2, 8, range(16))
     1727        sage: block_matrix(2, [[B,0,0,B],[C]], subdivide=False)
     1728        [ 0  1  0  0  0  0  0  1]
     1729        [ 2  3  0  0  0  0  2  3]
     1730        [ 0  1  2  3  4  5  6  7]
     1731        [ 8  9 10 11 12 13 14 15]
     1732
     1733    Ambiguity is not tolerated.  ::
     1734   
     1735        sage: B = matrix(2, range(4))
     1736        sage: C = matrix(2, 8, range(16))
     1737        sage: block_matrix(2, [[B,0,B,0],[C]], subdivide=False)
     1738        Traceback (most recent call last):
     1739        ...
     1740        ValueError: insufficient information to determine submatrix widths
     1741
     1742    Historically, giving only a flat list of submatrices, whose number
     1743    was a perfect square, would create a new matrix by laying out the submatrices
     1744    in a square grid.  This behavior is now deprecated.  ::
     1745   
     1746        sage: A = matrix(2, 3, range(6))
     1747        sage: B = matrix(3, 3, range(9))
     1748        sage: block_matrix([A, A, B, B])
     1749        doctest:...: DeprecationWarning: invocation of block_matrix with just a list whose length is a perfect square is deprecated. See the documentation for details.
     1750        [0 1 2|0 1 2]
     1751        [3 4 5|3 4 5]
     1752        [-----+-----]
     1753        [0 1 2|0 1 2]
     1754        [3 4 5|3 4 5]
     1755        [6 7 8|6 7 8]
     1756       
     1757    Historically, a flat list of matrices whose number is not a perfect square,
     1758    with no specification of the number of rows or columns, would raise an error.
     1759    This behavior continues, but could be removed when the deprecation above is
     1760    completed.  ::
     1761   
     1762        sage: A = matrix(2, 3, range(6))
     1763        sage: B = matrix(3, 3, range(9))
     1764        sage: block_matrix([A, A, A, B, B, B])
     1765        Traceback (most recent call last):
     1766        ...
     1767        ValueError: must specify nrows or ncols for non-square block matrix.
    17221768    """
    17231769    args = list(args)
    17241770    sparse = kwds.get('sparse',None)
     
    17321778    if len(args) >= 1 and rings.is_Ring(args[0]):
    17331779        # A ring is specified
    17341780        if kwds.get('ring', args[0]) != args[0]:
    1735             raise ValueError, "Specified rings are not the same"
     1781            raise ValueError("base ring specified twice and they are different")
    17361782        ring = args[0]
    17371783        args.pop(0)
    17381784    else:
     
    17431789            nrows = int(args[0])
    17441790            args.pop(0)
    17451791            if kwds.get('nrows', nrows) != nrows:
    1746                 raise ValueError, "Number of rows specified in two places and they are not the same"
     1792                raise ValueError("number of rows specified twice and they are different")
    17471793        except TypeError:
    17481794            nrows = kwds.get('nrows', None)
    17491795    else:
     
    17551801            ncols = int(args[0])
    17561802            args.pop(0)
    17571803            if kwds.get('ncols', ncols) != ncols:
    1758                 raise ValueError, "Number of columns specified in two places and they are not the same"
     1804                raise ValueError("number of columns specified twice and they are different")
    17591805        except TypeError:
    17601806            ncols = kwds.get('ncols', None)
    17611807    else:
     
    17701816        args = [[]]
    17711817    if len(args) > 1:
    17721818        print args
    1773         raise TypeError, "Invalid block_matrix invocation"
     1819        raise TypeError("invalid block_matrix invocation")
    17741820
    17751821    sub_matrices = args[0]
    17761822
     
    17781824        # a single matrix (check nrows/ncols/ring)
    17791825        if (nrows is not None and nrows != 1) or \
    17801826           (ncols is not None and ncols != 1):
    1781             raise ValueError, "Invalid nrows/ncols passed to block_matrix"
     1827            raise ValueError("invalid nrows/ncols passed to block_matrix")
    17821828        if ring is not None:
    17831829            M = M.change_ring(ring)
    17841830        if sparse is not None and M.is_sparse() != sparse:
     
    17861832        return M
    17871833
    17881834    if not isinstance(sub_matrices, (list, tuple)):
    1789         raise TypeError, "Invalid block_matrix invocation"
     1835        raise TypeError("invalid block_matrix invocation")
    17901836
    17911837    subdivide = kwds.get('subdivide', True)
    17921838
     
    17971843    if len(sub_matrices) == 0:
    17981844        if (nrows is not None and nrows != 0) or \
    17991845           (ncols is not None and ncols != 0):
    1800             raise ValueError, "Invalid nrows/ncols passed to block_matrix"
     1846            raise ValueError("invalid nrows/ncols passed to block_matrix")
    18011847    elif isinstance(sub_matrices[0], (list, tuple)):
    18021848        # A list of lists: verify all elements are lists, and if
    18031849        # ncols is set, the lengths match.
    18041850        if nrows is not None and len(sub_matrices) != nrows:
    1805             raise ValueError, "Invalid nrows passed to block_matrix"
     1851            raise ValueError("invalid nrows passed to block_matrix")
    18061852        first_len = len(sub_matrices[0])
    18071853        if ncols is not None and first_len != ncols:
    1808             raise ValueError, "Invalid ncols passed to block_matrix"
     1854            raise ValueError("invalid ncols passed to block_matrix")
    18091855        same_length = all(isinstance(v, (list, tuple)) and len(v) == first_len for v in sub_matrices)
    18101856        if subdivide and not same_length:
    1811             raise ValueError, "List of rows is not valid (rows are wrong types or lengths)"
     1857            raise ValueError("list of rows is not valid (rows are wrong types or lengths)")
    18121858        try_grid = same_length
    18131859    else:
    18141860        # A flat list
     
    18181864            if ncols is None:
    18191865                if n.is_square():
    18201866                    import warnings
    1821                     warnings.warn("This invocation of block_matrix is deprecated. See its documentation for details.", DeprecationWarning, stacklevel=2)
     1867                    warnings.warn("invocation of block_matrix with just a list whose length is a perfect square is deprecated. See the documentation for details.", DeprecationWarning, stacklevel=2)
    18221868                    nrows = ncols = n.sqrt()
    18231869                else:
    1824                     raise ValueError, "Must specify nrows or ncols for non-square block matrix."
     1870                    # this form (ie just a flat list) could be allowed once deprecated invocation (above) goes away
     1871                    raise ValueError("must specify nrows or ncols for non-square block matrix.")
    18251872            else:
    18261873                nrows = int(n/ncols)
    18271874        elif ncols is None:
    18281875            ncols = int(n/nrows)
    18291876        if nrows * ncols != n:
    1830             raise ValueError, "Given number of rows (%s), columns (%s) incompatible with number of submatrices (%s)" % (nrows, ncols, n)
     1877            raise ValueError("given number of rows (%s), columns (%s) incompatible with number of submatrices (%s)" % (nrows, ncols, n))
    18311878        # Now create a list of lists from this
    18321879        sub_matrices = [ sub_matrices[i*ncols : (i+1)*ncols] for i in range(nrows) ]
    18331880
     
    18601907            (row_heights, col_widths) = _determine_block_matrix_grid(sub_matrices)
    18611908        except ValueError as e:
    18621909            if subdivide:
    1863                 raise ValueError, e
     1910                raise ValueError(e)
    18641911
    18651912
    18661913    if col_widths is None:
     
    19231970    Create a block matrix whose diagonal block entries are given by
    19241971    sub_matrices, with zero elsewhere.
    19251972   
    1926     See also ``block_matrix``.
     1973    See also :meth:`block_matrix`.
    19271974   
    19281975    EXAMPLES::
    19291976