def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_evaluate[0]) if iterable(args[0]): if isinstance(args[0], Point) and not evaluate: return args[0] args = args[0] # unpack the arguments into a friendly Tuple # if we were already a Point, we're doing an excess # iteration, but we'll worry about efficiency later coords = Tuple(*args) if any(a.is_number and im(a) for a in coords): raise ValueError('Imaginary coordinates not permitted.') # Turn any Floats into rationals and simplify # any expressions before we instantiate if evaluate: coords = coords.xreplace( dict([(f, simplify(nsimplify(f, rational=True))) for f in coords.atoms(Float)])) if len(coords) == 2: return Point2D(coords, **kwargs) if len(coords) == 3: return Point3D(coords, **kwargs) return GeometryEntity.__new__(cls, *coords)
def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_evaluate[0]) if iterable(args[0]): if isinstance(args[0], Point) and not evaluate: return args[0] args = args[0] # unpack the arguments into a friendly Tuple # if we were already a Point, we're doing an excess # iteration, but we'll worry about efficiency later coords = Tuple(*args) if any(a.is_number and im(a) for a in coords): raise ValueError('Imaginary coordinates not permitted.') # Turn any Floats into rationals and simplify # any expressions before we instantiate if evaluate: coords = coords.xreplace(dict( [(f, simplify(nsimplify(f, rational=True))) for f in coords.atoms(Float)])) if len(coords) == 2: return Point2D(coords, **kwargs) if len(coords) == 3: return Point3D(coords, **kwargs) return GeometryEntity.__new__(cls, *coords)
def __new__(cls, *args, **kwargs): from sympy.geometry.util import find from .polygon import Triangle evaluate = kwargs.get('evaluate', global_evaluate[0]) if len(args) == 1 and isinstance(args[0], Expr): x = kwargs.get('x', 'x') y = kwargs.get('y', 'y') equation = args[0] if isinstance(equation, Eq): equation = equation.lhs - equation.rhs x = find(x, equation) y = find(y, equation) try: a, b, c, d, e = linear_coeffs(equation, x**2, y**2, x, y) except ValueError: raise GeometryError( "The given equation is not that of a circle.") if a == 0 or b == 0 or a != b: raise GeometryError( "The given equation is not that of a circle.") center_x = -c / a / 2 center_y = -d / b / 2 r2 = (center_x**2) + (center_y**2) - e return Circle((center_x, center_y), sqrt(r2), evaluate=evaluate) else: c, r = None, None if len(args) == 3: args = [Point(a, dim=2, evaluate=evaluate) for a in args] t = Triangle(*args) if not isinstance(t, Triangle): return t c = t.circumcenter r = t.circumradius elif len(args) == 2: # Assume (center, radius) pair c = Point(args[0], dim=2, evaluate=evaluate) r = args[1] # TODO: use this instead of the 'if evaluate' block below, but # this will prohibit imaginary radius # r = Point(r, 0, evaluate=evaluate).x # convert via Point as necessary if evaluate: r = simplify(nsimplify(r, rational=True)) if not (c is None or r is None): if r == 0: return c return GeometryEntity.__new__(cls, c, r, **kwargs) raise GeometryError("Circle.__new__ received unknown arguments")
def __new__(cls, *args, **kwargs): eval = kwargs.get("evaluate", global_evaluate[0]) if isinstance(args[0], Point3D): if not eval: return args[0] args = args[0].args else: if iterable(args[0]): args = args[0] if len(args) != 3: raise TypeError("Enter a 3 dimensional point") coords = Tuple(*args) if eval: coords = coords.xreplace(dict([(f, simplify(nsimplify(f, rational=True))) for f in coords.atoms(Float)])) return GeometryEntity.__new__(cls, *coords)
def __new__(cls, *args, **kwargs): if iterable(args[0]): coords = Tuple(*args[0]) elif isinstance(args[0], Point): coords = args[0].args else: coords = Tuple(*args) if len(coords) != 2: raise NotImplementedError( "Only two dimensional points currently supported") if kwargs.get('evaluate', True): coords = [simplify(nsimplify(c, rational=True)) for c in coords] return GeometryEntity.__new__(cls, *coords)
def __new__(cls, *args, **kwargs): if iterable(args[0]): args = args[0] elif isinstance(args[0], Point): args = args[0].args coords = Tuple(*args) if len(coords) != 2: raise NotImplementedError( "Only two dimensional points currently supported") if kwargs.get('evaluate', True): coords = coords.xreplace(dict( [(f, simplify(nsimplify(f, rational=True))) for f in coords.atoms(Float)])) return GeometryEntity.__new__(cls, *coords)
def __new__(cls, *args, **kwargs): eval = kwargs.get('evaluate', global_evaluate[0]) if isinstance(args[0], Point3D): if not eval: return args[0] args = args[0].args else: if iterable(args[0]): args = args[0] if len(args) != 3: raise TypeError("Enter a 3 dimensional point") coords = Tuple(*args) if eval: coords = coords.xreplace( dict([(f, simplify(nsimplify(f, rational=True))) for f in coords.atoms(Float)])) return GeometryEntity.__new__(cls, *coords)
def __new__(cls, *args, **kwargs): eval = kwargs.get('evaluate', global_evaluate[0]) check = True if isinstance(args[0], Point): if not eval: return args[0] args = args[0].args check = False else: if iterable(args[0]): args = args[0] if len(args) != 2: raise NotImplementedError( "Only two dimensional points currently supported") coords = Tuple(*args) if check: if any(a.is_number and im(a) for a in coords): raise ValueError('Imaginary args not permitted.') if eval: coords = coords.xreplace( dict([(f, simplify(nsimplify(f, rational=True))) for f in coords.atoms(Float)])) return GeometryEntity.__new__(cls, *coords)
def __new__(cls, *args, **kwargs): eval = kwargs.get('evaluate', global_evaluate[0]) check = True if isinstance(args[0], Point): if not eval: return args[0] args = args[0].args check = False else: if iterable(args[0]): args = args[0] if len(args) != 2: raise ValueError( "Only two dimensional points currently supported") coords = Tuple(*args) if check: if any(a.is_number and im(a) for a in coords): raise ValueError('Imaginary args not permitted.') if eval: coords = coords.xreplace(dict( [(f, simplify(nsimplify(f, rational=True))) for f in coords.atoms(Float)])) return GeometryEntity.__new__(cls, *coords)
def _jordan_form(M, calc_transform=True, *, chop=False): """Return $(P, J)$ where $J$ is a Jordan block matrix and $P$ is a matrix such that $M = P J P^{-1}$ Parameters ========== calc_transform : bool If ``False``, then only $J$ is returned. chop : bool All matrices are converted to exact types when computing eigenvalues and eigenvectors. As a result, there may be approximation errors. If ``chop==True``, these errors will be truncated. Examples ======== >>> from sympy.matrices import Matrix >>> M = Matrix([[ 6, 5, -2, -3], [-3, -1, 3, 3], [ 2, 1, -2, -3], [-1, 1, 5, 5]]) >>> P, J = M.jordan_form() >>> J Matrix([ [2, 1, 0, 0], [0, 2, 0, 0], [0, 0, 2, 1], [0, 0, 0, 2]]) See Also ======== jordan_block """ if not M.is_square: raise NonSquareMatrixError("Only square matrices have Jordan forms") mat = M has_floats = M.has(Float) if has_floats: try: max_prec = max(term._prec for term in M.values() if isinstance(term, Float)) except ValueError: # if no term in the matrix is explicitly a Float calling max() # will throw a error so setting max_prec to default value of 53 max_prec = 53 # setting minimum max_dps to 15 to prevent loss of precision in # matrix containing non evaluated expressions max_dps = max(prec_to_dps(max_prec), 15) def restore_floats(*args): """If ``has_floats`` is `True`, cast all ``args`` as matrices of floats.""" if has_floats: args = [m.evalf(n=max_dps, chop=chop) for m in args] if len(args) == 1: return args[0] return args # cache calculations for some speedup mat_cache = {} def eig_mat(val, pow): """Cache computations of ``(M - val*I)**pow`` for quick retrieval""" if (val, pow) in mat_cache: return mat_cache[(val, pow)] if (val, pow - 1) in mat_cache: mat_cache[(val, pow)] = mat_cache[(val, pow - 1)].multiply( mat_cache[(val, 1)], dotprodsimp=None) else: mat_cache[(val, pow)] = (mat - val * M.eye(M.rows)).pow(pow) return mat_cache[(val, pow)] # helper functions def nullity_chain(val, algebraic_multiplicity): """Calculate the sequence [0, nullity(E), nullity(E**2), ...] until it is constant where ``E = M - val*I``""" # mat.rank() is faster than computing the null space, # so use the rank-nullity theorem cols = M.cols ret = [0] nullity = cols - eig_mat(val, 1).rank() i = 2 while nullity != ret[-1]: ret.append(nullity) if nullity == algebraic_multiplicity: break nullity = cols - eig_mat(val, i).rank() i += 1 # Due to issues like #7146 and #15872, SymPy sometimes # gives the wrong rank. In this case, raise an error # instead of returning an incorrect matrix if nullity < ret[-1] or nullity > algebraic_multiplicity: raise MatrixError("SymPy had encountered an inconsistent " "result while computing Jordan block: " "{}".format(M)) return ret def blocks_from_nullity_chain(d): """Return a list of the size of each Jordan block. If d_n is the nullity of E**n, then the number of Jordan blocks of size n is 2*d_n - d_(n-1) - d_(n+1)""" # d[0] is always the number of columns, so skip past it mid = [2 * d[n] - d[n - 1] - d[n + 1] for n in range(1, len(d) - 1)] # d is assumed to plateau with "d[ len(d) ] == d[-1]", so # 2*d_n - d_(n-1) - d_(n+1) == d_n - d_(n-1) end = [d[-1] - d[-2]] if len(d) > 1 else [d[0]] return mid + end def pick_vec(small_basis, big_basis): """Picks a vector from big_basis that isn't in the subspace spanned by small_basis""" if len(small_basis) == 0: return big_basis[0] for v in big_basis: _, pivots = M.hstack(*(small_basis + [v])).echelon_form(with_pivots=True) if pivots[-1] == len(small_basis): return v # roots doesn't like Floats, so replace them with Rationals if has_floats: mat = mat.applyfunc(lambda x: nsimplify(x, rational=True)) # first calculate the jordan block structure eigs = mat.eigenvals() # Make sure that we have all roots in radical form for x in eigs: if x.has(CRootOf): raise MatrixError( "Jordan normal form is not implemented if the matrix have " "eigenvalues in CRootOf form") # most matrices have distinct eigenvalues # and so are diagonalizable. In this case, don't # do extra work! if len(eigs.keys()) == mat.cols: blocks = list(sorted(eigs.keys(), key=default_sort_key)) jordan_mat = mat.diag(*blocks) if not calc_transform: return restore_floats(jordan_mat) jordan_basis = [eig_mat(eig, 1).nullspace()[0] for eig in blocks] basis_mat = mat.hstack(*jordan_basis) return restore_floats(basis_mat, jordan_mat) block_structure = [] for eig in sorted(eigs.keys(), key=default_sort_key): algebraic_multiplicity = eigs[eig] chain = nullity_chain(eig, algebraic_multiplicity) block_sizes = blocks_from_nullity_chain(chain) # if block_sizes = = [a, b, c, ...], then the number of # Jordan blocks of size 1 is a, of size 2 is b, etc. # create an array that has (eig, block_size) with one # entry for each block size_nums = [(i + 1, num) for i, num in enumerate(block_sizes)] # we expect larger Jordan blocks to come earlier size_nums.reverse() block_structure.extend( (eig, size) for size, num in size_nums for _ in range(num)) jordan_form_size = sum(size for eig, size in block_structure) if jordan_form_size != M.rows: raise MatrixError("SymPy had encountered an inconsistent result while " "computing Jordan block. : {}".format(M)) blocks = (mat.jordan_block(size=size, eigenvalue=eig) for eig, size in block_structure) jordan_mat = mat.diag(*blocks) if not calc_transform: return restore_floats(jordan_mat) # For each generalized eigenspace, calculate a basis. # We start by looking for a vector in null( (A - eig*I)**n ) # which isn't in null( (A - eig*I)**(n-1) ) where n is # the size of the Jordan block # # Ideally we'd just loop through block_structure and # compute each generalized eigenspace. However, this # causes a lot of unneeded computation. Instead, we # go through the eigenvalues separately, since we know # their generalized eigenspaces must have bases that # are linearly independent. jordan_basis = [] for eig in sorted(eigs.keys(), key=default_sort_key): eig_basis = [] for block_eig, size in block_structure: if block_eig != eig: continue null_big = (eig_mat(eig, size)).nullspace() null_small = (eig_mat(eig, size - 1)).nullspace() # we want to pick something that is in the big basis # and not the small, but also something that is independent # of any other generalized eigenvectors from a different # generalized eigenspace sharing the same eigenvalue. vec = pick_vec(null_small + eig_basis, null_big) new_vecs = [ eig_mat(eig, i).multiply(vec, dotprodsimp=None) for i in range(size) ] eig_basis.extend(new_vecs) jordan_basis.extend(reversed(new_vecs)) basis_mat = mat.hstack(*jordan_basis) return restore_floats(basis_mat, jordan_mat)
def __new__(cls, *args, **kwargs): evaluate = kwargs.get('evaluate', global_evaluate[0]) on_morph = kwargs.get('on_morph', 'ignore') # unpack into coords coords = args[0] if len(args) == 1 else args # check args and handle quickly handle Point instances if isinstance(coords, Point): # even if we're mutating the dimension of a point, we # don't reevaluate its coordinates evaluate = False if len(coords) == kwargs.get('dim', len(coords)): return coords if not is_sequence(coords): raise TypeError(filldedent(''' Expecting sequence of coordinates, not `{}`''' .format(func_name(coords)))) # A point where only `dim` is specified is initialized # to zeros. if len(coords) == 0 and kwargs.get('dim', None): coords = (S.Zero,)*kwargs.get('dim') coords = Tuple(*coords) dim = kwargs.get('dim', len(coords)) if len(coords) < 2: raise ValueError(filldedent(''' Point requires 2 or more coordinates or keyword `dim` > 1.''')) if len(coords) != dim: message = ("Dimension of {} needs to be changed" "from {} to {}.").format(coords, len(coords), dim) if on_morph == 'ignore': pass elif on_morph == "error": raise ValueError(message) elif on_morph == 'warn': warnings.warn(message) else: raise ValueError(filldedent(''' on_morph value should be 'error', 'warn' or 'ignore'.''')) if any(i for i in coords[dim:]): raise ValueError('Nonzero coordinates cannot be removed.') if any(a.is_number and im(a) for a in coords): raise ValueError('Imaginary coordinates are not permitted.') if not all(isinstance(a, Expr) for a in coords): raise TypeError('Coordinates must be valid SymPy expressions.') # pad with zeros appropriately coords = coords[:dim] + (S.Zero,)*(dim - len(coords)) # Turn any Floats into rationals and simplify # any expressions before we instantiate if evaluate: coords = coords.xreplace(dict( [(f, simplify(nsimplify(f, rational=True))) for f in coords.atoms(Float)])) # return 2D or 3D instances if len(coords) == 2: kwargs['_nocheck'] = True return Point2D(*coords, **kwargs) elif len(coords) == 3: kwargs['_nocheck'] = True return Point3D(*coords, **kwargs) # the general Point return GeometryEntity.__new__(cls, *coords)
def _eigenvals(M, error_when_incomplete=True, dotprodsimp=None, **flags): r"""Return eigenvalues using the Berkowitz agorithm to compute the characteristic polynomial. Parameters ========== error_when_incomplete : bool, optional If it is set to ``True``, it will raise an error if not all eigenvalues are computed. This is caused by ``roots`` not returning a full list of eigenvalues. dotprodsimp : bool, optional Specifies whether intermediate term algebraic simplification is used during matrix multiplications to control expression blowup and thus speed up calculation. simplify : bool or function, optional If it is set to ``True``, it attempts to return the most simplified form of expressions returned by applying default simplification method in every routine. If it is set to ``False``, it will skip simplification in this particular routine to save computation resources. If a function is passed to, it will attempt to apply the particular function as simplification method. rational : bool, optional If it is set to ``True``, every floating point numbers would be replaced with rationals before computation. It can solve some issues of ``roots`` routine not working well with floats. multiple : bool, optional If it is set to ``True``, the result will be in the form of a list. If it is set to ``False``, the result will be in the form of a dictionary. Returns ======= eigs : list or dict Eigenvalues of a matrix. The return format would be specified by the key ``multiple``. Raises ====== MatrixError If not enough roots had got computed. NonSquareMatrixError If attempted to compute eigenvalues from a non-square matrix. Examples ======== >>> from sympy.matrices import Matrix >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1]) >>> M.eigenvals() {-1: 1, 0: 1, 2: 1} See Also ======== MatrixDeterminant.charpoly eigenvects Notes ===== Eigenvalues of a matrix `A` can be computed by solving a matrix equation `\det(A - \lambda I) = 0` """ simplify = flags.get( 'simplify', False ) # Collect simplify flag before popped up, to reuse later in the routine. multiple = flags.get( 'multiple', False ) # Collect multiple flag to decide whether return as a dict or list. rational = flags.pop('rational', True) if not M: return {} if rational: M = M.applyfunc(lambda x: nsimplify(x, rational=True) if x.has(Float) else x) if M.is_upper or M.is_lower: if not M.is_square: raise NonSquareMatrixError() diagonal_entries = [M[i, i] for i in range(M.rows)] if multiple: eigs = diagonal_entries else: eigs = {} for diagonal_entry in diagonal_entries: if diagonal_entry not in eigs: eigs[diagonal_entry] = 0 eigs[diagonal_entry] += 1 else: flags.pop('simplify', None) # pop unsupported flag if isinstance(simplify, FunctionType): eigs = roots( M.charpoly(x=Dummy('x'), simplify=simplify, dotprodsimp=dotprodsimp), **flags) else: eigs = roots(M.charpoly(x=Dummy('x'), dotprodsimp=dotprodsimp), **flags) # make sure the algebraic multiplicity sums to the # size of the matrix if error_when_incomplete and (sum(eigs.values()) if isinstance(eigs, dict) else len(eigs)) != M.cols: raise MatrixError("Could not compute eigenvalues for {}".format(M)) # Since 'simplify' flag is unsupported in roots() # simplify() function will be applied once at the end of the routine. if not simplify: return eigs if not isinstance(simplify, FunctionType): simplify = _simplify # With 'multiple' flag set true, simplify() will be mapped for the list # Otherwise, simplify() will be mapped for the keys of the dictionary if not multiple: return {simplify(key): value for key, value in eigs.items()} else: return [simplify(value) for value in eigs]
def _eigenvals( M, error_when_incomplete=True, *, simplify=False, multiple=False, rational=False, **flags): r"""Return eigenvalues using the Berkowitz agorithm to compute the characteristic polynomial. Parameters ========== error_when_incomplete : bool, optional If it is set to ``True``, it will raise an error if not all eigenvalues are computed. This is caused by ``roots`` not returning a full list of eigenvalues. simplify : bool or function, optional If it is set to ``True``, it attempts to return the most simplified form of expressions returned by applying default simplification method in every routine. If it is set to ``False``, it will skip simplification in this particular routine to save computation resources. If a function is passed to, it will attempt to apply the particular function as simplification method. rational : bool, optional If it is set to ``True``, every floating point numbers would be replaced with rationals before computation. It can solve some issues of ``roots`` routine not working well with floats. multiple : bool, optional If it is set to ``True``, the result will be in the form of a list. If it is set to ``False``, the result will be in the form of a dictionary. Returns ======= eigs : list or dict Eigenvalues of a matrix. The return format would be specified by the key ``multiple``. Raises ====== MatrixError If not enough roots had got computed. NonSquareMatrixError If attempted to compute eigenvalues from a non-square matrix. Examples ======== >>> from sympy.matrices import Matrix >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1]) >>> M.eigenvals() {-1: 1, 0: 1, 2: 1} See Also ======== MatrixDeterminant.charpoly eigenvects Notes ===== Eigenvalues of a matrix `A` can be computed by solving a matrix equation `\det(A - \lambda I) = 0` """ if not M: if multiple: return [] return {} if not M.is_square: raise NonSquareMatrixError("{} must be a square matrix.".format(M)) if M.is_upper or M.is_lower: return _eigenvals_triangular(M, multiple=multiple) if all(x.is_number for x in M) and M.has(Float): return _eigenvals_mpmath(M, multiple=multiple) if rational: M = M.applyfunc( lambda x: nsimplify(x, rational=True) if x.has(Float) else x) if multiple: return _eigenvals_list( M, error_when_incomplete=error_when_incomplete, simplify=simplify, **flags) return _eigenvals_dict( M, error_when_incomplete=error_when_incomplete, simplify=simplify, **flags)
def _eigenvals(M, error_when_incomplete=True, **flags): r"""Return eigenvalues using the Berkowitz agorithm to compute the characteristic polynomial. Parameters ========== error_when_incomplete : bool, optional If it is set to ``True``, it will raise an error if not all eigenvalues are computed. This is caused by ``roots`` not returning a full list of eigenvalues. simplify : bool or function, optional If it is set to ``True``, it attempts to return the most simplified form of expressions returned by applying default simplification method in every routine. If it is set to ``False``, it will skip simplification in this particular routine to save computation resources. If a function is passed to, it will attempt to apply the particular function as simplification method. rational : bool, optional If it is set to ``True``, every floating point numbers would be replaced with rationals before computation. It can solve some issues of ``roots`` routine not working well with floats. multiple : bool, optional If it is set to ``True``, the result will be in the form of a list. If it is set to ``False``, the result will be in the form of a dictionary. Returns ======= eigs : list or dict Eigenvalues of a matrix. The return format would be specified by the key ``multiple``. Raises ====== MatrixError If not enough roots had got computed. NonSquareMatrixError If attempted to compute eigenvalues from a non-square matrix. Examples ======== >>> from sympy.matrices import Matrix >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1]) >>> M.eigenvals() {-1: 1, 0: 1, 2: 1} See Also ======== MatrixDeterminant.charpoly eigenvects Notes ===== Eigenvalues of a matrix `A` can be computed by solving a matrix equation `\det(A - \lambda I) = 0` """ if not M: return {} if not M.is_square: raise NonSquareMatrixError("{} must be a square matrix.".format(M)) simplify = flags.pop('simplify', False) multiple = flags.get('multiple', False) rational = flags.pop('rational', True) if M.is_upper or M.is_lower: return _eigenvals_triangular(M, multiple=multiple) if all(x.is_number for x in M) and M.has(Float): return _eigenvals_mpmath(M, multiple=multiple) if rational: M = M.applyfunc(lambda x: nsimplify(x, rational=True) if x.has(Float) else x) if isinstance(simplify, FunctionType): eigs = roots(M.charpoly(simplify=simplify), **flags) else: eigs = roots(M.charpoly(), **flags) # make sure the algebraic multiplicity sums to the # size of the matrix if error_when_incomplete: if not multiple and sum(eigs.values()) != M.rows or \ multiple and len(eigs) != M.cols: raise MatrixError("Could not compute eigenvalues for {}".format(M)) # Since 'simplify' flag is unsupported in roots() # simplify() function will be applied once at the end of the routine. if not simplify: return eigs if not isinstance(simplify, FunctionType): simplify = _simplify # With 'multiple' flag set true, simplify() will be mapped for the list # Otherwise, simplify() will be mapped for the keys of the dictionary if not multiple: return {simplify(key): value for key, value in eigs.items()} else: return [simplify(value) for value in eigs]
def _eigenvects(M, error_when_incomplete=True, iszerofunc=_iszero, *, chop=False, **flags): """Compute eigenvectors of the matrix. Parameters ========== error_when_incomplete : bool, optional Raise an error when not all eigenvalues are computed. This is caused by ``roots`` not returning a full list of eigenvalues. iszerofunc : function, optional Specifies a zero testing function to be used in ``rref``. Default value is ``_iszero``, which uses SymPy's naive and fast default assumption handler. It can also accept any user-specified zero testing function, if it is formatted as a function which accepts a single symbolic argument and returns ``True`` if it is tested as zero and ``False`` if it is tested as non-zero, and ``None`` if it is undecidable. simplify : bool or function, optional If ``True``, ``as_content_primitive()`` will be used to tidy up normalization artifacts. It will also be used by the ``nullspace`` routine. chop : bool or positive number, optional If the matrix contains any Floats, they will be changed to Rationals for computation purposes, but the answers will be returned after being evaluated with evalf. The ``chop`` flag is passed to ``evalf``. When ``chop=True`` a default precision will be used; a number will be interpreted as the desired level of precision. Returns ======= ret : [(eigenval, multiplicity, eigenspace), ...] A ragged list containing tuples of data obtained by ``eigenvals`` and ``nullspace``. ``eigenspace`` is a list containing the ``eigenvector`` for each eigenvalue. ``eigenvector`` is a vector in the form of a ``Matrix``. e.g. a vector of length 3 is returned as ``Matrix([a_1, a_2, a_3])``. Raises ====== NotImplementedError If failed to compute nullspace. Examples ======== >>> from sympy.matrices import Matrix >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1]) >>> M.eigenvects() [(-1, 1, [Matrix([ [-1], [ 1], [ 0]])]), (0, 1, [Matrix([ [ 0], [-1], [ 1]])]), (2, 1, [Matrix([ [2/3], [1/3], [ 1]])])] See Also ======== eigenvals MatrixSubspaces.nullspace """ simplify = flags.get('simplify', True) primitive = flags.get('simplify', False) flags.pop('simplify', None) # remove this if it's there flags.pop('multiple', None) # remove this if it's there if not isinstance(simplify, FunctionType): simpfunc = _simplify if simplify else lambda x: x has_floats = M.has(Float) if has_floats: if all(x.is_number for x in M): return _eigenvects_mpmath(M) M = M.applyfunc(lambda x: nsimplify(x, rational=True)) ret = _eigenvects_DOM(M) if ret is None: ret = _eigenvects_sympy(M, iszerofunc, simplify=simplify, **flags) if primitive: # if the primitive flag is set, get rid of any common # integer denominators def denom_clean(l): from sympy import gcd return [(v / gcd(list(v))).applyfunc(simpfunc) for v in l] ret = [(val, mult, denom_clean(es)) for val, mult, es in ret] if has_floats: # if we had floats to start with, turn the eigenvectors to floats ret = [(val.evalf(chop=chop), mult, [v.evalf(chop=chop) for v in es]) for val, mult, es in ret] return ret
def nsimplify(self, constants=[], tolerance=None, full=False): """See the nsimplify function in sympy.simplify""" from sympy.simplify import nsimplify return nsimplify(self, constants, tolerance, full)
def _eigenvects(M, error_when_incomplete=True, iszerofunc=_iszero, **flags): """Return list of triples (eigenval, multiplicity, eigenspace). Parameters ========== error_when_incomplete : bool, optional Raise an error when not all eigenvalues are computed. This is caused by ``roots`` not returning a full list of eigenvalues. iszerofunc : function, optional Specifies a zero testing function to be used in ``rref``. Default value is ``_iszero``, which uses SymPy's naive and fast default assumption handler. It can also accept any user-specified zero testing function, if it is formatted as a function which accepts a single symbolic argument and returns ``True`` if it is tested as zero and ``False`` if it is tested as non-zero, and ``None`` if it is undecidable. simplify : bool or function, optional If ``True``, ``as_content_primitive()`` will be used to tidy up normalization artifacts. It will also be used by the ``nullspace`` routine. chop : bool or positive number, optional If the matrix contains any Floats, they will be changed to Rationals for computation purposes, but the answers will be returned after being evaluated with evalf. The ``chop`` flag is passed to ``evalf``. When ``chop=True`` a default precision will be used; a number will be interpreted as the desired level of precision. Returns ======= ret : [(eigenval, multiplicity, eigenspace), ...] A ragged list containing tuples of data obtained by ``eigenvals`` and ``nullspace``. ``eigenspace`` is a list containing the ``eigenvector`` for each eigenvalue. ``eigenvector`` is a vector in the form of a ``Matrix``. e.g. a vector of length 3 is returned as ``Matrix([a_1, a_2, a_3])``. Raises ====== NotImplementedError If failed to compute nullspace. Examples ======== >>> from sympy.matrices import Matrix >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1]) >>> M.eigenvects() [(-1, 1, [Matrix([ [-1], [ 1], [ 0]])]), (0, 1, [Matrix([ [ 0], [-1], [ 1]])]), (2, 1, [Matrix([ [2/3], [1/3], [ 1]])])] See Also ======== eigenvals MatrixSubspaces.nullspace """ def eigenspace(eigenval): """Get a basis for the eigenspace for a particular eigenvalue""" m = M - M.eye(M.rows) * eigenval ret = m.nullspace(iszerofunc=iszerofunc) # the nullspace for a real eigenvalue should be # non-trivial. If we didn't find an eigenvector, try once # more a little harder if len(ret) == 0 and simplify: ret = m.nullspace(iszerofunc=iszerofunc, simplify=True) if len(ret) == 0: raise NotImplementedError( "Can't evaluate eigenvector for eigenvalue %s" % eigenval ) return ret simplify = flags.get("simplify", True) if not isinstance(simplify, FunctionType): simpfunc = _simplify if simplify else lambda x: x primitive = flags.get("simplify", False) chop = flags.pop("chop", False) flags.pop("multiple", None) # remove this if it's there has_floats = M.has( Float ) # roots doesn't like Floats, so replace them with Rationals if has_floats: M = M.applyfunc(lambda x: nsimplify(x, rational=True)) eigenvals = M.eigenvals( rational=False, error_when_incomplete=error_when_incomplete, **flags ) ret = [ (val, mult, eigenspace(val)) for val, mult in sorted(eigenvals.items(), key=default_sort_key) ] if primitive: # if the primitive flag is set, get rid of any common # integer denominators def denom_clean(l): from sympy import gcd return [(v / gcd(list(v))).applyfunc(simpfunc) for v in l] ret = [(val, mult, denom_clean(es)) for val, mult, es in ret] if has_floats: # if we had floats to start with, turn the eigenvectors to floats ret = [ (val.evalf(chop=chop), mult, [v.evalf(chop=chop) for v in es]) for val, mult, es in ret ] return ret
def _eigenvals(M, error_when_incomplete=True, *, simplify=False, multiple=False, rational=False, **flags): r"""Compute eigenvalues of the matrix. Parameters ========== error_when_incomplete : bool, optional If it is set to ``True``, it will raise an error if not all eigenvalues are computed. This is caused by ``roots`` not returning a full list of eigenvalues. simplify : bool or function, optional If it is set to ``True``, it attempts to return the most simplified form of expressions returned by applying default simplification method in every routine. If it is set to ``False``, it will skip simplification in this particular routine to save computation resources. If a function is passed to, it will attempt to apply the particular function as simplification method. rational : bool, optional If it is set to ``True``, every floating point numbers would be replaced with rationals before computation. It can solve some issues of ``roots`` routine not working well with floats. multiple : bool, optional If it is set to ``True``, the result will be in the form of a list. If it is set to ``False``, the result will be in the form of a dictionary. Returns ======= eigs : list or dict Eigenvalues of a matrix. The return format would be specified by the key ``multiple``. Raises ====== MatrixError If not enough roots had got computed. NonSquareMatrixError If attempted to compute eigenvalues from a non-square matrix. Examples ======== >>> from sympy.matrices import Matrix >>> M = Matrix(3, 3, [0, 1, 1, 1, 0, 0, 1, 1, 1]) >>> M.eigenvals() {-1: 1, 0: 1, 2: 1} See Also ======== MatrixDeterminant.charpoly eigenvects Notes ===== Eigenvalues of a matrix $A$ can be computed by solving a matrix equation $\det(A - \lambda I) = 0$ It's not always possible to return radical solutions for eigenvalues for matrices larger than $4, 4$ shape due to Abel-Ruffini theorem. If there is no radical solution is found for the eigenvalue, it may return eigenvalues in the form of :class:`sympy.polys.rootoftools.ComplexRootOf`. """ if not M: if multiple: return [] return {} if not M.is_square: raise NonSquareMatrixError("{} must be a square matrix.".format(M)) if M._rep.domain not in (ZZ, QQ): # Skip this check for ZZ/QQ because it can be slow if all(x.is_number for x in M) and M.has(Float): return _eigenvals_mpmath(M, multiple=multiple) if rational: M = M.applyfunc(lambda x: nsimplify(x, rational=True) if x.has(Float) else x) if multiple: return _eigenvals_list(M, error_when_incomplete=error_when_incomplete, simplify=simplify, **flags) return _eigenvals_dict(M, error_when_incomplete=error_when_incomplete, simplify=simplify, **flags)