{"instance_id": "sympy__sympy-13757", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/polys/polytools.py b/sympy/polys/polytools.py\nindex d5ac051f63..32b7027a28 100644\n--- a/sympy/polys/polytools.py\n+++ b/sympy/polys/polytools.py\n@@ -106,6 +106,7 @@ class Poly(Expr):\n \n     is_commutative = True\n     is_Poly = True\n+    _op_priority = 10.001\n \n     def __new__(cls, rep, *gens, **args):\n         \"\"\"Create a new polynomial instance out of something useful. \"\"\"\n", "model": "claude-sonnet-5-5", "steps": 14, "finished": false, "patch_lines": 12, "candidates": [{"compile_ok": 0, "loc_hits": 1, "files": 1, "diff_lines": 12, "steps": 14}], "ms": 39621}
{"instance_id": "sympy__sympy-13798", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py\nindex ad4d7d9613..ecb4a95fbf 100644\n--- a/sympy/printing/latex.py\n+++ b/sympy/printing/latex.py\n@@ -156,11 +156,23 @@ def __init__(self, settings=None):\n             \"times\": r\" \\times \"\n         }\n \n-        self._settings['mul_symbol_latex'] = \\\n-            mul_symbol_table[self._settings['mul_symbol']]\n-\n-        self._settings['mul_symbol_latex_numbers'] = \\\n-            mul_symbol_table[self._settings['mul_symbol'] or 'dot']\n+        try:\n+            self._settings['mul_symbol_latex'] = \\\n+                mul_symbol_table[self._settings['mul_symbol']]\n+        except KeyError:\n+            self._settings['mul_symbol_latex'] = \\\n+                self._settings['mul_symbol']\n+        try:\n+            self._settings['mul_symbol_latex_numbers'] = \\\n+                mul_symbol_table[self._settings['mul_symbol'] or 'dot']\n+        except KeyError:\n+            if (self._settings['mul_symbol'].strip() in\n+                    ['', ' ', '\\\\', '\\\\,', '\\\\ ']):\n+                self._settings['mul_symbol_latex_numbers'] = \\\n+                    mul_symbol_table['dot']\n+            else:\n+                self._settings['mul_symbol_latex_numbers'] = \\\n+                    self._settings['mul_symbol']\n \n         self._delim_dict = {'(': ')', '[': ']'}\n \n@@ -2155,7 +2167,8 @@ def latex(expr, **settings):\n     \\frac{1}{2 \\pi} \\int r\\, dr\n \n     mul_symbol: The symbol to use for multiplication. Can be one of None,\n-    \"ldot\", \"dot\", or \"times\".\n+    \"ldot\", \"dot\", or \"times\". Any other string is used as-is as the\n+    LaTeX multiplication symbol.\n \n     >>> print(latex((2*tau)**sin(Rational(7,2)), mul_symbol=\"times\"))\n     \\left(2 \\times \\tau\\right)^{\\sin{\\left (\\frac{7}{2} \\right )}}\n", "model": "claude-sonnet-5-5", "steps": 9, "finished": true, "patch_lines": 43, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 43, "steps": 9}], "ms": 17195}
{"instance_id": "sympy__sympy-13852", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/functions/special/tests/test_zeta_functions.py b/sympy/functions/special/tests/test_zeta_functions.py\nindex 3911dadd10..27e229f135 100644\n--- a/sympy/functions/special/tests/test_zeta_functions.py\n+++ b/sympy/functions/special/tests/test_zeta_functions.py\n@@ -128,10 +128,11 @@ def test_polylog_expansion():\n     assert polylog(s, 1) == zeta(s)\n     assert polylog(s, -1) == -dirichlet_eta(s)\n \n-    assert myexpand(polylog(1, z), -log(1 + exp_polar(-I*pi)*z))\n+    assert myexpand(polylog(1, z), -log(1 - z))\n     assert myexpand(polylog(0, z), z/(1 - z))\n     assert myexpand(polylog(-1, z), z**2/(1 - z)**2 + z/(1 - z))\n     assert myexpand(polylog(-5, z), None)\n+    assert expand_func(polylog(2, S(1)/2)) == pi**2/12 - log(2)**2/2\n \n \n def test_lerchphi_expansion():\ndiff --git a/sympy/functions/special/zeta_functions.py b/sympy/functions/special/zeta_functions.py\nindex b8e2b66195..3b7ce4f44c 100644\n--- a/sympy/functions/special/zeta_functions.py\n+++ b/sympy/functions/special/zeta_functions.py\n@@ -253,7 +253,7 @@ class polylog(Function):\n     >>> from sympy import expand_func\n     >>> from sympy.abc import z\n     >>> expand_func(polylog(1, z))\n-    -log(z*exp_polar(-I*pi) + 1)\n+    -log(-z + 1)\n     >>> expand_func(polylog(0, z))\n     z/(-z + 1)\n \n@@ -288,10 +288,12 @@ def _eval_rewrite_as_lerchphi(self, s, z):\n         return z*lerchphi(z, s, 1)\n \n     def _eval_expand_func(self, **hints):\n-        from sympy import log, expand_mul, Dummy, exp_polar, I\n+        from sympy import log, expand_mul, Dummy\n         s, z = self.args\n         if s == 1:\n-            return -log(1 + exp_polar(-I*pi)*z)\n+            return -log(1 - z)\n+        if s == 2 and z == S.Half:\n+            return pi**2/12 - log(2)**2/2\n         if s.is_Integer and s <= 0:\n             u = Dummy('u')\n             start = u/(1 - u)\n", "model": "claude-sonnet-5-5", "steps": 14, "finished": false, "patch_lines": 45, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 2, "diff_lines": 45, "steps": 14}], "ms": 38338}
{"instance_id": "sympy__sympy-13877", "model_name_or_path": "cain-70b-e124", "model_patch": "diff --git a/sympy/matrices/matrices.py b/sympy/matrices/matrices.py\nindex 97cde62e26..b78805a86f 100644\n--- a/sympy/matrices/matrices.py\n+++ b/sympy/matrices/matrices.py\n@@ -1,4248 +1,4 @@\n-from __future__ import print_function, division\n-\n-import collections\n-from mpmath.libmp.libmpf import prec_to_dps\n-from sympy.assumptions.refine import refine\n-from sympy.core.add import Add\n-from sympy.core.basic import Basic, Atom\n-from sympy.core.expr import Expr\n-from sympy.core.power import Pow\n-from sympy.core.symbol import (Symbol, Dummy, symbols,\n-    _uniquely_named_symbol)\n-from sympy.core.numbers import Integer, ilcm, Float\n-from sympy.core.singleton import S\n-from sympy.core.sympify import sympify\n-from sympy.functions.elementary.miscellaneous import sqrt, Max, Min\n-from sympy.functions import Abs, exp, factorial\n-from sympy.polys import PurePoly, roots, cancel, gcd\n-from sympy.printing import sstr\n-from sympy.simplify import simplify as _simplify, signsimp, nsimplify\n-from sympy.core.compatibility import reduce, as_int, string_types\n-\n-from sympy.utilities.iterables import flatten, numbered_symbols\n-from sympy.core.decorators import call_highest_priority\n-from sympy.core.compatibility import is_sequence, default_sort_key, range, \\\n-    NotIterable\n-\n-\n-from types import FunctionType\n-\n-from .common import (a2idx, classof, MatrixError, ShapeError,\n-        NonSquareMatrixError, MatrixCommon)\n-\n-\n-def _iszero(x):\n-    \"\"\"Returns True if x is zero.\"\"\"\n-    try:\n-        return x.is_zero\n-    except AttributeError:\n-        return None\n-\n-\n-class DeferredVector(Symbol, NotIterable):\n-    \"\"\"A vector whose components are deferred (e.g. for use with lambdify)\n-\n-    Examples\n-    ========\n-\n-    >>> from sympy import DeferredVector, lambdify\n-    >>> X = DeferredVector( 'X' )\n-    >>> X\n-    X\n-    >>> expr = (X[0] + 2, X[2] + 3)\n-    >>> func = lambdify( X, expr)\n-    >>> func( [1, 2, 3] )\n-    (3, 6)\n-    \"\"\"\n-\n-    def __getitem__(self, i):\n-        if i == -0:\n-            i = 0\n-        if i < 0:\n-            raise IndexError('DeferredVector index out of range')\n-        component_name = '%s[%d]' % (self.name, i)\n-        return Symbol(component_name)\n-\n-    def __str__(self):\n-        return sstr(self)\n-\n-    def __repr__(self):\n-        return \"DeferredVector('%s')\" % self.name\n-\n-\n-class MatrixDeterminant(MatrixCommon):\n-    \"\"\"Provides basic matrix determinant operations.\n-    Should not be instantiated directly.\"\"\"\n-\n-    def _eval_berkowitz_toeplitz_matrix(self):\n-        \"\"\"Return (A,T) where T the Toeplitz matrix used in the Berkowitz algorithm\n-        corresponding to `self` and A is the first principal submatrix.\"\"\"\n-\n-        # the 0 x 0 case is trivial\n-        if self.rows == 0 and self.cols == 0:\n-            return self._new(1,1, [S.One])\n-\n-        #\n-        # Partition self = [ a_11  R ]\n-        #                  [ C     A ]\n-        #\n-\n-        a, R = self[0,0],   self[0, 1:]\n-        C, A = self[1:, 0], self[1:,1:]\n-\n-        #\n-        # The Toeplitz matrix looks like\n-        #\n-        #  [ 1                                     ]\n-        #  [ -a         1                          ]\n-        #  [ -RC       -a        1                 ]\n-        #  [ -RAC     -RC       -a       1         ]\n-        #  [ -RA**2C -RAC      -RC      -a       1 ]\n-        #  etc.\n-\n-        # Compute the diagonal entries.\n-        # Because multiplying matrix times vector is so much\n-        # more efficient than matrix times matrix, recursively\n-        # compute -R * A**n * C.\n-        diags = [C]\n-        for i in range(self.rows - 2):\n-            diags.append(A * diags[i])\n-        diags = [(-R*d)[0, 0] for d in diags]\n-        diags = [S.One, -a] + diags\n-\n-        def entry(i,j):\n-            if j > i:\n-                return S.Zero\n-            return diags[i - j]\n-\n-        toeplitz = self._new(self.cols + 1, self.rows, entry)\n-        return (A, toeplitz)\n-\n-    def _eval_berkowitz_vector(self):\n-        \"\"\" Run the Berkowitz algorithm and return a vector whose entries\n-            are the coefficients of the characteristic polynomial of `self`.\n-\n-            Given N x N matrix, efficiently compute\n-            coefficients of characteristic polynomials of 'self'\n-            without division in the ground domain.\n-\n-            This method is particularly useful for computing determinant,\n-            principal minors and characteristic polynomial when 'self'\n-            has complicated coefficients e.g. polynomials. Semi-direct\n-            usage of this algorithm is also important in computing\n-            efficiently sub-resultant PRS.\n-\n-            Assuming that M is a square matrix of dimension N x N and\n-            I is N x N identity matrix, then the Berkowitz vector is\n-            an N x 1 vector whose entries are coefficients of the\n-            polynomial\n-\n-                           charpoly(M) = det(t*I - M)\n-\n-            As a consequence, all polynomials generated by Berkowitz\n-            algorithm are monic.\n-\n-           For more information on the implemented algorithm refer to:\n-\n-           [1] S.J. Berkowitz, On computing the determinant in small\n-               parallel time using a small number of processors, ACM,\n-               Information Processing Letters 18, 1984, pp. 147-150\n-\n-           [2] M. Keber, Division-Free computation of sub-resultants\n-               using Bezout matrices, Tech. Report MPI-I-2006-1-006,\n-               Saarbrucken, 2006\n-        \"\"\"\n-\n-        # handle the trivial cases\n-        if self.rows == 0 and self.cols == 0:\n-            return self._new(1, 1, [S.One])\n-        elif self.rows == 1 and self.cols == 1:\n-            return self._new(2, 1, [S.One, -self[0,0]])\n-\n-        submat, toeplitz = self._eval_berkowitz_toeplitz_matrix()\n-        return toeplitz * submat._eval_berkowitz_vector()\n-\n-    def _eval_det_bareiss(self):\n-        \"\"\"Compute matrix determinant using Bareiss' fraction-free\n-        algorithm which is an extension of the well known Gaussian\n-        elimination method. This approach is best suited for dense\n-        symbolic matrices and will result in a determinant with\n-        minimal number of fractions. It means that less term\n-        rewriting is needed on resulting formulae.\n-\n-        TODO: Implement algorithm for sparse matrices (SFF),\n-        http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.\n-        \"\"\"\n-\n-        # XXX included as a workaround for issue #12362.  Should use `_find_reasonable_pivot` instead\n-        def _find_pivot(l):\n-            for pos,val in enumerate(l):\n-                if val:\n-                    return (pos, val, None, None)\n-            return (None, None, None, None)\n-\n-\n-        # Recursively implemented Bareiss' algorithm as per Deanna Richelle Leggett's\n-        # thesis http://www.math.usm.edu/perry/Research/Thesis_DRL.pdf\n-        def bareiss(mat, cumm=1):\n-            if mat.rows == 0:\n-                return S.One\n-            elif mat.rows == 1:\n-                return mat[0, 0]\n-\n-            # find a pivot and extract the remaining matrix\n-            # XXX should use `_find_reasonable_pivot`.  Blocked by issue #12362\n-            pivot_pos, pivot_val, _, _ = _find_pivot(mat[:, 0])\n-            if pivot_pos == None:\n-                return S.Zero\n-\n-            # if we have a valid pivot, we'll do a \"row swap\", so keep the\n-            # sign of the det\n-            sign = (-1) ** (pivot_pos % 2)\n-\n-            # we want every row but the pivot row and every column\n-            rows = list(i for i in range(mat.rows) if i != pivot_pos)\n-            cols = list(range(mat.cols))\n-            tmp_mat = mat.extract(rows, cols)\n-\n-            def entry(i, j):\n-                ret = (pivot_val*tmp_mat[i, j + 1] - mat[pivot_pos, j + 1]*tmp_mat[i, 0]) / cumm\n-                if not ret.is_Atom:\n-                    cancel(ret)\n-                return ret\n-\n-            return sign*bareiss(self._new(mat.rows - 1, mat.cols - 1, entry), pivot_val)\n-\n-        return cancel(bareiss(self))\n-\n-    def _eval_det_berkowitz(self):\n-        \"\"\" Use the Berkowitz algorithm to compute the determinant.\"\"\"\n-        berk_vector = self._eval_berkowitz_vector()\n-        return (-1)**(len(berk_vector) - 1) * berk_vector[-1]\n-\n-    def _eval_det_lu(self, iszerofunc=_iszero, simpfunc=None):\n-        \"\"\" Computes the determinant of a matrix from its LU decomposition.\n-        This function uses the LU decomposition computed by\n-        LUDecomposition_Simple().\n-\n-        The keyword arguments iszerofunc and simpfunc are passed to\n-        LUDecomposition_Simple().\n-        iszerofunc is a callable that returns a boolean indicating if its\n-        input is zero, or None if it cannot make the determination.\n-        simpfunc is a callable that simplifies its input.\n-        The default is simpfunc=None, which indicate that the pivot search\n-        algorithm should not attempt to simplify any candidate pivots.\n-        If simpfunc fails to simplify its input, then it must return its input\n-        instead of a copy.\"\"\"\n-\n-        if self.rows == 0:\n-            return S.One\n-            # sympy/matrices/tests/test_matrices.py contains a test that\n-            # suggests that the determinant of a 0 x 0 matrix is one, by\n-            # convention.\n-\n-        lu, row_swaps = self.LUdecomposition_Simple(iszerofunc=iszerofunc, simpfunc=None)\n-        # P*A = L*U => det(A) = det(L)*det(U)/det(P) = det(P)*det(U).\n-        # Lower triangular factor L encoded in lu has unit diagonal => det(L) = 1.\n-        # P is a permutation matrix => det(P) in {-1, 1} => 1/det(P) = det(P).\n-        # LUdecomposition_Simple() returns a list of row exchange index pairs, rather\n-        # than a permutation matrix, but det(P) = (-1)**len(row_swaps).\n-\n-        # Avoid forming the potentially time consuming  product of U's diagonal entries\n-        # if the product is zero.\n-        # Bottom right entry of U is 0 => det(A) = 0.\n-        # It may be impossible to determine if this entry of U is zero when it is symbolic.\n-        if iszerofunc(lu[lu.rows-1, lu.rows-1]):\n-            return S.Zero\n-\n-        # Compute det(P)\n-        det = -S.One if len(row_swaps)%2 else S.One\n-\n-        # Compute det(U) by calculating the product of U's diagonal entries.\n-        # The upper triangular portion of lu is the upper triangular portion of the\n-        # U factor in the LU decomposition.\n-        for k in range(lu.rows):\n-            det *= lu[k, k]\n-\n-        # return det(P)*det(U)\n-        return det\n-\n-    def _eval_determinant(self):\n-        \"\"\"Assumed to exist by matrix expressions; If we subclass\n-        MatrixDeterminant, we can fully evaluate determinants.\"\"\"\n-        return self.det()\n-\n-    def adjugate(self, method=\"berkowitz\"):\n-        \"\"\"Returns the adjugate, or classical adjoint, of\n-        a matrix.  That is, the transpose of the matrix of cofactors.\n-\n-\n-        http://en.wikipedia.org/wiki/Adjugate\n-\n-        See Also\n-        ========\n-\n-        cofactor_matrix\n-        transpose\n-        \"\"\"\n-        return self.cofactor_matrix(method).transpose()\n-\n-    def charpoly(self, x='lambda', simplify=_simplify):\n-        \"\"\"Computes characteristic polynomial det(x*I - self) where I is\n-        the identity matrix.\n-\n-        A PurePoly is returned, so using different variables for ``x`` does\n-        not affect the comparison or the polynomials:\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> from sympy.abc import x, y\n-        >>> A = Matrix([[1, 3], [2, 0]])\n-        >>> A.charpoly(x) == A.charpoly(y)\n-        True\n-\n-        Specifying ``x`` is optional; a symbol named ``lambda`` is used by\n-        default (which looks good when pretty-printed in unicode):\n-\n-        >>> A.charpoly().as_expr()\n-        lambda**2 - lambda - 6\n-\n-        And if ``x`` clashes with an existing symbol, underscores will\n-        be preppended to the name to make it unique:\n-\n-        >>> A = Matrix([[1, 2], [x, 0]])\n-        >>> A.charpoly(x).as_expr()\n-        _x**2 - _x - 2*x\n-\n-        Whether you pass a symbol or not, the generator can be obtained\n-        with the gen attribute since it may not be the same as the symbol\n-        that was passed:\n-\n-        >>> A.charpoly(x).gen\n-        _x\n-        >>> A.charpoly(x).gen == x\n-        False\n-\n-        Notes\n-        =====\n-\n-        The Samuelson-Berkowitz algorithm is used to compute\n-        the characteristic polynomial efficiently and without any\n-        division operations.  Thus the characteristic polynomial over any\n-        commutative ring without zero divisors can be computed.\n-\n-        See Also\n-        ========\n-\n-        det\n-        \"\"\"\n-\n-        if self.rows != self.cols:\n-            raise NonSquareMatrixError()\n-\n-        berk_vector = self._eval_berkowitz_vector()\n-        x = _uniquely_named_symbol(x, berk_vector)\n-        return PurePoly([simplify(a) for a in berk_vector], x)\n-\n-    def cofactor(self, i, j, method=\"berkowitz\"):\n-        \"\"\"Calculate the cofactor of an element.\n-\n-        See Also\n-        ========\n-\n-        cofactor_matrix\n-        minor\n-        minor_submatrix\n-        \"\"\"\n-\n-        if self.rows != self.cols or self.rows < 1:\n-            raise NonSquareMatrixError()\n-\n-        return (-1)**((i + j) % 2) * self.minor(i, j, method)\n-\n-    def cofactor_matrix(self, method=\"berkowitz\"):\n-        \"\"\"Return a matrix containing the cofactor of each element.\n-\n-        See Also\n-        ========\n-\n-        cofactor\n-        minor\n-        minor_submatrix\n-        adjugate\n-        \"\"\"\n-\n-        if self.rows != self.cols or self.rows < 1:\n-            raise NonSquareMatrixError()\n-\n-        return self._new(self.rows, self.cols,\n-                         lambda i, j: self.cofactor(i, j, method))\n-\n-    def det(self, method=\"bareiss\"):\n-        \"\"\"Computes the determinant of a matrix.  If the matrix\n-        is at most 3x3, a hard-coded formula is used.\n-        Otherwise, the determinant using the method `method`.\n-\n-\n-        Possible values for \"method\":\n-          bareis\n-          berkowitz\n-          lu\n-        \"\"\"\n-\n-        # sanitize `method`\n-        method = method.lower()\n-        if method == \"bareis\":\n-            method = \"bareiss\"\n-        if method == \"det_lu\":\n-            method = \"lu\"\n-        if method not in (\"bareiss\", \"berkowitz\", \"lu\"):\n-            raise ValueError(\"Determinant method '%s' unrecognized\" % method)\n-\n-        # if methods were made internal and all determinant calculations\n-        # passed through here, then these lines could be factored out of\n-        # the method routines\n-        if self.rows != self.cols:\n-            raise NonSquareMatrixError()\n-\n-        n = self.rows\n-        if n == 0:\n-            return S.One\n-        elif n == 1:\n-            return self[0,0]\n-        elif n == 2:\n-            return self[0, 0] * self[1, 1] - self[0, 1] * self[1, 0]\n-        elif n == 3:\n-            return  (self[0, 0] * self[1, 1] * self[2, 2]\n-                   + self[0, 1] * self[1, 2] * self[2, 0]\n-                   + self[0, 2] * self[1, 0] * self[2, 1]\n-                   - self[0, 2] * self[1, 1] * self[2, 0]\n-                   - self[0, 0] * self[1, 2] * self[2, 1]\n-                   - self[0, 1] * self[1, 0] * self[2, 2])\n-\n-        if method == \"bareiss\":\n-            return self._eval_det_bareiss()\n-        elif method == \"berkowitz\":\n-            return self._eval_det_berkowitz()\n-        elif method == \"lu\":\n-            return self._eval_det_lu()\n-\n-    def minor(self, i, j, method=\"berkowitz\"):\n-        \"\"\"Return the (i,j) minor of `self`.  That is,\n-        return the determinant of the matrix obtained by deleting\n-        the `i`th row and `j`th column from `self`.\n-\n-        See Also\n-        ========\n-\n-        minor_submatrix\n-        cofactor\n-        det\n-        \"\"\"\n-\n-        if self.rows != self.cols or self.rows < 1:\n-            raise NonSquareMatrixError()\n-\n-        return self.minor_submatrix(i, j).det(method=method)\n-\n-    def minor_submatrix(self, i, j):\n-        \"\"\"Return the submatrix obtained by removing the `i`th row\n-        and `j`th column from `self`.\n-\n-        See Also\n-        ========\n-\n-        minor\n-        cofactor\n-        \"\"\"\n-\n-        if i < 0:\n-            i += self.rows\n-        if j < 0:\n-            j += self.cols\n-\n-        if not 0 <= i < self.rows or not 0 <= j < self.cols:\n-            raise ValueError(\"`i` and `j` must satisfy 0 <= i < `self.rows` \"\n-                             \"(%d)\" % self.rows + \"and 0 <= j < `self.cols` (%d).\" % self.cols)\n-\n-        rows = [a for a in range(self.rows) if a != i]\n-        cols = [a for a in range(self.cols) if a != j]\n-        return self.extract(rows, cols)\n-\n-\n-class MatrixReductions(MatrixDeterminant):\n-    \"\"\"Provides basic matrix row/column operations.\n-    Should not be instantiated directly.\"\"\"\n-\n-    def _eval_col_op_swap(self, col1, col2):\n-        def entry(i, j):\n-            if j == col1:\n-                return self[i, col2]\n-            elif j == col2:\n-                return self[i, col1]\n-            return self[i, j]\n-        return self._new(self.rows, self.cols, entry)\n-\n-    def _eval_col_op_multiply_col_by_const(self, col, k):\n-        def entry(i, j):\n-            if j == col:\n-                return k * self[i, j]\n-            return self[i, j]\n-        return self._new(self.rows, self.cols, entry)\n-\n-    def _eval_col_op_add_multiple_to_other_col(self, col, k, col2):\n-        def entry(i, j):\n-            if j == col:\n-                return self[i, j] + k * self[i, col2]\n-            return self[i, j]\n-        return self._new(self.rows, self.cols, entry)\n-\n-    def _eval_row_op_swap(self, row1, row2):\n-        def entry(i, j):\n-            if i == row1:\n-                return self[row2, j]\n-            elif i == row2:\n-                return self[row1, j]\n-            return self[i, j]\n-        return self._new(self.rows, self.cols, entry)\n-\n-    def _eval_row_op_multiply_row_by_const(self, row, k):\n-        def entry(i, j):\n-            if i == row:\n-                return k * self[i, j]\n-            return self[i, j]\n-        return self._new(self.rows, self.cols, entry)\n-\n-    def _eval_row_op_add_multiple_to_other_row(self, row, k, row2):\n-        def entry(i, j):\n-            if i == row:\n-                return self[i, j] + k * self[row2, j]\n-            return self[i, j]\n-        return self._new(self.rows, self.cols, entry)\n-\n-    def _eval_echelon_form(self, iszerofunc, simpfunc):\n-        \"\"\"Returns (mat, swaps) where `mat` is a row-equivalent matrix\n-        in echelon form and `swaps` is a list of row-swaps performed.\"\"\"\n-        reduced, pivot_cols, swaps = self._row_reduce(iszerofunc, simpfunc,\n-                                                      normalize_last=True,\n-                                                      normalize=False,\n-                                                      zero_above=False)\n-        return reduced, pivot_cols, swaps\n-\n-    def _eval_is_echelon(self, iszerofunc):\n-        if self.rows <= 0 or self.cols <= 0:\n-            return True\n-        zeros_below = all(iszerofunc(t) for t in self[1:, 0])\n-        if iszerofunc(self[0, 0]):\n-            return zeros_below and self[:, 1:]._eval_is_echelon(iszerofunc)\n-        return zeros_below and self[1:, 1:]._eval_is_echelon(iszerofunc)\n-\n-    def _eval_rref(self, iszerofunc, simpfunc, normalize_last=True):\n-        reduced, pivot_cols, swaps = self._row_reduce(iszerofunc, simpfunc,\n-                                                      normalize_last, normalize=True,\n-                                                      zero_above=True)\n-        return reduced, pivot_cols\n-\n-    def _normalize_op_args(self, op, col, k, col1, col2, error_str=\"col\"):\n-        \"\"\"Validate the arguments for a row/column operation.  `error_str`\n-        can be one of \"row\" or \"col\" depending on the arguments being parsed.\"\"\"\n-        if op not in [\"n->kn\", \"n<->m\", \"n->n+km\"]:\n-            raise ValueError(\"Unknown {} operation '{}'. Valid col operations \"\n-                             \"are 'n->kn', 'n<->m', 'n->n+km'\".format(error_str, op))\n-\n-        # normalize and validate the arguments\n-        if op == \"n->kn\":\n-            col = col if col is not None else col1\n-            if col is None or k is None:\n-                raise ValueError(\"For a {0} operation 'n->kn' you must provide the \"\n-                                 \"kwargs `{0}` and `k`\".format(error_str))\n-            if not 0 <= col <= self.cols:\n-                raise ValueError(\"This matrix doesn't have a {} '{}'\".format(error_str, col))\n-\n-        if op == \"n<->m\":\n-            # we need two cols to swap. It doesn't matter\n-            # how they were specified, so gather them together and\n-            # remove `None`\n-            cols = set((col, k, col1, col2)).difference([None])\n-            if len(cols) > 2:\n-                # maybe the user left `k` by mistake?\n-                cols = set((col, col1, col2)).difference([None])\n-            if len(cols) != 2:\n-                raise ValueError(\"For a {0} operation 'n<->m' you must provide the \"\n-                                 \"kwargs `{0}1` and `{0}2`\".format(error_str))\n-            col1, col2 = cols\n-            if not 0 <= col1 <= self.cols:\n-                raise ValueError(\"This matrix doesn't have a {} '{}'\".format(error_str, col1))\n-            if not 0 <= col2 <= self.cols:\n-                raise ValueError(\"This matrix doesn't have a {} '{}'\".format(error_str, col2))\n-\n-        if op == \"n->n+km\":\n-            col = col1 if col is None else col\n-            col2 = col1 if col2 is None else col2\n-            if col is None or col2 is None or k is None:\n-                raise ValueError(\"For a {0} operation 'n->n+km' you must provide the \"\n-                                 \"kwargs `{0}`, `k`, and `{0}2`\".format(error_str))\n-            if col == col2:\n-                raise ValueError(\"For a {0} operation 'n->n+km' `{0}` and `{0}2` must \"\n-                                 \"be different.\".format(error_str))\n-            if not 0 <= col <= self.cols:\n-                raise ValueError(\"This matrix doesn't have a {} '{}'\".format(error_str, col))\n-            if not 0 <= col2 <= self.cols:\n-                raise ValueError(\"This matrix doesn't have a {} '{}'\".format(error_str, col2))\n-\n-        return op, col, k, col1, col2\n-\n-    def _permute_complexity_right(self, iszerofunc):\n-        \"\"\"Permute columns with complicated elements as\n-        far right as they can go.  Since the `sympy` row reduction\n-        algorithms start on the left, having complexity right-shifted\n-        speeds things up.\n-\n-        Returns a tuple (mat, perm) where perm is a permutation\n-        of the columns to perform to shift the complex columns right, and mat\n-        is the permuted matrix.\"\"\"\n-\n-        def complexity(i):\n-            # the complexity of a column will be judged by how many\n-            # element's zero-ness cannot be determined\n-            return sum(1 if iszerofunc(e) is None else 0 for e in self[:, i])\n-        complex = [(complexity(i), i) for i in range(self.cols)]\n-        perm = [j for (i, j) in sorted(complex)]\n-\n-        return (self.permute(perm, orientation='cols'), perm)\n-\n-    def _row_reduce(self, iszerofunc, simpfunc, normalize_last=True,\n-                    normalize=True, zero_above=True):\n-        \"\"\"Row reduce `self` and return a tuple (rref_matrix,\n-        pivot_cols, swaps) where pivot_cols are the pivot columns\n-        and swaps are any row swaps that were used in the process\n-        of row reduction.\n-\n-        Parameters\n-        ==========\n-\n-        iszerofunc : determines if an entry can be used as a pivot\n-        simpfunc : used to simplify elements and test if they are\n-            zero if `iszerofunc` returns `None`\n-        normalize_last : indicates where all row reduction should\n-            happen in a fraction-free manner and then the rows are\n-            normalized (so that the pivots are 1), or whether\n-            rows should be normalized along the way (like the naive\n-            row reduction algorithm)\n-        normalize : whether pivot rows should be normalized so that\n-            the pivot value is 1\n-        zero_above : whether entries above the pivot should be zeroed.\n-            If `zero_above=False`, an echelon matrix will be returned.\n-        \"\"\"\n-        rows, cols = self.rows, self.cols\n-        mat = list(self)\n-        def get_col(i):\n-            return mat[i::cols]\n-\n-        def row_swap(i, j):\n-            mat[i*cols:(i + 1)*cols], mat[j*cols:(j + 1)*cols] = \\\n-                mat[j*cols:(j + 1)*cols], mat[i*cols:(i + 1)*cols]\n-\n-        def cross_cancel(a, i, b, j):\n-            \"\"\"Does the row op row[i] = a*row[i] - b*row[j]\"\"\"\n-            q = (j - i)*cols\n-            for p in range(i*cols, (i + 1)*cols):\n-                mat[p] = a*mat[p] - b*mat[p + q]\n-\n-        piv_row, piv_col = 0, 0\n-        pivot_cols = []\n-        swaps = []\n-        # use a fraction free method to zero above and below each pivot\n-        while piv_col < cols and piv_row < rows:\n-            pivot_offset, pivot_val, \\\n-            assumed_nonzero, newly_determined = _find_reasonable_pivot(\n-                get_col(piv_col)[piv_row:], iszerofunc, simpfunc)\n-\n-            # _find_reasonable_pivot may have simplified some things\n-            # in the process.  Let's not let them go to waste\n-            for (offset, val) in newly_determined:\n-                offset += piv_row\n-                mat[offset*cols + piv_col] = val\n-\n-            if pivot_offset is None:\n-                piv_col += 1\n-                continue\n-\n-            pivot_cols.append(piv_col)\n-            if pivot_offset != 0:\n-                row_swap(piv_row, pivot_offset + piv_row)\n-                swaps.append((piv_row, pivot_offset + piv_row))\n-\n-            # if we aren't normalizing last, we normalize\n-            # before we zero the other rows\n-            if normalize_last is False:\n-                i, j = piv_row, piv_col\n-                mat[i*cols + j] = S.One\n-                for p in range(i*cols + j + 1, (i + 1)*cols):\n-                    mat[p] = mat[p] / pivot_val\n-                # after normalizing, the pivot value is 1\n-                pivot_val = S.One\n-\n-            # zero above and below the pivot\n-            for row in range(rows):\n-                # don't zero our current row\n-                if row == piv_row:\n-                    continue\n-                # don't zero above the pivot unless we're told.\n-                if zero_above is False and row < piv_row:\n-                    continue\n-                # if we're already a zero, don't do anything\n-                val = mat[row*cols + piv_col]\n-                if iszerofunc(val):\n-                    continue\n-\n-                cross_cancel(pivot_val, row, val, piv_row)\n-            piv_row += 1\n-\n-        # normalize each row\n-        if normalize_last is True and normalize is True:\n-            for piv_i, piv_j in enumerate(pivot_cols):\n-                pivot_val = mat[piv_i*cols + piv_j]\n-                mat[piv_i*cols + piv_j] = S.One\n-                for p in range(piv_i*cols + piv_j + 1, (piv_i + 1)*cols):\n-                    mat[p] = mat[p] / pivot_val\n-\n-        return self._new(self.rows, self.cols, mat), tuple(pivot_cols), tuple(swaps)\n-\n-    def echelon_form(self, iszerofunc=_iszero, simplify=False, with_pivots=False):\n-        \"\"\"Returns a matrix row-equivalent to `self` that is\n-        in echelon form.  Note that echelon form of a matrix\n-        is *not* unique, however, properties like the row\n-        space and the null space are preserved.\"\"\"\n-        simpfunc = simplify if isinstance(\n-            simplify, FunctionType) else _simplify\n-\n-        mat, pivots, swaps = self._eval_echelon_form(iszerofunc, simpfunc)\n-        if with_pivots:\n-            return mat, pivots\n-        return mat\n-\n-    def elementary_col_op(self, op=\"n->kn\", col=None, k=None, col1=None, col2=None):\n-        \"\"\"Performs the elementary column operation `op`.\n-\n-        `op` may be one of\n-\n-            * \"n->kn\" (column n goes to k*n)\n-            * \"n<->m\" (swap column n and column m)\n-            * \"n->n+km\" (column n goes to column n + k*column m)\n-\n-        Parameters\n-        =========\n-\n-        op : string; the elementary row operation\n-        col : the column to apply the column operation\n-        k : the multiple to apply in the column operation\n-        col1 : one column of a column swap\n-        col2 : second column of a column swap or column \"m\" in the column operation\n-               \"n->n+km\"\n-        \"\"\"\n-\n-        op, col, k, col1, col2 = self._normalize_op_args(op, col, k, col1, col2, \"col\")\n-\n-        # now that we've validated, we're all good to dispatch\n-        if op == \"n->kn\":\n-            return self._eval_col_op_multiply_col_by_const(col, k)\n-        if op == \"n<->m\":\n-            return self._eval_col_op_swap(col1, col2)\n-        if op == \"n->n+km\":\n-            return self._eval_col_op_add_multiple_to_other_col(col, k, col2)\n-\n-    def elementary_row_op(self, op=\"n->kn\", row=None, k=None, row1=None, row2=None):\n-        \"\"\"Performs the elementary row operation `op`.\n-\n-        `op` may be one of\n-\n-            * \"n->kn\" (row n goes to k*n)\n-            * \"n<->m\" (swap row n and row m)\n-            * \"n->n+km\" (row n goes to row n + k*row m)\n-\n-        Parameters\n-        ==========\n-\n-        op : string; the elementary row operation\n-        row : the row to apply the row operation\n-        k : the multiple to apply in the row operation\n-        row1 : one row of a row swap\n-        row2 : second row of a row swap or row \"m\" in the row operation\n-               \"n->n+km\"\n-        \"\"\"\n-\n-        op, row, k, row1, row2 = self._normalize_op_args(op, row, k, row1, row2, \"row\")\n-\n-        # now that we've validated, we're all good to dispatch\n-        if op == \"n->kn\":\n-            return self._eval_row_op_multiply_row_by_const(row, k)\n-        if op == \"n<->m\":\n-            return self._eval_row_op_swap(row1, row2)\n-        if op == \"n->n+km\":\n-            return self._eval_row_op_add_multiple_to_other_row(row, k, row2)\n-\n-    @property\n-    def is_echelon(self, iszerofunc=_iszero):\n-        \"\"\"Returns `True` if he matrix is in echelon form.\n-        That is, all rows of zeros are at the bottom, and below\n-        each leading non-zero in a row are exclusively zeros.\"\"\"\n-\n-        return self._eval_is_echelon(iszerofunc)\n-\n-    def rank(self, iszerofunc=_iszero, simplify=False):\n-        \"\"\"\n-        Returns the rank of a matrix\n-\n-        >>> from sympy import Matrix\n-        >>> from sympy.abc import x\n-        >>> m = Matrix([[1, 2], [x, 1 - 1/x]])\n-        >>> m.rank()\n-        2\n-        >>> n = Matrix(3, 3, range(1, 10))\n-        >>> n.rank()\n-        2\n-        \"\"\"\n-        simpfunc = simplify if isinstance(\n-            simplify, FunctionType) else _simplify\n-\n-        # for small matrices, we compute the rank explicitly\n-        # if is_zero on elements doesn't answer the question\n-        # for small matrices, we fall back to the full routine.\n-        if self.rows <= 0 or self.cols <= 0:\n-            return 0\n-        if self.rows <= 1 or self.cols <= 1:\n-            zeros = [iszerofunc(x) for x in self]\n-            if False in zeros:\n-                return 1\n-        if self.rows == 2 and self.cols == 2:\n-            zeros = [iszerofunc(x) for x in self]\n-            if not False in zeros and not None in zeros:\n-                return 0\n-            det = self.det()\n-            if iszerofunc(det) and False in zeros:\n-                return 1\n-            if iszerofunc(det) is False:\n-                return 2\n-\n-        mat, _ = self._permute_complexity_right(iszerofunc=iszerofunc)\n-        echelon_form, pivots, swaps = mat._eval_echelon_form(iszerofunc=iszerofunc, simpfunc=simpfunc)\n-        return len(pivots)\n-\n-    def rref(self, iszerofunc=_iszero, simplify=False, pivots=True, normalize_last=True):\n-        \"\"\"Return reduced row-echelon form of matrix and indices of pivot vars.\n-\n-        Parameters\n-        ==========\n-\n-        iszerofunc : Function\n-            A function used for detecting whether an element can\n-            act as a pivot.  `lambda x: x.is_zero` is used by default.\n-        simplify : Function\n-            A function used to simplify elements when looking for a pivot.\n-            By default SymPy's `simplify`is used.\n-        pivots : True or False\n-            If `True`, a tuple containing the row-reduced matrix and a tuple\n-            of pivot columns is returned.  If `False` just the row-reduced\n-            matrix is returned.\n-        normalize_last : True or False\n-            If `True`, no pivots are normalized to `1` until after all entries\n-            above and below each pivot are zeroed.  This means the row\n-            reduction algorithm is fraction free until the very last step.\n-            If `False`, the naive row reduction procedure is used where\n-            each pivot is normalized to be `1` before row operations are\n-            used to zero above and below the pivot.\n-\n-        Notes\n-        =====\n-\n-        The default value of `normalize_last=True` can provide significant\n-        speedup to row reduction, especially on matrices with symbols.  However,\n-        if you depend on the form row reduction algorithm leaves entries\n-        of the matrix, set `noramlize_last=False`\n-\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> from sympy.abc import x\n-        >>> m = Matrix([[1, 2], [x, 1 - 1/x]])\n-        >>> m.rref()\n-        (Matrix([\n-        [1, 0],\n-        [0, 1]]), (0, 1))\n-        >>> rref_matrix, rref_pivots = m.rref()\n-        >>> rref_matrix\n-        Matrix([\n-        [1, 0],\n-        [0, 1]])\n-        >>> rref_pivots\n-        (0, 1)\n-        \"\"\"\n-        simpfunc = simplify if isinstance(\n-            simplify, FunctionType) else _simplify\n-\n-        ret, pivot_cols = self._eval_rref(iszerofunc=iszerofunc,\n-                                          simpfunc=simpfunc,\n-                                          normalize_last=normalize_last)\n-        if pivots:\n-            ret = (ret, pivot_cols)\n-        return ret\n-\n-\n-class MatrixSubspaces(MatrixReductions):\n-    \"\"\"Provides methods relating to the fundamental subspaces\n-    of a matrix.  Should not be instantiated directly.\"\"\"\n-\n-    def columnspace(self, simplify=False):\n-        \"\"\"Returns a list of vectors (Matrix objects) that span columnspace of self\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix\n-        >>> m = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6])\n-        >>> m\n-        Matrix([\n-        [ 1,  3, 0],\n-        [-2, -6, 0],\n-        [ 3,  9, 6]])\n-        >>> m.columnspace()\n-        [Matrix([\n-        [ 1],\n-        [-2],\n-        [ 3]]), Matrix([\n-        [0],\n-        [0],\n-        [6]])]\n-\n-        See Also\n-        ========\n-\n-        nullspace\n-        rowspace\n-        \"\"\"\n-        reduced, pivots = self.echelon_form(simplify=simplify, with_pivots=True)\n-\n-        return [self.col(i) for i in pivots]\n-\n-    def nullspace(self, simplify=False):\n-        \"\"\"Returns list of vectors (Matrix objects) that span nullspace of self\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix\n-        >>> m = Matrix(3, 3, [1, 3, 0, -2, -6, 0, 3, 9, 6])\n-        >>> m\n-        Matrix([\n-        [ 1,  3, 0],\n-        [-2, -6, 0],\n-        [ 3,  9, 6]])\n-        >>> m.nullspace()\n-        [Matrix([\n-        [-3],\n-        [ 1],\n-        [ 0]])]\n-\n-        See Also\n-        ========\n-\n-        columnspace\n-        rowspace\n-        \"\"\"\n-\n-        reduced, pivots = self.rref(simplify=simplify)\n-\n-        free_vars = [i for i in range(self.cols) if i not in pivots]\n-\n-        basis = []\n-        for free_var in free_vars:\n-            # for each free variable, we will set it to 1 and all others\n-            # to 0.  Then, we will use back substitution to solve the system\n-            vec = [S.Zero]*self.cols\n-            vec[free_var] = S.One\n-            for piv_row, piv_col in enumerate(pivots):\n-                for pos in pivots[piv_row+1:] + (free_var,):\n-                    vec[piv_col] -= reduced[piv_row, pos]\n-            basis.append(vec)\n-\n-        return [self._new(self.cols, 1, b) for b in basis]\n-\n-    def rowspace(self, simplify=False):\n-        \"\"\"Returns a list of vectors that span the row space of self.\"\"\"\n-\n-        reduced, pivots = self.echelon_form(simplify=simplify, with_pivots=True)\n-\n-        return [reduced.row(i) for i in range(len(pivots))]\n-\n-    @classmethod\n-    def orthogonalize(cls, *vecs, **kwargs):\n-        \"\"\"Apply the Gram-Schmidt orthogonalization procedure\n-        to vectors supplied in `vecs`.\n-\n-        Arguments\n-        =========\n-\n-        vecs : vectors to be made orthogonal\n-        normalize : bool. Whether the returned vectors\n-                    should be renormalized to be unit vectors.\n-        \"\"\"\n-\n-        normalize = kwargs.get('normalize', False)\n-\n-        def project(a, b):\n-            return b * (a.dot(b) / b.dot(b))\n-\n-        def perp_to_subspace(vec, basis):\n-            \"\"\"projects vec onto the subspace given\n-            by the orthogonal basis `basis`\"\"\"\n-            components = [project(vec, b) for b in basis]\n-            if len(basis) == 0:\n-                return vec\n-            return vec - reduce(lambda a, b: a + b, components)\n-\n-        ret = []\n-        # make sure we start with a non-zero vector\n-        while len(vecs) > 0 and vecs[0].is_zero:\n-            del vecs[0]\n-\n-        for vec in vecs:\n-            perp = perp_to_subspace(vec, ret)\n-            if not perp.is_zero:\n-                ret.append(perp)\n-\n-        if normalize:\n-            ret = [vec / vec.norm() for vec in ret]\n-\n-        return ret\n-\n-\n-class MatrixEigen(MatrixSubspaces):\n-    \"\"\"Provides basic matrix eigenvalue/vector operations.\n-    Should not be instantiated directly.\"\"\"\n-\n-    _cache_is_diagonalizable = None\n-    _cache_eigenvects = None\n-\n-    def diagonalize(self, reals_only=False, sort=False, normalize=False):\n-        \"\"\"\n-        Return (P, D), where D is diagonal and\n-\n-            D = P^-1 * M * P\n-\n-        where M is current matrix.\n-\n-        Parameters\n-        ==========\n-\n-        reals_only : bool. Whether to throw an error if complex numbers are need\n-                     to diagonalize. (Default: False)\n-        sort : bool. Sort the eigenvalues along the diagonal. (Default: False)\n-        normalize : bool. If True, normalize the columns of P. (Default: False)\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])\n-        >>> m\n-        Matrix([\n-        [1,  2, 0],\n-        [0,  3, 0],\n-        [2, -4, 2]])\n-        >>> (P, D) = m.diagonalize()\n-        >>> D\n-        Matrix([\n-        [1, 0, 0],\n-        [0, 2, 0],\n-        [0, 0, 3]])\n-        >>> P\n-        Matrix([\n-        [-1, 0, -1],\n-        [ 0, 0, -1],\n-        [ 2, 1,  2]])\n-        >>> P.inv() * m * P\n-        Matrix([\n-        [1, 0, 0],\n-        [0, 2, 0],\n-        [0, 0, 3]])\n-\n-        See Also\n-        ========\n-\n-        is_diagonal\n-        is_diagonalizable\n-        \"\"\"\n-\n-        if not self.is_square:\n-            raise NonSquareMatrixError()\n-\n-        if not self.is_diagonalizable(reals_only=reals_only, clear_cache=False):\n-            raise MatrixError(\"Matrix is not diagonalizable\")\n-\n-        eigenvecs = self._cache_eigenvects\n-        if eigenvecs is None:\n-            eigenvecs = self.eigenvects(simplify=True)\n-\n-        if sort:\n-            eigenvecs = sorted(eigenvecs, key=default_sort_key)\n-\n-        p_cols, diag = [], []\n-        for val, mult, basis in eigenvecs:\n-            diag += [val] * mult\n-            p_cols += basis\n-\n-        if normalize:\n-            p_cols = [v / v.norm() for v in p_cols]\n-\n-        return self.hstack(*p_cols), self.diag(*diag)\n-\n-    def eigenvals(self, error_when_incomplete=True, **flags):\n-        \"\"\"Return eigenvalues using the Berkowitz agorithm to compute\n-        the characteristic polynomial.\n-\n-        Parameters\n-        ==========\n-\n-        error_when_incomplete : bool\n-            Raise an error when not all eigenvalues are computed. This is\n-            caused by ``roots`` not returning a full list of eigenvalues.\n-\n-        Since the roots routine doesn't always work well with Floats,\n-        they will be replaced with Rationals before calling that\n-        routine. If this is not desired, set flag ``rational`` to False.\n-        \"\"\"\n-        mat = self\n-        if not mat:\n-            return {}\n-        if flags.pop('rational', True):\n-            if any(v.has(Float) for v in mat):\n-                mat = mat.applyfunc(lambda x: nsimplify(x, rational=True))\n-\n-        flags.pop('simplify', None)  # pop unsupported flag\n-        eigs = roots(mat.charpoly(x=Dummy('x')), **flags)\n-\n-        # make sure the algebraic multiplicty sums to the\n-        # size of the matrix\n-        if error_when_incomplete and sum(m for m in eigs.values()) != self.cols:\n-            raise MatrixError(\"Could not compute eigenvalues for {}\".format(self))\n-\n-        return eigs\n-\n-    def eigenvects(self, error_when_incomplete=True, **flags):\n-        \"\"\"Return list of triples (eigenval, multiplicity, basis).\n-\n-        The flag ``simplify`` has two effects:\n-            1) if bool(simplify) is True, as_content_primitive()\n-            will be used to tidy up normalization artifacts;\n-            2) if nullspace needs simplification to compute the\n-            basis, the simplify flag will be passed on to the\n-            nullspace routine which will interpret it there.\n-\n-        Parameters\n-        ==========\n-\n-        error_when_incomplete : bool\n-            Raise an error when not all eigenvalues are computed. This is\n-            caused by ``roots`` not returning a full list of eigenvalues.\n-\n-        If the matrix contains any Floats, they will be changed to Rationals\n-        for computation purposes, but the answers will be returned after being\n-        evaluated with evalf. If it is desired to removed small imaginary\n-        portions during the evalf step, pass a value for the ``chop`` flag.\n-        \"\"\"\n-        from sympy.matrices import eye\n-\n-        simplify = flags.get('simplify', True)\n-        if not isinstance(simplify, FunctionType):\n-            simpfunc = _simplify if simplify else lambda x: x\n-        primitive = flags.get('simplify', False)\n-        chop = flags.pop('chop', False)\n-\n-        flags.pop('multiple', None)  # remove this if it's there\n-\n-        mat = self\n-        # roots doesn't like Floats, so replace them with Rationals\n-        has_floats = any(v.has(Float) for v in self)\n-        if has_floats:\n-            mat = mat.applyfunc(lambda x: nsimplify(x, rational=True))\n-\n-        def eigenspace(eigenval):\n-            \"\"\"Get a basis for the eigenspace for a particular eigenvalue\"\"\"\n-            m = mat - self.eye(mat.rows) * eigenval\n-            ret = m.nullspace()\n-            # the nullspace for a real eigenvalue should be\n-            # non-trivial.  If we didn't find an eigenvector, try once\n-            # more a little harder\n-            if len(ret) == 0 and simplify:\n-                ret = m.nullspace(simplify=True)\n-            if len(ret) == 0:\n-                raise NotImplementedError(\n-                        \"Can't evaluate eigenvector for eigenvalue %s\" % eigenval)\n-            return ret\n-\n-        eigenvals = mat.eigenvals(rational=False,\n-                                  error_when_incomplete=error_when_incomplete,\n-                                  **flags)\n-        ret = [(val, mult, eigenspace(val)) for val, mult in\n-                    sorted(eigenvals.items(), key=default_sort_key)]\n-        if primitive:\n-            # if the primitive flag is set, get rid of any common\n-            # integer denominators\n-            def denom_clean(l):\n-                from sympy import gcd\n-                return [(v / gcd(list(v))).applyfunc(simpfunc) for v in l]\n-            ret = [(val, mult, denom_clean(es)) for val, mult, es in ret]\n-        if has_floats:\n-            # if we had floats to start with, turn the eigenvectors to floats\n-            ret = [(val.evalf(chop=chop), mult, [v.evalf(chop=chop) for v in es]) for val, mult, es in ret]\n-        return ret\n-\n-    def is_diagonalizable(self, reals_only=False, **kwargs):\n-        \"\"\"Returns true if a matrix is diagonalizable.\n-\n-        Parameters\n-        ==========\n-\n-        reals_only : bool. If reals_only=True, determine whether the matrix can be\n-                     diagonalized without complex numbers. (Default: False)\n-\n-        kwargs\n-        ======\n-\n-        clear_cache : bool. If True, clear the result of any computations when finished.\n-                      (Default: True)\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])\n-        >>> m\n-        Matrix([\n-        [1,  2, 0],\n-        [0,  3, 0],\n-        [2, -4, 2]])\n-        >>> m.is_diagonalizable()\n-        True\n-        >>> m = Matrix(2, 2, [0, 1, 0, 0])\n-        >>> m\n-        Matrix([\n-        [0, 1],\n-        [0, 0]])\n-        >>> m.is_diagonalizable()\n-        False\n-        >>> m = Matrix(2, 2, [0, 1, -1, 0])\n-        >>> m\n-        Matrix([\n-        [ 0, 1],\n-        [-1, 0]])\n-        >>> m.is_diagonalizable()\n-        True\n-        >>> m.is_diagonalizable(reals_only=True)\n-        False\n-\n-        See Also\n-        ========\n-\n-        is_diagonal\n-        diagonalize\n-        \"\"\"\n-\n-        clear_cache = kwargs.get('clear_cache', True)\n-        if 'clear_subproducts' in kwargs:\n-            clear_cache = kwargs.get('clear_subproducts')\n-\n-        def cleanup():\n-            \"\"\"Clears any cached values if requested\"\"\"\n-            if clear_cache:\n-                self._cache_eigenvects = None\n-                self._cache_is_diagonalizable = None\n-\n-        if not self.is_square:\n-            cleanup()\n-            return False\n-\n-        # use the cached value if we have it\n-        if self._cache_is_diagonalizable is not None:\n-            ret = self._cache_is_diagonalizable\n-            cleanup()\n-            return ret\n-\n-        if all(e.is_real for e in self) and self.is_symmetric():\n-            # every real symmetric matrix is real diagonalizable\n-            self._cache_is_diagonalizable = True\n-            cleanup()\n-            return True\n-\n-        self._cache_eigenvects = self.eigenvects(simplify=True)\n-        ret = True\n-        for val, mult, basis in self._cache_eigenvects:\n-            # if we have a complex eigenvalue\n-            if reals_only and not val.is_real:\n-                ret = False\n-            # if the geometric multiplicity doesn't equal the algebraic\n-            if mult != len(basis):\n-                ret = False\n-        cleanup()\n-        return ret\n-\n-    def jordan_form(self, calc_transform=True, **kwargs):\n-        \"\"\"Return `(P, J)` where `J` is a Jordan block\n-        matrix and `P` is a matrix such that\n-\n-            `self == P*J*P**-1`\n-\n-\n-        Parameters\n-        ==========\n-\n-        calc_transform : bool\n-            If ``False``, then only `J` is returned.\n-        chop : bool\n-            All matrices are convered to exact types when computing\n-            eigenvalues and eigenvectors.  As a result, there may be\n-            approximation errors.  If ``chop==True``, these errors\n-            will be truncated.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> m = Matrix([[ 6,  5, -2, -3], [-3, -1,  3,  3], [ 2,  1, -2, -3], [-1,  1,  5,  5]])\n-        >>> P, J = m.jordan_form()\n-        >>> J\n-        Matrix([\n-        [2, 1, 0, 0],\n-        [0, 2, 0, 0],\n-        [0, 0, 2, 1],\n-        [0, 0, 0, 2]])\n-\n-        See Also\n-        ========\n-\n-        jordan_block\n-        \"\"\"\n-        if not self.is_square:\n-            raise NonSquareMatrixError(\"Only square matrices have Jordan forms\")\n-\n-        chop = kwargs.pop('chop', False)\n-        mat = self\n-        has_floats = any(v.has(Float) for v in self)\n-\n-        if has_floats:\n-            try:\n-                max_prec = max(term._prec for term in self._mat if isinstance(term, Float))\n-            except ValueError:\n-                # if no term in the matrix is explicitly a Float calling max()\n-                # will throw a error so setting max_prec to default value of 53\n-                max_prec = 53\n-            # setting minimum max_dps to 15 to prevent loss of precision in\n-            # matrix containing non evaluated expressions\n-            max_dps = max(prec_to_dps(max_prec), 15)\n-\n-        def restore_floats(*args):\n-            \"\"\"If `has_floats` is `True`, cast all `args` as\n-            matrices of floats.\"\"\"\n-            if has_floats:\n-                args = [m.evalf(prec=max_dps, chop=chop) for m in args]\n-            if len(args) == 1:\n-                return args[0]\n-            return args\n-\n-        # cache calculations for some speedup\n-        mat_cache = {}\n-        def eig_mat(val, pow):\n-            \"\"\"Cache computations of (self - val*I)**pow for quick\n-            retrieval\"\"\"\n-            if (val, pow) in mat_cache:\n-                return mat_cache[(val, pow)]\n-            if (val, pow - 1) in mat_cache:\n-                mat_cache[(val, pow)] = mat_cache[(val, pow - 1)] * mat_cache[(val, 1)]\n-            else:\n-                mat_cache[(val, pow)] = (mat - val*self.eye(self.rows))**pow\n-            return mat_cache[(val, pow)]\n-\n-        # helper functions\n-        def nullity_chain(val):\n-            \"\"\"Calculate the sequence  [0, nullity(E), nullity(E**2), ...]\n-            until it is constant where `E = self - val*I`\"\"\"\n-            # mat.rank() is faster than computing the null space,\n-            # so use the rank-nullity theorem\n-            cols = self.cols\n-            ret = [0]\n-            nullity = cols - eig_mat(val, 1).rank()\n-            i = 2\n-            while nullity != ret[-1]:\n-                ret.append(nullity)\n-                nullity = cols - eig_mat(val, i).rank()\n-                i += 1\n-            return ret\n-\n-        def blocks_from_nullity_chain(d):\n-            \"\"\"Return a list of the size of each Jordan block.\n-            If d_n is the nullity of E**n, then the number\n-            of Jordan blocks of size n is\n-\n-                2*d_n - d_(n-1) - d_(n+1)\"\"\"\n-            # d[0] is always the number of columns, so skip past it\n-            mid = [2*d[n] - d[n - 1] - d[n + 1] for n in range(1, len(d) - 1)]\n-            # d is assumed to plateau with \"d[ len(d) ] == d[-1]\", so\n-            # 2*d_n - d_(n-1) - d_(n+1) == d_n - d_(n-1)\n-            end = [d[-1] - d[-2]] if len(d) > 1 else [d[0]]\n-            return mid + end\n-\n-        def pick_vec(small_basis, big_basis):\n-            \"\"\"Picks a vector from big_basis that isn't in\n-            the subspace spanned by small_basis\"\"\"\n-            if len(small_basis) == 0:\n-                return big_basis[0]\n-            for v in big_basis:\n-                _, pivots = self.hstack(*(small_basis + [v])).echelon_form(with_pivots=True)\n-                if pivots[-1] == len(small_basis):\n-                    return v\n-\n-        # roots doesn't like Floats, so replace them with Rationals\n-        if has_floats:\n-            mat = mat.applyfunc(lambda x: nsimplify(x, rational=True))\n-\n-        # first calculate the jordan block structure\n-        eigs = mat.eigenvals()\n-\n-        # make sure that we found all the roots by counting\n-        # the algebraic multiplicity\n-        if sum(m for m in eigs.values()) != mat.cols:\n-            raise MatrixError(\"Could not compute eigenvalues for {}\".format(mat))\n-\n-        # most matrices have distinct eigenvalues\n-        # and so are diagonalizable.  In this case, don't\n-        # do extra work!\n-        if len(eigs.keys()) == mat.cols:\n-            blocks = list(sorted(eigs.keys(), key=default_sort_key))\n-            jordan_mat = mat.diag(*blocks)\n-            if not calc_transform:\n-                return restore_floats(jordan_mat)\n-            jordan_basis = [eig_mat(eig, 1).nullspace()[0] for eig in blocks]\n-            basis_mat = mat.hstack(*jordan_basis)\n-            return restore_floats(basis_mat, jordan_mat)\n-\n-        block_structure = []\n-        for eig in sorted(eigs.keys(), key=default_sort_key):\n-            chain = nullity_chain(eig)\n-            block_sizes = blocks_from_nullity_chain(chain)\n-            # if block_sizes == [a, b, c, ...], then the number of\n-            # Jordan blocks of size 1 is a, of size 2 is b, etc.\n-            # create an array that has (eig, block_size) with one\n-            # entry for each block\n-            size_nums = [(i+1, num) for i, num in enumerate(block_sizes)]\n-            # we expect larger Jordan blocks to come earlier\n-            size_nums.reverse()\n-\n-            block_structure.extend(\n-                (eig, size) for size, num in size_nums for _ in range(num))\n-        blocks = (mat.jordan_block(size=size, eigenvalue=eig) for eig, size in block_structure)\n-        jordan_mat = mat.diag(*blocks)\n-\n-        if not calc_transform:\n-            return restore_floats(jordan_mat)\n-\n-        # For each generalized eigenspace, calculate a basis.\n-        # We start by looking for a vector in null( (A - eig*I)**n )\n-        # which isn't in null( (A - eig*I)**(n-1) ) where n is\n-        # the size of the Jordan block\n-        #\n-        # Ideally we'd just loop through block_structure and\n-        # compute each generalized eigenspace.  However, this\n-        # causes a lot of unneeded computation.  Instead, we\n-        # go through the eigenvalues separately, since we know\n-        # their generalized eigenspaces must have bases that\n-        # are linearly independent.\n-        jordan_basis = []\n-\n-        for eig in sorted(eigs.keys(), key=default_sort_key):\n-            eig_basis = []\n-            for block_eig, size in block_structure:\n-                if block_eig != eig:\n-                    continue\n-                null_big = (eig_mat(eig, size)).nullspace()\n-                null_small = (eig_mat(eig, size - 1)).nullspace()\n-                # we want to pick something that is in the big basis\n-                # and not the small, but also something that is independent\n-                # of any other generalized eigenvectors from a different\n-                # generalized eigenspace sharing the same eigenvalue.\n-                vec = pick_vec(null_small + eig_basis, null_big)\n-                new_vecs = [(eig_mat(eig, i))*vec for i in range(size)]\n-                eig_basis.extend(new_vecs)\n-                jordan_basis.extend(reversed(new_vecs))\n-\n-        basis_mat = mat.hstack(*jordan_basis)\n-\n-        return restore_floats(basis_mat, jordan_mat)\n-\n-    def left_eigenvects(self, **flags):\n-        \"\"\"Returns left eigenvectors and eigenvalues.\n-\n-        This function returns the list of triples (eigenval, multiplicity,\n-        basis) for the left eigenvectors. Options are the same as for\n-        eigenvects(), i.e. the ``**flags`` arguments gets passed directly to\n-        eigenvects().\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> M = Matrix([[0, 1, 1], [1, 0, 0], [1, 1, 1]])\n-        >>> M.eigenvects()\n-        [(-1, 1, [Matrix([\n-        [-1],\n-        [ 1],\n-        [ 0]])]), (0, 1, [Matrix([\n-        [ 0],\n-        [-1],\n-        [ 1]])]), (2, 1, [Matrix([\n-        [2/3],\n-        [1/3],\n-        [  1]])])]\n-        >>> M.left_eigenvects()\n-        [(-1, 1, [Matrix([[-2, 1, 1]])]), (0, 1, [Matrix([[-1, -1, 1]])]), (2,\n-        1, [Matrix([[1, 1, 1]])])]\n-\n-        \"\"\"\n-        eigs = self.transpose().eigenvects(**flags)\n-\n-        return [(val, mult, [l.transpose() for l in basis]) for val, mult, basis in eigs]\n-\n-    def singular_values(self):\n-        \"\"\"Compute the singular values of a Matrix\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix, Symbol\n-        >>> x = Symbol('x', real=True)\n-        >>> A = Matrix([[0, 1, 0], [0, x, 0], [-1, 0, 0]])\n-        >>> A.singular_values()\n-        [sqrt(x**2 + 1), 1, 0]\n-\n-        See Also\n-        ========\n-\n-        condition_number\n-        \"\"\"\n-        mat = self\n-        # Compute eigenvalues of A.H A\n-        valmultpairs = (mat.H * mat).eigenvals()\n-\n-        # Expands result from eigenvals into a simple list\n-        vals = []\n-        for k, v in valmultpairs.items():\n-            vals += [sqrt(k)] * v  # dangerous! same k in several spots!\n-        # sort them in descending order\n-        vals.sort(reverse=True, key=default_sort_key)\n-\n-        return vals\n-\n-\n-\n-class MatrixCalculus(MatrixCommon):\n-    \"\"\"Provides calculus-related matrix operations.\"\"\"\n-\n-    def diff(self, *args):\n-        \"\"\"Calculate the derivative of each element in the matrix.\n-        ``args`` will be passed to the ``integrate`` function.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix\n-        >>> from sympy.abc import x, y\n-        >>> M = Matrix([[x, y], [1, 0]])\n-        >>> M.diff(x)\n-        Matrix([\n-        [1, 0],\n-        [0, 0]])\n-\n-        See Also\n-        ========\n-\n-        integrate\n-        limit\n-        \"\"\"\n-        from sympy import Derivative\n-        return Derivative(self, *args, evaluate=True)\n-\n-    def _eval_derivative(self, arg):\n-        return self.applyfunc(lambda x: x.diff(arg))\n-\n-    def integrate(self, *args):\n-        \"\"\"Integrate each element of the matrix.  ``args`` will\n-        be passed to the ``integrate`` function.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix\n-        >>> from sympy.abc import x, y\n-        >>> M = Matrix([[x, y], [1, 0]])\n-        >>> M.integrate((x, ))\n-        Matrix([\n-        [x**2/2, x*y],\n-        [     x,   0]])\n-        >>> M.integrate((x, 0, 2))\n-        Matrix([\n-        [2, 2*y],\n-        [2,   0]])\n-\n-        See Also\n-        ========\n-\n-        limit\n-        diff\n-        \"\"\"\n-        return self.applyfunc(lambda x: x.integrate(*args))\n-\n-    def jacobian(self, X):\n-        \"\"\"Calculates the Jacobian matrix (derivative of a vector-valued function).\n-\n-        Parameters\n-        ==========\n-\n-        self : vector of expressions representing functions f_i(x_1, ..., x_n).\n-        X : set of x_i's in order, it can be a list or a Matrix\n-\n-        Both self and X can be a row or a column matrix in any order\n-        (i.e., jacobian() should always work).\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import sin, cos, Matrix\n-        >>> from sympy.abc import rho, phi\n-        >>> X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])\n-        >>> Y = Matrix([rho, phi])\n-        >>> X.jacobian(Y)\n-        Matrix([\n-        [cos(phi), -rho*sin(phi)],\n-        [sin(phi),  rho*cos(phi)],\n-        [   2*rho,             0]])\n-        >>> X = Matrix([rho*cos(phi), rho*sin(phi)])\n-        >>> X.jacobian(Y)\n-        Matrix([\n-        [cos(phi), -rho*sin(phi)],\n-        [sin(phi),  rho*cos(phi)]])\n-\n-        See Also\n-        ========\n-\n-        hessian\n-        wronskian\n-        \"\"\"\n-        if not isinstance(X, MatrixBase):\n-            X = self._new(X)\n-        # Both X and self can be a row or a column matrix, so we need to make\n-        # sure all valid combinations work, but everything else fails:\n-        if self.shape[0] == 1:\n-            m = self.shape[1]\n-        elif self.shape[1] == 1:\n-            m = self.shape[0]\n-        else:\n-            raise TypeError(\"self must be a row or a column matrix\")\n-        if X.shape[0] == 1:\n-            n = X.shape[1]\n-        elif X.shape[1] == 1:\n-            n = X.shape[0]\n-        else:\n-            raise TypeError(\"X must be a row or a column matrix\")\n-\n-        # m is the number of functions and n is the number of variables\n-        # computing the Jacobian is now easy:\n-        return self._new(m, n, lambda j, i: self[j].diff(X[i]))\n-\n-    def limit(self, *args):\n-        \"\"\"Calculate the limit of each element in the matrix.\n-        ``args`` will be passed to the ``limit`` function.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix\n-        >>> from sympy.abc import x, y\n-        >>> M = Matrix([[x, y], [1, 0]])\n-        >>> M.limit(x, 2)\n-        Matrix([\n-        [2, y],\n-        [1, 0]])\n-\n-        See Also\n-        ========\n-\n-        integrate\n-        diff\n-        \"\"\"\n-        return self.applyfunc(lambda x: x.limit(*args))\n-\n-\n-# https://github.com/sympy/sympy/pull/12854\n-class MatrixDeprecated(MatrixCommon):\n-    \"\"\"A class to house deprecated matrix methods.\"\"\"\n-\n-    def berkowitz_charpoly(self, x=Dummy('lambda'), simplify=_simplify):\n-        return self.charpoly(x=x)\n-\n-    def berkowitz_det(self):\n-        \"\"\"Computes determinant using Berkowitz method.\n-\n-        See Also\n-        ========\n-\n-        det\n-        berkowitz\n-        \"\"\"\n-        return self.det(method='berkowitz')\n-\n-    def berkowitz_eigenvals(self, **flags):\n-        \"\"\"Computes eigenvalues of a Matrix using Berkowitz method.\n-\n-        See Also\n-        ========\n-\n-        berkowitz\n-        \"\"\"\n-        return self.eigenvals(**flags)\n-\n-    def berkowitz_minors(self):\n-        \"\"\"Computes principal minors using Berkowitz method.\n-\n-        See Also\n-        ========\n-\n-        berkowitz\n-        \"\"\"\n-        sign, minors = S.One, []\n-\n-        for poly in self.berkowitz():\n-            minors.append(sign * poly[-1])\n-            sign = -sign\n-\n-        return tuple(minors)\n-\n-    def berkowitz(self):\n-        from sympy.matrices import zeros\n-        berk = ((1,),)\n-        if not self:\n-            return berk\n-\n-        if not self.is_square:\n-            raise NonSquareMatrixError()\n-\n-        A, N = self, self.rows\n-        transforms = [0] * (N - 1)\n-\n-        for n in range(N, 1, -1):\n-            T, k = zeros(n + 1, n), n - 1\n-\n-            R, C = -A[k, :k], A[:k, k]\n-            A, a = A[:k, :k], -A[k, k]\n-\n-            items = [C]\n-\n-            for i in range(0, n - 2):\n-                items.append(A * items[i])\n-\n-            for i, B in enumerate(items):\n-                items[i] = (R * B)[0, 0]\n-\n-            items = [S.One, a] + items\n-\n-            for i in range(n):\n-                T[i:, i] = items[:n - i + 1]\n-\n-            transforms[k - 1] = T\n-\n-        polys = [self._new([S.One, -A[0, 0]])]\n-\n-        for i, T in enumerate(transforms):\n-            polys.append(T * polys[i])\n-\n-        return berk + tuple(map(tuple, polys))\n-\n-    def cofactorMatrix(self, method=\"berkowitz\"):\n-        return self.cofactor_matrix(method=method)\n-\n-    def det_bareis(self):\n-        return self.det(method='bareiss')\n-\n-    def det_bareiss(self):\n-        \"\"\"Compute matrix determinant using Bareiss' fraction-free\n-        algorithm which is an extension of the well known Gaussian\n-        elimination method. This approach is best suited for dense\n-        symbolic matrices and will result in a determinant with\n-        minimal number of fractions. It means that less term\n-        rewriting is needed on resulting formulae.\n-\n-        TODO: Implement algorithm for sparse matrices (SFF),\n-        http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.\n-\n-        See Also\n-        ========\n-\n-        det\n-        berkowitz_det\n-        \"\"\"\n-        return self.det(method='bareiss')\n-\n-    def det_LU_decomposition(self):\n-        \"\"\"Compute matrix determinant using LU decomposition\n-\n-\n-        Note that this method fails if the LU decomposition itself\n-        fails. In particular, if the matrix has no inverse this method\n-        will fail.\n-\n-        TODO: Implement algorithm for sparse matrices (SFF),\n-        http://www.eecis.udel.edu/~saunders/papers/sffge/it5.ps.\n-\n-        See Also\n-        ========\n-\n-\n-        det\n-        det_bareiss\n-        berkowitz_det\n-        \"\"\"\n-        return self.det(method='lu')\n-\n-    def jordan_cell(self, eigenval, n):\n-        return self.jordan_block(size=n, eigenvalue=eigenval)\n-\n-    def jordan_cells(self, calc_transformation=True):\n-        P, J = self.jordan_form()\n-        return P, J.get_diag_blocks()\n-\n-    def minorEntry(self, i, j, method=\"berkowitz\"):\n-        return self.minor(i, j, method=method)\n-\n-    def minorMatrix(self, i, j):\n-        return self.minor_submatrix(i, j)\n-\n-    def permuteBkwd(self, perm):\n-        \"\"\"Permute the rows of the matrix with the given permutation in reverse.\"\"\"\n-        return self.permute_rows(perm, direction='backward')\n-\n-    def permuteFwd(self, perm):\n-        \"\"\"Permute the rows of the matrix with the given permutation.\"\"\"\n-        return self.permute_rows(perm, direction='forward')\n-\n-\n-class MatrixBase(MatrixDeprecated,\n-                 MatrixCalculus,\n-                 MatrixEigen,\n-                 MatrixCommon):\n-    \"\"\"Base class for matrix objects.\"\"\"\n-    # Added just for numpy compatibility\n-    __array_priority__ = 11\n-\n-    is_Matrix = True\n-    _class_priority = 3\n-    _sympify = staticmethod(sympify)\n-\n-    __hash__ = None  # Mutable\n-\n-    def __array__(self):\n-        from .dense import matrix2numpy\n-        return matrix2numpy(self)\n-\n-    def __getattr__(self, attr):\n-        if attr in ('diff', 'integrate', 'limit'):\n-            def doit(*args):\n-                item_doit = lambda item: getattr(item, attr)(*args)\n-                return self.applyfunc(item_doit)\n-\n-            return doit\n-        else:\n-            raise AttributeError(\n-                \"%s has no attribute %s.\" % (self.__class__.__name__, attr))\n-\n-    def __len__(self):\n-        \"\"\"Return the number of elements of self.\n-\n-        Implemented mainly so bool(Matrix()) == False.\n-        \"\"\"\n-        return self.rows * self.cols\n-\n-    def __mathml__(self):\n-        mml = \"\"\n-        for i in range(self.rows):\n-            mml += \"<matrixrow>\"\n-            for j in range(self.cols):\n-                mml += self[i, j].__mathml__()\n-            mml += \"</matrixrow>\"\n-        return \"<matrix>\" + mml + \"</matrix>\"\n-\n-    # needed for python 2 compatibility\n-    def __ne__(self, other):\n-        return not self == other\n-\n-    def _matrix_pow_by_jordan_blocks(self, num):\n-        from sympy.matrices import diag, MutableMatrix\n-        from sympy import binomial\n-\n-        def jordan_cell_power(jc, n):\n-            N = jc.shape[0]\n-            l = jc[0, 0]\n-            if l == 0 and (n < N - 1) != False:\n-                raise ValueError(\"Matrix det == 0; not invertible\")\n-            elif l == 0 and N > 1 and n % 1 != 0:\n-                raise ValueError(\"Non-integer power cannot be evaluated\")\n-            for i in range(N):\n-                for j in range(N-i):\n-                    bn = binomial(n, i)\n-                    if isinstance(bn, binomial):\n-                        bn = bn._eval_expand_func()\n-                    jc[j, i+j] = l**(n-i)*bn\n-\n-        P, J = self.jordan_form()\n-        jordan_cells = J.get_diag_blocks()\n-        # Make sure jordan_cells matrices are mutable:\n-        jordan_cells = [MutableMatrix(j) for j in jordan_cells]\n-        for j in jordan_cells:\n-            jordan_cell_power(j, num)\n-        return self._new(P*diag(*jordan_cells)*P.inv())\n-\n-    def __repr__(self):\n-        return sstr(self)\n-\n-    def __str__(self):\n-        if self.rows == 0 or self.cols == 0:\n-            return 'Matrix(%s, %s, [])' % (self.rows, self.cols)\n-        return \"Matrix(%s)\" % str(self.tolist())\n-\n-    def _diagonalize_clear_subproducts(self):\n-        del self._is_symbolic\n-        del self._is_symmetric\n-        del self._eigenvects\n-\n-    def _format_str(self, printer=None):\n-        if not printer:\n-            from sympy.printing.str import StrPrinter\n-            printer = StrPrinter()\n-        # Handle zero dimensions:\n-        if self.rows == 0 or self.cols == 0:\n-            return 'Matrix(%s, %s, [])' % (self.rows, self.cols)\n-        if self.rows == 1:\n-            return \"Matrix([%s])\" % self.table(printer, rowsep=',\\n')\n-        return \"Matrix([\\n%s])\" % self.table(printer, rowsep=',\\n')\n-\n-    @classmethod\n-    def _handle_creation_inputs(cls, *args, **kwargs):\n-        \"\"\"Return the number of rows, cols and flat matrix elements.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix, I\n-\n-        Matrix can be constructed as follows:\n-\n-        * from a nested list of iterables\n-\n-        >>> Matrix( ((1, 2+I), (3, 4)) )\n-        Matrix([\n-        [1, 2 + I],\n-        [3,     4]])\n-\n-        * from un-nested iterable (interpreted as a column)\n-\n-        >>> Matrix( [1, 2] )\n-        Matrix([\n-        [1],\n-        [2]])\n-\n-        * from un-nested iterable with dimensions\n-\n-        >>> Matrix(1, 2, [1, 2] )\n-        Matrix([[1, 2]])\n-\n-        * from no arguments (a 0 x 0 matrix)\n-\n-        >>> Matrix()\n-        Matrix(0, 0, [])\n-\n-        * from a rule\n-\n-        >>> Matrix(2, 2, lambda i, j: i/(j + 1) )\n-        Matrix([\n-        [0,   0],\n-        [1, 1/2]])\n-\n-        \"\"\"\n-        from sympy.matrices.sparse import SparseMatrix\n-\n-        flat_list = None\n-\n-        if len(args) == 1:\n-            # Matrix(SparseMatrix(...))\n-            if isinstance(args[0], SparseMatrix):\n-                return args[0].rows, args[0].cols, flatten(args[0].tolist())\n-\n-            # Matrix(Matrix(...))\n-            elif isinstance(args[0], MatrixBase):\n-                return args[0].rows, args[0].cols, args[0]._mat\n-\n-            # Matrix(MatrixSymbol('X', 2, 2))\n-            elif isinstance(args[0], Basic) and args[0].is_Matrix:\n-                return args[0].rows, args[0].cols, args[0].as_explicit()._mat\n-\n-            # Matrix(numpy.ones((2, 2)))\n-            elif hasattr(args[0], \"__array__\"):\n-                # NumPy array or matrix or some other object that implements\n-                # __array__. So let's first use this method to get a\n-                # numpy.array() and then make a python list out of it.\n-                arr = args[0].__array__()\n-                if len(arr.shape) == 2:\n-                    rows, cols = arr.shape[0], arr.shape[1]\n-                    flat_list = [cls._sympify(i) for i in arr.ravel()]\n-                    return rows, cols, flat_list\n-                elif len(arr.shape) == 1:\n-                    rows, cols = arr.shape[0], 1\n-                    flat_list = [S.Zero] * rows\n-                    for i in range(len(arr)):\n-                        flat_list[i] = cls._sympify(arr[i])\n-                    return rows, cols, flat_list\n-                else:\n-                    raise NotImplementedError(\n-                        \"SymPy supports just 1D and 2D matrices\")\n-\n-            # Matrix([1, 2, 3]) or Matrix([[1, 2], [3, 4]])\n-            elif is_sequence(args[0]) \\\n-                    and not isinstance(args[0], DeferredVector):\n-                in_mat = []\n-                ncol = set()\n-                for row in args[0]:\n-                    if isinstance(row, MatrixBase):\n-                        in_mat.extend(row.tolist())\n-                        if row.cols or row.rows:  # only pay attention if it's not 0x0\n-                            ncol.add(row.cols)\n-                    else:\n-                        in_mat.append(row)\n-                        try:\n-                            ncol.add(len(row))\n-                        except TypeError:\n-                            ncol.add(1)\n-                if len(ncol) > 1:\n-                    raise ValueError(\"Got rows of variable lengths: %s\" %\n-                                     sorted(list(ncol)))\n-                cols = ncol.pop() if ncol else 0\n-                rows = len(in_mat) if cols else 0\n-                if rows:\n-                    if not is_sequence(in_mat[0]):\n-                        cols = 1\n-                        flat_list = [cls._sympify(i) for i in in_mat]\n-                        return rows, cols, flat_list\n-                flat_list = []\n-                for j in range(rows):\n-                    for i in range(cols):\n-                        flat_list.append(cls._sympify(in_mat[j][i]))\n-\n-        elif len(args) == 3:\n-            rows = as_int(args[0])\n-            cols = as_int(args[1])\n-\n-            if rows < 0 or cols < 0:\n-                raise ValueError(\"Cannot create a {} x {} matrix. \"\n-                                 \"Both dimensions must be positive\".format(rows, cols))\n-\n-            # Matrix(2, 2, lambda i, j: i+j)\n-            if len(args) == 3 and isinstance(args[2], collections.Callable):\n-                op = args[2]\n-                flat_list = []\n-                for i in range(rows):\n-                    flat_list.extend(\n-                        [cls._sympify(op(cls._sympify(i), cls._sympify(j)))\n-                         for j in range(cols)])\n-\n-            # Matrix(2, 2, [1, 2, 3, 4])\n-            elif len(args) == 3 and is_sequence(args[2]):\n-                flat_list = args[2]\n-                if len(flat_list) != rows * cols:\n-                    raise ValueError(\n-                        'List length should be equal to rows*columns')\n-                flat_list = [cls._sympify(i) for i in flat_list]\n-\n-\n-        # Matrix()\n-        elif len(args) == 0:\n-            # Empty Matrix\n-            rows = cols = 0\n-            flat_list = []\n-\n-        if flat_list is None:\n-            raise TypeError(\"Data type not understood\")\n-\n-        return rows, cols, flat_list\n-\n-    def _setitem(self, key, value):\n-        \"\"\"Helper to set value at location given by key.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix, I, zeros, ones\n-        >>> m = Matrix(((1, 2+I), (3, 4)))\n-        >>> m\n-        Matrix([\n-        [1, 2 + I],\n-        [3,     4]])\n-        >>> m[1, 0] = 9\n-        >>> m\n-        Matrix([\n-        [1, 2 + I],\n-        [9,     4]])\n-        >>> m[1, 0] = [[0, 1]]\n-\n-        To replace row r you assign to position r*m where m\n-        is the number of columns:\n-\n-        >>> M = zeros(4)\n-        >>> m = M.cols\n-        >>> M[3*m] = ones(1, m)*2; M\n-        Matrix([\n-        [0, 0, 0, 0],\n-        [0, 0, 0, 0],\n-        [0, 0, 0, 0],\n-        [2, 2, 2, 2]])\n-\n-        And to replace column c you can assign to position c:\n-\n-        >>> M[2] = ones(m, 1)*4; M\n-        Matrix([\n-        [0, 0, 4, 0],\n-        [0, 0, 4, 0],\n-        [0, 0, 4, 0],\n-        [2, 2, 4, 2]])\n-        \"\"\"\n-        from .dense import Matrix\n-\n-        is_slice = isinstance(key, slice)\n-        i, j = key = self.key2ij(key)\n-        is_mat = isinstance(value, MatrixBase)\n-        if type(i) is slice or type(j) is slice:\n-            if is_mat:\n-                self.copyin_matrix(key, value)\n-                return\n-            if not isinstance(value, Expr) and is_sequence(value):\n-                self.copyin_list(key, value)\n-                return\n-            raise ValueError('unexpected value: %s' % value)\n-        else:\n-            if (not is_mat and\n-                    not isinstance(value, Basic) and is_sequence(value)):\n-                value = Matrix(value)\n-                is_mat = True\n-            if is_mat:\n-                if is_slice:\n-                    key = (slice(*divmod(i, self.cols)),\n-                           slice(*divmod(j, self.cols)))\n-                else:\n-                    key = (slice(i, i + value.rows),\n-                           slice(j, j + value.cols))\n-                self.copyin_matrix(key, value)\n-            else:\n-                return i, j, self._sympify(value)\n-            return\n-\n-    def add(self, b):\n-        \"\"\"Return self + b \"\"\"\n-        return self + b\n-\n-    def cholesky_solve(self, rhs):\n-        \"\"\"Solves Ax = B using Cholesky decomposition,\n-        for a general square non-singular matrix.\n-        For a non-square matrix with rows > cols,\n-        the least squares solution is returned.\n-\n-        See Also\n-        ========\n-\n-        lower_triangular_solve\n-        upper_triangular_solve\n-        gauss_jordan_solve\n-        diagonal_solve\n-        LDLsolve\n-        LUsolve\n-        QRsolve\n-        pinv_solve\n-        \"\"\"\n-        if self.is_symmetric():\n-            L = self._cholesky()\n-        elif self.rows >= self.cols:\n-            L = (self.T * self)._cholesky()\n-            rhs = self.T * rhs\n-        else:\n-            raise NotImplementedError('Under-determined System. '\n-                                      'Try M.gauss_jordan_solve(rhs)')\n-        Y = L._lower_triangular_solve(rhs)\n-        return (L.T)._upper_triangular_solve(Y)\n-\n-    def cholesky(self):\n-        \"\"\"Returns the Cholesky decomposition L of a matrix A\n-        such that L * L.T = A\n-\n-        A must be a square, symmetric, positive-definite\n-        and non-singular matrix.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix\n-        >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))\n-        >>> A.cholesky()\n-        Matrix([\n-        [ 5, 0, 0],\n-        [ 3, 3, 0],\n-        [-1, 1, 3]])\n-        >>> A.cholesky() * A.cholesky().T\n-        Matrix([\n-        [25, 15, -5],\n-        [15, 18,  0],\n-        [-5,  0, 11]])\n-\n-        See Also\n-        ========\n-\n-        LDLdecomposition\n-        LUdecomposition\n-        QRdecomposition\n-        \"\"\"\n-\n-        if not self.is_square:\n-            raise NonSquareMatrixError(\"Matrix must be square.\")\n-        if not self.is_symmetric():\n-            raise ValueError(\"Matrix must be symmetric.\")\n-        return self._cholesky()\n-\n-    def condition_number(self):\n-        \"\"\"Returns the condition number of a matrix.\n-\n-        This is the maximum singular value divided by the minimum singular value\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix, S\n-        >>> A = Matrix([[1, 0, 0], [0, 10, 0], [0, 0, S.One/10]])\n-        >>> A.condition_number()\n-        100\n-\n-        See Also\n-        ========\n-\n-        singular_values\n-        \"\"\"\n-        if not self:\n-            return S.Zero\n-        singularvalues = self.singular_values()\n-        return Max(*singularvalues) / Min(*singularvalues)\n-\n-    def copy(self):\n-        \"\"\"\n-        Returns the copy of a matrix.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> A = Matrix(2, 2, [1, 2, 3, 4])\n-        >>> A.copy()\n-        Matrix([\n-        [1, 2],\n-        [3, 4]])\n-\n-        \"\"\"\n-        return self._new(self.rows, self.cols, self._mat)\n-\n-    def cross(self, b):\n-        r\"\"\"\n-        Return the cross product of ``self`` and ``b`` relaxing the condition\n-        of compatible dimensions: if each has 3 elements, a matrix of the\n-        same type and shape as ``self`` will be returned. If ``b`` has the same\n-        shape as ``self`` then common identities for the cross product (like\n-        `a \\times b = - b \\times a`) will hold.\n-\n-        Parameters\n-        ==========\n-            b : 3x1 or 1x3 Matrix\n-\n-        See Also\n-        ========\n-\n-        dot\n-        multiply\n-        multiply_elementwise\n-        \"\"\"\n-        if not is_sequence(b):\n-            raise TypeError(\n-                \"`b` must be an ordered iterable or Matrix, not %s.\" %\n-                type(b))\n-        if not (self.rows * self.cols == b.rows * b.cols == 3):\n-            raise ShapeError(\"Dimensions incorrect for cross product: %s x %s\" %\n-                             ((self.rows, self.cols), (b.rows, b.cols)))\n-        else:\n-            return self._new(self.rows, self.cols, (\n-                (self[1] * b[2] - self[2] * b[1]),\n-                (self[2] * b[0] - self[0] * b[2]),\n-                (self[0] * b[1] - self[1] * b[0])))\n-\n-    @property\n-    def D(self):\n-        \"\"\"Return Dirac conjugate (if self.rows == 4).\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix, I, eye\n-        >>> m = Matrix((0, 1 + I, 2, 3))\n-        >>> m.D\n-        Matrix([[0, 1 - I, -2, -3]])\n-        >>> m = (eye(4) + I*eye(4))\n-        >>> m[0, 3] = 2\n-        >>> m.D\n-        Matrix([\n-        [1 - I,     0,      0,      0],\n-        [    0, 1 - I,      0,      0],\n-        [    0,     0, -1 + I,      0],\n-        [    2,     0,      0, -1 + I]])\n-\n-        If the matrix does not have 4 rows an AttributeError will be raised\n-        because this property is only defined for matrices with 4 rows.\n-\n-        >>> Matrix(eye(2)).D\n-        Traceback (most recent call last):\n-        ...\n-        AttributeError: Matrix has no attribute D.\n-\n-        See Also\n-        ========\n-\n-        conjugate: By-element conjugation\n-        H: Hermite conjugation\n-        \"\"\"\n-        from sympy.physics.matrices import mgamma\n-        if self.rows != 4:\n-            # In Python 3.2, properties can only return an AttributeError\n-            # so we can't raise a ShapeError -- see commit which added the\n-            # first line of this inline comment. Also, there is no need\n-            # for a message since MatrixBase will raise the AttributeError\n-            raise AttributeError\n-        return self.H * mgamma(0)\n-\n-    def diagonal_solve(self, rhs):\n-        \"\"\"Solves Ax = B efficiently, where A is a diagonal Matrix,\n-        with non-zero diagonal entries.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix, eye\n-        >>> A = eye(2)*2\n-        >>> B = Matrix([[1, 2], [3, 4]])\n-        >>> A.diagonal_solve(B) == B/2\n-        True\n-\n-        See Also\n-        ========\n-\n-        lower_triangular_solve\n-        upper_triangular_solve\n-        gauss_jordan_solve\n-        cholesky_solve\n-        LDLsolve\n-        LUsolve\n-        QRsolve\n-        pinv_solve\n-        \"\"\"\n-        if not self.is_diagonal:\n-            raise TypeError(\"Matrix should be diagonal\")\n-        if rhs.rows != self.rows:\n-            raise TypeError(\"Size mis-match\")\n-        return self._diagonal_solve(rhs)\n-\n-    def dot(self, b):\n-        \"\"\"Return the dot product of Matrix self and b relaxing the condition\n-        of compatible dimensions: if either the number of rows or columns are\n-        the same as the length of b then the dot product is returned. If self\n-        is a row or column vector, a scalar is returned. Otherwise, a list\n-        of results is returned (and in that case the number of columns in self\n-        must match the length of b).\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n-        >>> v = [1, 1, 1]\n-        >>> M.row(0).dot(v)\n-        6\n-        >>> M.col(0).dot(v)\n-        12\n-        >>> M.dot(v)\n-        [6, 15, 24]\n-\n-        See Also\n-        ========\n-\n-        cross\n-        multiply\n-        multiply_elementwise\n-        \"\"\"\n-        from .dense import Matrix\n-\n-        if not isinstance(b, MatrixBase):\n-            if is_sequence(b):\n-                if len(b) != self.cols and len(b) != self.rows:\n-                    raise ShapeError(\n-                        \"Dimensions incorrect for dot product: %s, %s\" % (\n-                            self.shape, len(b)))\n-                return self.dot(Matrix(b))\n-            else:\n-                raise TypeError(\n-                    \"`b` must be an ordered iterable or Matrix, not %s.\" %\n-                    type(b))\n-\n-        mat = self\n-        if mat.cols == b.rows:\n-            if b.cols != 1:\n-                mat = mat.T\n-                b = b.T\n-            prod = flatten((mat * b).tolist())\n-            if len(prod) == 1:\n-                return prod[0]\n-            return prod\n-        if mat.cols == b.cols:\n-            return mat.dot(b.T)\n-        elif mat.rows == b.rows:\n-            return mat.T.dot(b)\n-        else:\n-            raise ShapeError(\"Dimensions incorrect for dot product: %s, %s\" % (\n-                self.shape, b.shape))\n-\n-    def dual(self):\n-        \"\"\"Returns the dual of a matrix, which is:\n-\n-        `(1/2)*levicivita(i, j, k, l)*M(k, l)` summed over indices `k` and `l`\n-\n-        Since the levicivita method is anti_symmetric for any pairwise\n-        exchange of indices, the dual of a symmetric matrix is the zero\n-        matrix. Strictly speaking the dual defined here assumes that the\n-        'matrix' `M` is a contravariant anti_symmetric second rank tensor,\n-        so that the dual is a covariant second rank tensor.\n-\n-        \"\"\"\n-        from sympy import LeviCivita\n-        from sympy.matrices import zeros\n-\n-        M, n = self[:, :], self.rows\n-        work = zeros(n)\n-        if self.is_symmetric():\n-            return work\n-\n-        for i in range(1, n):\n-            for j in range(1, n):\n-                acum = 0\n-                for k in range(1, n):\n-                    acum += LeviCivita(i, j, 0, k) * M[0, k]\n-                work[i, j] = acum\n-                work[j, i] = -acum\n-\n-        for l in range(1, n):\n-            acum = 0\n-            for a in range(1, n):\n-                for b in range(1, n):\n-                    acum += LeviCivita(0, l, a, b) * M[a, b]\n-            acum /= 2\n-            work[0, l] = -acum\n-            work[l, 0] = acum\n-\n-        return work\n-\n-    def exp(self):\n-        \"\"\"Return the exponentiation of a square matrix.\"\"\"\n-        if not self.is_square:\n-            raise NonSquareMatrixError(\n-                \"Exponentiation is valid only for square matrices\")\n-        try:\n-            P, J = self.jordan_form()\n-            cells = J.get_diag_blocks()\n-        except MatrixError:\n-            raise NotImplementedError(\n-                \"Exponentiation is implemented only for matrices for which the Jordan normal form can be computed\")\n-\n-        def _jblock_exponential(b):\n-            # This function computes the matrix exponential for one single Jordan block\n-            nr = b.rows\n-            l = b[0, 0]\n-            if nr == 1:\n-                res = exp(l)\n-            else:\n-                from sympy import eye\n-                # extract the diagonal part\n-                d = b[0, 0] * eye(nr)\n-                # and the nilpotent part\n-                n = b - d\n-                # compute its exponential\n-                nex = eye(nr)\n-                for i in range(1, nr):\n-                    nex = nex + n ** i / factorial(i)\n-                # combine the two parts\n-                res = exp(b[0, 0]) * nex\n-            return (res)\n-\n-        blocks = list(map(_jblock_exponential, cells))\n-        from sympy.matrices import diag\n-        eJ = diag(*blocks)\n-        # n = self.rows\n-        ret = P * eJ * P.inv()\n-        return type(self)(ret)\n-\n-    def gauss_jordan_solve(self, b, freevar=False):\n-        \"\"\"\n-        Solves Ax = b using Gauss Jordan elimination.\n-\n-        There may be zero, one, or infinite solutions.  If one solution\n-        exists, it will be returned. If infinite solutions exist, it will\n-        be returned parametrically. If no solutions exist, It will throw\n-        ValueError.\n-\n-        Parameters\n-        ==========\n-\n-        b : Matrix\n-            The right hand side of the equation to be solved for.  Must have\n-            the same number of rows as matrix A.\n-\n-        freevar : List\n-            If the system is underdetermined (e.g. A has more columns than\n-            rows), infinite solutions are possible, in terms of arbitrary\n-            values of free variables. Then the index of the free variables\n-            in the solutions (column Matrix) will be returned by freevar, if\n-            the flag `freevar` is set to `True`.\n-\n-        Returns\n-        =======\n-\n-        x : Matrix\n-            The matrix that will satisfy Ax = B.  Will have as many rows as\n-            matrix A has columns, and as many columns as matrix B.\n-\n-        params : Matrix\n-            If the system is underdetermined (e.g. A has more columns than\n-            rows), infinite solutions are possible, in terms of arbitrary\n-            parameters. These arbitrary parameters are returned as params\n-            Matrix.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> A = Matrix([[1, 2, 1, 1], [1, 2, 2, -1], [2, 4, 0, 6]])\n-        >>> b = Matrix([7, 12, 4])\n-        >>> sol, params = A.gauss_jordan_solve(b)\n-        >>> sol\n-        Matrix([\n-        [-2*tau0 - 3*tau1 + 2],\n-        [                 tau0],\n-        [           2*tau1 + 5],\n-        [                 tau1]])\n-        >>> params\n-        Matrix([\n-        [tau0],\n-        [tau1]])\n-\n-        >>> A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])\n-        >>> b = Matrix([3, 6, 9])\n-        >>> sol, params = A.gauss_jordan_solve(b)\n-        >>> sol\n-        Matrix([\n-        [-1],\n-        [ 2],\n-        [ 0]])\n-        >>> params\n-        Matrix(0, 1, [])\n-\n-        See Also\n-        ========\n-\n-        lower_triangular_solve\n-        upper_triangular_solve\n-        cholesky_solve\n-        diagonal_solve\n-        LDLsolve\n-        LUsolve\n-        QRsolve\n-        pinv\n-\n-        References\n-        ==========\n-\n-        .. [1] http://en.wikipedia.org/wiki/Gaussian_elimination\n-\n-        \"\"\"\n-        from sympy.matrices import Matrix, zeros\n-\n-        aug = self.hstack(self.copy(), b.copy())\n-        row, col = aug[:, :-1].shape\n-\n-        # solve by reduced row echelon form\n-        A, pivots = aug.rref(simplify=True)\n-        A, v = A[:, :-1], A[:, -1]\n-        pivots = list(filter(lambda p: p < col, pivots))\n-        rank = len(pivots)\n-\n-        # Bring to block form\n-        permutation = Matrix(range(col)).T\n-        A = A.vstack(A, permutation)\n-\n-        for i, c in enumerate(pivots):\n-            A.col_swap(i, c)\n-\n-        A, permutation = A[:-1, :], A[-1, :]\n-\n-        # check for existence of solutions\n-        # rank of aug Matrix should be equal to rank of coefficient matrix\n-        if not v[rank:, 0].is_zero:\n-            raise ValueError(\"Linear system has no solution\")\n-\n-        # Get index of free symbols (free parameters)\n-        free_var_index = permutation[\n-                         len(pivots):]  # non-pivots columns are free variables\n-\n-        # Free parameters\n-        # what are current unnumbered free symbol names?\n-        name = _uniquely_named_symbol('tau', aug,\n-            compare=lambda i: str(i).rstrip('1234567890')).name\n-        gen = numbered_symbols(name)\n-        tau = Matrix([next(gen) for k in range(col - rank)]).reshape(col - rank, 1)\n-\n-        # Full parametric solution\n-        V = A[:rank, rank:]\n-        vt = v[:rank, 0]\n-        free_sol = tau.vstack(vt - V * tau, tau)\n-\n-        # Undo permutation\n-        sol = zeros(col, 1)\n-        for k, v in enumerate(free_sol):\n-            sol[permutation[k], 0] = v\n-\n-        if freevar:\n-            return sol, tau, free_var_index\n-        else:\n-            return sol, tau\n-\n-    def inv_mod(self, m):\n-        r\"\"\"\n-        Returns the inverse of the matrix `K` (mod `m`), if it exists.\n-\n-        Method to find the matrix inverse of `K` (mod `m`) implemented in this function:\n-\n-        * Compute `\\mathrm{adj}(K) = \\mathrm{cof}(K)^t`, the adjoint matrix of `K`.\n-\n-        * Compute `r = 1/\\mathrm{det}(K) \\pmod m`.\n-\n-        * `K^{-1} = r\\cdot \\mathrm{adj}(K) \\pmod m`.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> A = Matrix(2, 2, [1, 2, 3, 4])\n-        >>> A.inv_mod(5)\n-        Matrix([\n-        [3, 1],\n-        [4, 2]])\n-        >>> A.inv_mod(3)\n-        Matrix([\n-        [1, 1],\n-        [0, 1]])\n-\n-        \"\"\"\n-        from sympy.ntheory import totient\n-        if not self.is_square:\n-            raise NonSquareMatrixError()\n-        N = self.cols\n-        phi = totient(m)\n-        det_K = self.det()\n-        if gcd(det_K, m) != 1:\n-            raise ValueError('Matrix is not invertible (mod %d)' % m)\n-        det_inv = pow(int(det_K), int(phi - 1), int(m))\n-        K_adj = self.adjugate()\n-        K_inv = self.__class__(N, N,\n-                               [det_inv * K_adj[i, j] % m for i in range(N) for\n-                                j in range(N)])\n-        return K_inv\n-\n-    def inverse_ADJ(self, iszerofunc=_iszero):\n-        \"\"\"Calculates the inverse using the adjugate matrix and a determinant.\n-\n-        See Also\n-        ========\n-\n-        inv\n-        inverse_LU\n-        inverse_GE\n-        \"\"\"\n-        if not self.is_square:\n-            raise NonSquareMatrixError(\"A Matrix must be square to invert.\")\n-\n-        d = self.det(method='berkowitz')\n-        zero = d.equals(0)\n-        if zero is None:\n-            # if equals() can't decide, will rref be able to?\n-            ok = self.rref(simplify=True)[0]\n-            zero = any(iszerofunc(ok[j, j]) for j in range(ok.rows))\n-        if zero:\n-            raise ValueError(\"Matrix det == 0; not invertible.\")\n-\n-        return self.adjugate() / d\n-\n-    def inverse_GE(self, iszerofunc=_iszero):\n-        \"\"\"Calculates the inverse using Gaussian elimination.\n-\n-        See Also\n-        ========\n-\n-        inv\n-        inverse_LU\n-        inverse_ADJ\n-        \"\"\"\n-        from .dense import Matrix\n-        if not self.is_square:\n-            raise NonSquareMatrixError(\"A Matrix must be square to invert.\")\n-\n-        big = Matrix.hstack(self.as_mutable(), Matrix.eye(self.rows))\n-        red = big.rref(iszerofunc=iszerofunc, simplify=True)[0]\n-        if any(iszerofunc(red[j, j]) for j in range(red.rows)):\n-            raise ValueError(\"Matrix det == 0; not invertible.\")\n-\n-        return self._new(red[:, big.rows:])\n-\n-    def inverse_LU(self, iszerofunc=_iszero):\n-        \"\"\"Calculates the inverse using LU decomposition.\n-\n-        See Also\n-        ========\n-\n-        inv\n-        inverse_GE\n-        inverse_ADJ\n-        \"\"\"\n-        if not self.is_square:\n-            raise NonSquareMatrixError()\n-\n-        ok = self.rref(simplify=True)[0]\n-        if any(iszerofunc(ok[j, j]) for j in range(ok.rows)):\n-            raise ValueError(\"Matrix det == 0; not invertible.\")\n-\n-        return self.LUsolve(self.eye(self.rows), iszerofunc=_iszero)\n-\n-    def inv(self, method=None, **kwargs):\n-        \"\"\"\n-        Return the inverse of a matrix.\n-\n-        CASE 1: If the matrix is a dense matrix.\n-\n-        Return the matrix inverse using the method indicated (default\n-        is Gauss elimination).\n-\n-        Parameters\n-        ==========\n-\n-        method : ('GE', 'LU', or 'ADJ')\n-\n-        Notes\n-        =====\n-\n-        According to the ``method`` keyword, it calls the appropriate method:\n-\n-          GE .... inverse_GE(); default\n-          LU .... inverse_LU()\n-          ADJ ... inverse_ADJ()\n-\n-        See Also\n-        ========\n-\n-        inverse_LU\n-        inverse_GE\n-        inverse_ADJ\n-\n-        Raises\n-        ------\n-        ValueError\n-            If the determinant of the matrix is zero.\n-\n-        CASE 2: If the matrix is a sparse matrix.\n-\n-        Return the matrix inverse using Cholesky or LDL (default).\n-\n-        kwargs\n-        ======\n-\n-        method : ('CH', 'LDL')\n-\n-        Notes\n-        =====\n-\n-        According to the ``method`` keyword, it calls the appropriate method:\n-\n-          LDL ... inverse_LDL(); default\n-          CH .... inverse_CH()\n-\n-        Raises\n-        ------\n-        ValueError\n-            If the determinant of the matrix is zero.\n-\n-        \"\"\"\n-        if not self.is_square:\n-            raise NonSquareMatrixError()\n-        if method is not None:\n-            kwargs['method'] = method\n-        return self._eval_inverse(**kwargs)\n-\n-    def is_nilpotent(self):\n-        \"\"\"Checks if a matrix is nilpotent.\n-\n-        A matrix B is nilpotent if for some integer k, B**k is\n-        a zero matrix.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> a = Matrix([[0, 0, 0], [1, 0, 0], [1, 1, 0]])\n-        >>> a.is_nilpotent()\n-        True\n-\n-        >>> a = Matrix([[1, 0, 1], [1, 0, 0], [1, 1, 0]])\n-        >>> a.is_nilpotent()\n-        False\n-        \"\"\"\n-        if not self:\n-            return True\n-        if not self.is_square:\n-            raise NonSquareMatrixError(\n-                \"Nilpotency is valid only for square matrices\")\n-        x = _uniquely_named_symbol('x', self)\n-        p = self.charpoly(x)\n-        if p.args[0] == x ** self.rows:\n-            return True\n-        return False\n-\n-    def key2bounds(self, keys):\n-        \"\"\"Converts a key with potentially mixed types of keys (integer and slice)\n-        into a tuple of ranges and raises an error if any index is out of self's\n-        range.\n-\n-        See Also\n-        ========\n-\n-        key2ij\n-        \"\"\"\n-\n-        islice, jslice = [isinstance(k, slice) for k in keys]\n-        if islice:\n-            if not self.rows:\n-                rlo = rhi = 0\n-            else:\n-                rlo, rhi = keys[0].indices(self.rows)[:2]\n-        else:\n-            rlo = a2idx(keys[0], self.rows)\n-            rhi = rlo + 1\n-        if jslice:\n-            if not self.cols:\n-                clo = chi = 0\n-            else:\n-                clo, chi = keys[1].indices(self.cols)[:2]\n-        else:\n-            clo = a2idx(keys[1], self.cols)\n-            chi = clo + 1\n-        return rlo, rhi, clo, chi\n-\n-    def key2ij(self, key):\n-        \"\"\"Converts key into canonical form, converting integers or indexable\n-        items into valid integers for self's range or returning slices\n-        unchanged.\n-\n-        See Also\n-        ========\n-\n-        key2bounds\n-        \"\"\"\n-        if is_sequence(key):\n-            if not len(key) == 2:\n-                raise TypeError('key must be a sequence of length 2')\n-            return [a2idx(i, n) if not isinstance(i, slice) else i\n-                    for i, n in zip(key, self.shape)]\n-        elif isinstance(key, slice):\n-            return key.indices(len(self))[:2]\n-        else:\n-            return divmod(a2idx(key, len(self)), self.cols)\n-\n-    def LDLdecomposition(self):\n-        \"\"\"Returns the LDL Decomposition (L, D) of matrix A,\n-        such that L * D * L.T == A\n-        This method eliminates the use of square root.\n-        Further this ensures that all the diagonal entries of L are 1.\n-        A must be a square, symmetric, positive-definite\n-        and non-singular matrix.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix, eye\n-        >>> A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))\n-        >>> L, D = A.LDLdecomposition()\n-        >>> L\n-        Matrix([\n-        [   1,   0, 0],\n-        [ 3/5,   1, 0],\n-        [-1/5, 1/3, 1]])\n-        >>> D\n-        Matrix([\n-        [25, 0, 0],\n-        [ 0, 9, 0],\n-        [ 0, 0, 9]])\n-        >>> L * D * L.T * A.inv() == eye(A.rows)\n-        True\n-\n-        See Also\n-        ========\n-\n-        cholesky\n-        LUdecomposition\n-        QRdecomposition\n-        \"\"\"\n-        if not self.is_square:\n-            raise NonSquareMatrixError(\"Matrix must be square.\")\n-        if not self.is_symmetric():\n-            raise ValueError(\"Matrix must be symmetric.\")\n-        return self._LDLdecomposition()\n-\n-    def LDLsolve(self, rhs):\n-        \"\"\"Solves Ax = B using LDL decomposition,\n-        for a general square and non-singular matrix.\n-\n-        For a non-square matrix with rows > cols,\n-        the least squares solution is returned.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix, eye\n-        >>> A = eye(2)*2\n-        >>> B = Matrix([[1, 2], [3, 4]])\n-        >>> A.LDLsolve(B) == B/2\n-        True\n-\n-        See Also\n-        ========\n-\n-        LDLdecomposition\n-        lower_triangular_solve\n-        upper_triangular_solve\n-        gauss_jordan_solve\n-        cholesky_solve\n-        diagonal_solve\n-        LUsolve\n-        QRsolve\n-        pinv_solve\n-        \"\"\"\n-        if self.is_symmetric():\n-            L, D = self.LDLdecomposition()\n-        elif self.rows >= self.cols:\n-            L, D = (self.T * self).LDLdecomposition()\n-            rhs = self.T * rhs\n-        else:\n-            raise NotImplementedError('Under-determined System. '\n-                                      'Try M.gauss_jordan_solve(rhs)')\n-        Y = L._lower_triangular_solve(rhs)\n-        Z = D._diagonal_solve(Y)\n-        return (L.T)._upper_triangular_solve(Z)\n-\n-    def lower_triangular_solve(self, rhs):\n-        \"\"\"Solves Ax = B, where A is a lower triangular matrix.\n-\n-        See Also\n-        ========\n-\n-        upper_triangular_solve\n-        gauss_jordan_solve\n-        cholesky_solve\n-        diagonal_solve\n-        LDLsolve\n-        LUsolve\n-        QRsolve\n-        pinv_solve\n-        \"\"\"\n-\n-        if not self.is_square:\n-            raise NonSquareMatrixError(\"Matrix must be square.\")\n-        if rhs.rows != self.rows:\n-            raise ShapeError(\"Matrices size mismatch.\")\n-        if not self.is_lower:\n-            raise ValueError(\"Matrix must be lower triangular.\")\n-        return self._lower_triangular_solve(rhs)\n-\n-    def LUdecomposition(self,\n-                        iszerofunc=_iszero,\n-                        simpfunc=None,\n-                        rankcheck=False):\n-        \"\"\"Returns (L, U, perm) where L is a lower triangular matrix with unit\n-        diagonal, U is an upper triangular matrix, and perm is a list of row\n-        swap index pairs. If A is the original matrix, then\n-        A = (L*U).permuteBkwd(perm), and the row permutation matrix P such\n-        that P*A = L*U can be computed by P=eye(A.row).permuteFwd(perm).\n-\n-        See documentation for LUCombined for details about the keyword argument\n-        rankcheck, iszerofunc, and simpfunc.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> a = Matrix([[4, 3], [6, 3]])\n-        >>> L, U, _ = a.LUdecomposition()\n-        >>> L\n-        Matrix([\n-        [  1, 0],\n-        [3/2, 1]])\n-        >>> U\n-        Matrix([\n-        [4,    3],\n-        [0, -3/2]])\n-\n-        See Also\n-        ========\n-\n-        cholesky\n-        LDLdecomposition\n-        QRdecomposition\n-        LUdecomposition_Simple\n-        LUdecompositionFF\n-        LUsolve\n-        \"\"\"\n-\n-        combined, p = self.LUdecomposition_Simple(iszerofunc=iszerofunc,\n-                                                  simpfunc=simpfunc,\n-                                                  rankcheck=rankcheck)\n-\n-        # L is lower triangular self.rows x self.rows\n-        # U is upper triangular self.rows x self.cols\n-        # L has unit diagonal. For each column in combined, the subcolumn\n-        # below the diagonal of combined is shared by L.\n-        # If L has more columns than combined, then the remaining subcolumns\n-        # below the diagonal of L are zero.\n-        # The upper triangular portion of L and combined are equal.\n-        def entry_L(i, j):\n-            if i < j:\n-                # Super diagonal entry\n-                return S.Zero\n-            elif i == j:\n-                return S.One\n-            elif j < combined.cols:\n-                return combined[i, j]\n-            # Subdiagonal entry of L with no corresponding\n-            # entry in combined\n-            return S.Zero\n-\n-        def entry_U(i, j):\n-            return S.Zero if i > j else combined[i, j]\n-\n-        L = self._new(combined.rows, combined.rows, entry_L)\n-        U = self._new(combined.rows, combined.cols, entry_U)\n-\n-        return L, U, p\n-\n-\n-    def LUdecomposition_Simple(self,\n-                               iszerofunc=_iszero,\n-                               simpfunc=None,\n-                               rankcheck=False):\n-        \"\"\"Compute an lu decomposition of m x n matrix A, where P*A = L*U\n-\n-        * L is m x m lower triangular with unit diagonal\n-        * U is m x n upper triangular\n-        * P is an m x m permutation matrix\n-\n-        Returns an m x n matrix lu, and an m element list perm where each\n-        element of perm is a pair of row exchange indices.\n-\n-        The factors L and U are stored in lu as follows:\n-        The subdiagonal elements of L are stored in the subdiagonal elements\n-        of lu, that is lu[i, j] = L[i, j] whenever i > j.\n-        The elements on the diagonal of L are all 1, and are not explicitly\n-        stored.\n-        U is stored in the upper triangular portion of lu, that is\n-        lu[i ,j] = U[i, j] whenever i <= j.\n-        The output matrix can be visualized as:\n-\n-            Matrix([\n-                [u, u, u, u],\n-                [l, u, u, u],\n-                [l, l, u, u],\n-                [l, l, l, u]])\n-\n-        where l represents a subdiagonal entry of the L factor, and u\n-        represents an entry from the upper triangular entry of the U\n-        factor.\n-\n-        perm is a list row swap index pairs such that if A is the original\n-        matrix, then A = (L*U).permuteBkwd(perm), and the row permutation\n-        matrix P such that ``P*A = L*U`` can be computed by\n-        ``P=eye(A.row).permuteFwd(perm)``.\n-\n-        The keyword argument rankcheck determines if this function raises a\n-        ValueError when passed a matrix whose rank is strictly less than\n-        min(num rows, num cols). The default behavior is to decompose a rank\n-        deficient matrix. Pass rankcheck=True to raise a\n-        ValueError instead. (This mimics the previous behavior of this function).\n-\n-        The keyword arguments iszerofunc and simpfunc are used by the pivot\n-        search algorithm.\n-        iszerofunc is a callable that returns a boolean indicating if its\n-        input is zero, or None if it cannot make the determination.\n-        simpfunc is a callable that simplifies its input.\n-        The default is simpfunc=None, which indicate that the pivot search\n-        algorithm should not attempt to simplify any candidate pivots.\n-        If simpfunc fails to simplify its input, then it must return its input\n-        instead of a copy.\n-\n-        When a matrix contains symbolic entries, the pivot search algorithm\n-        differs from the case where every entry can be categorized as zero or\n-        nonzero.\n-        The algorithm searches column by column through the submatrix whose\n-        top left entry coincides with the pivot position.\n-        If it exists, the pivot is the first entry in the current search\n-        column that iszerofunc guarantees is nonzero.\n-        If no such candidate exists, then each candidate pivot is simplified\n-        if simpfunc is not None.\n-        The search is repeated, with the difference that a candidate may be\n-        the pivot if ``iszerofunc()`` cannot guarantee that it is nonzero.\n-        In the second search the pivot is the first candidate that\n-        iszerofunc can guarantee is nonzero.\n-        If no such candidate exists, then the pivot is the first candidate\n-        for which iszerofunc returns None.\n-        If no such candidate exists, then the search is repeated in the next\n-        column to the right.\n-        The pivot search algorithm differs from the one in `rref()`, which\n-        relies on ``_find_reasonable_pivot()``.\n-        Future versions of ``LUdecomposition_simple()`` may use\n-        ``_find_reasonable_pivot()``.\n-\n-        See Also\n-        ========\n-\n-        LUdecomposition\n-        LUdecompositionFF\n-        LUsolve\n-        \"\"\"\n-\n-        if rankcheck:\n-            # https://github.com/sympy/sympy/issues/9796\n-            pass\n-\n-        if self.rows == 0 or self.cols == 0:\n-            # Define LU decomposition of a matrix with no entries as a matrix\n-            # of the same dimensions with all zero entries.\n-            return self.zeros(self.rows, self.cols), []\n-\n-        lu = self.as_mutable()\n-        row_swaps = []\n-\n-        pivot_col = 0\n-        for pivot_row in range(0, lu.rows - 1):\n-            # Search for pivot. Prefer entry that iszeropivot determines\n-            # is nonzero, over entry that iszeropivot cannot guarantee\n-            # is  zero.\n-            # XXX `_find_reasonable_pivot` uses slow zero testing. Blocked by bug #10279\n-            # Future versions of LUdecomposition_simple can pass iszerofunc and simpfunc\n-            # to _find_reasonable_pivot().\n-            # In pass 3 of _find_reasonable_pivot(), the predicate in `if x.equals(S.Zero):`\n-            # calls sympy.simplify(), and not the simplification function passed in via\n-            # the keyword argument simpfunc.\n-\n-            iszeropivot = True\n-            while pivot_col != self.cols and iszeropivot:\n-                sub_col = (lu[r, pivot_col] for r in range(pivot_row, self.rows))\n-                pivot_row_offset, pivot_value, is_assumed_non_zero, ind_simplified_pairs =\\\n-                    _find_reasonable_pivot_naive(sub_col, iszerofunc, simpfunc)\n-                iszeropivot = pivot_value is None\n-                if iszeropivot:\n-                    # All candidate pivots in this column are zero.\n-                    # Proceed to next column.\n-                    pivot_col += 1\n-\n-            if rankcheck and pivot_col != pivot_row:\n-                # All entries including and below the pivot position are\n-                # zero, which indicates that the rank of the matrix is\n-                # strictly less than min(num rows, num cols)\n-                # Mimic behavior of previous implementation, by throwing a\n-                # ValueError.\n-                raise ValueError(\"Rank of matrix is strictly less than\"\n-                                 \" number of rows or columns.\"\n-                                 \" Pass keyword argument\"\n-                                 \" rankcheck=False to compute\"\n-                                 \" the LU decomposition of this matrix.\")\n-\n-            candidate_pivot_row = None if pivot_row_offset is None else pivot_row + pivot_row_offset\n-\n-            if candidate_pivot_row is None and iszeropivot:\n-                # If candidate_pivot_row is None and iszeropivot is True\n-                # after pivot search has completed, then the submatrix\n-                # below and to the right of (pivot_row, pivot_col) is\n-                # all zeros, indicating that Gaussian elimination is\n-                # complete.\n-                return lu, row_swaps\n-\n-            # Update entries simplified during pivot search.\n-            for offset, val in ind_simplified_pairs:\n-                lu[pivot_row + offset, pivot_col] = val\n-\n-            if pivot_row != candidate_pivot_row:\n-                # Row swap book keeping:\n-                # Record which rows were swapped.\n-                # Update stored portion of L factor by multiplying L on the\n-                # left and right with the current permutation.\n-                # Swap rows of U.\n-                row_swaps.append([pivot_row, candidate_pivot_row])\n-\n-                # Update L.\n-                lu[pivot_row, 0:pivot_row], lu[candidate_pivot_row, 0:pivot_row] = \\\n-                    lu[candidate_pivot_row, 0:pivot_row], lu[pivot_row, 0:pivot_row]\n-\n-                # Swap pivot row of U with candidate pivot row.\n-                lu[pivot_row, pivot_col:lu.cols], lu[candidate_pivot_row, pivot_col:lu.cols] = \\\n-                    lu[candidate_pivot_row, pivot_col:lu.cols], lu[pivot_row, pivot_col:lu.cols]\n-\n-            # Introduce zeros below the pivot by adding a multiple of the\n-            # pivot row to a row under it, and store the result in the\n-            # row under it.\n-            # Only entries in the target row whose index is greater than\n-            # start_col may be nonzero.\n-            start_col = pivot_col + 1\n-            for row in range(pivot_row + 1, lu.rows):\n-                # Store factors of L in the subcolumn below\n-                # (pivot_row, pivot_row).\n-                lu[row, pivot_row] =\\\n-                    lu[row, pivot_col]/lu[pivot_row, pivot_col]\n-\n-                # Form the linear combination of the pivot row and the current\n-                # row below the pivot row that zeros the entries below the pivot.\n-                # Employing slicing instead of a loop here raises\n-                # NotImplementedError: Cannot add Zero to MutableSparseMatrix\n-                # in sympy/matrices/tests/test_sparse.py.\n-                # c = pivot_row + 1 if pivot_row == pivot_col else pivot_col\n-                for c in range(start_col, lu.cols):\n-                    lu[row, c] = lu[row, c] - lu[row, pivot_row]*lu[pivot_row, c]\n-\n-            if pivot_row != pivot_col:\n-                # matrix rank < min(num rows, num cols),\n-                # so factors of L are not stored directly below the pivot.\n-                # These entries are zero by construction, so don't bother\n-                # computing them.\n-                for row in range(pivot_row + 1, lu.rows):\n-                    lu[row, pivot_col] = S.Zero\n-\n-            pivot_col += 1\n-            if pivot_col == lu.cols:\n-                # All candidate pivots are zero implies that Gaussian\n-                # elimination is complete.\n-                return lu, row_swaps\n-\n-        return lu, row_swaps\n-\n-    def LUdecompositionFF(self):\n-        \"\"\"Compute a fraction-free LU decomposition.\n-\n-        Returns 4 matrices P, L, D, U such that PA = L D**-1 U.\n-        If the elements of the matrix belong to some integral domain I, then all\n-        elements of L, D and U are guaranteed to belong to I.\n-\n-        **Reference**\n-            - W. Zhou & D.J. Jeffrey, \"Fraction-free matrix factors: new forms\n-              for LU and QR factors\". Frontiers in Computer Science in China,\n-              Vol 2, no. 1, pp. 67-80, 2008.\n-\n-        See Also\n-        ========\n-\n-        LUdecomposition\n-        LUdecomposition_Simple\n-        LUsolve\n-        \"\"\"\n-        from sympy.matrices import SparseMatrix\n-        zeros = SparseMatrix.zeros\n-        eye = SparseMatrix.eye\n-\n-        n, m = self.rows, self.cols\n-        U, L, P = self.as_mutable(), eye(n), eye(n)\n-        DD = zeros(n, n)\n-        oldpivot = 1\n-\n-        for k in range(n - 1):\n-            if U[k, k] == 0:\n-                for kpivot in range(k + 1, n):\n-                    if U[kpivot, k]:\n-                        break\n-                else:\n-                    raise ValueError(\"Matrix is not full rank\")\n-                U[k, k:], U[kpivot, k:] = U[kpivot, k:], U[k, k:]\n-                L[k, :k], L[kpivot, :k] = L[kpivot, :k], L[k, :k]\n-                P[k, :], P[kpivot, :] = P[kpivot, :], P[k, :]\n-            L[k, k] = Ukk = U[k, k]\n-            DD[k, k] = oldpivot * Ukk\n-            for i in range(k + 1, n):\n-                L[i, k] = Uik = U[i, k]\n-                for j in range(k + 1, m):\n-                    U[i, j] = (Ukk * U[i, j] - U[k, j] * Uik) / oldpivot\n-                U[i, k] = 0\n-            oldpivot = Ukk\n-        DD[n - 1, n - 1] = oldpivot\n-        return P, L, DD, U\n-\n-    def LUsolve(self, rhs, iszerofunc=_iszero):\n-        \"\"\"Solve the linear system Ax = rhs for x where A = self.\n-\n-        This is for symbolic matrices, for real or complex ones use\n-        mpmath.lu_solve or mpmath.qr_solve.\n-\n-        See Also\n-        ========\n-\n-        lower_triangular_solve\n-        upper_triangular_solve\n-        gauss_jordan_solve\n-        cholesky_solve\n-        diagonal_solve\n-        LDLsolve\n-        QRsolve\n-        pinv_solve\n-        LUdecomposition\n-        \"\"\"\n-        if rhs.rows != self.rows:\n-            raise ShapeError(\n-                \"`self` and `rhs` must have the same number of rows.\")\n-\n-        A, perm = self.LUdecomposition_Simple(iszerofunc=_iszero)\n-        n = self.rows\n-        b = rhs.permute_rows(perm).as_mutable()\n-        # forward substitution, all diag entries are scaled to 1\n-        for i in range(n):\n-            for j in range(i):\n-                scale = A[i, j]\n-                b.zip_row_op(i, j, lambda x, y: x - y * scale)\n-        # backward substitution\n-        for i in range(n - 1, -1, -1):\n-            for j in range(i + 1, n):\n-                scale = A[i, j]\n-                b.zip_row_op(i, j, lambda x, y: x - y * scale)\n-            scale = A[i, i]\n-            b.row_op(i, lambda x, _: x / scale)\n-        return rhs.__class__(b)\n-\n-    def multiply(self, b):\n-        \"\"\"Returns self*b\n-\n-        See Also\n-        ========\n-\n-        dot\n-        cross\n-        multiply_elementwise\n-        \"\"\"\n-        return self * b\n-\n-    def normalized(self):\n-        \"\"\"Return the normalized version of ``self``.\n-\n-        See Also\n-        ========\n-\n-        norm\n-        \"\"\"\n-        if self.rows != 1 and self.cols != 1:\n-            raise ShapeError(\"A Matrix must be a vector to normalize.\")\n-        norm = self.norm()\n-        out = self.applyfunc(lambda i: i / norm)\n-        return out\n-\n-    def norm(self, ord=None):\n-        \"\"\"Return the Norm of a Matrix or Vector.\n-        In the simplest case this is the geometric size of the vector\n-        Other norms can be specified by the ord parameter\n-\n-\n-        =====  ============================  ==========================\n-        ord    norm for matrices             norm for vectors\n-        =====  ============================  ==========================\n-        None   Frobenius norm                2-norm\n-        'fro'  Frobenius norm                - does not exist\n-        inf    maximum row sum               max(abs(x))\n-        -inf   --                            min(abs(x))\n-        1      maximum column sum            as below\n-        -1     --                            as below\n-        2      2-norm (largest sing. value)  as below\n-        -2     smallest singular value       as below\n-        other  - does not exist              sum(abs(x)**ord)**(1./ord)\n-        =====  ============================  ==========================\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix, Symbol, trigsimp, cos, sin, oo\n-        >>> x = Symbol('x', real=True)\n-        >>> v = Matrix([cos(x), sin(x)])\n-        >>> trigsimp( v.norm() )\n-        1\n-        >>> v.norm(10)\n-        (sin(x)**10 + cos(x)**10)**(1/10)\n-        >>> A = Matrix([[1, 1], [1, 1]])\n-        >>> A.norm(1) # maximum sum of absolute values of A is 2\n-        2\n-        >>> A.norm(2) # Spectral norm (max of |Ax|/|x| under 2-vector-norm)\n-        2\n-        >>> A.norm(-2) # Inverse spectral norm (smallest singular value)\n-        0\n-        >>> A.norm() # Frobenius Norm\n-        2\n-        >>> A.norm(oo) # Infinity Norm\n-        2\n-        >>> Matrix([1, -2]).norm(oo)\n-        2\n-        >>> Matrix([-1, 2]).norm(-oo)\n-        1\n-\n-        See Also\n-        ========\n-\n-        normalized\n-        \"\"\"\n-        # Row or Column Vector Norms\n-        vals = list(self.values()) or [0]\n-        if self.rows == 1 or self.cols == 1:\n-            if ord == 2 or ord is None:  # Common case sqrt(<x, x>)\n-                return sqrt(Add(*(abs(i) ** 2 for i in vals)))\n-\n-            elif ord == 1:  # sum(abs(x))\n-                return Add(*(abs(i) for i in vals))\n-\n-            elif ord == S.Infinity:  # max(abs(x))\n-                return Max(*[abs(i) for i in vals])\n-\n-            elif ord == S.NegativeInfinity:  # min(abs(x))\n-                return Min(*[abs(i) for i in vals])\n-\n-            # Otherwise generalize the 2-norm, Sum(x_i**ord)**(1/ord)\n-            # Note that while useful this is not mathematically a norm\n-            try:\n-                return Pow(Add(*(abs(i) ** ord for i in vals)), S(1) / ord)\n-            except (NotImplementedError, TypeError):\n-                raise ValueError(\"Expected order to be Number, Symbol, oo\")\n-\n-        # Matrix Norms\n-        else:\n-            if ord == 1:  # Maximum column sum\n-                m = self.applyfunc(abs)\n-                return Max(*[sum(m.col(i)) for i in range(m.cols)])\n-\n-            elif ord == 2:  # Spectral Norm\n-                # Maximum singular value\n-                return Max(*self.singular_values())\n-\n-            elif ord == -2:\n-                # Minimum singular value\n-                return Min(*self.singular_values())\n-\n-            elif ord == S.Infinity:   # Infinity Norm - Maximum row sum\n-                m = self.applyfunc(abs)\n-                return Max(*[sum(m.row(i)) for i in range(m.rows)])\n-\n-            elif (ord is None or isinstance(ord,\n-                                            string_types) and ord.lower() in\n-                ['f', 'fro', 'frobenius', 'vector']):\n-                # Reshape as vector and send back to norm function\n-                return self.vec().norm(ord=2)\n-\n-            else:\n-                raise NotImplementedError(\"Matrix Norms under development\")\n-\n-    def pinv_solve(self, B, arbitrary_matrix=None):\n-        \"\"\"Solve Ax = B using the Moore-Penrose pseudoinverse.\n-\n-        There may be zero, one, or infinite solutions.  If one solution\n-        exists, it will be returned.  If infinite solutions exist, one will\n-        be returned based on the value of arbitrary_matrix.  If no solutions\n-        exist, the least-squares solution is returned.\n-\n-        Parameters\n-        ==========\n-\n-        B : Matrix\n-            The right hand side of the equation to be solved for.  Must have\n-            the same number of rows as matrix A.\n-        arbitrary_matrix : Matrix\n-            If the system is underdetermined (e.g. A has more columns than\n-            rows), infinite solutions are possible, in terms of an arbitrary\n-            matrix.  This parameter may be set to a specific matrix to use\n-            for that purpose; if so, it must be the same shape as x, with as\n-            many rows as matrix A has columns, and as many columns as matrix\n-            B.  If left as None, an appropriate matrix containing dummy\n-            symbols in the form of ``wn_m`` will be used, with n and m being\n-            row and column position of each symbol.\n-\n-        Returns\n-        =======\n-\n-        x : Matrix\n-            The matrix that will satisfy Ax = B.  Will have as many rows as\n-            matrix A has columns, and as many columns as matrix B.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> A = Matrix([[1, 2, 3], [4, 5, 6]])\n-        >>> B = Matrix([7, 8])\n-        >>> A.pinv_solve(B)\n-        Matrix([\n-        [ _w0_0/6 - _w1_0/3 + _w2_0/6 - 55/18],\n-        [-_w0_0/3 + 2*_w1_0/3 - _w2_0/3 + 1/9],\n-        [ _w0_0/6 - _w1_0/3 + _w2_0/6 + 59/18]])\n-        >>> A.pinv_solve(B, arbitrary_matrix=Matrix([0, 0, 0]))\n-        Matrix([\n-        [-55/18],\n-        [   1/9],\n-        [ 59/18]])\n-\n-        See Also\n-        ========\n-\n-        lower_triangular_solve\n-        upper_triangular_solve\n-        gauss_jordan_solve\n-        cholesky_solve\n-        diagonal_solve\n-        LDLsolve\n-        LUsolve\n-        QRsolve\n-        pinv\n-\n-        Notes\n-        =====\n-\n-        This may return either exact solutions or least squares solutions.\n-        To determine which, check ``A * A.pinv() * B == B``.  It will be\n-        True if exact solutions exist, and False if only a least-squares\n-        solution exists.  Be aware that the left hand side of that equation\n-        may need to be simplified to correctly compare to the right hand\n-        side.\n-\n-        References\n-        ==========\n-\n-        .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse#Obtaining_all_solutions_of_a_linear_system\n-\n-        \"\"\"\n-        from sympy.matrices import eye\n-        A = self\n-        A_pinv = self.pinv()\n-        if arbitrary_matrix is None:\n-            rows, cols = A.cols, B.cols\n-            w = symbols('w:{0}_:{1}'.format(rows, cols), cls=Dummy)\n-            arbitrary_matrix = self.__class__(cols, rows, w).T\n-        return A_pinv * B + (eye(A.cols) - A_pinv * A) * arbitrary_matrix\n-\n-    def pinv(self):\n-        \"\"\"Calculate the Moore-Penrose pseudoinverse of the matrix.\n-\n-        The Moore-Penrose pseudoinverse exists and is unique for any matrix.\n-        If the matrix is invertible, the pseudoinverse is the same as the\n-        inverse.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> Matrix([[1, 2, 3], [4, 5, 6]]).pinv()\n-        Matrix([\n-        [-17/18,  4/9],\n-        [  -1/9,  1/9],\n-        [ 13/18, -2/9]])\n-\n-        See Also\n-        ========\n-\n-        inv\n-        pinv_solve\n-\n-        References\n-        ==========\n-\n-        .. [1] https://en.wikipedia.org/wiki/Moore-Penrose_pseudoinverse\n-\n-        \"\"\"\n-        A = self\n-        AH = self.H\n-        # Trivial case: pseudoinverse of all-zero matrix is its transpose.\n-        if A.is_zero:\n-            return AH\n-        try:\n-            if self.rows >= self.cols:\n-                return (AH * A).inv() * AH\n-            else:\n-                return AH * (A * AH).inv()\n-        except ValueError:\n-            # Matrix is not full rank, so A*AH cannot be inverted.\n-            raise NotImplementedError('Rank-deficient matrices are not yet '\n-                                      'supported.')\n-\n-    def print_nonzero(self, symb=\"X\"):\n-        \"\"\"Shows location of non-zero entries for fast shape lookup.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix, eye\n-        >>> m = Matrix(2, 3, lambda i, j: i*3+j)\n-        >>> m\n-        Matrix([\n-        [0, 1, 2],\n-        [3, 4, 5]])\n-        >>> m.print_nonzero()\n-        [ XX]\n-        [XXX]\n-        >>> m = eye(4)\n-        >>> m.print_nonzero(\"x\")\n-        [x   ]\n-        [ x  ]\n-        [  x ]\n-        [   x]\n-\n-        \"\"\"\n-        s = []\n-        for i in range(self.rows):\n-            line = []\n-            for j in range(self.cols):\n-                if self[i, j] == 0:\n-                    line.append(\" \")\n-                else:\n-                    line.append(str(symb))\n-            s.append(\"[%s]\" % ''.join(line))\n-        print('\\n'.join(s))\n-\n-    def project(self, v):\n-        \"\"\"Return the projection of ``self`` onto the line containing ``v``.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix, S, sqrt\n-        >>> V = Matrix([sqrt(3)/2, S.Half])\n-        >>> x = Matrix([[1, 0]])\n-        >>> V.project(x)\n-        Matrix([[sqrt(3)/2, 0]])\n-        >>> V.project(-x)\n-        Matrix([[sqrt(3)/2, 0]])\n-        \"\"\"\n-        return v * (self.dot(v) / v.dot(v))\n-\n-    def QRdecomposition(self):\n-        \"\"\"Return Q, R where A = Q*R, Q is orthogonal and R is upper triangular.\n-\n-        Examples\n-        ========\n-\n-        This is the example from wikipedia:\n-\n-        >>> from sympy import Matrix\n-        >>> A = Matrix([[12, -51, 4], [6, 167, -68], [-4, 24, -41]])\n-        >>> Q, R = A.QRdecomposition()\n-        >>> Q\n-        Matrix([\n-        [ 6/7, -69/175, -58/175],\n-        [ 3/7, 158/175,   6/175],\n-        [-2/7,    6/35,  -33/35]])\n-        >>> R\n-        Matrix([\n-        [14,  21, -14],\n-        [ 0, 175, -70],\n-        [ 0,   0,  35]])\n-        >>> A == Q*R\n-        True\n-\n-        QR factorization of an identity matrix:\n-\n-        >>> A = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])\n-        >>> Q, R = A.QRdecomposition()\n-        >>> Q\n-        Matrix([\n-        [1, 0, 0],\n-        [0, 1, 0],\n-        [0, 0, 1]])\n-        >>> R\n-        Matrix([\n-        [1, 0, 0],\n-        [0, 1, 0],\n-        [0, 0, 1]])\n-\n-        See Also\n-        ========\n-\n-        cholesky\n-        LDLdecomposition\n-        LUdecomposition\n-        QRsolve\n-        \"\"\"\n-        cls = self.__class__\n-        mat = self.as_mutable()\n-\n-        if not mat.rows >= mat.cols:\n-            raise MatrixError(\n-                \"The number of rows must be greater than columns\")\n-        n = mat.rows\n-        m = mat.cols\n-        rank = n\n-        row_reduced = mat.rref()[0]\n-        for i in range(row_reduced.rows):\n-            if row_reduced.row(i).norm() == 0:\n-                rank -= 1\n-        if not rank == mat.cols:\n-            raise MatrixError(\"The rank of the matrix must match the columns\")\n-        Q, R = mat.zeros(n, m), mat.zeros(m)\n-        for j in range(m):  # for each column vector\n-            tmp = mat[:, j]  # take original v\n-            for i in range(j):\n-                # subtract the project of mat on new vector\n-                tmp -= Q[:, i] * mat[:, j].dot(Q[:, i])\n-                tmp.expand()\n-            # normalize it\n-            R[j, j] = tmp.norm()\n-            Q[:, j] = tmp / R[j, j]\n-            if Q[:, j].norm() != 1:\n-                raise NotImplementedError(\n-                    \"Could not normalize the vector %d.\" % j)\n-            for i in range(j):\n-                R[i, j] = Q[:, i].dot(mat[:, j])\n-        return cls(Q), cls(R)\n-\n-    def QRsolve(self, b):\n-        \"\"\"Solve the linear system 'Ax = b'.\n-\n-        'self' is the matrix 'A', the method argument is the vector\n-        'b'.  The method returns the solution vector 'x'.  If 'b' is a\n-        matrix, the system is solved for each column of 'b' and the\n-        return value is a matrix of the same shape as 'b'.\n-\n-        This method is slower (approximately by a factor of 2) but\n-        more stable for floating-point arithmetic than the LUsolve method.\n-        However, LUsolve usually uses an exact arithmetic, so you don't need\n-        to use QRsolve.\n-\n-        This is mainly for educational purposes and symbolic matrices, for real\n-        (or complex) matrices use mpmath.qr_solve.\n-\n-        See Also\n-        ========\n-\n-        lower_triangular_solve\n-        upper_triangular_solve\n-        gauss_jordan_solve\n-        cholesky_solve\n-        diagonal_solve\n-        LDLsolve\n-        LUsolve\n-        pinv_solve\n-        QRdecomposition\n-        \"\"\"\n-\n-        Q, R = self.as_mutable().QRdecomposition()\n-        y = Q.T * b\n-\n-        # back substitution to solve R*x = y:\n-        # We build up the result \"backwards\" in the vector 'x' and reverse it\n-        # only in the end.\n-        x = []\n-        n = R.rows\n-        for j in range(n - 1, -1, -1):\n-            tmp = y[j, :]\n-            for k in range(j + 1, n):\n-                tmp -= R[j, k] * x[n - 1 - k]\n-            x.append(tmp / R[j, j])\n-        return self._new([row._mat for row in reversed(x)])\n-\n-    def solve_least_squares(self, rhs, method='CH'):\n-        \"\"\"Return the least-square fit to the data.\n-\n-        By default the cholesky_solve routine is used (method='CH'); other\n-        methods of matrix inversion can be used. To find out which are\n-        available, see the docstring of the .inv() method.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy.matrices import Matrix, ones\n-        >>> A = Matrix([1, 2, 3])\n-        >>> B = Matrix([2, 3, 4])\n-        >>> S = Matrix(A.row_join(B))\n-        >>> S\n-        Matrix([\n-        [1, 2],\n-        [2, 3],\n-        [3, 4]])\n-\n-        If each line of S represent coefficients of Ax + By\n-        and x and y are [2, 3] then S*xy is:\n-\n-        >>> r = S*Matrix([2, 3]); r\n-        Matrix([\n-        [ 8],\n-        [13],\n-        [18]])\n-\n-        But let's add 1 to the middle value and then solve for the\n-        least-squares value of xy:\n-\n-        >>> xy = S.solve_least_squares(Matrix([8, 14, 18])); xy\n-        Matrix([\n-        [ 5/3],\n-        [10/3]])\n-\n-        The error is given by S*xy - r:\n-\n-        >>> S*xy - r\n-        Matrix([\n-        [1/3],\n-        [1/3],\n-        [1/3]])\n-        >>> _.norm().n(2)\n-        0.58\n-\n-        If a different xy is used, the norm will be higher:\n-\n-        >>> xy += ones(2, 1)/10\n-        >>> (S*xy - r).norm().n(2)\n-        1.5\n-\n-        \"\"\"\n-        if method == 'CH':\n-            return self.cholesky_solve(rhs)\n-        t = self.T\n-        return (t * self).inv(method=method) * t * rhs\n-\n-    def solve(self, rhs, method='GE'):\n-        \"\"\"Return solution to self*soln = rhs using given inversion method.\n-\n-        For a list of possible inversion methods, see the .inv() docstring.\n-        \"\"\"\n-\n-        if not self.is_square:\n-            if self.rows < self.cols:\n-                raise ValueError('Under-determined system. '\n-                                 'Try M.gauss_jordan_solve(rhs)')\n-            elif self.rows > self.cols:\n-                raise ValueError('For over-determined system, M, having '\n-                                 'more rows than columns, try M.solve_least_squares(rhs).')\n-        else:\n-            return self.inv(method=method) * rhs\n-\n-    def table(self, printer, rowstart='[', rowend=']', rowsep='\\n',\n-              colsep=', ', align='right'):\n-        r\"\"\"\n-        String form of Matrix as a table.\n-\n-        ``printer`` is the printer to use for on the elements (generally\n-        something like StrPrinter())\n-\n-        ``rowstart`` is the string used to start each row (by default '[').\n-\n-        ``rowend`` is the string used to end each row (by default ']').\n-\n-        ``rowsep`` is the string used to separate rows (by default a newline).\n-\n-        ``colsep`` is the string used to separate columns (by default ', ').\n-\n-        ``align`` defines how the elements are aligned. Must be one of 'left',\n-        'right', or 'center'.  You can also use '<', '>', and '^' to mean the\n-        same thing, respectively.\n-\n-        This is used by the string printer for Matrix.\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> from sympy.printing.str import StrPrinter\n-        >>> M = Matrix([[1, 2], [-33, 4]])\n-        >>> printer = StrPrinter()\n-        >>> M.table(printer)\n-        '[  1, 2]\\n[-33, 4]'\n-        >>> print(M.table(printer))\n-        [  1, 2]\n-        [-33, 4]\n-        >>> print(M.table(printer, rowsep=',\\n'))\n-        [  1, 2],\n-        [-33, 4]\n-        >>> print('[%s]' % M.table(printer, rowsep=',\\n'))\n-        [[  1, 2],\n-        [-33, 4]]\n-        >>> print(M.table(printer, colsep=' '))\n-        [  1 2]\n-        [-33 4]\n-        >>> print(M.table(printer, align='center'))\n-        [ 1 , 2]\n-        [-33, 4]\n-        >>> print(M.table(printer, rowstart='{', rowend='}'))\n-        {  1, 2}\n-        {-33, 4}\n-        \"\"\"\n-        # Handle zero dimensions:\n-        if self.rows == 0 or self.cols == 0:\n-            return '[]'\n-        # Build table of string representations of the elements\n-        res = []\n-        # Track per-column max lengths for pretty alignment\n-        maxlen = [0] * self.cols\n-        for i in range(self.rows):\n-            res.append([])\n-            for j in range(self.cols):\n-                s = printer._print(self[i, j])\n-                res[-1].append(s)\n-                maxlen[j] = max(len(s), maxlen[j])\n-        # Patch strings together\n-        align = {\n-            'left': 'ljust',\n-            'right': 'rjust',\n-            'center': 'center',\n-            '<': 'ljust',\n-            '>': 'rjust',\n-            '^': 'center',\n-        }[align]\n-        for i, row in enumerate(res):\n-            for j, elem in enumerate(row):\n-                row[j] = getattr(elem, align)(maxlen[j])\n-            res[i] = rowstart + colsep.join(row) + rowend\n-        return rowsep.join(res)\n-\n-    def upper_triangular_solve(self, rhs):\n-        \"\"\"Solves Ax = B, where A is an upper triangular matrix.\n-\n-        See Also\n-        ========\n-\n-        lower_triangular_solve\n-        gauss_jordan_solve\n-        cholesky_solve\n-        diagonal_solve\n-        LDLsolve\n-        LUsolve\n-        QRsolve\n-        pinv_solve\n-        \"\"\"\n-        if not self.is_square:\n-            raise NonSquareMatrixError(\"Matrix must be square.\")\n-        if rhs.rows != self.rows:\n-            raise TypeError(\"Matrix size mismatch.\")\n-        if not self.is_upper:\n-            raise TypeError(\"Matrix is not upper triangular.\")\n-        return self._upper_triangular_solve(rhs)\n-\n-    def vech(self, diagonal=True, check_symmetry=True):\n-        \"\"\"Return the unique elements of a symmetric Matrix as a one column matrix\n-        by stacking the elements in the lower triangle.\n-\n-        Arguments:\n-        diagonal -- include the diagonal cells of self or not\n-        check_symmetry -- checks symmetry of self but not completely reliably\n-\n-        Examples\n-        ========\n-\n-        >>> from sympy import Matrix\n-        >>> m=Matrix([[1, 2], [2, 3]])\n-        >>> m\n-        Matrix([\n-        [1, 2],\n-        [2, 3]])\n-        >>> m.vech()\n-        Matrix([\n-        [1],\n-        [2],\n-        [3]])\n-        >>> m.vech(diagonal=False)\n-        Matrix([[2]])\n-\n-        See Also\n-        ========\n-\n-        vec\n-        \"\"\"\n-        from sympy.matrices import zeros\n-\n-        c = self.cols\n-        if c != self.rows:\n-            raise ShapeError(\"Matrix must be square\")\n-        if check_symmetry:\n-            self.simplify()\n-            if self != self.transpose():\n-                raise ValueError(\n-                    \"Matrix appears to be asymmetric; consider check_symmetry=False\")\n-        count = 0\n-        if diagonal:\n-            v = zeros(c * (c + 1) // 2, 1)\n-            for j in range(c):\n-                for i in range(j, c):\n-                    v[count] = self[i, j]\n-                    count += 1\n-        else:\n-            v = zeros(c * (c - 1) // 2, 1)\n-            for j in range(c):\n-                for i in range(j + 1, c):\n-                    v[count] = self[i, j]\n-                    count += 1\n-        return v\n-\n-\n-def classof(A, B):\n-    \"\"\"\n-    Get the type of the result when combining matrices of different types.\n-\n-    Currently the strategy is that immutability is contagious.\n-\n-    Examples\n-    ========\n-\n-    >>> from sympy import Matrix, ImmutableMatrix\n-    >>> from sympy.matrices.matrices import classof\n-    >>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix\n-    >>> IM = ImmutableMatrix([[1, 2], [3, 4]])\n-    >>> classof(M, IM)\n-    <class 'sympy.matrices.immutable.ImmutableDenseMatrix'>\n-    \"\"\"\n-    try:\n-        if A._class_priority > B._class_priority:\n-            return A.__class__\n-        else:\n-            return B.__class__\n-    except AttributeError:\n-        pass\n-    try:\n-        import numpy\n-        if isinstance(A, numpy.ndarray):\n-            return B.__class__\n-        if isinstance(B, numpy.ndarray):\n-            return A.__class__\n-    except (AttributeError, ImportError):\n-        pass\n-    raise TypeError(\"Incompatible classes %s, %s\" % (A.__class__, B.__class__))\n-\n-\n-def a2idx(j, n=None):\n-    \"\"\"Return integer after making positive and validating against n.\"\"\"\n-    if type(j) is not int:\n-        try:\n-            j = j.__index__()\n-        except AttributeError:\n-            raise IndexError(\"Invalid index a[%r]\" % (j,))\n-    if n is not None:\n-        if j < 0:\n-            j += n\n-        if not (j >= 0 and j < n):\n-            raise IndexError(\"Index out of range: a[%s]\" % j)\n-    return int(j)\n-\n-\n-def _find_reasonable_pivot(col, iszerofunc=_iszero, simpfunc=_simplify):\n-    \"\"\" Find the lowest index of an item in `col` that is\n-    suitable for a pivot.  If `col` consists only of\n-    Floats, the pivot with the largest norm is returned.\n-    Otherwise, the first element where `iszerofunc` returns\n-    False is used.  If `iszerofunc` doesn't return false,\n-    items are simplified and retested until a suitable\n-    pivot is found.\n-\n-    Returns a 4-tuple\n-        (pivot_offset, pivot_val, assumed_nonzero, newly_determined)\n-    where pivot_offset is the index of the pivot, pivot_val is\n-    the (possibly simplified) value of the pivot, assumed_nonzero\n-    is True if an assumption that the pivot was non-zero\n-    was made without being proved, and newly_determined are\n-    elements that were simplified during the process of pivot\n-    finding.\"\"\"\n-\n-    newly_determined = []\n-    col = list(col)\n-    # a column that contains a mix of floats and integers\n-    # but at least one float is considered a numerical\n-    # column, and so we do partial pivoting\n-    if all(isinstance(x, (Float, Integer)) for x in col) and any(\n-            isinstance(x, Float) for x in col):\n-        col_abs = [abs(x) for x in col]\n-        max_value = max(col_abs)\n-        if iszerofunc(max_value):\n-            # just because iszerofunc returned True, doesn't\n-            # mean the value is numerically zero.  Make sure\n-            # to replace all entries with numerical zeros\n-            if max_value != 0:\n-                newly_determined = [(i, 0) for i, x in enumerate(col) if x != 0]\n-            return (None, None, False, newly_determined)\n-        index = col_abs.index(max_value)\n-        return (index, col[index], False, newly_determined)\n-\n-    # PASS 1 (iszerofunc directly)\n-    possible_zeros = []\n-    for i, x in enumerate(col):\n-        is_zero = iszerofunc(x)\n-        # is someone wrote a custom iszerofunc, it may return\n-        # BooleanFalse or BooleanTrue instead of True or False,\n-        # so use == for comparison instead of `is`\n-        if is_zero == False:\n-            # we found something that is definitely not zero\n-            return (i, x, False, newly_determined)\n-        possible_zeros.append(is_zero)\n-\n-    # by this point, we've found no certain non-zeros\n-    if all(possible_zeros):\n-        # if everything is definitely zero, we have\n-        # no pivot\n-        return (None, None, False, newly_determined)\n-\n-    # PASS 2 (iszerofunc after simplify)\n-    # we haven't found any for-sure non-zeros, so\n-    # go through the elements iszerofunc couldn't\n-    # make a determination about and opportunistically\n-    # simplify to see if we find something\n-    for i, x in enumerate(col):\n-        if possible_zeros[i] is not None:\n-            continue\n-        simped = simpfunc(x)\n-        is_zero = iszerofunc(simped)\n-        if is_zero == True or is_zero == False:\n-            newly_determined.append((i, simped))\n-        if is_zero == False:\n-            return (i, simped, False, newly_determined)\n-        possible_zeros[i] = is_zero\n-\n-    # after simplifying, some things that were recognized\n-    # as zeros might be zeros\n-    if all(possible_zeros):\n-        # if everything is definitely zero, we have\n-        # no pivot\n-        return (None, None, False, newly_determined)\n-\n-    # PASS 3 (.equals(0))\n-    # some expressions fail to simplify to zero, but\n-    # `.equals(0)` evaluates to True.  As a last-ditch\n-    # attempt, apply `.equals` to these expressions\n-    for i, x in enumerate(col):\n-        if possible_zeros[i] is not None:\n-            continue\n-        if x.equals(S.Zero):\n-            # `.iszero` may return False with\n-            # an implicit assumption (e.g., `x.equals(0)`\n-            # when `x` is a symbol), so only treat it\n-            # as proved when `.equals(0)` returns True\n-            possible_zeros[i] = True\n-            newly_determined.append((i, S.Zero))\n-\n-    if all(possible_zeros):\n-        return (None, None, False, newly_determined)\n-\n-    # at this point there is nothing that could definitely\n-    # be a pivot.  To maintain compatibility with existing\n-    # behavior, we'll assume that an illdetermined thing is\n-    # non-zero.  We should probably raise a warning in this case\n-    i = possible_zeros.index(None)\n-    return (i, col[i], True, newly_determined)\n-\n-def _find_reasonable_pivot_naive(col, iszerofunc=_iszero, simpfunc=None):\n-    \"\"\"\n-    Helper that computes the pivot value and location from a\n-    sequence of contiguous matrix column elements. As a side effect\n-    of the pivot search, this function may simplify some of the elements\n-    of the input column. A list of these simplified entries and their\n-    indices are also returned.\n-    This function mimics the behavior of _find_reasonable_pivot(),\n-    but does less work trying to determine if an indeterminate candidate\n-    pivot simplifies to zero. This more naive approach can be much faster,\n-    with the trade-off that it may erroneously return a pivot that is zero.\n-\n-    `col` is a sequence of contiguous column entries to be searched for\n-    a suitable pivot.\n-    `iszerofunc` is a callable that returns a Boolean that indicates\n-    if its input is zero, or None if no such determination can be made.\n-    `simpfunc` is a callable that simplifies its input. It must return\n-    its input if it does not simplify its input. Passing in\n-    `simpfunc=None` indicates that the pivot search should not attempt\n-    to simplify any candidate pivots.\n-\n-    Returns a 4-tuple:\n-    (pivot_offset, pivot_val, assumed_nonzero, newly_determined)\n-    `pivot_offset` is the sequence index of the pivot.\n-    `pivot_val` is the value of the pivot.\n-    pivot_val and col[pivot_index] are equivalent, but will be different\n-    when col[pivot_index] was simplified during the pivot search.\n-    `assumed_nonzero` is a boolean indicating if the pivot cannot be\n-    guaranteed to be zero. If assumed_nonzero is true, then the pivot\n-    may or may not be non-zero. If assumed_nonzero is false, then\n-    the pivot is non-zero.\n-    `newly_determined` is a list of index-value pairs of pivot candidates\n-    that were simplified during the pivot search.\n-    \"\"\"\n-\n-    # indeterminates holds the index-value pairs of each pivot candidate\n-    # that is neither zero or non-zero, as determined by iszerofunc().\n-    # If iszerofunc() indicates that a candidate pivot is guaranteed\n-    # non-zero, or that every candidate pivot is zero then the contents\n-    # of indeterminates are unused.\n-    # Otherwise, the only viable candidate pivots are symbolic.\n-    # In this case, indeterminates will have at least one entry,\n-    # and all but the first entry are ignored when simpfunc is None.\n-    indeterminates = []\n-    for i, col_val in enumerate(col):\n-        col_val_is_zero = iszerofunc(col_val)\n-        if col_val_is_zero == False:\n-            # This pivot candidate is non-zero.\n-            return i, col_val, False, []\n-        elif col_val_is_zero is None:\n-            # The candidate pivot's comparison with zero\n-            # is indeterminate.\n-            indeterminates.append((i, col_val))\n-\n-    if len(indeterminates) == 0:\n-        # All candidate pivots are guaranteed to be zero, i.e. there is\n-        # no pivot.\n-        return None, None, False, []\n-\n-    if simpfunc is None:\n-        # Caller did not pass in a simplification function that might\n-        # determine if an indeterminate pivot candidate is guaranteed\n-        # to be nonzero, so assume the first indeterminate candidate\n-        # is non-zero.\n-        return indeterminates[0][0], indeterminates[0][1], True, []\n-\n-    # newly_determined holds index-value pairs of candidate pivots\n-    # that were simplified during the search for a non-zero pivot.\n-    newly_determined = []\n-    for i, col_val in indeterminates:\n-        tmp_col_val = simpfunc(col_val)\n-        if id(col_val) != id(tmp_col_val):\n-            # simpfunc() simplified this candidate pivot.\n-            newly_determined.append((i, tmp_col_val))\n-            if iszerofunc(tmp_col_val) == False:\n-                # Candidate pivot simplified to a guaranteed non-zero value.\n-                return i, tmp_col_val, False, newly_determined\n-\n-    return indeterminates[0][0], indeterminates[0][1], True, newly_determined\n+        def _eval_det_bareiss(self):\n+            if self.has(a):\n+                return self.det(method=\"lu\")\n+            return cancel(bareiss(self))\n\\ No newline at end of file\n"}
{"instance_id": "sympy__sympy-13878", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/stats/crv_types.py b/sympy/stats/crv_types.py\nindex fff7da80ae..1014bc2430 100644\n--- a/sympy/stats/crv_types.py\n+++ b/sympy/stats/crv_types.py\n@@ -47,7 +47,8 @@\n \n from sympy import (log, sqrt, pi, S, Dummy, Interval, sympify, gamma,\n                    Piecewise, And, Eq, binomial, factorial, Sum, floor, Abs,\n-                   Lambda, Basic, lowergamma, erf, erfc, I)\n+                   Lambda, Basic, lowergamma, erf, erfc, I, uppergamma, hyper,\n+                   asin)\n from sympy import beta as beta_fn\n from sympy import cos, exp, besseli\n from sympy.stats.crv import (SingleContinuousPSpace, SingleContinuousDistribution,\n@@ -150,9 +151,20 @@ def rv(symbol, cls, args):\n class ArcsinDistribution(SingleContinuousDistribution):\n     _argnames = ('a', 'b')\n \n+    @property\n+    def set(self):\n+        return Interval(self.a, self.b)\n+\n     def pdf(self, x):\n         return 1/(pi*sqrt((x - self.a)*(self.b - x)))\n \n+    def _cdf(self, x):\n+        a, b = self.a, self.b\n+        return Piecewise(\n+            (S.Zero, x < a),\n+            (2*asin(sqrt((x - a)/(b - a)))/pi, x <= b),\n+            (S.One, True))\n+\n def Arcsin(name, a=0, b=1):\n     r\"\"\"\n     Create a Continuous Random Variable with an arcsin distribution.\n@@ -670,6 +682,11 @@ def pdf(self, x):\n         p, a, b = self.p, self.a, self.b\n         return a*p/x*((x/b)**(a*p)/(((x/b)**a + 1)**(p + 1)))\n \n+    def _cdf(self, x):\n+        p, a, b = self.p, self.a, self.b\n+        return Piecewise(((S.One + (S(x)/b)**-a)**-p, x > 0),\n+                         (S.Zero, True))\n+\n \n def Dagum(name, p, a, b):\n     r\"\"\"\n@@ -1032,7 +1049,9 @@ def FisherZ(name, d1, d2):\n class FrechetDistribution(SingleContinuousDistribution):\n     _argnames = ('a', 's', 'm')\n \n-    set = Interval(0, oo)\n+    @property\n+    def set(self):\n+        return Interval(self.m, oo)\n \n     def __new__(cls, a, s=1, m=0):\n         a, s, m = list(map(sympify, (a, s, m)))\n@@ -1042,6 +1061,11 @@ def pdf(self, x):\n         a, s, m = self.a, self.s, self.m\n         return a/s * ((x-m)/s)**(-1-a) * exp(-((x-m)/s)**(-a))\n \n+    def _cdf(self, x):\n+        a, s, m = self.a, self.s, self.m\n+        return Piecewise((exp(-((x-m)/s)**(-a)), x >= m),\n+                         (S.Zero, True))\n+\n def Frechet(name, a, s=1, m=0):\n     r\"\"\"\n     Create a continuous random variable with a Frechet distribution.\n@@ -1108,6 +1132,12 @@ def pdf(self, x):\n         k, theta = self.k, self.theta\n         return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k)\n \n+    def _cdf(self, x):\n+        k, theta = self.k, self.theta\n+        return Piecewise(\n+                (lowergamma(k, S(x)/theta)/gamma(k), x > 0),\n+                (S.Zero, True))\n+\n     def sample(self):\n         return random.gammavariate(self.k, self.theta)\n \n@@ -1200,6 +1230,11 @@ def pdf(self, x):\n         a, b = self.a, self.b\n         return b**a/gamma(a) * x**(-a-1) * exp(-b/x)\n \n+    def _cdf(self, x):\n+        a, b = self.a, self.b\n+        return Piecewise((uppergamma(a, b/x)/gamma(a), x > 0),\n+                         (S.Zero, True))\n+\n def GammaInverse(name, a, b):\n     r\"\"\"\n     Create a continuous random variable with an inverse Gamma distribution.\n@@ -1374,16 +1409,6 @@ def Gompertz(name, b, eta):\n class KumaraswamyDistribution(SingleContinuousDistribution):\n     _argnames = ('a', 'b')\n \n-    set = Interval(0, oo)\n-\n-    @staticmethod\n-    def check(a, b):\n-        _value_check(a > 0, \"a must be positive\")\n-        _value_check(b > 0, \"b must be positive\")\n-\n-    def pdf(self, x):\n-        a, b = self.a, self.b\n-        return a * b * x**(a-1) * (1-x**a)**(b-1)\n \n def Kumaraswamy(name, a, b):\n     r\"\"\"\n", "model": "claude-sonnet-5-5", "steps": 8, "finished": false, "patch_lines": 112, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 112, "steps": 8}], "ms": 35965}
{"instance_id": "sympy__sympy-13974", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/physics/quantum/tensorproduct.py b/sympy/physics/quantum/tensorproduct.py\nindex 9dd10d219e..e61ebf5f5c 100644\n--- a/sympy/physics/quantum/tensorproduct.py\n+++ b/sympy/physics/quantum/tensorproduct.py\n@@ -268,6 +268,18 @@ def _eval_trace(self, **kwargs):\n                          for idx, value in enumerate(exp.args)])\n \n \n+def tensor_product_simp_Pow(e):\n+    \"\"\"Evaluate an integer power of a ``TensorProduct``.\n+\n+    ``TensorProduct(A, B)**n`` becomes ``TensorProduct(A**n, B**n)``.\n+    Anything else is returned unchanged.\n+    \"\"\"\n+    if isinstance(e, Pow) and isinstance(e.base, TensorProduct) \\\n+            and e.exp.is_integer:\n+        return TensorProduct(*[arg**e.exp for arg in e.base.args])\n+    return e\n+\n+\n def tensor_product_simp_Mul(e):\n     \"\"\"Simplify a Mul with TensorProducts.\n \n@@ -315,6 +327,15 @@ def tensor_product_simp_Mul(e):\n     if not isinstance(e, Mul):\n         return e\n     c_part, nc_part = e.args_cnc()\n+    # expand integer powers of TensorProducts: (AxB)**n -> (A**n)x(B**n)\n+    new_nc = [tensor_product_simp_Pow(nc) for nc in nc_part]\n+    if new_nc != nc_part:\n+        nc_part = new_nc\n+        # flatten any scalars/products produced\n+        e = Mul(*c_part) * Mul(*nc_part)\n+        if not isinstance(e, Mul):\n+            return e\n+        c_part, nc_part = e.args_cnc()\n     n_nc = len(nc_part)\n     if n_nc == 0 or n_nc == 1:\n         return e\n@@ -376,13 +397,16 @@ def tensor_product_simp(e, **hints):\n     commutators and anticommutators as well:\n \n     >>> tensor_product_simp(e**2)\n-    (A*C)x(B*D)**2\n+    ((A*C)**2)x((B*D)**2)\n \n     \"\"\"\n     if isinstance(e, Add):\n         return Add(*[tensor_product_simp(arg) for arg in e.args])\n     elif isinstance(e, Pow):\n-        return tensor_product_simp(e.base) ** e.exp\n+        base = tensor_product_simp(e.base)\n+        if isinstance(base, TensorProduct):\n+            return tensor_product_simp_Pow(Pow(base, e.exp, evaluate=False))\n+        return base ** e.exp\n     elif isinstance(e, Mul):\n         return tensor_product_simp_Mul(e)\n     elif isinstance(e, Commutator):\n", "model": "claude-sonnet-5-5", "steps": 10, "finished": true, "patch_lines": 58, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 58, "steps": 10}], "ms": 40103}
{"instance_id": "sympy__sympy-14248", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py\nindex 8253b2f682..72b08a3823 100644\n--- a/sympy/printing/latex.py\n+++ b/sympy/printing/latex.py\n@@ -1477,8 +1477,13 @@ def _print_Adjoint(self, expr):\n             return r\"%s^\\dagger\" % self._print(mat)\n \n     def _print_MatAdd(self, expr):\n-        terms = list(expr.args)\n-        tex = \" + \".join(map(self._print, terms))\n+        terms = [self._print(i) for i in expr.args]\n+        tex = terms[0]\n+        for t in terms[1:]:\n+            if t.startswith('-'):\n+                tex += \" \" + t\n+            else:\n+                tex += \" + \" + t\n         return tex\n \n     def _print_MatMul(self, expr):\n@@ -1488,7 +1493,15 @@ def parens(x):\n             if isinstance(x, (Add, MatAdd, HadamardProduct)):\n                 return r\"\\left(%s\\right)\" % self._print(x)\n             return self._print(x)\n-        return ' '.join(map(parens, expr.args))\n+\n+        args = list(expr.args)\n+        if args[0].is_Number and args[0].is_negative:\n+            if args[0] is S.NegativeOne:\n+                args = args[1:]\n+            else:\n+                args[0] = -args[0]\n+            return '- ' + ' '.join(map(parens, args))\n+        return ' '.join(map(parens, args))\n \n     def _print_Mod(self, expr, exp=None):\n         if exp is not None:\ndiff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py\nindex db24f4c612..e4fb658662 100644\n--- a/sympy/printing/pretty/pretty.py\n+++ b/sympy/printing/pretty/pretty.py\n@@ -819,7 +819,20 @@ def _print_BlockMatrix(self, B):\n         return self._print(B.blocks)\n \n     def _print_MatAdd(self, expr):\n-        return self._print_seq(expr.args, None, None, ' + ')\n+        s = None\n+        for item in expr.args:\n+            pform = self._print(item)\n+            if s is None:\n+                s = pform     # First element\n+            else:\n+                coeff = item.as_coeff_mmul()[0]\n+                if _coeff_isneg(S(coeff)):\n+                    s = prettyForm(*stringPict.next(s, ' '))\n+                else:\n+                    s = prettyForm(*stringPict.next(s, ' + '))\n+                s = prettyForm(*stringPict.next(s, pform))\n+\n+        return s\n \n     def _print_MatMul(self, expr):\n         args = list(expr.args)\ndiff --git a/sympy/printing/str.py b/sympy/printing/str.py\nindex 0baefe0f7f..15570cc4c0 100644\n--- a/sympy/printing/str.py\n+++ b/sympy/printing/str.py\n@@ -304,16 +304,38 @@ def _print_Mul(self, expr):\n             return sign + '*'.join(a_str) + \"/(%s)\" % '*'.join(b_str)\n \n     def _print_MatMul(self, expr):\n-        return '*'.join([self.parenthesize(arg, precedence(expr))\n-            for arg in expr.args])\n+        args = list(expr.args)\n+        if args[0].is_Number and args[0].is_negative:\n+            sign = \"-\"\n+            if args[0] is S.NegativeOne:\n+                args = args[1:]\n+            else:\n+                args[0] = -args[0]\n+        else:\n+            sign = \"\"\n+\n+        return sign + '*'.join([self.parenthesize(arg, precedence(expr))\n+            for arg in args])\n \n     def _print_HadamardProduct(self, expr):\n         return '.*'.join([self.parenthesize(arg, precedence(expr))\n             for arg in expr.args])\n \n     def _print_MatAdd(self, expr):\n-        return ' + '.join([self.parenthesize(arg, precedence(expr))\n-            for arg in expr.args])\n+        terms = [self.parenthesize(arg, precedence(expr))\n+             for arg in expr.args]\n+        l = []\n+        for t in terms:\n+            if t.startswith('-'):\n+                sign = \"-\"\n+                t = t[1:]\n+            else:\n+                sign = \"+\"\n+            l.extend([sign, t])\n+        sign = l.pop(0)\n+        if sign == '+':\n+            sign = \"\"\n+        return sign + ' '.join(l)\n \n     def _print_NaN(self, expr):\n         return 'nan'\n", "model": "claude-sonnet-5-5", "steps": 16, "finished": false, "patch_lines": 110, "candidates": [{"compile_ok": 0, "loc_hits": 3, "files": 3, "diff_lines": 110, "steps": 16}], "ms": 45760}
{"instance_id": "sympy__sympy-14976", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/printing/pycode.py b/sympy/printing/pycode.py\nindex d06901425d..6d0a8b5b06 100644\n--- a/sympy/printing/pycode.py\n+++ b/sympy/printing/pycode.py\n@@ -331,6 +331,11 @@ def _print_Float(self, e):\n         args = str(tuple(map(int, e._mpf_)))\n         return '{func}({args})'.format(func=self._module_format('mpmath.mpf'), args=args)\n \n+    def _print_Rational(self, e):\n+        return '{0}({1})/{0}({2})'.format(\n+            self._module_format('mpmath.mpf'),\n+            e.p,\n+            e.q)\n \n     def _print_uppergamma(self, e):\n         return \"{0}({1}, {2}, {3})\".format(\n", "model": "claude-sonnet-5-5", "steps": 5, "finished": true, "patch_lines": 16, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 16, "steps": 5}], "ms": 13085}
{"instance_id": "sympy__sympy-15017", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/tensor/array/dense_ndim_array.py b/sympy/tensor/array/dense_ndim_array.py\nindex 9be94a8631..9790712755 100644\n--- a/sympy/tensor/array/dense_ndim_array.py\n+++ b/sympy/tensor/array/dense_ndim_array.py\n@@ -149,7 +149,7 @@ def _new(cls, iterable, shape, **kwargs):\n         self._shape = shape\n         self._array = list(flat_list)\n         self._rank = len(shape)\n-        self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0\n+        self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 1\n         return self\n \n     def __setitem__(self, index, value):\n@@ -174,7 +174,7 @@ def _new(cls, iterable, shape, **kwargs):\n         self._shape = shape\n         self._array = list(flat_list)\n         self._rank = len(shape)\n-        self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0\n+        self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 1\n         return self\n \n     def __setitem__(self, index, value):\ndiff --git a/sympy/tensor/array/sparse_ndim_array.py b/sympy/tensor/array/sparse_ndim_array.py\nindex 72b5d51299..0cf329a012 100644\n--- a/sympy/tensor/array/sparse_ndim_array.py\n+++ b/sympy/tensor/array/sparse_ndim_array.py\n@@ -130,7 +130,7 @@ def __new__(cls, iterable=None, shape=None, **kwargs):\n \n         shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)\n         shape = Tuple(*map(_sympify, shape))\n-        loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0\n+        loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 1\n \n         # Sparse array:\n         if isinstance(flat_list, (dict, Dict)):\n@@ -167,7 +167,7 @@ def __new__(cls, iterable=None, shape=None, **kwargs):\n         self = object.__new__(cls)\n         self._shape = shape\n         self._rank = len(shape)\n-        self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 0\n+        self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else 1\n \n         # Sparse array:\n         if isinstance(flat_list, (dict, Dict)):\n", "model": "claude-sonnet-5-5", "steps": 16, "finished": false, "patch_lines": 44, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 2, "diff_lines": 44, "steps": 16}], "ms": 44619}
{"instance_id": "sympy__sympy-15345", "model_name_or_path": "cain-anthropic-e124", "model_patch": "diff --git a/sympy/printing/mathematica.py b/sympy/printing/mathematica.py\nindex ea7e3a2d94..5f248c3aad 100644\n--- a/sympy/printing/mathematica.py\n+++ b/sympy/printing/mathematica.py\n@@ -101,6 +101,12 @@ def _print_Function(self, expr):\n                     return \"%s[%s]\" % (mfunc, self.stringify(expr.args, \", \"))\n         return expr.func.__name__ + \"[%s]\" % self.stringify(expr.args, \", \")\n \n+    def _print_Max(self, expr):\n+        return \"Max[%s]\" % self.stringify(expr.args, \", \")\n+\n+    def _print_Min(self, expr):\n+        return \"Min[%s]\" % self.stringify(expr.args, \", \")\n+\n     def _print_Integral(self, expr):\n         if len(expr.variables) == 1 and not expr.limits[0][1:]:\n             args = [expr.args[0], expr.variables[0]]\n", "model": "claude-sonnet-5-5", "steps": 6, "finished": true, "patch_lines": 17, "candidates": [{"compile_ok": 0, "loc_hits": 0, "files": 1, "diff_lines": 17, "steps": 6}], "ms": 14931}
